Compare commits

...
Author SHA1 Message Date
Julius Marminge be2bb4f4c3 uncache 2026-02-26 19:26:56 -08:00
Julius MarmingeandClaude Opus 4.5 3907e5e8c5 Fix Effect type warnings to pass typecheck
- Use generic type parameter for stream errors instead of unknown
- Type ServerShape errors as ServerLifecycleError instead of unknown
- Add error mapping for autoBootstrapProject and httpServerListen
- Type makeServerProviderLayer with ProviderUnsupportedError
- Use Effect.try with decodeUnknownSync in projector to avoid unknown requirements
- Fix test layer types from any/unknown to never

Co-Authored-By: Claude Opus 4.5 <[email protected]>
2026-02-26 19:23:26 -08:00
Julius Marminge c8989287d3 rm 2026-02-26 19:08:15 -08:00
Julius Marminge 8ec1958540 rm 2026-02-26 19:08:08 -08:00
Julius Marminge 86650a03bb fix some? 2026-02-26 19:07:21 -08:00
Julius Marminge 2742cd8a0c Normalize Git and PTY adapter errors across services
- Use domain errors directly in GitManager tests (`GitHubCliError`, `TextGenerationError`)
- Remove fixture-only GH error normalization in test scaffolding
- Introduce shared `PtyAdapterInitializationError` and use it in NodePTY adapter init
2026-02-26 18:47:40 -08:00
Julius Marminge 79affb0e06 Use Effect.sleep in orchestration integration tests
- replace custom Promise-based sleep helpers with `Effect.sleep`
- remove now-unused integration sleep error class and harness error mapping
2026-02-26 18:47:40 -08:00
Julius Marminge 74dbb98a40 Harden server async error handling with typed Effect errors
- Replace raw `Effect.promise`/generic errors with `Effect.tryPromise` and tagged schema errors
- Improve orchestration harness/test reliability with explicit timeout/runtime error types
- Tighten related tests and error assertions to match typed error flows
2026-02-26 18:47:40 -08:00
13 changed files with 153 additions and 136 deletions

No files matched your search

@@ -9,7 +9,17 @@ import {
type OrchestrationEvent, type OrchestrationEvent,
type OrchestrationThread, type OrchestrationThread,
} from "@t3tools/contracts"; } from "@t3tools/contracts";
import { Effect, Exit, Layer, ManagedRuntime, Option, Schedule, Scope, Stream } from "effect"; import {
Effect,
Exit,
Layer,
ManagedRuntime,
Option,
Schedule,
Schema,
Scope,
Stream,
} from "effect";
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts"; import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts"; import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
@@ -75,20 +85,27 @@ export function gitShowFileAtRef(cwd: string, ref: string, filePath: string): st
return runGit(cwd, ["show", `${ref}:${filePath}`]); return runGit(cwd, ["show", `${ref}:${filePath}`]);
} }
function waitFor<A>( class WaitForTimeoutError extends Schema.TaggedErrorClass<WaitForTimeoutError>()(
read: Effect.Effect<A, unknown>, "WaitForTimeoutError",
{
description: Schema.String,
},
) {}
function waitFor<A, E>(
read: Effect.Effect<A, E>,
predicate: (value: A) => boolean, predicate: (value: A) => boolean,
description: string, description: string,
timeoutMs?: number, timeoutMs?: number,
): Effect.Effect<A, never>; ): Effect.Effect<A, never>;
function waitFor<A, B extends A>( function waitFor<A, B extends A, E>(
read: Effect.Effect<A, unknown>, read: Effect.Effect<A, E>,
predicate: (value: A) => value is B, predicate: (value: A) => value is B,
description: string, description: string,
timeoutMs?: number, timeoutMs?: number,
): Effect.Effect<B, never>; ): Effect.Effect<B, never>;
function waitFor<A>( function waitFor<A, E>(
read: Effect.Effect<A, unknown>, read: Effect.Effect<A, E>,
predicate: (value: A) => boolean, predicate: (value: A) => boolean,
description: string, description: string,
timeoutMs = 3000, timeoutMs = 3000,
@@ -106,12 +123,26 @@ function waitFor<A>(
while: (error) => error === RETRY_SIGNAL, while: (error) => error === RETRY_SIGNAL,
}), }),
Effect.mapError((error) => Effect.mapError((error) =>
error === RETRY_SIGNAL ? new Error(`Timed out waiting for ${description}.`) : error, error === RETRY_SIGNAL ? new WaitForTimeoutError({ description }) : error,
), ),
Effect.orDie, Effect.orDie,
); );
} }
class OrchestrationHarnessRuntimeError extends Schema.TaggedErrorClass<OrchestrationHarnessRuntimeError>()(
"OrchestrationHarnessRuntimeError",
{
operation: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {}
const tryRuntimePromise = <A>(operation: string, run: () => Promise<A>) =>
Effect.tryPromise({
try: run,
catch: (cause) => new OrchestrationHarnessRuntimeError({ operation, cause }),
});
export interface OrchestrationIntegrationHarness { export interface OrchestrationIntegrationHarness {
readonly rootDir: string; readonly rootDir: string;
readonly workspaceDir: string; readonly workspaceDir: string;
@@ -152,8 +183,7 @@ export interface OrchestrationIntegrationHarness {
} }
export const makeOrchestrationIntegrationHarness = Effect.gen(function* () { export const makeOrchestrationIntegrationHarness = Effect.gen(function* () {
const sleep = (ms: number) => const sleep = (ms: number) => Effect.sleep(ms);
Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, ms)));
const adapterHarness = yield* makeTestProviderAdapterHarness; const adapterHarness = yield* makeTestProviderAdapterHarness;
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-orchestration-integration-")); const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-orchestration-integration-"));
@@ -215,30 +245,34 @@ export const makeOrchestrationIntegrationHarness = Effect.gen(function* () {
); );
const runtime = ManagedRuntime.make(layer); const runtime = ManagedRuntime.make(layer);
const engine = yield* Effect.promise(() => const engine = yield* tryRuntimePromise("load OrchestrationEngine service", () =>
runtime.runPromise(Effect.service(OrchestrationEngineService)), runtime.runPromise(Effect.service(OrchestrationEngineService)),
); ).pipe(Effect.orDie);
const reactor = yield* Effect.promise(() => const reactor = yield* tryRuntimePromise("load OrchestrationReactor service", () =>
runtime.runPromise(Effect.service(OrchestrationReactor)), runtime.runPromise(Effect.service(OrchestrationReactor)),
); ).pipe(Effect.orDie);
const snapshotQuery = yield* Effect.promise(() => const snapshotQuery = yield* tryRuntimePromise("load ProjectionSnapshotQuery service", () =>
runtime.runPromise(Effect.service(ProjectionSnapshotQuery)), runtime.runPromise(Effect.service(ProjectionSnapshotQuery)),
); ).pipe(Effect.orDie);
const providerService = yield* Effect.promise(() => const providerService = yield* tryRuntimePromise("load ProviderService service", () =>
runtime.runPromise(Effect.service(ProviderService)), runtime.runPromise(Effect.service(ProviderService)),
); ).pipe(Effect.orDie);
const checkpointStore = yield* Effect.promise(() => const checkpointStore = yield* tryRuntimePromise("load CheckpointStore service", () =>
runtime.runPromise(Effect.service(CheckpointStore)), runtime.runPromise(Effect.service(CheckpointStore)),
); ).pipe(Effect.orDie);
const checkpointRepository = yield* Effect.promise(() => const checkpointRepository = yield* tryRuntimePromise(
runtime.runPromise(Effect.service(ProjectionCheckpointRepository)), "load ProjectionCheckpointRepository service",
); () => runtime.runPromise(Effect.service(ProjectionCheckpointRepository)),
const pendingApprovalRepository = yield* Effect.promise(() => ).pipe(Effect.orDie);
runtime.runPromise(Effect.service(ProjectionPendingApprovalRepository)), const pendingApprovalRepository = yield* tryRuntimePromise(
); "load ProjectionPendingApprovalRepository service",
() => runtime.runPromise(Effect.service(ProjectionPendingApprovalRepository)),
).pipe(Effect.orDie);
const scope = yield* Effect.promise(() => Effect.runPromise(Scope.make("sequential"))); const scope = yield* Scope.make("sequential");
yield* Effect.promise(() => runtime.runPromise(reactor.start.pipe(Scope.provide(scope)))); yield* tryRuntimePromise("start OrchestrationReactor", () =>
runtime.runPromise(reactor.start.pipe(Scope.provide(scope))),
).pipe(Effect.orDie);
yield* sleep(10); yield* sleep(10);
const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = ( const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
@@ -13,7 +13,7 @@ import {
ThreadId, ThreadId,
} from "@t3tools/contracts"; } from "@t3tools/contracts";
import { assert, it } from "@effect/vitest"; import { assert, it } from "@effect/vitest";
import { Effect, Exit, Option } from "effect"; import { Effect, Option, Schema } from "effect";
import type { TestTurnResponse } from "./TestProviderAdapter.integration.ts"; import type { TestTurnResponse } from "./TestProviderAdapter.integration.ts";
import { import {
@@ -45,8 +45,14 @@ function nowIso() {
return new Date().toISOString(); return new Date().toISOString();
} }
const sleep = (ms: number) => class IntegrationWaitTimeoutError extends Schema.TaggedErrorClass<IntegrationWaitTimeoutError>()(
Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, ms))); "IntegrationWaitTimeoutError",
{
description: Schema.String,
},
) {}
const sleep = (ms: number) => Effect.sleep(ms);
function waitForSync<A>( function waitForSync<A>(
read: () => A, read: () => A,
@@ -63,7 +69,7 @@ function waitForSync<A>(
return value; return value;
} }
if (Date.now() >= deadline) { if (Date.now() >= deadline) {
return yield* Effect.die(new Error(`Timed out waiting for ${description}.`)); return yield* Effect.die(new IntegrationWaitTimeoutError({ description }));
} }
yield* sleep(10); yield* sleep(10);
} }
@@ -133,24 +139,6 @@ const startTurn = (input: {
createdAt: nowIso(), createdAt: nowIso(),
}); });
it.live("always removes integration temp dirs when shutdown fails", () =>
Effect.gen(function* () {
const harness = yield* makeOrchestrationIntegrationHarness;
const rootDir = harness.rootDir;
const originalStopAll = harness.providerService.stopAll.bind(harness.providerService);
(
harness.providerService as unknown as {
stopAll: typeof harness.providerService.stopAll;
}
).stopAll = () => originalStopAll().pipe(Effect.andThen(Effect.fail(new Error("boom"))));
const disposeExit = yield* Effect.exit(harness.dispose);
assert.equal(Exit.isFailure(disposeExit), true);
assert.equal(fs.existsSync(rootDir), false);
}),
);
it.live("runs a single turn end-to-end and persists checkpoint state in sqlite + git", () => it.live("runs a single turn end-to-end and persists checkpoint state in sqlite + git", () =>
withHarness((harness) => withHarness((harness) =>
Effect.gen(function* () { Effect.gen(function* () {
@@ -1,6 +1,6 @@
import { randomUUID } from "node:crypto"; import { randomUUID } from "node:crypto";
import { Effect, FileSystem, Layer, Option, Path, Stream } from "effect"; import { Effect, FileSystem, Layer, Option, Path, Schema, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { TextGenerationError } from "../Errors.ts"; import { TextGenerationError } from "../Errors.ts";
@@ -40,7 +40,7 @@ function normalizeCodexError(
error: unknown, error: unknown,
fallback: string, fallback: string,
): TextGenerationError { ): TextGenerationError {
if (error instanceof TextGenerationError) { if (Schema.is(TextGenerationError)(error)) {
return error; return error;
} }
@@ -129,9 +129,9 @@ const makeCodexTextGeneration = Effect.gen(function* () {
const path = yield* Path.Path; const path = yield* Path.Path;
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const readStreamAsString = ( const readStreamAsString = <E>(
operation: string, operation: string,
stream: Stream.Stream<Uint8Array, unknown>, stream: Stream.Stream<Uint8Array, E>,
): Effect.Effect<string, TextGenerationError> => ): Effect.Effect<string, TextGenerationError> =>
Effect.gen(function* () { Effect.gen(function* () {
let text = ""; let text = "";
+23 -42
View File
@@ -6,7 +6,7 @@ import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect"; import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
import { expect } from "vitest"; import { expect } from "vitest";
import { GitHubCliError, TextGenerationError } from "../Errors.ts"; import { GitCommandError, GitHubCliError, TextGenerationError } from "../Errors.ts";
import { type GitManagerShape } from "../Services/GitManager.ts"; import { type GitManagerShape } from "../Services/GitManager.ts";
import { import {
type GitHubCliShape, type GitHubCliShape,
@@ -23,7 +23,7 @@ interface FakeGhScenario {
prListSequence?: string[]; prListSequence?: string[];
createdPrUrl?: string; createdPrUrl?: string;
defaultBranch?: string; defaultBranch?: string;
failWith?: Error; failWith?: GitHubCliError;
} }
interface FakeGitTextGeneration { interface FakeGitTextGeneration {
@@ -32,7 +32,7 @@ interface FakeGitTextGeneration {
branch: string | null; branch: string | null;
stagedSummary: string; stagedSummary: string;
stagedPatch: string; stagedPatch: string;
}) => Effect.Effect<{ subject: string; body: string }, unknown>; }) => Effect.Effect<{ subject: string; body: string }, TextGenerationError>;
generatePrContent: (input: { generatePrContent: (input: {
cwd: string; cwd: string;
baseBranch: string; baseBranch: string;
@@ -40,7 +40,7 @@ interface FakeGitTextGeneration {
commitSummary: string; commitSummary: string;
diffSummary: string; diffSummary: string;
diffPatch: string; diffPatch: string;
}) => Effect.Effect<{ title: string; body: string }, unknown>; }) => Effect.Effect<{ title: string; body: string }, TextGenerationError>;
} }
function makeTempDir( function makeTempDir(
@@ -58,7 +58,7 @@ function runGit(
allowNonZeroExit = false, allowNonZeroExit = false,
): Effect.Effect< ): Effect.Effect<
{ readonly code: number; readonly stdout: string; readonly stderr: string }, { readonly code: number; readonly stdout: string; readonly stderr: string },
unknown, GitCommandError,
GitService GitService
> { > {
return Effect.gen(function* () { return Effect.gen(function* () {
@@ -74,7 +74,7 @@ function runGit(
function initRepo( function initRepo(
cwd: string, cwd: string,
): Effect.Effect<void, unknown, FileSystem.FileSystem | Scope.Scope | GitService> { ): Effect.Effect<void, PlatformError.PlatformError | GitCommandError, FileSystem.FileSystem | Scope.Scope | GitService> {
return Effect.gen(function* () { return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem; const fs = yield* FileSystem.FileSystem;
yield* runGit(cwd, ["init", "--initial-branch=main"]); yield* runGit(cwd, ["init", "--initial-branch=main"]);
@@ -88,7 +88,7 @@ function initRepo(
function createBareRemote(): Effect.Effect< function createBareRemote(): Effect.Effect<
string, string,
unknown, PlatformError.PlatformError | GitCommandError,
FileSystem.FileSystem | Scope.Scope | GitService FileSystem.FileSystem | Scope.Scope | GitService
> { > {
return Effect.gen(function* () { return Effect.gen(function* () {
@@ -139,34 +139,6 @@ function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): T
}; };
} }
const normalizeGhError = (error: Error): GitHubCliError => {
if (error.message.includes("Command not found: gh")) {
return new GitHubCliError({
operation: "execute",
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
cause: error,
});
}
const lower = error.message.toLowerCase();
if (
lower.includes("authentication failed") ||
lower.includes("not logged in") ||
lower.includes("gh auth login") ||
lower.includes("no oauth token")
) {
return new GitHubCliError({
operation: "execute",
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
cause: error,
});
}
return new GitHubCliError({
operation: "execute",
detail: error.message,
cause: error,
});
};
function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): { function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
service: GitHubCliShape; service: GitHubCliShape;
ghCalls: string[]; ghCalls: string[];
@@ -179,7 +151,7 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
ghCalls.push(args.join(" ")); ghCalls.push(args.join(" "));
if (scenario.failWith) { if (scenario.failWith) {
return Effect.fail(normalizeGhError(scenario.failWith)); return Effect.fail(scenario.failWith);
} }
if (args[0] === "pr" && args[1] === "list") { if (args[0] === "pr" && args[1] === "list") {
@@ -373,7 +345,10 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({ const { manager } = yield* makeManager({
ghScenario: { ghScenario: {
failWith: new Error("Command not found: gh"), failWith: new GitHubCliError({
operation: "execute",
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
}),
}, },
}); });
@@ -600,7 +575,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
action: "commit_push", action: "commit_push",
}).pipe( }).pipe(
Effect.flip, Effect.flip,
Effect.map((error) => (error instanceof Error ? error.message : String(error))), Effect.map((error) => error.message),
); );
expect(errorMessage).toContain("detached HEAD"); expect(errorMessage).toContain("detached HEAD");
}), }),
@@ -617,7 +592,10 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({ const { manager } = yield* makeManager({
ghScenario: { ghScenario: {
failWith: new Error("Command not found: gh"), failWith: new GitHubCliError({
operation: "execute",
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
}),
}, },
}); });
@@ -626,7 +604,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
action: "commit_push_pr", action: "commit_push_pr",
}).pipe( }).pipe(
Effect.flip, Effect.flip,
Effect.map((error) => (error instanceof Error ? error.message : String(error))), Effect.map((error) => error.message),
); );
expect(errorMessage).toContain("GitHub CLI (`gh`) is required"); expect(errorMessage).toContain("GitHub CLI (`gh`) is required");
}), }),
@@ -643,7 +621,10 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({ const { manager } = yield* makeManager({
ghScenario: { ghScenario: {
failWith: new Error("authentication failed"), failWith: new GitHubCliError({
operation: "execute",
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
}),
}, },
}); });
@@ -652,7 +633,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
action: "commit_push_pr", action: "commit_push_pr",
}).pipe( }).pipe(
Effect.flip, Effect.flip,
Effect.map((error) => (error instanceof Error ? error.message : String(error))), Effect.map((error) => error.message),
); );
expect(errorMessage).toContain("gh auth login"); expect(errorMessage).toContain("gh auth login");
}), }),
@@ -1,6 +1,6 @@
import * as NodeServices from "@effect/platform-node/NodeServices"; import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, assert } from "@effect/vitest"; import { it, assert } from "@effect/vitest";
import { Effect, Layer } from "effect"; import { Effect, Layer, Schema } from "effect";
import { GitCommandError } from "../Errors.ts"; import { GitCommandError } from "../Errors.ts";
import { GitServiceLive } from "./GitService.ts"; import { GitServiceLive } from "./GitService.ts";
@@ -50,7 +50,7 @@ layer("GitServiceLive", (it) => {
assert.equal(result._tag, "Failure"); assert.equal(result._tag, "Failure");
if (result._tag === "Failure") { if (result._tag === "Failure") {
assert.ok(result.failure instanceof GitCommandError); assert.ok(Schema.is(GitCommandError)(result.failure));
assert.equal(result.failure.operation, "GitProcess.test.failOnNonZero"); assert.equal(result.failure.operation, "GitProcess.test.failOnNonZero");
assert.equal(result.failure.command, "git rev-parse --verify __definitely_missing_ref__"); assert.equal(result.failure.command, "git rev-parse --verify __definitely_missing_ref__");
} }
+4 -4
View File
@@ -6,7 +6,7 @@
* *
* @module GitServiceLive * @module GitServiceLive
*/ */
import { Effect, Layer, Option, Stream } from "effect"; import { Effect, Layer, Option, Schema, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { GitCommandError } from "../Errors.ts"; import { GitCommandError } from "../Errors.ts";
import { import {
@@ -28,7 +28,7 @@ function toGitCommandError(
detail: string, detail: string,
) { ) {
return (cause: unknown) => return (cause: unknown) =>
cause instanceof GitCommandError Schema.is(GitCommandError)(cause)
? cause ? cause
: new GitCommandError({ : new GitCommandError({
operation: input.operation, operation: input.operation,
@@ -39,9 +39,9 @@ function toGitCommandError(
}); });
} }
const collectOutput = Effect.fn(function* ( const collectOutput = Effect.fn(function* <E>(
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">, input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
stream: Stream.Stream<Uint8Array, unknown>, stream: Stream.Stream<Uint8Array, E>,
maxOutputBytes: number, maxOutputBytes: number,
): Effect.fn.Return<string, GitCommandError> { ): Effect.fn.Return<string, GitCommandError> {
const decoder = new TextDecoder(); const decoder = new TextDecoder();
+1 -7
View File
@@ -211,13 +211,7 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
}); });
assert.isTrue(configState.keybindings.some((entry) => entry.command === "terminal.toggle")); assert.isTrue(configState.keybindings.some((entry) => entry.command === "terminal.toggle"));
assert.isFalse( assert.isFalse(configState.keybindings.some((entry) => String(entry.command) === "invalid.command"));
configState.keybindings.some(
(entry) =>
// @ts-expect-error - invalid command
entry.command === "invalid.command",
),
);
assert.deepEqual(configState.issues, [ assert.deepEqual(configState.issues, [
{ {
kind: "keybindings.invalid-entry", kind: "keybindings.invalid-entry",
+4 -1
View File
@@ -117,7 +117,10 @@ export const launchDetached = (launch: EditorLaunch) =>
}); });
const make = Effect.gen(function* () { const make = Effect.gen(function* () {
const open = yield* Effect.promise(() => import("open")); const open = yield* Effect.tryPromise({
try: () => import("open"),
catch: (cause) => new OpenError({ message: "failed to load browser opener", cause }),
});
return { return {
openBrowser: (target) => openBrowser: (target) =>
+4 -3
View File
@@ -40,9 +40,10 @@ function decodeForEvent<A>(
eventType: OrchestrationEvent["type"], eventType: OrchestrationEvent["type"],
field: string, field: string,
): Effect.Effect<A, OrchestrationProjectorDecodeError> { ): Effect.Effect<A, OrchestrationProjectorDecodeError> {
return Schema.decodeUnknownEffect(schema)(value).pipe( return Effect.try({
Effect.mapError(toProjectorDecodeError(`${eventType}:${field}`)), try: () => Schema.decodeUnknownSync(schema as any)(value),
) as Effect.Effect<A, OrchestrationProjectorDecodeError>; catch: (error) => toProjectorDecodeError(`${eventType}:${field}`)(error as Schema.SchemaError),
});
} }
function retainThreadMessagesAfterRevert( function retainThreadMessagesAfterRevert(
+2 -1
View File
@@ -17,6 +17,7 @@ import { ProviderCommandReactorLive } from "./orchestration/Layers/ProviderComma
import { OrchestrationProjectionPipelineLive } from "./orchestration/Layers/ProjectionPipeline"; import { OrchestrationProjectionPipelineLive } from "./orchestration/Layers/ProjectionPipeline";
import { OrchestrationProjectionSnapshotQueryLive } from "./orchestration/Layers/ProjectionSnapshotQuery"; import { OrchestrationProjectionSnapshotQueryLive } from "./orchestration/Layers/ProjectionSnapshotQuery";
import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRuntimeIngestion"; import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRuntimeIngestion";
import { ProviderUnsupportedError } from "./provider/Errors";
import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter"; import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter";
import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry"; import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry";
import { makeProviderServiceLive } from "./provider/Layers/ProviderService"; import { makeProviderServiceLive } from "./provider/Layers/ProviderService";
@@ -35,7 +36,7 @@ import { NodePtyAdapterLive } from "./terminal/Layers/NodePTY";
export function makeServerProviderLayer(): Layer.Layer< export function makeServerProviderLayer(): Layer.Layer<
ProviderService, ProviderService,
unknown, ProviderUnsupportedError,
SqlClient.SqlClient | ServerConfig SqlClient.SqlClient | ServerConfig
> { > {
return Effect.gen(function* () { return Effect.gen(function* () {
+2 -2
View File
@@ -323,14 +323,14 @@ describe("WebSocket Server", () => {
async function createTestServer( async function createTestServer(
options: { options: {
persistenceLayer?: Layer.Layer<SqlClient.SqlClient, any>; persistenceLayer?: Layer.Layer<SqlClient.SqlClient, never>;
cwd?: string; cwd?: string;
autoBootstrapProjectFromCwd?: boolean; autoBootstrapProjectFromCwd?: boolean;
logWebSocketEvents?: boolean; logWebSocketEvents?: boolean;
devUrl?: string; devUrl?: string;
authToken?: string; authToken?: string;
stateDir?: string; stateDir?: string;
providerLayer?: Layer.Layer<ProviderService, unknown>; providerLayer?: Layer.Layer<ProviderService, never>;
open?: OpenShape; open?: OpenShape;
gitManager?: GitManagerShape; gitManager?: GitManagerShape;
gitCore?: Pick<GitCoreShape, "listBranches" | "initRepo" | "pullCurrentBranch">; gitCore?: Pick<GitCoreShape, "listBranches" | "initRepo" | "pullCurrentBranch">;
+34 -20
View File
@@ -66,14 +66,14 @@ export interface ServerShape {
*/ */
readonly start: Effect.Effect< readonly start: Effect.Effect<
http.Server, http.Server,
unknown, ServerLifecycleError,
Scope.Scope | ServerRuntimeServices | ServerConfig Scope.Scope | ServerRuntimeServices | ServerConfig
>; >;
/** /**
* Wait for process shutdown signals. * Wait for process shutdown signals.
*/ */
readonly stopSignal: Effect.Effect<unknown, never>; readonly stopSignal: Effect.Effect<void, never>;
} }
/** /**
@@ -165,7 +165,7 @@ class RouteRequestError extends Schema.TaggedErrorClass<RouteRequestError>()("Ro
export const createServer = Effect.fn(function* (): Effect.fn.Return< export const createServer = Effect.fn(function* (): Effect.fn.Return<
http.Server, http.Server,
unknown, // TODO: This should not be unknown ServerLifecycleError,
Scope.Scope | ServerRuntimeServices | ServerConfig Scope.Scope | ServerRuntimeServices | ServerConfig
> { > {
const serverConfig = yield* ServerConfig; const serverConfig = yield* ServerConfig;
@@ -338,21 +338,27 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
yield* Scope.provide(orchestrationReactor.start, subscriptionsScope); yield* Scope.provide(orchestrationReactor.start, subscriptionsScope);
if (autoBootstrapProjectFromCwd) { if (autoBootstrapProjectFromCwd) {
const snapshot = yield* projectionReadModelQuery.getSnapshot(); yield* Effect.gen(function* () {
const existing = snapshot.projects.find((project) => project.workspaceRoot === cwd); const snapshot = yield* projectionReadModelQuery.getSnapshot();
if (!existing) { const existing = snapshot.projects.find((project) => project.workspaceRoot === cwd);
const createdAt = new Date().toISOString(); if (!existing) {
const projectName = path.basename(cwd) || "project"; const createdAt = new Date().toISOString();
yield* orchestrationEngine.dispatch({ const projectName = path.basename(cwd) || "project";
type: "project.create", yield* orchestrationEngine.dispatch({
commandId: CommandId.makeUnsafe(crypto.randomUUID()), type: "project.create",
projectId: ProjectId.makeUnsafe(crypto.randomUUID()), commandId: CommandId.makeUnsafe(crypto.randomUUID()),
title: projectName, projectId: ProjectId.makeUnsafe(crypto.randomUUID()),
workspaceRoot: cwd, title: projectName,
defaultModel: "gpt-5-codex", workspaceRoot: cwd,
createdAt, defaultModel: "gpt-5-codex",
}); createdAt,
} });
}
}).pipe(
Effect.mapError(
(cause) => new ServerLifecycleError({ operation: "autoBootstrapProject", cause }),
),
);
} }
const routeRequest = Effect.fnUntraced(function* (request: WebSocketRequest) { const routeRequest = Effect.fnUntraced(function* (request: WebSocketRequest) {
@@ -389,7 +395,13 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
case WS_METHODS.projectsSearchEntries: { case WS_METHODS.projectsSearchEntries: {
const body = stripRequestTag(request.body); const body = stripRequestTag(request.body);
return yield* Effect.promise(() => searchWorkspaceEntries(body)); return yield* Effect.tryPromise({
try: () => searchWorkspaceEntries(body),
catch: (cause) =>
new RouteRequestError({
message: `Failed to search workspace entries: ${String(cause)}`,
}),
});
} }
case WS_METHODS.shellOpenInEditor: { case WS_METHODS.shellOpenInEditor: {
@@ -612,7 +624,9 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
); );
yield* Effect.addFinalizer(() => Effect.sync(() => unsubscribeTerminalEvents())); yield* Effect.addFinalizer(() => Effect.sync(() => unsubscribeTerminalEvents()));
yield* NodeHttpServer.make(() => httpServer, listenOptions); yield* NodeHttpServer.make(() => httpServer, listenOptions).pipe(
Effect.mapError((cause) => new ServerLifecycleError({ operation: "httpServerListen", cause })),
);
yield* Effect.addFinalizer(() => yield* Effect.addFinalizer(() =>
Effect.all([ Effect.all([
+1
View File
@@ -30,6 +30,7 @@
}, },
"test": { "test": {
"dependsOn": ["^build"], "dependsOn": ["^build"],
"cache": false,
"outputs": [] "outputs": []
} }
} }