@devries-cameron20 / t3code Mirror · read-only / commits / 25b02f4ba2
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 25, 05:00 UTC

Enable stricter Effect LSP rules (#2596)

Co-authored-by: Cursor Agent <cursoragent@cursor.com>

Julius Marminge committed May 8, 2026 at 09:58 UTC 25b02f4ba28d9c6a1adff3475625e5b3fdacce4b
409 files changed +3120 -2111
apps/desktop/src/backend/DesktopBackendManager.test.ts
+1 -1
@@ -15,7 +15,7 @@ import * as Schema from "effect/Schema";
15 import * as Sink from "effect/Sink";
16 import * as Scope from "effect/Scope";
17 import * as Stream from "effect/Stream";
18 -import { TestClock } from "effect/testing";
18 +import * as TestClock from "effect/testing/TestClock";
19 import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
20 import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
21
apps/desktop/src/ssh/DesktopSshEnvironment.ts
+3 -3
@@ -3,7 +3,7 @@ import type {
3 DesktopSshEnvironmentBootstrap,
4 DesktopSshEnvironmentTarget,
5 } from "@t3tools/contracts";
6 -import { type NetError, NetService } from "@t3tools/shared/Net";
6 +import * as NetService from "@t3tools/shared/Net";
7 import {
8 SshPasswordPrompt,
9 type SshPasswordPromptShape,
@@ -35,7 +35,7 @@ export type DesktopSshEnvironmentRuntimeServices =
35 | FileSystem.FileSystem
36 | Path.Path
37 | HttpClient.HttpClient
38 - | NetService;
38 + | NetService.NetService;
39
40 export type DesktopSshEnvironmentOperationError =
41 | SshCommandError
@@ -44,7 +44,7 @@ export type DesktopSshEnvironmentOperationError =
44 | SshPairingError
45 | SshReadinessError
46 | SshPasswordPromptError
47 - | NetError;
47 + | NetService.NetError;
48
49 export type DesktopSshEnvironmentDiscoverError = SshHostDiscoveryError;
50
apps/desktop/src/ssh/DesktopSshPasswordPrompts.test.ts
+1 -1
@@ -4,7 +4,7 @@ import * as Effect from "effect/Effect";
4 import * as Fiber from "effect/Fiber";
5 import * as Layer from "effect/Layer";
6 import * as Option from "effect/Option";
7 -import { TestClock } from "effect/testing";
7 +import * as TestClock from "effect/testing/TestClock";
8 import type * as Electron from "electron";
9
10 import * as ElectronWindow from "../electron/ElectronWindow.ts";
apps/desktop/src/updates/DesktopUpdates.test.ts
+1 -1
@@ -8,7 +8,7 @@ import * as Effect from "effect/Effect";
8 import * as Fiber from "effect/Fiber";
9 import * as Layer from "effect/Layer";
10 import * as Option from "effect/Option";
11 -import { TestClock } from "effect/testing";
11 +import * as TestClock from "effect/testing/TestClock";
12
13 import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
14 import * as DesktopConfig from "../app/DesktopConfig.ts";
apps/desktop/tsconfig.json
+1 -13
@@ -3,19 +3,7 @@
3 "compilerOptions": {
4 "composite": true,
5 "types": ["node", "electron"],
6 - "lib": ["ESNext", "DOM", "esnext.disposable"],
7 - "plugins": [
8 - {
9 - "name": "@effect/language-service",
10 - "namespaceImportPackages": ["@effect/platform-node", "effect"],
11 - "diagnosticSeverity": {
12 - "importFromBarrel": "error",
13 - "anyUnknownInErrorContext": "error",
14 - "instanceOfSchema": "warning",
15 - "deterministicKeys": "warning"
16 - }
17 - }
18 - ]
6 + "lib": ["ESNext", "DOM", "esnext.disposable"]
7 },
8 "include": ["src", "tsdown.config.ts"]
9 }
apps/server/integration/OrchestrationEngineHarness.integration.ts
+13 -14
@@ -1,3 +1,4 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 import { execFileSync } from "node:child_process";
3
4 import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -8,20 +9,18 @@ import {
9 type OrchestrationEvent,
10 type OrchestrationThread,
11 } from "@t3tools/contracts";
11 -import {
12 - Effect,
13 - Exit,
14 - FileSystem,
15 - Layer,
16 - ManagedRuntime,
17 - Option,
18 - Path,
19 - Ref,
20 - Schedule,
21 - Schema,
22 - Scope,
23 - Stream,
24 -} from "effect";
12 +import * as Effect from "effect/Effect";
13 +import * as Exit from "effect/Exit";
14 +import * as FileSystem from "effect/FileSystem";
15 +import * as Layer from "effect/Layer";
16 +import * as ManagedRuntime from "effect/ManagedRuntime";
17 +import * as Option from "effect/Option";
18 +import * as Path from "effect/Path";
19 +import * as Ref from "effect/Ref";
20 +import * as Schedule from "effect/Schedule";
21 +import * as Schema from "effect/Schema";
22 +import * as Scope from "effect/Scope";
23 +import * as Stream from "effect/Stream";
24
25 import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
26 import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
apps/server/integration/TestProviderAdapter.integration.ts
+7 -7
@@ -1,5 +1,3 @@
1 -import { randomUUID } from "node:crypto";
2 -
1 import {
2 ApprovalRequestId,
3 EventId,
@@ -12,7 +10,10 @@ import {
10 TurnId,
11 ProviderDriverKind,
12 } from "@t3tools/contracts";
15 -import { Effect, Queue, Stream } from "effect";
13 +import * as Effect from "effect/Effect";
14 +import * as Queue from "effect/Queue";
15 +import * as Random from "effect/Random";
16 +import * as Stream from "effect/Stream";
17
18 import {
19 ProviderAdapterSessionNotFoundError,
@@ -202,7 +203,7 @@ interface MakeTestProviderAdapterHarnessOptions {
203 }
204
205 function nowIso(): string {
205 - return new Date().toISOString();
206 + return "2026-01-01T00:00:00.000Z";
207 }
208
209 function sessionNotFound(
@@ -308,10 +309,9 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
309 for (const fixtureEvent of response.events) {
310 const rawEvent: Record<string, unknown> = {
311 ...(fixtureEvent as Record<string, unknown>),
311 - eventId: randomUUID(),
312 + eventId: yield* Random.nextUUIDv4,
313 provider,
314 sessionId: RuntimeSessionId.make(String(input.threadId)),
314 - createdAt: nowIso(),
315 };
316 rawEvent.threadId = state.snapshot.threadId;
317 if (Object.hasOwn(rawEvent, "turnId")) {
@@ -366,7 +366,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
366 if (deferredTurnCompletedEvents.length === 0) {
367 yield* emit({
368 type: "turn.completed",
369 - eventId: EventId.make(randomUUID()),
369 + eventId: EventId.make(yield* Random.nextUUIDv4),
370 provider,
371 createdAt: nowIso(),
372 threadId: state.snapshot.threadId,
apps/server/integration/orchestrationEngine.integration.test.ts
+12 -5
@@ -1,3 +1,4 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 import fs from "node:fs";
3 import path from "node:path";
4
@@ -17,7 +18,10 @@ import {
18 ProviderInstanceId,
19 } from "@t3tools/contracts";
20 import { assert, it } from "@effect/vitest";
20 -import { Effect, Option, Schema } from "effect";
21 +import * as Clock from "effect/Clock";
22 +import * as Effect from "effect/Effect";
23 +import * as Option from "effect/Option";
24 +import * as Schema from "effect/Schema";
25
26 import type { TestTurnResponse } from "./TestProviderAdapter.integration.ts";
27 import {
@@ -47,7 +51,7 @@ const CODEX_PROVIDER = ProviderDriverKind.make("codex");
51 const CLAUDE_AGENT_PROVIDER = ProviderDriverKind.make("claudeAgent");
52
53 function nowIso() {
50 - return new Date().toISOString();
54 + return "2026-05-01T00:00:00.000Z";
55 }
56
57 class IntegrationWaitTimeoutError extends Schema.TaggedErrorClass<IntegrationWaitTimeoutError>()(
@@ -64,14 +68,14 @@ function waitForSync<A>(
68 timeoutMs = 10_000,
69 ): Effect.Effect<A, never> {
70 return Effect.gen(function* () {
67 - const deadline = Date.now() + timeoutMs;
71 + const deadline = (yield* Clock.currentTimeMillis) + timeoutMs;
72
73 while (true) {
74 const value = read();
75 if (predicate(value)) {
76 return value;
77 }
74 - if (Date.now() >= deadline) {
78 + if ((yield* Clock.currentTimeMillis) >= deadline) {
79 return yield* Effect.die(new IntegrationWaitTimeoutError({ description }));
80 }
81 yield* Effect.sleep(10);
@@ -156,6 +160,7 @@ const startTurn = (input: {
160 readonly messageId: string;
161 readonly text: string;
162 readonly modelSelection?: ModelSelection;
163 + readonly createdAt?: string;
164 }) =>
165 input.harness.engine.dispatch({
166 type: "thread.turn.start",
@@ -174,7 +179,7 @@ const startTurn = (input: {
179 : {}),
180 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
181 runtimeMode: "approval-required",
177 - createdAt: nowIso(),
182 + createdAt: input.createdAt ?? nowIso(),
183 });
184
185 it.live("runs a single turn end-to-end and persists checkpoint state in sqlite + git", () =>
@@ -755,6 +760,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
760 commandId: "cmd-turn-start-revert-1",
761 messageId: "msg-user-revert-1",
762 text: "First edit",
763 + createdAt: "2026-02-24T10:04:59.900Z",
764 });
765
766 yield* harness.waitForThread(
@@ -813,6 +819,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
819 commandId: "cmd-turn-start-revert-2",
820 messageId: "msg-user-revert-2",
821 text: "Second edit",
822 + createdAt: "2026-02-24T10:05:00.900Z",
823 });
824
825 yield* harness.waitForThread(
apps/server/integration/providerService.integration.test.ts
+6 -1
@@ -3,7 +3,12 @@ import { ProviderDriverKind, ProviderInstanceId, ThreadId } from "@t3tools/contr
3 import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts/settings";
4 import * as NodeServices from "@effect/platform-node/NodeServices";
5 import { it, assert } from "@effect/vitest";
6 -import { Effect, FileSystem, Layer, Path, Queue, Stream } from "effect";
6 +import * as Effect from "effect/Effect";
7 +import * as FileSystem from "effect/FileSystem";
8 +import * as Layer from "effect/Layer";
9 +import * as Path from "effect/Path";
10 +import * as Queue from "effect/Queue";
11 +import * as Stream from "effect/Stream";
12
13 import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
14 import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts";
apps/server/scripts/acp-mock-agent.ts
+1
@@ -1,4 +1,5 @@
1 #!/usr/bin/env bun
2 +// @effect-diagnostics nodeBuiltinImport:off
3 import { appendFileSync } from "node:fs";
4
5 import * as Effect from "effect/Effect";
apps/server/scripts/cli.ts
+13 -3
@@ -1,8 +1,13 @@
1 #!/usr/bin/env node
2 -
2 import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
3 import * as NodeServices from "@effect/platform-node/NodeServices";
5 -import { Data, Effect, FileSystem, Logger, Option, Path } from "effect";
4 +import * as Data from "effect/Data";
5 +import * as Effect from "effect/Effect";
6 +import * as FileSystem from "effect/FileSystem";
7 +import * as Logger from "effect/Logger";
8 +import * as Option from "effect/Option";
9 +import * as Path from "effect/Path";
10 +import * as Schema from "effect/Schema";
11 import { Command, Flag } from "effect/unstable/cli";
12 import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
13
@@ -11,6 +16,7 @@ import {
16 PUBLISH_ICON_OVERRIDES,
17 } from "../../../scripts/lib/brand-assets.ts";
18 import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";
19 +import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
20 import rootPackageJson from "../../../package.json" with { type: "json" };
21 import serverPackageJson from "../package.json" with { type: "json" };
22
@@ -30,6 +36,9 @@ interface PackageJson {
36 overrides: Record<string, string>;
37 }
38
39 +const PackageJsonPrettyJson = fromJsonStringPretty(Schema.Unknown);
40 +const encodePackageJson = Schema.encodeEffect(PackageJsonPrettyJson);
41 +
42 class CliError extends Data.TaggedError("CliError")<{
43 readonly message: string;
44 readonly cause?: unknown;
@@ -227,8 +236,9 @@ const publishCmd = Command.make(
236 };
237
238 const original = yield* fs.readFileString(packageJsonPath);
239 + const packageJsonString = yield* encodePackageJson(pkg);
240 yield* fs.writeFileString(backupPath, original);
231 - yield* fs.writeFileString(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`);
241 + yield* fs.writeFileString(packageJsonPath, `${packageJsonString}\n`);
242 yield* Effect.log("[cli] Prepared package.json for publish");
243
244 const iconBackups = yield* applyPublishIconOverrides(repoRoot, serverDir);
apps/server/scripts/cursor-acp-model-mismatch-probe.ts
+8 -4
@@ -1,6 +1,8 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
3 import process from "node:process";
4 import readline from "node:readline";
5 +import * as NodeTimers from "node:timers";
6
7 type JsonPrimitive = null | boolean | number | string;
8 type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue };
@@ -114,7 +116,8 @@ function matchesKeyword(option: SessionConfigOption, keyword: string): boolean {
116
117 function sleep(ms: number) {
118 return new Promise<void>((resolve) => {
117 - setTimeout(resolve, ms);
119 + // @effect-diagnostics-next-line globalTimers:off - Standalone Node probe script, not an Effect runtime test.
120 + NodeTimers.setTimeout(resolve, ms);
121 });
122 }
123
@@ -177,7 +180,8 @@ class JsonRpcChild {
180 const id = this.nextId++;
181
182 const responsePromise = new Promise<JsonValue | undefined>((resolve, reject) => {
180 - const timeout = setTimeout(() => {
183 + // @effect-diagnostics-next-line globalTimers:off - Standalone Node probe script request timeout.
184 + const timeout = NodeTimers.setTimeout(() => {
185 this.pending.delete(id);
186 reject(new Error(`Timed out waiting for ${method} response after ${timeoutMs}ms.`));
187 }, timeoutMs);
@@ -185,11 +189,11 @@ class JsonRpcChild {
189 this.pending.set(id, {
190 method,
191 resolve: (value) => {
188 - clearTimeout(timeout);
192 + NodeTimers.clearTimeout(timeout);
193 resolve(value);
194 },
195 reject: (error) => {
192 - clearTimeout(timeout);
196 + NodeTimers.clearTimeout(timeout);
197 reject(error);
198 },
199 });
apps/server/src/atomicWrite.ts
+3 -1
@@ -1,4 +1,6 @@
1 -import { Effect, FileSystem, Path } from "effect";
1 +import * as Effect from "effect/Effect";
2 +import * as FileSystem from "effect/FileSystem";
3 +import * as Path from "effect/Path";
4 import * as Random from "effect/Random";
5
6 export const writeFileStringAtomically = (input: {
apps/server/src/attachmentPaths.ts
+6 -5
@@ -1,9 +1,10 @@
1 -import path from "node:path";
1 +// @effect-diagnostics nodeBuiltinImport:off
2 +import NodePath from "node:path";
3
4 export const ATTACHMENTS_ROUTE_PREFIX = "/attachments";
5
6 export function normalizeAttachmentRelativePath(rawRelativePath: string): string | null {
6 - const normalized = path.normalize(rawRelativePath).replace(/^[/\\]+/, "");
7 + const normalized = NodePath.normalize(rawRelativePath).replace(/^[/\\]+/, "");
8 if (normalized.length === 0 || normalized.startsWith("..") || normalized.includes("\0")) {
9 return null;
10 }
@@ -19,9 +20,9 @@ export function resolveAttachmentRelativePath(input: {
20 return null;
21 }
22
22 - const attachmentsRoot = path.resolve(input.attachmentsDir);
23 - const filePath = path.resolve(path.join(attachmentsRoot, normalizedRelativePath));
24 - if (!filePath.startsWith(`${attachmentsRoot}${path.sep}`)) {
23 + const attachmentsRoot = NodePath.resolve(input.attachmentsDir);
24 + const filePath = NodePath.resolve(NodePath.join(attachmentsRoot, normalizedRelativePath));
25 + if (!filePath.startsWith(`${attachmentsRoot}${NodePath.sep}`)) {
26 return null;
27 }
28 return filePath;
apps/server/src/attachmentStore.test.ts
+1
@@ -1,3 +1,4 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 import fs from "node:fs";
3 import os from "node:os";
4 import path from "node:path";
apps/server/src/attachmentStore.ts
+1
@@ -1,3 +1,4 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 import { randomUUID } from "node:crypto";
3 import { existsSync } from "node:fs";
4
apps/server/src/auth/Layers/AuthControlPlane.test.ts
+2 -1
@@ -1,6 +1,7 @@
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { expect, it } from "@effect/vitest";
3 -import { Effect, Layer } from "effect";
3 +import * as Effect from "effect/Effect";
4 +import * as Layer from "effect/Layer";
5
6 import type { ServerConfigShape } from "../../config.ts";
7 import { ServerConfig } from "../../config.ts";
apps/server/src/auth/Layers/AuthControlPlane.ts
+3 -1
@@ -1,5 +1,7 @@
1 import type { AuthClientSession, AuthPairingLink } from "@t3tools/contracts";
2 -import { DateTime, Effect, Layer } from "effect";
2 +import * as DateTime from "effect/DateTime";
3 +import * as Effect from "effect/Effect";
4 +import * as Layer from "effect/Layer";
5
6 import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";
7 import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
apps/server/src/auth/Layers/BootstrapCredentialService.test.ts
+4 -2
@@ -1,7 +1,9 @@
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { expect, it } from "@effect/vitest";
3 -import { Duration, Effect, Layer } from "effect";
4 -import { TestClock } from "effect/testing";
3 +import * as Duration from "effect/Duration";
4 +import * as Effect from "effect/Effect";
5 +import * as Layer from "effect/Layer";
6 +import * as TestClock from "effect/testing/TestClock";
7
8 import type { ServerConfigShape } from "../../config.ts";
9 import { ServerConfig } from "../../config.ts";
apps/server/src/auth/Layers/BootstrapCredentialService.ts
+8 -2
@@ -1,6 +1,12 @@
1 import type { AuthPairingLink } from "@t3tools/contracts";
2 -import { DateTime, Duration, Effect, Layer, PubSub, Ref, Stream } from "effect";
3 -import { Option } from "effect";
2 +import * as DateTime from "effect/DateTime";
3 +import * as Duration from "effect/Duration";
4 +import * as Effect from "effect/Effect";
5 +import * as Layer from "effect/Layer";
6 +import * as PubSub from "effect/PubSub";
7 +import * as Ref from "effect/Ref";
8 +import * as Stream from "effect/Stream";
9 +import * as Option from "effect/Option";
10
11 import { ServerConfig } from "../../config.ts";
12 import { AuthPairingLinkRepositoryLive } from "../../persistence/Layers/AuthPairingLinks.ts";
apps/server/src/auth/Layers/ServerAuth.test.ts
+2 -1
@@ -1,6 +1,7 @@
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { expect, it } from "@effect/vitest";
3 -import { Effect, Layer } from "effect";
3 +import * as Effect from "effect/Effect";
4 +import * as Layer from "effect/Layer";
5
6 import type { ServerConfigShape } from "../../config.ts";
7 import { ServerConfig } from "../../config.ts";
apps/server/src/auth/Layers/ServerAuth.ts
+4 -1
@@ -6,7 +6,10 @@ import {
6 type AuthSessionState,
7 type AuthWebSocketTokenResult,
8 } from "@t3tools/contracts";
9 -import { DateTime, Effect, Layer, Option } from "effect";
9 +import * as DateTime from "effect/DateTime";
10 +import * as Effect from "effect/Effect";
11 +import * as Layer from "effect/Layer";
12 +import * as Option from "effect/Option";
13 import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
14
15 import { AuthControlPlane } from "../Services/AuthControlPlane.ts";
apps/server/src/auth/Layers/ServerAuthPolicy.test.ts
+2 -1
@@ -1,6 +1,7 @@
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { expect, it } from "@effect/vitest";
3 -import { Effect, Layer } from "effect";
3 +import * as Effect from "effect/Effect";
4 +import * as Layer from "effect/Layer";
5
6 import type { ServerConfigShape } from "../../config.ts";
7 import { ServerConfig } from "../../config.ts";
apps/server/src/auth/Layers/ServerAuthPolicy.ts
+2 -1
@@ -1,5 +1,6 @@
1 import type { ServerAuthDescriptor } from "@t3tools/contracts";
2 -import { Effect, Layer } from "effect";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4
5 import { ServerConfig } from "../../config.ts";
6 import { ServerAuthPolicy, type ServerAuthPolicyShape } from "../Services/ServerAuthPolicy.ts";
apps/server/src/auth/Layers/ServerSecretStore.test.ts
+6 -1
@@ -1,6 +1,11 @@
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { expect, it } from "@effect/vitest";
3 -import { Cause, Deferred, Effect, FileSystem, Layer, Ref } from "effect";
3 +import * as Cause from "effect/Cause";
4 +import * as Deferred from "effect/Deferred";
5 +import * as Effect from "effect/Effect";
6 +import * as FileSystem from "effect/FileSystem";
7 +import * as Layer from "effect/Layer";
8 +import * as Ref from "effect/Ref";
9 import * as PlatformError from "effect/PlatformError";
10
11 import { ServerConfig } from "../../config.ts";
apps/server/src/auth/Layers/ServerSecretStore.ts
+5 -1
@@ -1,6 +1,10 @@
1 import * as Crypto from "node:crypto";
2
3 -import { Effect, FileSystem, Layer, Path, Predicate } from "effect";
3 +import * as Effect from "effect/Effect";
4 +import * as FileSystem from "effect/FileSystem";
5 +import * as Layer from "effect/Layer";
6 +import * as Path from "effect/Path";
7 +import * as Predicate from "effect/Predicate";
8 import * as PlatformError from "effect/PlatformError";
9
10 import { ServerConfig } from "../../config.ts";
apps/server/src/auth/Layers/SessionCredentialService.test.ts
+4 -2
@@ -1,7 +1,9 @@
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { expect, it } from "@effect/vitest";
3 -import { Duration, Effect, Layer } from "effect";
4 -import { TestClock } from "effect/testing";
3 +import * as Duration from "effect/Duration";
4 +import * as Effect from "effect/Effect";
5 +import * as Layer from "effect/Layer";
6 +import * as TestClock from "effect/testing/TestClock";
7
8 import type { ServerConfigShape } from "../../config.ts";
9 import { ServerConfig } from "../../config.ts";
apps/server/src/auth/Layers/SessionCredentialService.ts
+33 -5
@@ -1,6 +1,14 @@
1 import { AuthSessionId, type AuthClientMetadata, type AuthClientSession } from "@t3tools/contracts";
2 -import { Clock, DateTime, Duration, Effect, Layer, PubSub, Ref, Schema, Stream } from "effect";
3 -import { Option } from "effect";
2 +import * as Clock from "effect/Clock";
3 +import * as DateTime from "effect/DateTime";
4 +import * as Duration from "effect/Duration";
5 +import * as Effect from "effect/Effect";
6 +import * as Layer from "effect/Layer";
7 +import * as PubSub from "effect/PubSub";
8 +import * as Ref from "effect/Ref";
9 +import * as Schema from "effect/Schema";
10 +import * as Stream from "effect/Stream";
11 +import * as Option from "effect/Option";
12
13 import { ServerConfig } from "../../config.ts";
14 import { AuthSessionRepositoryLive } from "../../persistence/Layers/AuthSessions.ts";
@@ -192,6 +200,7 @@ export const makeSessionCredentialService = Effect.gen(function* () {
200 ),
201 );
202
203 + const encodeClaims = Schema.encodeEffect(Schema.fromJsonString(SessionClaims));
204 const issue: SessionCredentialServiceShape["issue"] = (input) =>
205 Effect.gen(function* () {
206 const sessionId = AuthSessionId.make(crypto.randomUUID());
@@ -209,7 +218,13 @@ export const makeSessionCredentialService = Effect.gen(function* () {
218 iat: issuedAt.epochMilliseconds,
219 exp: expiresAt.epochMilliseconds,
220 };
212 - const encodedPayload = base64UrlEncode(JSON.stringify(claims));
221 +
222 + const encodedPayload = yield* encodeClaims(claims).pipe(
223 + Effect.map(base64UrlEncode),
224 + Effect.mapError(
225 + (cause) => new SessionCredentialError({ message: "Failed to encode claims", cause }),
226 + ),
227 + );
228 const signature = signPayload(encodedPayload, signingSecret);
229 const client = input?.client ?? createDefaultClientMetadata();
230 yield* authSessions.create({
@@ -297,12 +312,19 @@ export const makeSessionCredentialService = Effect.gen(function* () {
312 });
313 }
314
315 + const expiresAt = DateTime.make(claims.exp);
316 + if (Option.isNone(expiresAt)) {
317 + return yield* new SessionCredentialError({
318 + message: "Invalid `exp` claim",
319 + });
320 + }
321 +
322 return {
323 sessionId: claims.sid,
324 token,
325 method: claims.method,
326 client: toClientMetadata(row.value.client),
305 - expiresAt: DateTime.makeUnsafe(claims.exp),
327 + expiresAt: expiresAt.value,
328 subject: claims.sub,
329 role: claims.role,
330 } satisfies VerifiedSession;
@@ -317,6 +339,7 @@ export const makeSessionCredentialService = Effect.gen(function* () {
339 ),
340 );
341
342 + const encodeWsClaims = Schema.encodeEffect(Schema.fromJsonString(WebSocketClaims));
343 const issueWebSocketToken: SessionCredentialServiceShape["issueWebSocketToken"] = (
344 sessionId,
345 input,
@@ -333,7 +356,12 @@ export const makeSessionCredentialService = Effect.gen(function* () {
356 iat: issuedAt.epochMilliseconds,
357 exp: expiresAt.epochMilliseconds,
358 };
336 - const encodedPayload = base64UrlEncode(JSON.stringify(claims));
359 + const encodedPayload = yield* encodeWsClaims(claims).pipe(
360 + Effect.map(base64UrlEncode),
361 + Effect.mapError(
362 + (cause) => new SessionCredentialError({ message: "Failed to encode claims", cause }),
363 + ),
364 + );
365 const signature = signPayload(encodedPayload, signingSecret);
366 return {
367 token: `${encodedPayload}.${signature}`,
apps/server/src/auth/Services/AuthControlPlane.ts
+5 -1
@@ -4,7 +4,11 @@ import type {
4 AuthPairingLink,
5 AuthSessionId,
6 } from "@t3tools/contracts";
7 -import { Data, DateTime, Duration, Effect, Context } from "effect";
7 +import * as Data from "effect/Data";
8 +import * as DateTime from "effect/DateTime";
9 +import * as Duration from "effect/Duration";
10 +import * as Effect from "effect/Effect";
11 +import * as Context from "effect/Context";
12 import type { SessionRole } from "./SessionCredentialService.ts";
13
14 export const DEFAULT_SESSION_SUBJECT = "cli-issued-session";
apps/server/src/auth/Services/BootstrapCredentialService.ts
+6 -2
@@ -1,6 +1,10 @@
1 import type { AuthPairingLink, ServerAuthBootstrapMethod } from "@t3tools/contracts";
2 -import { Data, DateTime, Duration, Context } from "effect";
3 -import type { Effect, Stream } from "effect";
2 +import * as Data from "effect/Data";
3 +import * as DateTime from "effect/DateTime";
4 +import * as Duration from "effect/Duration";
5 +import * as Context from "effect/Context";
6 +import type * as Effect from "effect/Effect";
7 +import type * as Stream from "effect/Stream";
8
9 export type BootstrapCredentialRole = "owner" | "client";
10
apps/server/src/auth/Services/ServerAuth.ts
+4 -2
@@ -12,8 +12,10 @@ import type {
12 ServerAuthSessionMethod,
13 AuthWebSocketTokenResult,
14 } from "@t3tools/contracts";
15 -import { Data, DateTime, Context } from "effect";
16 -import type { Effect } from "effect";
15 +import * as Data from "effect/Data";
16 +import * as DateTime from "effect/DateTime";
17 +import * as Context from "effect/Context";
18 +import type * as Effect from "effect/Effect";
19 import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
20 import type { SessionRole } from "./SessionCredentialService.ts";
21
apps/server/src/auth/Services/ServerAuthPolicy.ts
+2 -2
@@ -1,6 +1,6 @@
1 import type { ServerAuthDescriptor } from "@t3tools/contracts";
2 -import { Context } from "effect";
3 -import type { Effect } from "effect";
2 +import * as Context from "effect/Context";
3 +import type * as Effect from "effect/Effect";
4
5 export interface ServerAuthPolicyShape {
6 readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
apps/server/src/auth/Services/ServerSecretStore.ts
+3 -2
@@ -1,5 +1,6 @@
1 -import { Data, Context } from "effect";
2 -import type { Effect } from "effect";
1 +import * as Data from "effect/Data";
2 +import * as Context from "effect/Context";
3 +import type * as Effect from "effect/Effect";
4
5 export class SecretStoreError extends Data.TaggedError("SecretStoreError")<{
6 readonly message: string;
apps/server/src/auth/Services/SessionCredentialService.ts
+6 -2
@@ -4,8 +4,12 @@ import type {
4 AuthSessionId,
5 ServerAuthSessionMethod,
6 } from "@t3tools/contracts";
7 -import { Data, DateTime, Duration, Context } from "effect";
8 -import type { Effect, Stream } from "effect";
7 +import * as Data from "effect/Data";
8 +import * as DateTime from "effect/DateTime";
9 +import * as Duration from "effect/Duration";
10 +import * as Context from "effect/Context";
11 +import type * as Effect from "effect/Effect";
12 +import type * as Stream from "effect/Stream";
13
14 export type SessionRole = "owner" | "client";
15
apps/server/src/auth/http.ts
+3 -1
@@ -6,7 +6,9 @@ import {
6 AuthRevokePairingLinkInput,
7 type AuthWebSocketTokenResult,
8 } from "@t3tools/contracts";
9 -import { DateTime, Effect, Schema } from "effect";
9 +import * as DateTime from "effect/DateTime";
10 +import * as Effect from "effect/Effect";
11 +import * as Schema from "effect/Schema";
12 import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
13
14 import { AuthError, ServerAuth } from "./Services/ServerAuth.ts";
apps/server/src/bin.test.ts
+7 -2
@@ -1,3 +1,4 @@
1 +// @effect-diagnostics-next-line nodeBuiltinImport:off - NodeHttpServer.layer takes `NodeHttp.createServer` as arg
2 import * as NodeHttp from "node:http";
3 import { mkdtempSync } from "node:fs";
4 import { tmpdir } from "node:os";
@@ -5,7 +6,7 @@ import { join } from "node:path";
6
7 import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
8 import * as NodeServices from "@effect/platform-node/NodeServices";
8 -import { NetService } from "@t3tools/shared/Net";
9 +import * as NetService from "@t3tools/shared/Net";
10 import { assert, it } from "@effect/vitest";
11 import * as Effect from "effect/Effect";
12 import * as Layer from "effect/Layer";
@@ -138,7 +139,7 @@ const withLiveProjectCliServer = <A, E, R>(baseDir: string, run: () => Effect.Ef
139 }
140 yield* persistServerRuntimeState({
141 path: config.serverRuntimeStatePath,
141 - state: makePersistedServerRuntimeState({
142 + state: yield* makePersistedServerRuntimeState({
143 config,
144 port: address.port,
145 }),
@@ -179,6 +180,7 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
180 const createdOutput = yield* captureStdout(
181 runCli(["auth", "pairing", "create", "--base-dir", baseDir, "--json"]),
182 );
183 + // @effect-diagnostics-next-line preferSchemaOverJson:off
184 const created = JSON.parse(createdOutput.output) as {
185 readonly id: string;
186 readonly credential: string;
@@ -186,6 +188,7 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
188 const listedOutput = yield* captureStdout(
189 runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]),
190 );
191 + // @effect-diagnostics-next-line preferSchemaOverJson:off
192 const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{
193 readonly id: string;
194 readonly credential?: string;
@@ -207,6 +210,7 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
210 const issuedOutput = yield* captureStdout(
211 runCli(["auth", "session", "issue", "--base-dir", baseDir, "--json"]),
212 );
213 + // @effect-diagnostics-next-line preferSchemaOverJson:off
214 const issued = JSON.parse(issuedOutput.output) as {
215 readonly sessionId: string;
216 readonly token: string;
@@ -215,6 +219,7 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
219 const listedOutput = yield* captureStdout(
220 runCli(["auth", "session", "list", "--base-dir", baseDir, "--json"]),
221 );
222 + // @effect-diagnostics-next-line preferSchemaOverJson:off
223 const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{
224 readonly sessionId: string;
225 readonly token?: string;
apps/server/src/bin.ts
+1 -1
@@ -4,7 +4,7 @@ import * as Effect from "effect/Effect";
4 import * as Layer from "effect/Layer";
5 import { Command } from "effect/unstable/cli";
6
7 -import { NetService } from "@t3tools/shared/Net";
7 +import * as NetService from "@t3tools/shared/Net";
8 import packageJson from "../package.json" with { type: "json" };
9 import { authCommand } from "./cli/auth.ts";
10 import { sharedServerCommandFlags } from "./cli/config.ts";
apps/server/src/bootstrap.test.ts
+4 -2
@@ -1,13 +1,15 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 import * as NFS from "node:fs";
3 import * as path from "node:path";
4 import { execFileSync, spawn } from "node:child_process";
5 import * as NodeServices from "@effect/platform-node/NodeServices";
6 import { assert, it } from "@effect/vitest";
6 -import { FileSystem, Schema } from "effect";
7 +import * as FileSystem from "effect/FileSystem";
8 +import * as Schema from "effect/Schema";
9 import * as Duration from "effect/Duration";
10 import * as Effect from "effect/Effect";
11 import * as Fiber from "effect/Fiber";
10 -import { TestClock } from "effect/testing";
12 +import * as TestClock from "effect/testing/TestClock";
13 import { vi } from "vitest";
14
15 import { readBootstrapEnvelope, resolveFdPath } from "./bootstrap.ts";
apps/server/src/bootstrap.ts
+7 -1
@@ -1,9 +1,15 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 import * as NFS from "node:fs";
3 import * as Net from "node:net";
4 import * as readline from "node:readline";
5 import type { Readable } from "node:stream";
6
6 -import { Data, Effect, Option, Predicate, Result, Schema } from "effect";
7 +import * as Data from "effect/Data";
8 +import * as Effect from "effect/Effect";
9 +import * as Option from "effect/Option";
10 +import * as Predicate from "effect/Predicate";
11 +import * as Result from "effect/Result";
12 +import * as Schema from "effect/Schema";
13 import { decodeJsonResult } from "@t3tools/shared/schemaJson";
14
15 class BootstrapError extends Data.TaggedError("BootstrapError")<{
apps/server/src/checkpointing/Errors.ts
+1 -1
@@ -1,4 +1,4 @@
1 -import { Schema } from "effect";
1 +import * as Schema from "effect/Schema";
2 import type { ProjectionRepositoryError } from "../persistence/Errors.ts";
3 import type { VcsError } from "@t3tools/contracts";
4
apps/server/src/checkpointing/Layers/CheckpointDiffQuery.test.ts
+3 -1
@@ -1,5 +1,7 @@
1 import { CheckpointRef, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
2 -import { Effect, Layer, Option } from "effect";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 +import * as Option from "effect/Option";
5 import { describe, expect, it } from "vitest";
6
7 import {
apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts
+4 -1
@@ -4,7 +4,10 @@ import {
4 type OrchestrationGetFullThreadDiffResult,
5 type OrchestrationGetTurnDiffResult as OrchestrationGetTurnDiffResultType,
6 } from "@t3tools/contracts";
7 -import { Effect, Layer, Option, Schema } from "effect";
7 +import * as Effect from "effect/Effect";
8 +import * as Layer from "effect/Layer";
9 +import * as Option from "effect/Option";
10 +import * as Schema from "effect/Schema";
11
12 import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
13 import { CheckpointInvariantError, CheckpointUnavailableError } from "../Errors.ts";
apps/server/src/checkpointing/Layers/CheckpointStore.test.ts
+6 -1
@@ -1,8 +1,13 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 import path from "node:path";
3
4 import * as NodeServices from "@effect/platform-node/NodeServices";
5 import { it } from "@effect/vitest";
5 -import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
6 +import * as Effect from "effect/Effect";
7 +import * as FileSystem from "effect/FileSystem";
8 +import * as Layer from "effect/Layer";
9 +import * as PlatformError from "effect/PlatformError";
10 +import * as Scope from "effect/Scope";
11 import { describe, expect } from "vitest";
12
13 import { checkpointRefForThreadTurn } from "../Utils.ts";
apps/server/src/checkpointing/Layers/CheckpointStore.ts
+4 -1
@@ -11,7 +11,10 @@
11 */
12 import { randomUUID } from "node:crypto";
13
14 -import { Effect, Layer, FileSystem, Path } from "effect";
14 +import * as Effect from "effect/Effect";
15 +import * as Layer from "effect/Layer";
16 +import * as FileSystem from "effect/FileSystem";
17 +import * as Path from "effect/Path";
18
19 import { CheckpointInvariantError } from "../Errors.ts";
20 import { VcsProcessExitError } from "@t3tools/contracts";
apps/server/src/checkpointing/Services/CheckpointDiffQuery.ts
+2 -2
@@ -12,8 +12,8 @@ import type {
12 OrchestrationGetTurnDiffInput,
13 OrchestrationGetTurnDiffResult,
14 } from "@t3tools/contracts";
15 -import { Context } from "effect";
16 -import type { Effect } from "effect";
15 +import * as Context from "effect/Context";
16 +import type * as Effect from "effect/Effect";
17
18 import type { CheckpointServiceError } from "../Errors.ts";
19
apps/server/src/checkpointing/Services/CheckpointStore.ts
+2 -2
@@ -10,8 +10,8 @@
10 *
11 * @module CheckpointStore
12 */
13 -import { Context } from "effect";
14 -import type { Effect } from "effect";
13 +import * as Context from "effect/Context";
14 +import type * as Effect from "effect/Effect";
15
16 import type { CheckpointStoreError } from "../Errors.ts";
17 import { CheckpointRef } from "@t3tools/contracts";
apps/server/src/checkpointing/Utils.ts
+1 -1
@@ -1,4 +1,4 @@
1 -import { Encoding } from "effect";
1 +import * as Encoding from "effect/Encoding";
2 import { CheckpointRef, ProjectId, type ThreadId } from "@t3tools/contracts";
3
4 export const CHECKPOINT_REFS_PREFIX = "refs/t3/checkpoints";
apps/server/src/cli/auth.ts
+5 -1
@@ -1,5 +1,9 @@
1 import { AuthSessionId } from "@t3tools/contracts";
2 -import { Console, Effect, Layer, Option, References } from "effect";
2 +import * as Console from "effect/Console";
3 +import * as Effect from "effect/Effect";
4 +import * as Layer from "effect/Layer";
5 +import * as Option from "effect/Option";
6 +import * as References from "effect/References";
7 import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli";
8
9 import { AuthControlPlaneRuntimeLive } from "../auth/Layers/AuthControlPlane.ts";
apps/server/src/cli/config.test.ts
+16 -9
@@ -1,13 +1,19 @@
1 -import os from "node:os";
1 +import NodeOS from "node:os";
2
3 import { assert, expect, it } from "@effect/vitest";
4 -import { ConfigProvider, Effect, FileSystem, Layer, Option, Path, Schema } from "effect";
4 +import * as ConfigProvider from "effect/ConfigProvider";
5 +import * as Effect from "effect/Effect";
6 +import * as FileSystem from "effect/FileSystem";
7 +import * as Layer from "effect/Layer";
8 +import * as Option from "effect/Option";
9 +import * as Path from "effect/Path";
10 +import * as Schema from "effect/Schema";
11
12 import {
13 DesktopBackendBootstrap,
14 type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
15 } from "@t3tools/contracts";
10 -import { NetService } from "@t3tools/shared/Net";
16 +import * as NetService from "@t3tools/shared/Net";
17 import * as NodeServices from "@effect/platform-node/NodeServices";
18 import { deriveServerPaths } from "../config.ts";
19 import { resolveServerConfig } from "./config.ts";
@@ -53,7 +59,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
59 it.effect("falls back to effect/config values when flags are omitted", () =>
60 Effect.gen(function* () {
61 const { join } = yield* Path.Path;
56 - const baseDir = join(os.tmpdir(), "t3-cli-config-env-base");
62 + const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-env-base");
63 const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:5173"));
64 const resolved = yield* resolveServerConfig(
65 {
@@ -119,7 +125,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
125 it.effect("uses CLI flags when provided", () =>
126 Effect.gen(function* () {
127 const { join } = yield* Path.Path;
122 - const baseDir = join(os.tmpdir(), "t3-cli-config-flags-base");
128 + const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-flags-base");
129 const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
130 const resolved = yield* resolveServerConfig(
131 {
@@ -147,7 +153,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
153 T3CODE_MODE: "desktop",
154 T3CODE_PORT: "4001",
155 T3CODE_HOST: "0.0.0.0",
150 - T3CODE_HOME: join(os.tmpdir(), "ignored-base"),
156 + T3CODE_HOME: join(NodeOS.tmpdir(), "ignored-base"),
157 VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
158 T3CODE_NO_BROWSER: "false",
159 T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
@@ -185,7 +191,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
191 it.effect("preserves explicit false CLI boolean flags over env and bootstrap values", () =>
192 Effect.gen(function* () {
193 const { join } = yield* Path.Path;
188 - const baseDir = join(os.tmpdir(), "t3-cli-config-false-flags");
194 + const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-false-flags");
195 const fd = yield* openBootstrapFd(
196 makeDesktopBootstrap({
197 noBrowser: true,
@@ -378,7 +384,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
384 it.effect("applies flag then env precedence over bootstrap envelope values", () =>
385 Effect.gen(function* () {
386 const { join } = yield* Path.Path;
381 - const baseDir = join(os.tmpdir(), "t3-cli-config-env-wins");
387 + const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-env-wins");
388 const fd = yield* openBootstrapFd(
389 makeDesktopBootstrap({
390 port: 4888,
@@ -459,6 +465,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
465 yield* fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true });
466 yield* fs.writeFileString(
467 derivedPaths.settingsPath,
468 + // @effect-diagnostics-next-line preferSchemaOverJson:off
469 `${JSON.stringify({
470 observability: {
471 otlpTracesUrl: "http://localhost:4318/v1/traces",
@@ -521,7 +528,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
528 it.effect("forces noBrowser and disables auto-bootstrap for headless startup presentation", () =>
529 Effect.gen(function* () {
530 const { join } = yield* Path.Path;
524 - const baseDir = join(os.tmpdir(), "t3-cli-config-headless-base");
531 + const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-headless-base");
532 const derivedPaths = yield* deriveServerPaths(baseDir, undefined);
533
534 const resolved = yield* resolveServerConfig(
apps/server/src/cli/config.ts
+12 -14
@@ -1,18 +1,16 @@
1 -import { NetService } from "@t3tools/shared/Net";
1 +import * as NetService from "@t3tools/shared/Net";
2 import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
3 import { DesktopBackendBootstrap, PortSchema } from "@t3tools/contracts";
4 -import {
5 - Config,
6 - Duration,
7 - Effect,
8 - FileSystem,
9 - LogLevel,
10 - Option,
11 - Path,
12 - Schema,
13 - SchemaIssue,
14 - SchemaTransformation,
15 -} from "effect";
4 +import * as Config from "effect/Config";
5 +import * as Duration from "effect/Duration";
6 +import * as Effect from "effect/Effect";
7 +import * as FileSystem from "effect/FileSystem";
8 +import * as LogLevel from "effect/LogLevel";
9 +import * as Option from "effect/Option";
10 +import * as Path from "effect/Path";
11 +import * as Schema from "effect/Schema";
12 +import * as SchemaIssue from "effect/SchemaIssue";
13 +import * as SchemaTransformation from "effect/SchemaTransformation";
14 import { Argument, Flag } from "effect/unstable/cli";
15
16 import { readBootstrapEnvelope } from "../bootstrap.ts";
@@ -215,7 +213,7 @@ export const resolveServerConfig = (
213 },
214 ) =>
215 Effect.gen(function* () {
218 - const { findAvailablePort } = yield* NetService;
216 + const { findAvailablePort } = yield* NetService.NetService;
217 const path = yield* Path.Path;
218 const fs = yield* FileSystem.FileSystem;
219 const env = yield* EnvServerConfig;
apps/server/src/cli/project.ts
+27 -21
@@ -4,18 +4,18 @@ import {
4 ProjectId,
5 type ClientOrchestrationCommand,
6 } from "@t3tools/contracts";
7 -import {
8 - Console,
9 - Duration,
10 - Effect,
11 - Exit,
12 - FileSystem,
13 - Layer,
14 - Option,
15 - Path,
16 - References,
17 - Schema,
18 -} from "effect";
7 +import * as Console from "effect/Console";
8 +import * as Data from "effect/Data";
9 +import * as DateTime from "effect/DateTime";
10 +import * as Duration from "effect/Duration";
11 +import * as Effect from "effect/Effect";
12 +import * as Exit from "effect/Exit";
13 +import * as FileSystem from "effect/FileSystem";
14 +import * as Layer from "effect/Layer";
15 +import * as Option from "effect/Option";
16 +import * as Path from "effect/Path";
17 +import * as References from "effect/References";
18 +import * as Schema from "effect/Schema";
19 import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli";
20 import {
21 FetchHttpClient,
@@ -54,6 +54,10 @@ type ProjectCliDispatchCommand = Extract<
54 { type: "project.create" | "project.meta.update" | "project.delete" }
55 >;
56
57 +class ProjectCommandError extends Data.TaggedError("ProjectCommandError")<{
58 + readonly message: string;
59 +}> {}
60 +
61 const ProjectCliRuntimeLive = Layer.mergeAll(
62 WorkspacePathsLive,
63 OrchestrationLayerLive.pipe(
@@ -124,7 +128,7 @@ const resolveProjectTitle = Effect.fn("resolveProjectTitle")(function* (
128 if (trimmed.length > 0) {
129 return trimmed;
130 }
127 - return yield* Effect.fail(new Error("Project title cannot be empty."));
131 + return yield* new ProjectCommandError({ message: "Project title cannot be empty." });
132 }
133
134 const path = yield* Path.Path;
@@ -138,7 +142,7 @@ const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (
142 }) {
143 const trimmedIdentifier = input.identifier.trim();
144 if (trimmedIdentifier.length === 0) {
141 - return yield* Effect.fail(new Error("Project identifier cannot be empty."));
145 + return yield* new ProjectCommandError({ message: "Project identifier cannot be empty." });
146 }
147
148 const activeProjects = input.snapshot.projects.filter((project) => project.deletedAt === null);
@@ -165,7 +169,9 @@ const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (
169
170 const resolved = exactWorkspaceMatch;
171 if (!resolved) {
168 - return yield* Effect.fail(new Error(`No active project found for '${trimmedIdentifier}'.`));
172 + return yield* new ProjectCommandError({
173 + message: `No active project found for '${trimmedIdentifier}'.`,
174 + });
175 }
176
177 return {
@@ -185,7 +191,7 @@ const fetchLiveOrchestrationSnapshot = (origin: string, bearerToken: string) =>
191 "2xx": decodeOrchestrationReadModelResponse,
192 orElse: (response) =>
193 readErrorMessageFromResponse(response).pipe(
188 - Effect.flatMap((message) => Effect.fail(new Error(message))),
194 + Effect.flatMap((message) => Effect.fail(new ProjectCommandError({ message }))),
195 ),
196 }),
197 );
@@ -206,7 +212,7 @@ const dispatchLiveOrchestrationCommand = (
212 "2xx": () => Effect.void,
213 orElse: (response) =>
214 readErrorMessageFromResponse(response).pipe(
209 - Effect.flatMap((message) => Effect.fail(new Error(message))),
215 + Effect.flatMap((message) => Effect.fail(new ProjectCommandError({ message }))),
216 ),
217 }),
218 ),
@@ -331,9 +337,9 @@ const projectAddCommand = Command.make("add", {
337 (project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot,
338 );
339 if (existingProject) {
334 - return yield* Effect.fail(
335 - new Error(`An active project already exists for '${workspaceRoot}'.`),
336 - );
340 + return yield* new ProjectCommandError({
341 + message: `An active project already exists for '${workspaceRoot}'.`,
342 + });
343 }
344
345 const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));
@@ -345,7 +351,7 @@ const projectAddCommand = Command.make("add", {
351 title,
352 workspaceRoot,
353 defaultModelSelection: getAutoBootstrapDefaultModelSelection(),
348 - createdAt: new Date().toISOString(),
354 + createdAt: DateTime.formatIso(yield* DateTime.now),
355 });
356 return `Added project ${projectId} (${title}) at ${workspaceRoot}.`;
357 }),
apps/server/src/cli/server.ts
+1 -1
@@ -1,4 +1,4 @@
1 -import { Effect } from "effect";
1 +import * as Effect from "effect/Effect";
2 import { Command, GlobalFlag } from "effect/unstable/cli";
3
4 import { ServerConfig, type StartupPresentation } from "../config.ts";
apps/server/src/cliAuthFormat.test.ts
+8 -8
@@ -1,5 +1,5 @@
1 import { expect, it } from "@effect/vitest";
2 -import { DateTime } from "effect";
2 +import * as DateTime from "effect/DateTime";
3
4 import {
5 formatIssuedPairingCredential,
@@ -15,8 +15,8 @@ it("formats issued pairing credentials with the secret and optional pair URL", (
15 credential: "secret-pairing-token",
16 role: "client",
17 subject: "one-time-token",
18 - createdAt: DateTime.fromDateUnsafe(new Date("2026-04-08T09:00:00.000Z")),
19 - expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")),
18 + createdAt: DateTime.makeUnsafe("2026-04-08T09:00:00.000Z"),
19 + expiresAt: DateTime.makeUnsafe("2026-04-08T10:00:00.000Z"),
20 },
21 { baseUrl: "https://example.com", json: false },
22 );
@@ -34,8 +34,8 @@ it("formats pairing listings without exposing the secret token", () => {
34 subject: "one-time-token",
35 label: "Phone",
36 role: "client",
37 - createdAt: DateTime.fromDateUnsafe(new Date("2026-04-08T09:00:00.000Z")),
38 - expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")),
37 + createdAt: DateTime.makeUnsafe("2026-04-08T09:00:00.000Z"),
38 + expiresAt: DateTime.makeUnsafe("2026-04-08T10:00:00.000Z"),
39 },
40 ],
41 { json: false },
@@ -57,7 +57,7 @@ it("formats issued sessions with the bearer token but omits tokens from listings
57 label: "deploy-bot",
58 deviceType: "bot",
59 },
60 - expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")),
60 + expiresAt: DateTime.makeUnsafe("2026-04-08T10:00:00.000Z"),
61 },
62 { json: false },
63 );
@@ -75,8 +75,8 @@ it("formats issued sessions with the bearer token but omits tokens from listings
75 },
76 connected: false,
77 current: false,
78 - issuedAt: DateTime.fromDateUnsafe(new Date("2026-04-08T09:00:00.000Z")),
79 - expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")),
78 + issuedAt: DateTime.makeUnsafe("2026-04-08T09:00:00.000Z"),
79 + expiresAt: DateTime.makeUnsafe("2026-04-08T10:00:00.000Z"),
80 lastConnectedAt: null,
81 },
82 ],
apps/server/src/cliAuthFormat.ts
+1 -1
@@ -1,5 +1,5 @@
1 import type { AuthClientMetadata, AuthClientSession, AuthPairingLink } from "@t3tools/contracts";
2 -import { DateTime } from "effect";
2 +import * as DateTime from "effect/DateTime";
3
4 import type { IssuedBearerSession, IssuedPairingLink } from "./auth/Services/AuthControlPlane.ts";
5
apps/server/src/config.ts
+7 -1
@@ -6,7 +6,13 @@
6 *
7 * @module ServerConfig
8 */
9 -import { Effect, FileSystem, Layer, LogLevel, Path, Schema, Context } from "effect";
9 +import * as Effect from "effect/Effect";
10 +import * as FileSystem from "effect/FileSystem";
11 +import * as Layer from "effect/Layer";
12 +import * as LogLevel from "effect/LogLevel";
13 +import * as Path from "effect/Path";
14 +import * as Schema from "effect/Schema";
15 +import * as Context from "effect/Context";
16
17 export const DEFAULT_PORT = 3773;
18
apps/server/src/diagnostics/TraceDiagnostics.ts
+5 -14
@@ -89,24 +89,14 @@ function toNumberValue(value: unknown): number | null {
89 function unixNanoToDateTime(value: unknown): DateTime.Utc | null {
90 const text = toStringValue(value);
91 if (!text) return null;
92 -
92 try {
93 const millis = Number(BigInt(text) / 1_000_000n);
95 - if (!Number.isFinite(millis)) return null;
96 - return DateTime.makeUnsafe(millis);
94 + return Option.getOrNull(DateTime.make(millis));
95 } catch {
96 return null;
97 }
98 }
99
102 -function isAfter(left: DateTime.Utc, right: DateTime.Utc): boolean {
103 - return DateTime.toEpochMillis(left) > DateTime.toEpochMillis(right);
104 -}
105 -
106 -function isBefore(left: DateTime.Utc, right: DateTime.Utc): boolean {
107 - return DateTime.toEpochMillis(left) < DateTime.toEpochMillis(right);
108 -}
109 -
100 function readExitTag(exit: unknown): string | null {
101 if (!isRecordObject(exit) || !("_tag" in exit)) return null;
102 return toStringValue(exit._tag);
@@ -254,10 +244,11 @@ export function aggregateTraceDiagnostics(
244
245 recordCount += 1;
246 firstSpanAt =
257 - startedAt && (firstSpanAt === null || isBefore(startedAt, firstSpanAt))
247 + startedAt && (firstSpanAt === null || DateTime.isLessThan(startedAt, firstSpanAt))
248 ? startedAt
249 : firstSpanAt;
260 - lastSpanAt = lastSpanAt === null || isAfter(endedAt, lastSpanAt) ? endedAt : lastSpanAt;
250 + lastSpanAt =
251 + lastSpanAt === null || DateTime.isGreaterThan(endedAt, lastSpanAt) ? endedAt : lastSpanAt;
252
253 const exitTag = readExitTag(parsed.exit);
254 const isFailure = exitTag === "Failure";
@@ -289,7 +280,7 @@ export function aggregateTraceDiagnostics(
280
281 const failureKey = `${name}\0${cause}`;
282 const existing = failuresByKey.get(failureKey);
292 - const isLatestFailure = !existing || isAfter(endedAt, existing.lastSeenAt);
283 + const isLatestFailure = !existing || DateTime.isGreaterThan(endedAt, existing.lastSeenAt);
284 failuresByKey.set(failureKey, {
285 name,
286 cause,
apps/server/src/environment/Layers/ServerEnvironment.test.ts
+6 -1
@@ -1,7 +1,12 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 import * as nodePath from "node:path";
3 import * as NodeServices from "@effect/platform-node/NodeServices";
4 import { expect, it } from "@effect/vitest";
4 -import { Effect, Exit, FileSystem, Layer, PlatformError } from "effect";
5 +import * as Effect from "effect/Effect";
6 +import * as Exit from "effect/Exit";
7 +import * as FileSystem from "effect/FileSystem";
8 +import * as Layer from "effect/Layer";
9 +import * as PlatformError from "effect/PlatformError";
10
11 import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "../../config.ts";
12 import { ServerEnvironment } from "../Services/ServerEnvironment.ts";
apps/server/src/environment/Layers/ServerEnvironment.ts
+5 -1
@@ -1,5 +1,9 @@
1 import { EnvironmentId, type ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
2 -import { Effect, FileSystem, Layer, Path, Random } from "effect";
2 +import * as Effect from "effect/Effect";
3 +import * as FileSystem from "effect/FileSystem";
4 +import * as Layer from "effect/Layer";
5 +import * as Path from "effect/Path";
6 +import * as Random from "effect/Random";
7
8 import { ServerConfig } from "../../config.ts";
9 import { ServerEnvironment, type ServerEnvironmentShape } from "../Services/ServerEnvironment.ts";
apps/server/src/environment/Layers/ServerEnvironmentLabel.test.ts
+2 -1
@@ -1,5 +1,6 @@
1 import { afterEach, describe, expect, it } from "@effect/vitest";
2 -import { Effect, FileSystem } from "effect";
2 +import * as Effect from "effect/Effect";
3 +import * as FileSystem from "effect/FileSystem";
4 import { vi } from "vitest";
5
6 vi.mock("../../processRunner.ts", () => ({
apps/server/src/environment/Layers/ServerEnvironmentLabel.ts
+2 -1
@@ -1,6 +1,7 @@
1 import * as OS from "node:os";
2
3 -import { Effect, FileSystem } from "effect";
3 +import * as Effect from "effect/Effect";
4 +import * as FileSystem from "effect/FileSystem";
5
6 import { runProcess } from "../../processRunner.ts";
7
apps/server/src/environment/Services/ServerEnvironment.ts
+2 -2
@@ -1,6 +1,6 @@
1 import type { EnvironmentId, ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
2 -import { Context } from "effect";
3 -import type { Effect } from "effect";
2 +import * as Context from "effect/Context";
3 +import type * as Effect from "effect/Effect";
4
5 export interface ServerEnvironmentShape {
6 readonly getEnvironmentId: Effect.Effect<EnvironmentId>;
apps/server/src/git/GitManager.test.ts
+58 -4
@@ -1,10 +1,15 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 import fs from "node:fs";
3 import path from "node:path";
4 import { spawnSync } from "node:child_process";
5
6 import * as NodeServices from "@effect/platform-node/NodeServices";
7 import { it } from "@effect/vitest";
7 -import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
8 +import * as Effect from "effect/Effect";
9 +import * as FileSystem from "effect/FileSystem";
10 +import * as Layer from "effect/Layer";
11 +import * as PlatformError from "effect/PlatformError";
12 +import * as Scope from "effect/Scope";
13 import { ChildProcessSpawner } from "effect/unstable/process";
14 import { expect } from "vitest";
15 import type {
@@ -32,6 +37,7 @@ import { ServerConfig } from "../config.ts";
37 import { ServerSettingsService } from "../serverSettings.ts";
38 import {
39 ProjectSetupScriptRunner,
40 + ProjectSetupScriptRunnerError,
41 type ProjectSetupScriptRunnerInput,
42 type ProjectSetupScriptRunnerShape,
43 } from "../project/Services/ProjectSetupScriptRunner.ts";
@@ -713,6 +719,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
719 const { manager } = yield* makeManager({
720 ghScenario: {
721 prListSequence: [
722 + // @effect-diagnostics-next-line preferSchemaOverJson:off
723 JSON.stringify([
724 {
725 number: 13,
@@ -754,6 +761,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
761 const { manager } = yield* makeManager({
762 ghScenario: {
763 prListSequence: [
764 + // @effect-diagnostics-next-line preferSchemaOverJson:off
765 JSON.stringify([
766 {
767 number: 14,
@@ -792,6 +800,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
800 const { manager } = yield* makeManager({
801 ghScenario: {
802 prListSequence: [
803 + // @effect-diagnostics-next-line preferSchemaOverJson:off
804 JSON.stringify([
805 {
806 number: 0,
@@ -843,6 +852,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
852 const { manager } = yield* makeManager({
853 ghScenario: {
854 prListSequence: [
855 + // @effect-diagnostics-next-line preferSchemaOverJson:off
856 JSON.stringify([
857 {
858 number: 16,
@@ -955,6 +965,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
965 };
966 const { manager, ghCalls } = yield* makeManager({
967 ghScenario: {
968 + // @effect-diagnostics-next-line preferSchemaOverJson:off
969 prListSequence: [JSON.stringify([existingPr]), JSON.stringify([existingPr])],
970 },
971 });
@@ -981,6 +992,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
992 const { manager } = yield* makeManager({
993 ghScenario: {
994 prListSequence: [
995 + // @effect-diagnostics-next-line preferSchemaOverJson:off
996 JSON.stringify([
997 {
998 number: 1661,
@@ -1034,8 +1046,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
1046 const { manager, ghCalls } = yield* makeManager({
1047 ghScenario: {
1048 prListSequence: [
1049 + // @effect-diagnostics-next-line preferSchemaOverJson:off
1050 JSON.stringify([]),
1051 + // @effect-diagnostics-next-line preferSchemaOverJson:off
1052 JSON.stringify([]),
1053 + // @effect-diagnostics-next-line preferSchemaOverJson:off
1054 JSON.stringify([
1055 {
1056 number: 488,
@@ -1110,6 +1125,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
1125 const { manager, ghCalls } = yield* makeManager({
1126 ghScenario: {
1127 prListByHeadSelector: {
1128 + // @effect-diagnostics-next-line preferSchemaOverJson:off
1129 "effect-atom": JSON.stringify([
1130 {
1131 number: 1618,
@@ -1121,6 +1137,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
1137 updatedAt: "2026-03-01T10:00:00Z",
1138 },
1139 ]),
1140 + // @effect-diagnostics-next-line preferSchemaOverJson:off
1141 "upstream/effect-atom": JSON.stringify([
1142 {
1143 number: 1518,
@@ -1132,8 +1149,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
1149 updatedAt: "2026-04-01T10:00:00Z",
1150 },
1151 ]),
1152 + // @effect-diagnostics-next-line preferSchemaOverJson:off
1153 "pingdotgg:effect-atom": JSON.stringify([]),
1154 + // @effect-diagnostics-next-line preferSchemaOverJson:off
1155 "my-org/upstream:effect-atom": JSON.stringify([]),
1156 + // @effect-diagnostics-next-line preferSchemaOverJson:off
1157 "pingdotgg:upstream/effect-atom": JSON.stringify([
1158 {
1159 number: 1518,
@@ -1145,6 +1165,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
1165 updatedAt: "2026-04-01T10:00:00Z",
1166 },
1167 ]),
1168 + // @effect-diagnostics-next-line preferSchemaOverJson:off
1169 "my-org/upstream:upstream/effect-atom": JSON.stringify([
1170 {
1171 number: 1518,
@@ -1194,6 +1215,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
1215 const { manager } = yield* makeManager({
1216 ghScenario: {
1217 prListSequence: [
1218 + // @effect-diagnostics-next-line preferSchemaOverJson:off
1219 JSON.stringify([
1220 {
1221 number: 22,
@@ -1231,6 +1253,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
1253 const { manager } = yield* makeManager({
1254 ghScenario: {
1255 prListSequence: [
1256 + // @effect-diagnostics-next-line preferSchemaOverJson:off
1257 JSON.stringify([
1258 {
1259 number: 23,
@@ -1262,6 +1285,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
1285 const { manager } = yield* makeManager({
1286 ghScenario: {
1287 prListSequence: [
1288 + // @effect-diagnostics-next-line preferSchemaOverJson:off
1289 JSON.stringify([
1290 {
1291 number: 45,
@@ -1612,6 +1636,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
1636 ghScenario: {
1637 prListSequence: [
1638 "[]",
1639 + // @effect-diagnostics-next-line preferSchemaOverJson:off
1640 JSON.stringify([
1641 {
1642 number: 77,
@@ -1747,6 +1772,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
1772 ghScenario: {
1773 prListSequence: [
1774 "[]",
1775 + // @effect-diagnostics-next-line preferSchemaOverJson:off
1776 JSON.stringify([
1777 {
1778 number: 303,
@@ -1793,6 +1819,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
1819 ghScenario: {
1820 prListSequence: [
1821 "[]",
1822 + // @effect-diagnostics-next-line preferSchemaOverJson:off
1823 JSON.stringify([
1824 {
1825 number: 404,
@@ -1833,6 +1860,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
1860 const { manager, ghCalls } = yield* makeManager({
1861 ghScenario: {
1862 prListSequence: [
1863 + // @effect-diagnostics-next-line preferSchemaOverJson:off
1864 JSON.stringify([
1865 {
1866 number: 42,
@@ -1886,7 +1914,9 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
1914 const { manager, ghCalls } = yield* makeManager({
1915 ghScenario: {
1916 prListSequence: [
1917 + // @effect-diagnostics-next-line preferSchemaOverJson:off
1918 JSON.stringify([]),
1919 + // @effect-diagnostics-next-line preferSchemaOverJson:off
1920 JSON.stringify([
1921 {
1922 number: 142,
@@ -1963,6 +1993,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
1993 const { manager, ghCalls } = yield* makeManager({
1994 ghScenario: {
1995 prListByHeadSelector: {
1996 + // @effect-diagnostics-next-line preferSchemaOverJson:off
1997 "effect-atom": JSON.stringify([
1998 {
1999 number: 1618,
@@ -1972,6 +2003,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
2003 headRefName: "effect-atom",
2004 },
2005 ]),
2006 + // @effect-diagnostics-next-line preferSchemaOverJson:off
2007 "upstream/effect-atom": JSON.stringify([
2008 {
2009 number: 1518,
@@ -1981,8 +2013,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
2013 headRefName: "upstream/effect-atom",
2014 },
2015 ]),
2016 + // @effect-diagnostics-next-line preferSchemaOverJson:off
2017 "pingdotgg:effect-atom": JSON.stringify([]),
2018 + // @effect-diagnostics-next-line preferSchemaOverJson:off
2019 "my-org/upstream:effect-atom": JSON.stringify([]),
2020 + // @effect-diagnostics-next-line preferSchemaOverJson:off
2021 "pingdotgg:upstream/effect-atom": JSON.stringify([
2022 {
2023 number: 1518,
@@ -1992,6 +2027,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
2027 headRefName: "upstream/effect-atom",
2028 },
2029 ]),
2030 + // @effect-diagnostics-next-line preferSchemaOverJson:off
2031 "my-org/upstream:upstream/effect-atom": JSON.stringify([
2032 {
2033 number: 1518,
@@ -2041,7 +2077,9 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
2077 const { manager, ghCalls } = yield* makeManager({
2078 ghScenario: {
2079 prListByHeadSelector: {
2080 + // @effect-diagnostics-next-line preferSchemaOverJson:off
2081 "t3code/pr-142/statemachine": JSON.stringify([]),
2082 + // @effect-diagnostics-next-line preferSchemaOverJson:off
2083 statemachine: JSON.stringify([
2084 {
2085 number: 41,
@@ -2051,6 +2089,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
2089 headRefName: "statemachine",
2090 },
2091 ]),
2092 + // @effect-diagnostics-next-line preferSchemaOverJson:off
2093 "octocat:statemachine": JSON.stringify([
2094 {
2095 number: 142,
@@ -2068,6 +2107,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
2107 },
2108 },
2109 ]),
2110 + // @effect-diagnostics-next-line preferSchemaOverJson:off
2111 "fork-seed:statemachine": JSON.stringify([]),
2112 },
2113 },
@@ -2112,6 +2152,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
2152 const { manager, ghCalls } = yield* makeManager({
2153 ghScenario: {
2154 prListByHeadSelector: {
2155 + // @effect-diagnostics-next-line preferSchemaOverJson:off
2156 "octocat:statemachine": JSON.stringify([
2157 {
2158 number: 142,
@@ -2129,8 +2170,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
2170 },
2171 },
2172 ]),
2173 + // @effect-diagnostics-next-line preferSchemaOverJson:off
2174 "fork-seed:statemachine": JSON.stringify([]),
2175 + // @effect-diagnostics-next-line preferSchemaOverJson:off
2176 "t3code/pr-142/statemachine": JSON.stringify([]),
2177 + // @effect-diagnostics-next-line preferSchemaOverJson:off
2178 statemachine: JSON.stringify([]),
2179 },
2180 },
@@ -2170,6 +2214,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
2214 ghScenario: {
2215 prListSequence: [
2216 "[]",
2217 + // @effect-diagnostics-next-line preferSchemaOverJson:off
2218 JSON.stringify([
2219 {
2220 number: 88,
@@ -2215,6 +2260,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
2260 const { manager, ghCalls } = yield* makeManager({
2261 ghScenario: {
2262 prListSequence: [
2263 + // @effect-diagnostics-next-line preferSchemaOverJson:off
2264 JSON.stringify([
2265 {
2266 number: 1661,
@@ -2232,6 +2278,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
2278 },
2279 },
2280 ]),
2281 + // @effect-diagnostics-next-line preferSchemaOverJson:off
2282 JSON.stringify([
2283 {
2284 number: 188,
@@ -2294,7 +2341,9 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
2341 ghScenario: {
2342 prListSequenceByHeadSelector: {
2343 "octocat:statemachine": [
2344 + // @effect-diagnostics-next-line preferSchemaOverJson:off
2345 JSON.stringify([]),
2346 + // @effect-diagnostics-next-line preferSchemaOverJson:off
2347 JSON.stringify([
2348 {
2349 number: 188,
@@ -2313,7 +2362,9 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
2362 },
2363 ]),
2364 ],
2365 + // @effect-diagnostics-next-line preferSchemaOverJson:off
2366 "fork-seed:statemachine": [JSON.stringify([])],
2367 + // @effect-diagnostics-next-line preferSchemaOverJson:off
2368 statemachine: [JSON.stringify([])],
2369 },
2370 },
@@ -2870,7 +2921,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
2921 yield* runGit(repoDir, ["add", "existing.txt"]);
2922 yield* runGit(repoDir, ["commit", "-m", "Existing worktree branch"]);
2923 yield* runGit(repoDir, ["checkout", "main"]);
2873 - const worktreePath = path.join(repoDir, "..", `pr-existing-${Date.now()}`);
2924 + const worktreePath = path.join(repoDir, "..", `pr-existing-${path.basename(repoDir)}`);
2925 yield* runGit(repoDir, ["worktree", "add", worktreePath, "feature/pr-existing-worktree"]);
2926
2927 const setupCalls: ProjectSetupScriptRunnerInput[] = [];
@@ -3044,7 +3095,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
3095 yield* runGit(repoDir, ["commit", "-m", "Reused fork PR branch"]);
3096 yield* runGit(repoDir, ["push", "-u", "fork-seed", "feature/pr-reused-fork"]);
3097 yield* runGit(repoDir, ["checkout", "main"]);
3047 - const worktreePath = path.join(repoDir, "..", `pr-reused-fork-${Date.now()}`);
3098 + const worktreePath = path.join(repoDir, "..", `pr-reused-fork-${path.basename(repoDir)}`);
3099 yield* runGit(repoDir, ["worktree", "add", worktreePath, "feature/pr-reused-fork"]);
3100 yield* runGit(worktreePath, ["branch", "--unset-upstream"], true);
3101
@@ -3112,7 +3163,8 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
3163 },
3164 },
3165 setupScriptRunner: {
3115 - runForThread: () => Effect.fail(new Error("terminal start failed")),
3166 + runForThread: () =>
3167 + Effect.fail(new ProjectSetupScriptRunnerError({ message: "terminal start failed" })),
3168 },
3169 });
3170
@@ -3289,7 +3341,9 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
3341 const { manager } = yield* makeManager({
3342 ghScenario: {
3343 prListSequence: [
3344 + // @effect-diagnostics-next-line preferSchemaOverJson:off
3345 JSON.stringify([]),
3346 + // @effect-diagnostics-next-line preferSchemaOverJson:off
3347 JSON.stringify([
3348 {
3349 number: 201,
apps/server/src/git/GitManager.ts
+13 -15
@@ -1,20 +1,18 @@
1 import { randomUUID } from "node:crypto";
2
3 -import {
4 - Array as Arr,
5 - Cache,
6 - Context,
7 - DateTime,
8 - Duration,
9 - Effect,
10 - Exit,
11 - FileSystem,
12 - Layer,
13 - Option,
14 - Order,
15 - Path,
16 - Ref,
17 -} from "effect";
3 +import * as Arr from "effect/Array";
4 +import * as Cache from "effect/Cache";
5 +import * as Context from "effect/Context";
6 +import * as DateTime from "effect/DateTime";
7 +import * as Duration from "effect/Duration";
8 +import * as Effect from "effect/Effect";
9 +import * as Exit from "effect/Exit";
10 +import * as FileSystem from "effect/FileSystem";
11 +import * as Layer from "effect/Layer";
12 +import * as Option from "effect/Option";
13 +import * as Order from "effect/Order";
14 +import * as Path from "effect/Path";
15 +import * as Ref from "effect/Ref";
16 import {
17 GitActionProgressEvent,
18 GitActionProgressPhase,
apps/server/src/git/GitWorkflowService.test.ts
+2 -1
@@ -1,5 +1,6 @@
1 import { assert, describe, it, vi } from "@effect/vitest";
2 -import { Effect, Layer } from "effect";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4
5 import * as GitManager from "./GitManager.ts";
6 import * as GitWorkflowService from "./GitWorkflowService.ts";
apps/server/src/git/GitWorkflowService.ts
+3 -1
@@ -1,4 +1,6 @@
1 -import { Context, Effect, Layer } from "effect";
1 +import * as Context from "effect/Context";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4
5 import {
6 GitManagerError,
apps/server/src/git/Utils.ts
+1
@@ -1,3 +1,4 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 import { existsSync } from "node:fs";
3 import { join } from "node:path";
4
apps/server/src/http.ts
+5 -1
@@ -1,6 +1,10 @@
1 import Mime from "@effect/platform-node/Mime";
2 import { decodeOtlpTraceRecords } from "@t3tools/shared/observability";
3 -import { Data, Effect, FileSystem, Option, Path } from "effect";
3 +import * as Data from "effect/Data";
4 +import * as Effect from "effect/Effect";
5 +import * as FileSystem from "effect/FileSystem";
6 +import * as Option from "effect/Option";
7 +import * as Path from "effect/Path";
8 import { cast } from "effect/Function";
9 import {
10 HttpBody,
apps/server/src/keybindings.test.ts
+8 -1
@@ -2,7 +2,13 @@ import { KeybindingCommand, KeybindingRule, KeybindingsConfig } from "@t3tools/c
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 import { assert, it } from "@effect/vitest";
4 import { assertFailure } from "@effect/vitest/utils";
5 -import { Cause, Effect, FileSystem, Layer, Logger, Path, Schema } from "effect";
5 +import * as Cause from "effect/Cause";
6 +import * as Effect from "effect/Effect";
7 +import * as FileSystem from "effect/FileSystem";
8 +import * as Layer from "effect/Layer";
9 +import * as Logger from "effect/Logger";
10 +import * as Path from "effect/Path";
11 +import * as Schema from "effect/Schema";
12 import { ServerConfig } from "./config.ts";
13
14 import {
@@ -229,6 +235,7 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
235 const { keybindingsConfigPath } = yield* ServerConfig;
236 yield* fs.writeFileString(
237 keybindingsConfigPath,
238 + // @effect-diagnostics-next-line preferSchemaOverJson:off
239 JSON.stringify([
240 { key: "mod+j", command: "terminal.toggle" },
241 { key: "mod+shift+d+o", command: "terminal.new" },
apps/server/src/keybindings.ts
+22 -34
@@ -19,33 +19,30 @@ import {
19 type ServerUpsertKeybindingInput,
20 type ServerConfigIssue,
21 } from "@t3tools/contracts";
22 -import {
23 - Array,
24 - Cache,
25 - Cause,
26 - Deferred,
27 - Duration,
28 - Effect,
29 - Exit,
30 - FileSystem,
31 - Path,
32 - Layer,
33 - Option,
34 - Predicate,
35 - PubSub,
36 - Schema,
37 - SchemaGetter,
38 - SchemaIssue,
39 - SchemaTransformation,
40 - Ref,
41 - Context,
42 - Scope,
43 - Stream,
44 -} from "effect";
22 +import * as Array from "effect/Array";
23 +import * as Cache from "effect/Cache";
24 +import * as Cause from "effect/Cause";
25 +import * as Deferred from "effect/Deferred";
26 +import * as Duration from "effect/Duration";
27 +import * as Effect from "effect/Effect";
28 +import * as Exit from "effect/Exit";
29 +import * as FileSystem from "effect/FileSystem";
30 +import * as Path from "effect/Path";
31 +import * as Layer from "effect/Layer";
32 +import * as Option from "effect/Option";
33 +import * as Predicate from "effect/Predicate";
34 +import * as PubSub from "effect/PubSub";
35 +import * as Schema from "effect/Schema";
36 +import * as SchemaIssue from "effect/SchemaIssue";
37 +import * as SchemaTransformation from "effect/SchemaTransformation";
38 +import * as Ref from "effect/Ref";
39 +import * as Context from "effect/Context";
40 +import * as Scope from "effect/Scope";
41 +import * as Stream from "effect/Stream";
42 import * as Semaphore from "effect/Semaphore";
43 import { ServerConfig } from "./config.ts";
44 import { writeFileStringAtomically } from "./atomicWrite.ts";
48 -import { fromLenientJson } from "@t3tools/shared/schemaJson";
45 +import { fromJsonStringPretty, fromLenientJson } from "@t3tools/shared/schemaJson";
46 import {
47 DEFAULT_KEYBINDINGS,
48 DEFAULT_RESOLVED_KEYBINDINGS,
@@ -172,16 +169,7 @@ function encodeWhenAst(node: KeybindingWhenNode): string {
169 }
170
171 const RawKeybindingsEntries = fromLenientJson(Schema.Array(Schema.Unknown));
175 -const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
176 -const PrettyJsonString = SchemaGetter.parseJson<string>().compose(
177 - SchemaGetter.stringifyJson({ space: 2 }),
178 -);
179 -const KeybindingsConfigPrettyJson = KeybindingsConfigJson.pipe(
180 - Schema.encode({
181 - decode: PrettyJsonString,
182 - encode: PrettyJsonString,
183 - }),
184 -);
172 +const KeybindingsConfigPrettyJson = fromJsonStringPretty(KeybindingsConfig);
173
174 export interface KeybindingsConfigState {
175 readonly keybindings: ResolvedKeybindingsConfig;
apps/server/src/observability/Attributes.ts
+2 -1
@@ -1,4 +1,5 @@
1 -import { Cause, Exit } from "effect";
1 +import * as Cause from "effect/Cause";
2 +import * as Exit from "effect/Exit";
3
4 export type MetricAttributeValue = string;
5 export type MetricAttributes = Readonly<Record<string, MetricAttributeValue>>;
apps/server/src/observability/Layers/Observability.ts
+4 -1
@@ -1,5 +1,8 @@
1 import { makeLocalFileTracer, makeTraceSink } from "@t3tools/shared/observability";
2 -import { Effect, Layer, References, Tracer } from "effect";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 +import * as References from "effect/References";
5 +import * as Tracer from "effect/Tracer";
6 import { OtlpMetrics, OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
7
8 import { ServerConfig } from "../../config.ts";
apps/server/src/observability/Metrics.test.ts
+5 -2
@@ -1,7 +1,10 @@
1 import { assert, describe, it } from "@effect/vitest";
2 import { ProviderDriverKind } from "@t3tools/contracts";
3 -import { Duration, Effect, Fiber, Metric } from "effect";
4 -import { TestClock } from "effect/testing";
3 +import * as Duration from "effect/Duration";
4 +import * as Effect from "effect/Effect";
5 +import * as Fiber from "effect/Fiber";
6 +import * as Metric from "effect/Metric";
7 +import * as TestClock from "effect/testing/TestClock";
8
9 import { withMetrics } from "./Metrics.ts";
10
apps/server/src/observability/Metrics.ts
+5 -1
@@ -1,4 +1,8 @@
1 -import { Clock, Duration, Effect, Exit, Metric } from "effect";
1 +import * as Clock from "effect/Clock";
2 +import * as Duration from "effect/Duration";
3 +import * as Effect from "effect/Effect";
4 +import * as Exit from "effect/Exit";
5 +import * as Metric from "effect/Metric";
6 import { dual } from "effect/Function";
7
8 import {
apps/server/src/observability/RpcInstrumentation.test.ts
+8 -2
@@ -1,7 +1,13 @@
1 import { assert, describe, it } from "@effect/vitest";
2 import { WS_METHODS } from "@t3tools/contracts";
3 -import { Duration, Effect, Exit, Fiber, Metric, Stream, Tracer } from "effect";
4 -import { TestClock } from "effect/testing";
3 +import * as Duration from "effect/Duration";
4 +import * as Effect from "effect/Effect";
5 +import * as Exit from "effect/Exit";
6 +import * as Fiber from "effect/Fiber";
7 +import * as Metric from "effect/Metric";
8 +import * as Stream from "effect/Stream";
9 +import * as Tracer from "effect/Tracer";
10 +import * as TestClock from "effect/testing/TestClock";
11
12 import {
13 observeRpcEffect,
apps/server/src/observability/RpcInstrumentation.ts
+7 -1
@@ -1,5 +1,11 @@
1 import { WS_METHODS } from "@t3tools/contracts";
2 -import { Clock, Duration, Effect, Exit, Metric, References, Stream } from "effect";
2 +import * as Clock from "effect/Clock";
3 +import * as Duration from "effect/Duration";
4 +import * as Effect from "effect/Effect";
5 +import * as Exit from "effect/Exit";
6 +import * as Metric from "effect/Metric";
7 +import * as References from "effect/References";
8 +import * as Stream from "effect/Stream";
9
10 import { outcomeFromExit } from "./Attributes.ts";
11 import { metricAttributes, rpcRequestDuration, rpcRequestsTotal, withMetrics } from "./Metrics.ts";
apps/server/src/observability/Services/BrowserTraceCollector.ts
+2 -2
@@ -1,6 +1,6 @@
1 import type { TraceRecord } from "@t3tools/shared/observability";
2 -import { Context } from "effect";
3 -import type { Effect } from "effect";
2 +import * as Context from "effect/Context";
3 +import type * as Effect from "effect/Effect";
4
5 export interface BrowserTraceCollectorShape {
6 readonly record: (records: ReadonlyArray<TraceRecord>) => Effect.Effect<void>;
apps/server/src/open.test.ts
+5 -2
@@ -1,7 +1,10 @@
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { assert, it } from "@effect/vitest";
3 import { assertSuccess } from "@effect/vitest/utils";
4 -import { FileSystem, Path, Effect } from "effect";
4 +import * as Effect from "effect/Effect";
5 +import * as FileSystem from "effect/FileSystem";
6 +import * as Path from "effect/Path";
7 +import * as Random from "effect/Random";
8
9 import {
10 isCommandAvailable,
@@ -488,7 +491,7 @@ it.layer(NodeServices.layer)("launchDetached", (it) => {
491 it.effect("rejects when command does not exist", () =>
492 Effect.gen(function* () {
493 const result = yield* launchDetached({
491 - command: `t3code-no-such-command-${Date.now()}`,
494 + command: `t3code-no-such-command-${yield* Random.nextUUIDv4}`,
495 args: [],
496 }).pipe(Effect.result);
497 assert.equal(result._tag, "Failure");
apps/server/src/open.ts
+4 -1
@@ -1,3 +1,4 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 /**
3 * Open - Browser/editor launch service interface.
4 *
@@ -10,7 +11,9 @@ import { spawn } from "node:child_process";
11
12 import { EDITORS, OpenError, type EditorId } from "@t3tools/contracts";
13 import { isCommandAvailable, type CommandAvailabilityOptions } from "@t3tools/shared/shell";
13 -import { Context, Effect, Layer } from "effect";
14 +import * as Context from "effect/Context";
15 +import * as Effect from "effect/Effect";
16 +import * as Layer from "effect/Layer";
17
18 // ==============================
19 // Definitions
apps/server/src/orchestration/Errors.ts
+2 -1
@@ -1,4 +1,5 @@
1 -import { SchemaIssue, Schema } from "effect";
1 +import * as SchemaIssue from "effect/SchemaIssue";
2 +import * as Schema from "effect/Schema";
3
4 import type { ProjectionRepositoryError } from "../persistence/Errors.ts";
5
apps/server/src/orchestration/Layers/CheckpointReactor.test.ts
+45 -37
@@ -1,3 +1,4 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 import fs from "node:fs";
3 import os from "node:os";
4 import path from "node:path";
@@ -19,7 +20,14 @@ import {
20 TurnId,
21 } from "@t3tools/contracts";
22 import * as NodeServices from "@effect/platform-node/NodeServices";
22 -import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
23 +import * as Clock from "effect/Clock";
24 +import * as Effect from "effect/Effect";
25 +import * as Exit from "effect/Exit";
26 +import * as Layer from "effect/Layer";
27 +import * as ManagedRuntime from "effect/ManagedRuntime";
28 +import * as PubSub from "effect/PubSub";
29 +import * as Scope from "effect/Scope";
30 +import * as Stream from "effect/Stream";
31 import { afterEach, describe, expect, it, vi } from "vitest";
32
33 import { CheckpointStoreLive } from "../../checkpointing/Layers/CheckpointStore.ts";
@@ -73,7 +81,7 @@ function createProviderServiceHarness(
81 sessionCwd = cwd,
82 providerName: ProviderSession["provider"] = ProviderDriverKind.make("codex"),
83 ) {
76 - const now = new Date().toISOString();
84 + const now = "2026-01-01T00:00:00.000Z";
85 const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
86 const rollbackConversation = vi.fn(
87 (_input: { readonly threadId: ThreadId; readonly numTurns: number }) => Effect.void,
@@ -148,7 +156,7 @@ async function waitForThread(
156 }) => boolean,
157 timeoutMs = 15_000,
158 ) {
151 - const deadline = Date.now() + timeoutMs;
159 + const deadline = (await Effect.runPromise(Clock.currentTimeMillis)) + timeoutMs;
160 const poll = async (): Promise<{
161 latestTurn: { turnId: string } | null;
162 checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
@@ -159,10 +167,10 @@ async function waitForThread(
167 if (thread && predicate(thread)) {
168 return thread;
169 }
162 - if (Date.now() >= deadline) {
170 + if ((await Effect.runPromise(Clock.currentTimeMillis)) >= deadline) {
171 throw new Error("Timed out waiting for thread state.");
172 }
165 - await new Promise((resolve) => setTimeout(resolve, 10));
173 + await Effect.runPromise(Effect.sleep("10 millis"));
174 return poll();
175 };
176 return poll();
@@ -173,7 +181,7 @@ async function waitForEvent(
181 predicate: (event: { type: string }) => boolean,
182 timeoutMs = 15_000,
183 ) {
176 - const deadline = Date.now() + timeoutMs;
184 + const deadline = (await Effect.runPromise(Clock.currentTimeMillis)) + timeoutMs;
185 const poll = async () => {
186 const events = await Effect.runPromise(
187 Stream.runCollect(engine.readEvents(0)).pipe(Effect.map((chunk) => Array.from(chunk))),
@@ -181,10 +189,10 @@ async function waitForEvent(
189 if (events.some(predicate)) {
190 return events;
191 }
184 - if (Date.now() >= deadline) {
192 + if ((await Effect.runPromise(Clock.currentTimeMillis)) >= deadline) {
193 throw new Error("Timed out waiting for orchestration event.");
194 }
187 - await new Promise((resolve) => setTimeout(resolve, 10));
195 + await Effect.runPromise(Effect.sleep("10 millis"));
196 return poll();
197 };
198 return poll();
@@ -223,15 +231,15 @@ function gitShowFileAtRef(cwd: string, ref: string, filePath: string): string {
231 }
232
233 async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 15_000) {
226 - const deadline = Date.now() + timeoutMs;
234 + const deadline = (await Effect.runPromise(Clock.currentTimeMillis)) + timeoutMs;
235 const poll = async (): Promise<void> => {
236 if (gitRefExists(cwd, ref)) {
237 return;
238 }
231 - if (Date.now() >= deadline) {
239 + if ((await Effect.runPromise(Clock.currentTimeMillis)) >= deadline) {
240 throw new Error(`Timed out waiting for git ref '${ref}'.`);
241 }
234 - await new Promise((resolve) => setTimeout(resolve, 10));
242 + await Effect.runPromise(Effect.sleep("10 millis"));
243 return poll();
244 };
245 return poll();
@@ -342,7 +350,7 @@ describe("CheckpointReactor", () => {
350 await Effect.runPromise(reactor.start().pipe(Scope.provide(scope)));
351 const drain = () => Effect.runPromise(reactor.drain);
352
345 - const createdAt = new Date().toISOString();
353 + const createdAt = "2026-01-01T00:00:00.000Z";
354 await Effect.runPromise(
355 engine.dispatch({
356 type: "project.create",
@@ -410,7 +418,7 @@ describe("CheckpointReactor", () => {
418
419 it("captures pre-turn baseline on turn.started and post-turn checkpoint on turn.completed", async () => {
420 const harness = await createHarness({ seedFilesystemCheckpoints: false });
413 - const createdAt = new Date().toISOString();
421 + const createdAt = "2026-01-01T00:00:00.000Z";
422
423 await Effect.runPromise(
424 harness.engine.dispatch({
@@ -435,7 +443,7 @@ describe("CheckpointReactor", () => {
443 eventId: EventId.make("evt-turn-started-1"),
444 provider: ProviderDriverKind.make("codex"),
445
438 - createdAt: new Date().toISOString(),
446 + createdAt: "2026-01-01T00:00:00.000Z",
447 threadId: ThreadId.make("thread-1"),
448 turnId: asTurnId("turn-1"),
449 });
@@ -450,7 +458,7 @@ describe("CheckpointReactor", () => {
458 eventId: EventId.make("evt-turn-completed-1"),
459 provider: ProviderDriverKind.make("codex"),
460
453 - createdAt: new Date().toISOString(),
461 + createdAt: "2026-01-01T00:00:00.000Z",
462 threadId: ThreadId.make("thread-1"),
463 turnId: asTurnId("turn-1"),
464 payload: { state: "completed" },
@@ -495,7 +503,7 @@ describe("CheckpointReactor", () => {
503 type: "turn.completed",
504 eventId: EventId.make("evt-turn-completed-refresh-local-status"),
505 provider: ProviderDriverKind.make("codex"),
498 - createdAt: new Date().toISOString(),
506 + createdAt: "2026-01-01T00:00:00.000Z",
507 threadId: ThreadId.make("thread-1"),
508 turnId: asTurnId("turn-refresh-local-status"),
509 payload: { state: "completed" },
@@ -508,7 +516,7 @@ describe("CheckpointReactor", () => {
516
517 it("ignores auxiliary thread turn completion while primary turn is active", async () => {
518 const harness = await createHarness({ seedFilesystemCheckpoints: false });
511 - const createdAt = new Date().toISOString();
519 + const createdAt = "2026-01-01T00:00:00.000Z";
520
521 await Effect.runPromise(
522 harness.engine.dispatch({
@@ -533,7 +541,7 @@ describe("CheckpointReactor", () => {
541 eventId: EventId.make("evt-turn-started-main"),
542 provider: ProviderDriverKind.make("codex"),
543
536 - createdAt: new Date().toISOString(),
544 + createdAt: "2026-01-01T00:00:00.000Z",
545 threadId: ThreadId.make("thread-1"),
546 turnId: asTurnId("turn-main"),
547 });
@@ -549,7 +557,7 @@ describe("CheckpointReactor", () => {
557 eventId: EventId.make("evt-turn-completed-aux"),
558 provider: ProviderDriverKind.make("codex"),
559
552 - createdAt: new Date().toISOString(),
560 + createdAt: "2026-01-01T00:00:00.000Z",
561 threadId: ThreadId.make("thread-1"),
562 turnId: asTurnId("turn-aux"),
563 payload: { state: "completed" },
@@ -565,7 +573,7 @@ describe("CheckpointReactor", () => {
573 eventId: EventId.make("evt-turn-completed-main"),
574 provider: ProviderDriverKind.make("codex"),
575
568 - createdAt: new Date().toISOString(),
576 + createdAt: "2026-01-01T00:00:00.000Z",
577 threadId: ThreadId.make("thread-1"),
578 turnId: asTurnId("turn-main"),
579 payload: { state: "completed" },
@@ -583,7 +591,7 @@ describe("CheckpointReactor", () => {
591 seedFilesystemCheckpoints: false,
592 providerName: ProviderDriverKind.make("claudeAgent"),
593 });
586 - const createdAt = new Date().toISOString();
594 + const createdAt = "2026-01-01T00:00:00.000Z";
595
596 await Effect.runPromise(
597 harness.engine.dispatch({
@@ -607,7 +615,7 @@ describe("CheckpointReactor", () => {
615 type: "turn.started",
616 eventId: EventId.make("evt-turn-started-claude-1"),
617 provider: ProviderDriverKind.make("claudeAgent"),
610 - createdAt: new Date().toISOString(),
618 + createdAt: "2026-01-01T00:00:00.000Z",
619 threadId: ThreadId.make("thread-1"),
620 turnId: asTurnId("turn-claude-1"),
621 });
@@ -621,7 +629,7 @@ describe("CheckpointReactor", () => {
629 type: "turn.completed",
630 eventId: EventId.make("evt-turn-completed-claude-1"),
631 provider: ProviderDriverKind.make("claudeAgent"),
624 - createdAt: new Date().toISOString(),
632 + createdAt: "2026-01-01T00:00:00.000Z",
633 threadId: ThreadId.make("thread-1"),
634 turnId: asTurnId("turn-claude-1"),
635 payload: { state: "completed" },
@@ -641,7 +649,7 @@ describe("CheckpointReactor", () => {
649
650 it("appends capture failure activity when turn diff summary cannot be derived", async () => {
651 const harness = await createHarness({ seedFilesystemCheckpoints: false });
644 - const createdAt = new Date().toISOString();
652 + const createdAt = "2026-01-01T00:00:00.000Z";
653
654 await Effect.runPromise(
655 harness.engine.dispatch({
@@ -666,7 +674,7 @@ describe("CheckpointReactor", () => {
674 eventId: EventId.make("evt-turn-completed-missing-baseline"),
675 provider: ProviderDriverKind.make("codex"),
676
669 - createdAt: new Date().toISOString(),
677 + createdAt: "2026-01-01T00:00:00.000Z",
678 threadId: ThreadId.make("thread-1"),
679 turnId: asTurnId("turn-missing-baseline"),
680 payload: { state: "completed" },
@@ -706,7 +714,7 @@ describe("CheckpointReactor", () => {
714 },
715 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
716 runtimeMode: "approval-required",
709 - createdAt: new Date().toISOString(),
717 + createdAt: "2026-01-01T00:00:00.000Z",
718 }),
719 );
720
@@ -729,7 +737,7 @@ describe("CheckpointReactor", () => {
737 seedFilesystemCheckpoints: false,
738 threadWorktreePath: null,
739 });
732 - const createdAt = new Date().toISOString();
740 + const createdAt = "2026-01-01T00:00:00.000Z";
741
742 await Effect.runPromise(
743 harness.engine.dispatch({
@@ -755,7 +763,7 @@ describe("CheckpointReactor", () => {
763 eventId: EventId.make("evt-turn-completed-missing-provider-cwd"),
764 provider: ProviderDriverKind.make("codex"),
765
758 - createdAt: new Date().toISOString(),
766 + createdAt: "2026-01-01T00:00:00.000Z",
767 threadId: ThreadId.make("thread-1"),
768 turnId: asTurnId("turn-missing-cwd"),
769 payload: { state: "completed" },
@@ -776,7 +784,7 @@ describe("CheckpointReactor", () => {
784
785 it("ignores non-v2 checkpoint.captured runtime events", async () => {
786 const harness = await createHarness();
779 - const createdAt = new Date().toISOString();
787 + const createdAt = "2026-01-01T00:00:00.000Z";
788
789 await Effect.runPromise(
790 harness.engine.dispatch({
@@ -801,7 +809,7 @@ describe("CheckpointReactor", () => {
809 eventId: EventId.make("evt-checkpoint-captured-3"),
810 provider: ProviderDriverKind.make("codex"),
811
804 - createdAt: new Date().toISOString(),
812 + createdAt: "2026-01-01T00:00:00.000Z",
813 threadId: ThreadId.make("thread-1"),
814 turnId: asTurnId("turn-3"),
815 turnCount: 3,
@@ -826,7 +834,7 @@ describe("CheckpointReactor", () => {
834 seedFilesystemCheckpoints: false,
835 providerSessionCwd: nonRepositorySessionCwd,
836 });
829 - const createdAt = new Date().toISOString();
837 + const createdAt = "2026-01-01T00:00:00.000Z";
838
839 await Effect.runPromise(
840 harness.engine.dispatch({
@@ -851,7 +859,7 @@ describe("CheckpointReactor", () => {
859 eventId: EventId.make("evt-runtime-capture-failure"),
860 provider: ProviderDriverKind.make("codex"),
861
854 - createdAt: new Date().toISOString(),
862 + createdAt: "2026-01-01T00:00:00.000Z",
863 threadId: ThreadId.make("thread-1"),
864 turnId: asTurnId("turn-runtime-failure"),
865 payload: { state: "completed" },
@@ -862,7 +870,7 @@ describe("CheckpointReactor", () => {
870 eventId: EventId.make("evt-turn-started-after-runtime-failure"),
871 provider: ProviderDriverKind.make("codex"),
872
865 - createdAt: new Date().toISOString(),
873 + createdAt: "2026-01-01T00:00:00.000Z",
874 threadId: ThreadId.make("thread-1"),
875 turnId: asTurnId("turn-after-runtime-failure"),
876 });
@@ -878,7 +886,7 @@ describe("CheckpointReactor", () => {
886
887 it("executes provider revert and emits thread.reverted for checkpoint revert requests", async () => {
888 const harness = await createHarness();
881 - const createdAt = new Date().toISOString();
889 + const createdAt = "2026-01-01T00:00:00.000Z";
890
891 await Effect.runPromise(
892 harness.engine.dispatch({
@@ -959,7 +967,7 @@ describe("CheckpointReactor", () => {
967
968 it("executes provider revert and emits thread.reverted for claude sessions", async () => {
969 const harness = await createHarness({ providerName: ProviderDriverKind.make("claudeAgent") });
962 - const createdAt = new Date().toISOString();
970 + const createdAt = "2026-01-01T00:00:00.000Z";
971
972 await Effect.runPromise(
973 harness.engine.dispatch({
@@ -1028,7 +1036,7 @@ describe("CheckpointReactor", () => {
1036
1037 it("processes consecutive revert requests with deterministic rollback sequencing", async () => {
1038 const harness = await createHarness();
1031 - const createdAt = new Date().toISOString();
1039 + const createdAt = "2026-01-01T00:00:00.000Z";
1040
1041 await Effect.runPromise(
1042 harness.engine.dispatch({
@@ -1111,7 +1119,7 @@ describe("CheckpointReactor", () => {
1119
1120 it("appends an error activity when revert is requested without an active session", async () => {
1121 const harness = await createHarness({ hasSession: false });
1114 - const createdAt = new Date().toISOString();
1122 + const createdAt = "2026-01-01T00:00:00.000Z";
1123
1124 await Effect.runPromise(
1125 harness.engine.dispatch({
apps/server/src/orchestration/Layers/CheckpointReactor.ts
+33 -20
@@ -8,7 +8,12 @@ import {
8 type OrchestrationEvent,
9 type ProviderRuntimeEvent,
10 } from "@t3tools/contracts";
11 -import { Cause, Effect, Layer, Option, Stream } from "effect";
11 +import * as Cause from "effect/Cause";
12 +import * as DateTime from "effect/DateTime";
13 +import * as Effect from "effect/Effect";
14 +import * as Layer from "effect/Layer";
15 +import * as Option from "effect/Option";
16 +import * as Stream from "effect/Stream";
17 import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
18
19 import { parseTurnDiffFilesFromUnifiedDiff } from "../../checkpointing/Diffs.ts";
@@ -28,6 +33,8 @@ import { isGitRepository } from "../../git/Utils.ts";
33 import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
34 import { WorkspaceEntries } from "../../workspace/Services/WorkspaceEntries.ts";
35
36 +const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
37 +
38 type ReactorInput =
39 | {
40 readonly source: "runtime";
@@ -584,7 +591,7 @@ const make = Effect.gen(function* () {
591 const handleRevertRequested = Effect.fn("handleRevertRequested")(function* (
592 event: Extract<OrchestrationEvent, { type: "thread.checkpoint-revert-requested" }>,
593 ) {
587 - const now = new Date().toISOString();
594 + const now = DateTime.formatIso(yield* DateTime.now);
595
596 const thread = yield* resolveThreadDetail(event.payload.threadId);
597 if (!thread) {
@@ -717,12 +724,14 @@ const make = Effect.gen(function* () {
724 if (event.type === "thread.checkpoint-revert-requested") {
725 yield* handleRevertRequested(event).pipe(
726 Effect.catch((error) =>
720 - appendRevertFailureActivity({
721 - threadId: event.payload.threadId,
722 - turnCount: event.payload.turnCount,
723 - detail: error.message,
724 - createdAt: new Date().toISOString(),
725 - }),
727 + Effect.flatMap(nowIso, (createdAt) =>
728 + appendRevertFailureActivity({
729 + threadId: event.payload.threadId,
730 + turnCount: event.payload.turnCount,
731 + detail: error.message,
732 + createdAt,
733 + }),
734 + ),
735 ),
736 );
737 return;
@@ -736,12 +745,14 @@ const make = Effect.gen(function* () {
745 if (event.type === "thread.turn-diff-completed") {
746 yield* captureCheckpointFromPlaceholder(event).pipe(
747 Effect.catch((error) =>
739 - appendCaptureFailureActivity({
740 - threadId: event.payload.threadId,
741 - turnId: event.payload.turnId,
742 - detail: error.message,
743 - createdAt: new Date().toISOString(),
744 - }).pipe(Effect.catch(() => Effect.void)),
748 + Effect.flatMap(nowIso, (createdAt) =>
749 + appendCaptureFailureActivity({
750 + threadId: event.payload.threadId,
751 + turnId: event.payload.turnId,
752 + detail: error.message,
753 + createdAt,
754 + }).pipe(Effect.catch(() => Effect.void)),
755 + ),
756 ),
757 );
758 }
@@ -760,12 +771,14 @@ const make = Effect.gen(function* () {
771 yield* refreshLocalGitStatusFromTurnCompletion(event);
772 yield* captureCheckpointFromTurnCompletion(event).pipe(
773 Effect.catch((error) =>
763 - appendCaptureFailureActivity({
764 - threadId: event.threadId,
765 - turnId,
766 - detail: error.message,
767 - createdAt: new Date().toISOString(),
768 - }).pipe(Effect.catch(() => Effect.void)),
774 + Effect.flatMap(nowIso, (createdAt) =>
775 + appendCaptureFailureActivity({
776 + threadId: event.threadId,
777 + turnId,
778 + detail: error.message,
779 + createdAt,
780 + }).pipe(Effect.catch(() => Effect.void)),
781 + ),
782 ),
783 );
784 return;
apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts
+8 -3
@@ -8,9 +8,14 @@ import {
8 TurnId,
9 type OrchestrationEvent,
10 ProviderInstanceId,
11 - type OrchestrationReadModel,
11 } from "@t3tools/contracts";
13 -import { Effect, Layer, ManagedRuntime, Metric, Option, Queue, Stream } from "effect";
12 +import * as Effect from "effect/Effect";
13 +import * as Layer from "effect/Layer";
14 +import * as ManagedRuntime from "effect/ManagedRuntime";
15 +import * as Metric from "effect/Metric";
16 +import * as Option from "effect/Option";
17 +import * as Queue from "effect/Queue";
18 +import * as Stream from "effect/Stream";
19 import { describe, expect, it } from "vitest";
20
21 import { PersistenceSqlError } from "../../persistence/Errors.ts";
@@ -69,7 +74,7 @@ async function createOrchestrationSystem() {
74 }
75
76 function now() {
72 - return new Date().toISOString();
77 + return "2026-01-01T00:00:00.000Z";
78 }
79
80 const hasMetricSnapshot = (
apps/server/src/orchestration/Layers/OrchestrationEngine.ts
+26 -20
@@ -5,20 +5,20 @@ import type {
5 ThreadId,
6 } from "@t3tools/contracts";
7 import { OrchestrationCommand } from "@t3tools/contracts";
8 -import {
9 - Cause,
10 - Deferred,
11 - Duration,
12 - Effect,
13 - Exit,
14 - Layer,
15 - Metric,
16 - Option,
17 - PubSub,
18 - Queue,
19 - Schema,
20 - Stream,
21 -} from "effect";
8 +import * as Cause from "effect/Cause";
9 +import * as Clock from "effect/Clock";
10 +import * as DateTime from "effect/DateTime";
11 +import * as Deferred from "effect/Deferred";
12 +import * as Duration from "effect/Duration";
13 +import * as Effect from "effect/Effect";
14 +import * as Exit from "effect/Exit";
15 +import * as Layer from "effect/Layer";
16 +import * as Metric from "effect/Metric";
17 +import * as Option from "effect/Option";
18 +import * as PubSub from "effect/PubSub";
19 +import * as Queue from "effect/Queue";
20 +import * as Schema from "effect/Schema";
21 +import * as Stream from "effect/Stream";
22 import * as SqlClient from "effect/unstable/sql/SqlClient";
23
24 import {
@@ -78,7 +78,8 @@ const makeOrchestrationEngine = Effect.gen(function* () {
78 const projectionPipeline = yield* OrchestrationProjectionPipeline;
79 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
80
81 - let commandReadModel = createEmptyReadModel(new Date().toISOString());
81 + const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
82 + let commandReadModel = createEmptyReadModel(yield* nowIso);
83
84 const commandQueue = yield* Queue.unbounded<CommandEnvelope>();
85 const eventPubSub = yield* PubSub.unbounded<OrchestrationEvent>();
@@ -97,7 +98,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
98
99 const processEnvelope = (envelope: CommandEnvelope): Effect.Effect<void> => {
100 const dispatchStartSequence = commandReadModel.snapshotSequence;
100 - const processingStartedAtMs = Date.now();
101 + let processingStartedAtMs = 0;
102 const aggregateRef = commandToAggregateRef(envelope.command);
103 const baseMetricAttributes = {
104 commandType: envelope.command.type,
@@ -120,6 +121,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
121
122 return Effect.exit(
123 Effect.gen(function* () {
124 + processingStartedAtMs = yield* Clock.currentTimeMillis;
125 yield* Effect.annotateCurrentSpan({
126 "orchestration.command_id": envelope.command.commandId,
127 "orchestration.command_type": envelope.command.type,
@@ -205,7 +207,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
207 ackEventType: event.type,
208 }),
209 ),
208 - Duration.millis(Math.max(0, Date.now() - envelope.startedAtMs)),
210 + Duration.millis(Math.max(0, (yield* Clock.currentTimeMillis) - envelope.startedAtMs)),
211 );
212 }
213 }
@@ -224,7 +226,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
226 orchestrationCommandDuration,
227 metricAttributes(baseMetricAttributes),
228 ),
227 - Duration.millis(Math.max(0, Date.now() - processingStartedAtMs)),
229 + Duration.millis(Math.max(0, (yield* Clock.currentTimeMillis) - processingStartedAtMs)),
230 );
231 yield* Metric.update(
232 Metric.withAttributes(
@@ -263,7 +265,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
265 commandId: envelope.command.commandId,
266 aggregateKind: aggregateRef.aggregateKind,
267 aggregateId: aggregateRef.aggregateId,
266 - acceptedAt: new Date().toISOString(),
268 + acceptedAt: yield* nowIso,
269 resultSequence: commandReadModel.snapshotSequence,
270 status: "rejected",
271 error: error.message,
@@ -293,7 +295,11 @@ const makeOrchestrationEngine = Effect.gen(function* () {
295 const dispatch: OrchestrationEngineShape["dispatch"] = (command) =>
296 Effect.gen(function* () {
297 const result = yield* Deferred.make<{ sequence: number }, OrchestrationDispatchError>();
296 - yield* Queue.offer(commandQueue, { command, result, startedAtMs: Date.now() });
298 + yield* Queue.offer(commandQueue, {
299 + command,
300 + result,
301 + startedAtMs: yield* Clock.currentTimeMillis,
302 + });
303 return yield* Deferred.await(result);
304 });
305
apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts
+5 -1
@@ -1,4 +1,8 @@
1 -import { Effect, Exit, Layer, ManagedRuntime, Scope } from "effect";
1 +import * as Effect from "effect/Effect";
2 +import * as Exit from "effect/Exit";
3 +import * as Layer from "effect/Layer";
4 +import * as ManagedRuntime from "effect/ManagedRuntime";
5 +import * as Scope from "effect/Scope";
6 import { afterEach, describe, expect, it } from "vitest";
7
8 import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
apps/server/src/orchestration/Layers/OrchestrationReactor.ts
+2 -1
@@ -1,4 +1,5 @@
1 -import { Effect, Layer } from "effect";
1 +import * as Effect from "effect/Effect";
2 +import * as Layer from "effect/Layer";
3
4 import {
5 OrchestrationReactor,
apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts
+23 -16
@@ -11,7 +11,10 @@ import {
11 } from "@t3tools/contracts";
12 import * as NodeServices from "@effect/platform-node/NodeServices";
13 import { assert, it } from "@effect/vitest";
14 -import { Effect, FileSystem, Layer, Path } from "effect";
14 +import * as Effect from "effect/Effect";
15 +import * as FileSystem from "effect/FileSystem";
16 +import * as Layer from "effect/Layer";
17 +import * as Path from "effect/Path";
18 import * as SqlClient from "effect/unstable/sql/SqlClient";
19
20 import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
@@ -55,7 +58,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
58 const projectionPipeline = yield* OrchestrationProjectionPipeline;
59 const eventStore = yield* OrchestrationEventStore;
60 const sql = yield* SqlClient.SqlClient;
58 - const now = new Date().toISOString();
61 + const now = "2026-01-01T00:00:00.000Z";
62
63 yield* eventStore.append({
64 type: "project.created",
@@ -180,7 +183,7 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-base-")))(
183 const projectionPipeline = yield* OrchestrationProjectionPipeline;
184 const eventStore = yield* OrchestrationEventStore;
185 const sql = yield* SqlClient.SqlClient;
183 - const now = new Date().toISOString();
186 + const now = "2026-01-01T00:00:00.000Z";
187
188 yield* eventStore.append({
189 type: "thread.message-sent",
@@ -224,6 +227,7 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-base-")))(
227 WHERE message_id = 'message-attachments'
228 `;
229 assert.equal(rows.length, 1);
230 + // @effect-diagnostics-next-line preferSchemaOverJson:off
231 assert.deepEqual(JSON.parse(rows[0]?.attachmentsJson ?? "null"), [
232 {
233 type: "image",
@@ -246,7 +250,7 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta
250 const projectionPipeline = yield* OrchestrationProjectionPipeline;
251 const eventStore = yield* OrchestrationEventStore;
252 const sql = yield* SqlClient.SqlClient;
249 - const now = new Date().toISOString();
253 + const now = "2026-01-01T00:00:00.000Z";
254
255 yield* eventStore.append({
256 type: "thread.message-sent",
@@ -297,6 +301,7 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta
301 WHERE message_id = 'message-attachments-safe'
302 `;
303 assert.equal(rows.length, 1);
304 + // @effect-diagnostics-next-line preferSchemaOverJson:off
305 assert.deepEqual(JSON.parse(rows[0]?.attachmentsJson ?? "null"), [
306 {
307 type: "image",
@@ -326,8 +331,8 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
331 const projectionPipeline = yield* OrchestrationProjectionPipeline;
332 const eventStore = yield* OrchestrationEventStore;
333 const sql = yield* SqlClient.SqlClient;
329 - const now = new Date().toISOString();
330 - const later = new Date(Date.now() + 1_000).toISOString();
334 + const now = "2026-01-01T00:00:00.000Z";
335 + const later = "2026-01-01T00:00:01.000Z";
336
337 yield* eventStore.append({
338 type: "project.created",
@@ -441,6 +446,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
446 WHERE message_id = 'message-clear-attachments'
447 `;
448 assert.equal(rows.length, 1);
449 + // @effect-diagnostics-next-line preferSchemaOverJson:off
450 assert.deepEqual(JSON.parse(rows[0]?.attachmentsJson ?? "null"), []);
451 }),
452 );
@@ -454,8 +460,8 @@ it.layer(
460 const projectionPipeline = yield* OrchestrationProjectionPipeline;
461 const eventStore = yield* OrchestrationEventStore;
462 const sql = yield* SqlClient.SqlClient;
457 - const now = new Date().toISOString();
458 - const later = new Date(Date.now() + 1_000).toISOString();
463 + const now = "2026-01-01T00:00:00.000Z";
464 + const later = "2026-01-01T00:00:01.000Z";
465
466 yield* eventStore.append({
467 type: "project.created",
@@ -576,6 +582,7 @@ it.layer(
582 WHERE message_id = 'message-overwrite'
583 `;
584 assert.equal(rows.length, 1);
585 + // @effect-diagnostics-next-line preferSchemaOverJson:off
586 assert.deepEqual(JSON.parse(rows[0]?.attachmentsJson ?? "null"), [
587 {
588 type: "image",
@@ -598,7 +605,7 @@ it.layer(
605 const eventStore = yield* OrchestrationEventStore;
606 const path = yield* Path.Path;
607 const sql = yield* SqlClient.SqlClient;
601 - const now = new Date().toISOString();
608 + const now = "2026-01-01T00:00:00.000Z";
609
610 const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
611 eventStore
@@ -722,7 +729,7 @@ it.layer(
729 const projectionPipeline = yield* OrchestrationProjectionPipeline;
730 const eventStore = yield* OrchestrationEventStore;
731 const { attachmentsDir } = yield* ServerConfig;
725 - const now = new Date().toISOString();
732 + const now = "2026-01-01T00:00:00.000Z";
733 const threadId = ThreadId.make("Thread Revert.Files");
734 const keepAttachmentId = "thread-revert-files-00000000-0000-4000-8000-000000000001";
735 const removeAttachmentId = "thread-revert-files-00000000-0000-4000-8000-000000000002";
@@ -931,7 +938,7 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta
938 const projectionPipeline = yield* OrchestrationProjectionPipeline;
939 const eventStore = yield* OrchestrationEventStore;
940 const { attachmentsDir } = yield* ServerConfig;
934 - const now = new Date().toISOString();
941 + const now = "2026-01-01T00:00:00.000Z";
942 const threadId = ThreadId.make("Thread Delete.Files");
943 const attachmentId = "thread-delete-files-00000000-0000-4000-8000-000000000001";
944 const otherThreadAttachmentId =
@@ -1063,7 +1070,7 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta
1070 const path = yield* Path.Path;
1071 const projectionPipeline = yield* OrchestrationProjectionPipeline;
1072 const eventStore = yield* OrchestrationEventStore;
1066 - const now = new Date().toISOString();
1073 + const now = "2026-01-01T00:00:00.000Z";
1074 const { attachmentsDir: attachmentsRootDir, stateDir } = yield* ServerConfig;
1075 const attachmentsSentinelPath = path.join(attachmentsRootDir, "sentinel.txt");
1076 const stateDirSentinelPath = path.join(stateDir, "state-sentinel.txt");
@@ -1103,7 +1110,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
1110 const projectionPipeline = yield* OrchestrationProjectionPipeline;
1111 const eventStore = yield* OrchestrationEventStore;
1112 const sql = yield* SqlClient.SqlClient;
1106 - const now = new Date().toISOString();
1113 + const now = "2026-01-01T00:00:00.000Z";
1114
1115 yield* eventStore.append({
1116 type: "project.created",
@@ -1230,7 +1237,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
1237 const projectionPipeline = yield* OrchestrationProjectionPipeline;
1238 const eventStore = yield* OrchestrationEventStore;
1239 const sql = yield* SqlClient.SqlClient;
1233 - const now = new Date().toISOString();
1240 + const now = "2026-01-01T00:00:00.000Z";
1241
1242 yield* eventStore.append({
1243 type: "project.created",
@@ -2187,7 +2194,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
2194 Effect.gen(function* () {
2195 const engine = yield* OrchestrationEngineService;
2196 const sql = yield* SqlClient.SqlClient;
2190 - const createdAt = new Date().toISOString();
2197 + const createdAt = "2026-01-01T00:00:00.000Z";
2198
2199 yield* engine.dispatch({
2200 type: "project.create",
@@ -2225,7 +2232,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
2232 Effect.gen(function* () {
2233 const engine = yield* OrchestrationEngineService;
2234 const sql = yield* SqlClient.SqlClient;
2228 - const createdAt = new Date().toISOString();
2235 + const createdAt = "2026-01-01T00:00:00.000Z";
2236
2237 yield* engine.dispatch({
2238 type: "project.create",
apps/server/src/orchestration/Layers/ProjectionPipeline.ts
+6 -1
@@ -4,7 +4,12 @@ import {
4 type OrchestrationEvent,
5 ThreadId,
6 } from "@t3tools/contracts";
7 -import { Effect, FileSystem, Layer, Option, Path, Stream } from "effect";
7 +import * as Effect from "effect/Effect";
8 +import * as FileSystem from "effect/FileSystem";
9 +import * as Layer from "effect/Layer";
10 +import * as Option from "effect/Option";
11 +import * as Path from "effect/Path";
12 +import * as Stream from "effect/Stream";
13 import * as SqlClient from "effect/unstable/sql/SqlClient";
14
15 import { toPersistenceSqlError, type ProjectionRepositoryError } from "../../persistence/Errors.ts";
apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts
+2 -1
@@ -8,7 +8,8 @@ import {
8 ProviderInstanceId,
9 } from "@t3tools/contracts";
10 import { assert, it } from "@effect/vitest";
11 -import { Effect, Layer } from "effect";
11 +import * as Effect from "effect/Effect";
12 +import * as Layer from "effect/Layer";
13 import * as SqlClient from "effect/unstable/sql/SqlClient";
14
15 import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
+8 -4
@@ -23,7 +23,11 @@ import {
23 ProjectId,
24 ThreadId,
25 } from "@t3tools/contracts";
26 -import { Effect, Layer, Option, Schema, Struct } from "effect";
26 +import * as Effect from "effect/Effect";
27 +import * as Layer from "effect/Layer";
28 +import * as Option from "effect/Option";
29 +import * as Schema from "effect/Schema";
30 +import * as Struct from "effect/Struct";
31 import * as SqlClient from "effect/unstable/sql/SqlClient";
32 import * as SqlSchema from "effect/unstable/sql/SqlSchema";
33
@@ -1005,7 +1009,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
1009 snapshotSequence: computeSnapshotSequence(stateRows),
1010 projects,
1011 threads,
1008 - updatedAt: updatedAt ?? new Date(0).toISOString(),
1012 + updatedAt: updatedAt ?? "1970-01-01T00:00:00.000Z",
1013 };
1014
1015 return yield* decodeReadModel(snapshot).pipe(
@@ -1204,7 +1208,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
1208 snapshotSequence: computeSnapshotSequence(stateRows),
1209 projects,
1210 threads,
1207 - updatedAt: updatedAt ?? new Date(0).toISOString(),
1211 + updatedAt: updatedAt ?? "1970-01-01T00:00:00.000Z",
1212 } satisfies OrchestrationReadModel;
1213 }),
1214 ),
@@ -1326,7 +1330,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
1330 hasActionableProposedPlan: row.hasActionableProposedPlan > 0,
1331 }),
1332 ),
1329 - updatedAt: updatedAt ?? new Date(0).toISOString(),
1333 + updatedAt: updatedAt ?? "1970-01-01T00:00:00.000Z",
1334 };
1335
1336 return yield* decodeShellSnapshot(snapshot).pipe(
apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
+43 -35
@@ -1,3 +1,4 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 import fs from "node:fs";
3 import os from "node:os";
4 import path from "node:path";
@@ -20,7 +21,13 @@ import {
21 ThreadId,
22 TurnId,
23 } from "@t3tools/contracts";
23 -import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
24 +import * as Effect from "effect/Effect";
25 +import * as Exit from "effect/Exit";
26 +import * as Layer from "effect/Layer";
27 +import * as ManagedRuntime from "effect/ManagedRuntime";
28 +import * as PubSub from "effect/PubSub";
29 +import * as Scope from "effect/Scope";
30 +import * as Stream from "effect/Stream";
31 import { afterEach, describe, expect, it, vi } from "vitest";
32
33 import { deriveServerPaths, ServerConfig } from "../../config.ts";
@@ -47,6 +54,7 @@ import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
54 import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
55 import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
56 import * as NodeServices from "@effect/platform-node/NodeServices";
57 +import * as Clock from "effect/Clock";
58 import { ServerSettingsService } from "../../serverSettings.ts";
59 import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
60 import { GitWorkflowService, type GitWorkflowServiceShape } from "../../git/GitWorkflowService.ts";
@@ -63,15 +71,15 @@ async function waitFor(
71 predicate: () => boolean | Promise<boolean>,
72 timeoutMs = 2000,
73 ): Promise<void> {
66 - const deadline = Date.now() + timeoutMs;
74 + const deadline = (await Effect.runPromise(Clock.currentTimeMillis)) + timeoutMs;
75 const poll = async (): Promise<void> => {
76 if (await predicate()) {
77 return;
78 }
71 - if (Date.now() >= deadline) {
79 + if ((await Effect.runPromise(Clock.currentTimeMillis)) >= deadline) {
80 throw new Error("Timed out waiting for expectation.");
81 }
74 - await new Promise((resolve) => setTimeout(resolve, 10));
82 + await Effect.runPromise(Effect.yieldNow);
83 return poll();
84 };
85
@@ -135,7 +143,7 @@ describe("ProviderCommandReactor", () => {
143 readonly threadModelSelection?: ModelSelection;
144 readonly sessionModelSwitch?: "unsupported" | "in-session";
145 }) {
138 - const now = new Date().toISOString();
146 + const now = "2026-01-01T00:00:00.000Z";
147 const baseDir = input?.baseDir ?? fs.mkdtempSync(path.join(os.tmpdir(), "t3code-reactor-"));
148 createdBaseDirs.add(baseDir);
149 const { stateDir } = deriveServerPathsSync(baseDir, undefined);
@@ -408,7 +416,7 @@ describe("ProviderCommandReactor", () => {
416
417 it("reacts to thread.turn.start by ensuring session and sending provider turn", async () => {
418 const harness = await createHarness();
411 - const now = new Date().toISOString();
419 + const now = "2026-01-01T00:00:00.000Z";
420
421 await Effect.runPromise(
422 harness.engine.dispatch({
@@ -447,7 +455,7 @@ describe("ProviderCommandReactor", () => {
455
456 it("generates a thread title on the first turn", async () => {
457 const harness = await createHarness();
450 - const now = new Date().toISOString();
458 + const now = "2026-01-01T00:00:00.000Z";
459 const seededTitle = "Please investigate reconnect failures after restar...";
460 harness.generateThreadTitle.mockReturnValue(Effect.succeed({ title: "Generated title" }));
461
@@ -497,7 +505,7 @@ describe("ProviderCommandReactor", () => {
505
506 it("does not overwrite an existing custom thread title on the first turn", async () => {
507 const harness = await createHarness();
500 - const now = new Date().toISOString();
508 + const now = "2026-01-01T00:00:00.000Z";
509 const seededTitle = "Please investigate reconnect failures after restar...";
510
511 await Effect.runPromise(
@@ -537,7 +545,7 @@ describe("ProviderCommandReactor", () => {
545
546 it("matches the client-seeded title even when the outgoing prompt is reformatted", async () => {
547 const harness = await createHarness();
540 - const now = new Date().toISOString();
548 + const now = "2026-01-01T00:00:00.000Z";
549 const seededTitle = "Fix reconnect spinner on resume";
550 harness.generateThreadTitle.mockReturnValue(
551 Effect.succeed({
@@ -588,7 +596,7 @@ describe("ProviderCommandReactor", () => {
596
597 it("generates a worktree branch name for the first turn", async () => {
598 const harness = await createHarness();
591 - const now = new Date().toISOString();
599 + const now = "2026-01-01T00:00:00.000Z";
600
601 await Effect.runPromise(
602 harness.engine.dispatch({
@@ -642,7 +650,7 @@ describe("ProviderCommandReactor", () => {
650
651 it("forwards codex model options through session start and turn send", async () => {
652 const harness = await createHarness();
645 - const now = new Date().toISOString();
653 + const now = "2026-01-01T00:00:00.000Z";
654
655 await Effect.runPromise(
656 harness.engine.dispatch({
@@ -689,7 +697,7 @@ describe("ProviderCommandReactor", () => {
697 model: "claude-sonnet-4-6",
698 },
699 });
692 - const now = new Date().toISOString();
700 + const now = "2026-01-01T00:00:00.000Z";
701
702 await Effect.runPromise(
703 harness.engine.dispatch({
@@ -739,7 +747,7 @@ describe("ProviderCommandReactor", () => {
747 model: "claude-opus-4-6",
748 },
749 });
742 - const now = new Date().toISOString();
750 + const now = "2026-01-01T00:00:00.000Z";
751
752 await Effect.runPromise(
753 harness.engine.dispatch({
@@ -784,7 +792,7 @@ describe("ProviderCommandReactor", () => {
792
793 it("forwards plan interaction mode to the provider turn request", async () => {
794 const harness = await createHarness();
787 - const now = new Date().toISOString();
795 + const now = "2026-01-01T00:00:00.000Z";
796
797 await Effect.runPromise(
798 harness.engine.dispatch({
@@ -822,7 +830,7 @@ describe("ProviderCommandReactor", () => {
830
831 it("preserves the active session model when in-session model switching is unsupported", async () => {
832 const harness = await createHarness({ sessionModelSwitch: "unsupported" });
825 - const now = new Date().toISOString();
833 + const now = "2026-01-01T00:00:00.000Z";
834
835 await Effect.runPromise(
836 harness.engine.dispatch({
@@ -875,7 +883,7 @@ describe("ProviderCommandReactor", () => {
883 const harness = await createHarness({
884 threadModelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" },
885 });
878 - const now = new Date().toISOString();
886 + const now = "2026-01-01T00:00:00.000Z";
887
888 await Effect.runPromise(
889 harness.engine.dispatch({
@@ -921,7 +929,7 @@ describe("ProviderCommandReactor", () => {
929
930 it("reuses the same provider session when runtime mode is unchanged", async () => {
931 const harness = await createHarness();
924 - const now = new Date().toISOString();
932 + const now = "2026-01-01T00:00:00.000Z";
933
934 await Effect.runPromise(
935 harness.engine.dispatch({
@@ -967,7 +975,7 @@ describe("ProviderCommandReactor", () => {
975
976 it("restarts an existing Codex thread on a compatible requested instance", async () => {
977 const harness = await createHarness();
970 - const now = new Date().toISOString();
978 + const now = "2026-01-01T00:00:00.000Z";
979
980 await Effect.runPromise(
981 harness.engine.dispatch({
@@ -1009,7 +1017,7 @@ describe("ProviderCommandReactor", () => {
1017 },
1018 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
1019 runtimeMode: "approval-required",
1012 - createdAt: new Date().toISOString(),
1020 + createdAt: "2026-01-01T00:00:00.000Z",
1021 }),
1022 );
1023
@@ -1034,7 +1042,7 @@ describe("ProviderCommandReactor", () => {
1042 model: "claude-sonnet-4-6",
1043 },
1044 });
1037 - const now = new Date().toISOString();
1045 + const now = "2026-01-01T00:00:00.000Z";
1046
1047 await Effect.runPromise(
1048 harness.engine.dispatch({
@@ -1107,7 +1115,7 @@ describe("ProviderCommandReactor", () => {
1115 model: "claude-sonnet-4-6",
1116 },
1117 });
1110 - const now = new Date().toISOString();
1118 + const now = "2026-01-01T00:00:00.000Z";
1119
1120 await Effect.runPromise(
1121 harness.engine.dispatch({
@@ -1170,7 +1178,7 @@ describe("ProviderCommandReactor", () => {
1178
1179 it("restarts the provider session when runtime mode is updated on the thread", async () => {
1180 const harness = await createHarness();
1173 - const now = new Date().toISOString();
1181 + const now = "2026-01-01T00:00:00.000Z";
1182
1183 await Effect.runPromise(
1184 harness.engine.dispatch({
@@ -1260,7 +1268,7 @@ describe("ProviderCommandReactor", () => {
1268 model: "claude-opus-4-6",
1269 },
1270 });
1263 - const now = new Date().toISOString();
1271 + const now = "2026-01-01T00:00:00.000Z";
1272
1273 await Effect.runPromise(
1274 harness.engine.dispatch({
@@ -1303,7 +1311,7 @@ describe("ProviderCommandReactor", () => {
1311
1312 it("does not stop the active session when restart fails before rebind", async () => {
1313 const harness = await createHarness();
1306 - const now = new Date().toISOString();
1314 + const now = "2026-01-01T00:00:00.000Z";
1315
1316 await Effect.runPromise(
1317 harness.engine.dispatch({
@@ -1336,7 +1344,7 @@ describe("ProviderCommandReactor", () => {
1344 await waitFor(() => harness.sendTurn.mock.calls.length === 1);
1345
1346 harness.startSession.mockImplementationOnce(
1339 - (_: unknown, __: unknown) => Effect.fail(new Error("simulated restart failure")) as never,
1347 + (_: unknown, __: unknown) => Effect.fail("simulated restart failure") as never,
1348 );
1349
1350 await Effect.runPromise(
@@ -1368,7 +1376,7 @@ describe("ProviderCommandReactor", () => {
1376
1377 it("rejects provider changes after a thread is already bound to a session provider", async () => {
1378 const harness = await createHarness();
1371 - const now = new Date().toISOString();
1379 + const now = "2026-01-01T00:00:00.000Z";
1380
1381 await Effect.runPromise(
1382 harness.engine.dispatch({
@@ -1440,7 +1448,7 @@ describe("ProviderCommandReactor", () => {
1448
1449 it("rejects cross-driver provider changes after the existing thread session has stopped", async () => {
1450 const harness = await createHarness();
1443 - const now = new Date().toISOString();
1451 + const now = "2026-01-01T00:00:00.000Z";
1452
1453 await Effect.runPromise(
1454 harness.engine.dispatch({
@@ -1506,7 +1514,7 @@ describe("ProviderCommandReactor", () => {
1514
1515 it("reacts to thread.turn.interrupt-requested by calling provider interrupt", async () => {
1516 const harness = await createHarness();
1509 - const now = new Date().toISOString();
1517 + const now = "2026-01-01T00:00:00.000Z";
1518
1519 await Effect.runPromise(
1520 harness.engine.dispatch({
@@ -1544,7 +1552,7 @@ describe("ProviderCommandReactor", () => {
1552
1553 it("starts a fresh session when only projected session state exists", async () => {
1554 const harness = await createHarness();
1547 - const now = new Date().toISOString();
1555 + const now = "2026-01-01T00:00:00.000Z";
1556
1557 await Effect.runPromise(
1558 harness.engine.dispatch({
@@ -1599,7 +1607,7 @@ describe("ProviderCommandReactor", () => {
1607
1608 it("rejects active runtime sessions that are missing provider instance ids", async () => {
1609 const harness = await createHarness();
1602 - const now = new Date().toISOString();
1610 + const now = "2026-01-01T00:00:00.000Z";
1611
1612 await Effect.runPromise(
1613 harness.engine.dispatch({
@@ -1670,7 +1678,7 @@ describe("ProviderCommandReactor", () => {
1678
1679 it("reacts to thread.approval.respond by forwarding provider approval response", async () => {
1680 const harness = await createHarness();
1673 - const now = new Date().toISOString();
1681 + const now = "2026-01-01T00:00:00.000Z";
1682
1683 await Effect.runPromise(
1684 harness.engine.dispatch({
@@ -1711,7 +1719,7 @@ describe("ProviderCommandReactor", () => {
1719
1720 it("reacts to thread.user-input.respond by forwarding structured user input answers", async () => {
1721 const harness = await createHarness();
1714 - const now = new Date().toISOString();
1722 + const now = "2026-01-01T00:00:00.000Z";
1723
1724 await Effect.runPromise(
1725 harness.engine.dispatch({
@@ -1756,7 +1764,7 @@ describe("ProviderCommandReactor", () => {
1764
1765 it("surfaces stale provider approval request failures without faking approval resolution", async () => {
1766 const harness = await createHarness();
1759 - const now = new Date().toISOString();
1767 + const now = "2026-01-01T00:00:00.000Z";
1768 harness.respondToRequest.mockImplementation(() =>
1769 Effect.fail(
1770 new ProviderAdapterRequestError({
@@ -1851,7 +1859,7 @@ describe("ProviderCommandReactor", () => {
1859
1860 it("surfaces stale provider user-input failures without faking user-input resolution", async () => {
1861 const harness = await createHarness();
1854 - const now = new Date().toISOString();
1862 + const now = "2026-01-01T00:00:00.000Z";
1863 harness.respondToUserInput.mockImplementation(() =>
1864 Effect.fail(
1865 new ProviderAdapterRequestError({
@@ -1960,7 +1968,7 @@ describe("ProviderCommandReactor", () => {
1968
1969 it("reacts to thread.session.stop by stopping provider session and clearing thread session state", async () => {
1970 const harness = await createHarness();
1963 - const now = new Date().toISOString();
1971 + const now = "2026-01-01T00:00:00.000Z";
1972
1973 await Effect.runPromise(
1974 harness.engine.dispatch({
apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
+9 -1
@@ -13,7 +13,15 @@ import {
13 type TurnId,
14 } from "@t3tools/contracts";
15 import { isTemporaryWorktreeBranch, WORKTREE_BRANCH_PREFIX } from "@t3tools/shared/git";
16 -import { Cache, Cause, Duration, Effect, Equal, Layer, Option, Schema, Stream } from "effect";
16 +import * as Cache from "effect/Cache";
17 +import * as Cause from "effect/Cause";
18 +import * as Duration from "effect/Duration";
19 +import * as Effect from "effect/Effect";
20 +import * as Equal from "effect/Equal";
21 +import * as Layer from "effect/Layer";
22 +import * as Option from "effect/Option";
23 +import * as Schema from "effect/Schema";
24 +import * as Stream from "effect/Stream";
25 import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
26
27 import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts
+69 -61
@@ -1,3 +1,4 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 import fs from "node:fs";
3 import os from "node:os";
4 import path from "node:path";
@@ -21,7 +22,14 @@ import {
22 ThreadId,
23 TurnId,
24 } from "@t3tools/contracts";
24 -import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
25 +import * as Clock from "effect/Clock";
26 +import * as Effect from "effect/Effect";
27 +import * as Exit from "effect/Exit";
28 +import * as Layer from "effect/Layer";
29 +import * as ManagedRuntime from "effect/ManagedRuntime";
30 +import * as PubSub from "effect/PubSub";
31 +import * as Scope from "effect/Scope";
32 +import * as Stream from "effect/Stream";
33 import { afterEach, describe, expect, it } from "vitest";
34
35 import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
@@ -165,17 +173,17 @@ async function waitForThread(
173 timeoutMs = 2000,
174 threadId: ThreadId = asThreadId("thread-1"),
175 ) {
168 - const deadline = Date.now() + timeoutMs;
176 + const deadline = (await Effect.runPromise(Clock.currentTimeMillis)) + timeoutMs;
177 const poll = async (): Promise<ProviderRuntimeTestThread> => {
178 const snapshot = await readModel();
179 const thread = snapshot.threads.find((entry) => entry.id === threadId);
180 if (thread && predicate(thread)) {
181 return thread;
182 }
175 - if (Date.now() >= deadline) {
183 + if ((await Effect.runPromise(Clock.currentTimeMillis)) >= deadline) {
184 throw new Error("Timed out waiting for thread state");
185 }
178 - await new Promise((resolve) => setTimeout(resolve, 10));
186 + await Effect.runPromise(Effect.yieldNow);
187 return poll();
188 };
189 return poll();
@@ -242,7 +250,7 @@ describe("ProviderRuntimeIngestion", () => {
250 await Effect.runPromise(ingestion.start().pipe(Scope.provide(scope)));
251 const drain = () => Effect.runPromise(ingestion.drain);
252
245 - const createdAt = new Date().toISOString();
253 + const createdAt = "2026-01-01T00:00:00.000Z";
254 await Effect.runPromise(
255 engine.dispatch({
256 type: "project.create",
@@ -312,7 +320,7 @@ describe("ProviderRuntimeIngestion", () => {
320
321 it("maps turn started/completed events into thread session updates", async () => {
322 const harness = await createHarness();
315 - const now = new Date().toISOString();
323 + const now = "2026-01-01T00:00:00.000Z";
324
325 harness.emit({
326 type: "turn.started",
@@ -333,7 +341,7 @@ describe("ProviderRuntimeIngestion", () => {
341 eventId: asEventId("evt-turn-completed"),
342 provider: ProviderDriverKind.make("codex"),
343 threadId: asThreadId("thread-1"),
336 - createdAt: new Date().toISOString(),
344 + createdAt: "2026-01-01T00:00:00.000Z",
345 turnId: asTurnId("turn-1"),
346 payload: {
347 state: "failed",
@@ -354,7 +362,7 @@ describe("ProviderRuntimeIngestion", () => {
362
363 it("applies provider session.state.changed transitions directly", async () => {
364 const harness = await createHarness();
357 - const waitingAt = new Date().toISOString();
365 + const waitingAt = "2026-01-01T00:00:00.000Z";
366
367 harness.emit({
368 type: "session.state.changed",
@@ -380,7 +388,7 @@ describe("ProviderRuntimeIngestion", () => {
388 eventId: asEventId("evt-session-state-error"),
389 provider: ProviderDriverKind.make("codex"),
390 threadId: asThreadId("thread-1"),
383 - createdAt: new Date().toISOString(),
391 + createdAt: "2026-01-01T00:00:00.000Z",
392 payload: {
393 state: "error",
394 reason: "provider crashed",
@@ -402,7 +410,7 @@ describe("ProviderRuntimeIngestion", () => {
410 eventId: asEventId("evt-session-state-stopped"),
411 provider: ProviderDriverKind.make("codex"),
412 threadId: asThreadId("thread-1"),
405 - createdAt: new Date().toISOString(),
413 + createdAt: "2026-01-01T00:00:00.000Z",
414 payload: {
415 state: "stopped",
416 },
@@ -423,7 +431,7 @@ describe("ProviderRuntimeIngestion", () => {
431 eventId: asEventId("evt-session-state-ready"),
432 provider: ProviderDriverKind.make("codex"),
433 threadId: asThreadId("thread-1"),
426 - createdAt: new Date().toISOString(),
434 + createdAt: "2026-01-01T00:00:00.000Z",
435 payload: {
436 state: "ready",
437 },
@@ -442,7 +450,7 @@ describe("ProviderRuntimeIngestion", () => {
450
451 it("does not clear active turn when session/thread started arrives mid-turn", async () => {
452 const harness = await createHarness();
445 - const now = new Date().toISOString();
453 + const now = "2026-01-01T00:00:00.000Z";
454
455 harness.emit({
456 type: "turn.started",
@@ -464,14 +472,14 @@ describe("ProviderRuntimeIngestion", () => {
472 type: "thread.started",
473 eventId: asEventId("evt-thread-started-midturn-lifecycle"),
474 provider: ProviderDriverKind.make("codex"),
467 - createdAt: new Date().toISOString(),
475 + createdAt: "2026-01-01T00:00:00.000Z",
476 threadId: asThreadId("thread-1"),
477 });
478 harness.emit({
479 type: "session.started",
480 eventId: asEventId("evt-session-started-midturn-lifecycle"),
481 provider: ProviderDriverKind.make("codex"),
474 - createdAt: new Date().toISOString(),
482 + createdAt: "2026-01-01T00:00:00.000Z",
483 threadId: asThreadId("thread-1"),
484 });
485
@@ -485,7 +493,7 @@ describe("ProviderRuntimeIngestion", () => {
493 type: "turn.completed",
494 eventId: asEventId("evt-turn-completed-midturn-lifecycle"),
495 provider: ProviderDriverKind.make("codex"),
488 - createdAt: new Date().toISOString(),
496 + createdAt: "2026-01-01T00:00:00.000Z",
497 threadId: asThreadId("thread-1"),
498 turnId: asTurnId("turn-midturn-lifecycle"),
499 status: "completed",
@@ -499,7 +507,7 @@ describe("ProviderRuntimeIngestion", () => {
507
508 it("accepts claude turn lifecycle when seeded thread id is a synthetic placeholder", async () => {
509 const harness = await createHarness();
502 - const seededAt = new Date().toISOString();
510 + const seededAt = "2026-01-01T00:00:00.000Z";
511
512 await Effect.runPromise(
513 harness.engine.dispatch({
@@ -523,7 +531,7 @@ describe("ProviderRuntimeIngestion", () => {
531 type: "turn.started",
532 eventId: asEventId("evt-turn-started-claude-placeholder"),
533 provider: ProviderDriverKind.make("claudeAgent"),
526 - createdAt: new Date().toISOString(),
534 + createdAt: "2026-01-01T00:00:00.000Z",
535 threadId: asThreadId("thread-1"),
536 turnId: asTurnId("turn-claude-placeholder"),
537 });
@@ -539,7 +547,7 @@ describe("ProviderRuntimeIngestion", () => {
547 type: "turn.completed",
548 eventId: asEventId("evt-turn-completed-claude-placeholder"),
549 provider: ProviderDriverKind.make("claudeAgent"),
542 - createdAt: new Date().toISOString(),
550 + createdAt: "2026-01-01T00:00:00.000Z",
551 threadId: asThreadId("thread-1"),
552 turnId: asTurnId("turn-claude-placeholder"),
553 status: "completed",
@@ -553,7 +561,7 @@ describe("ProviderRuntimeIngestion", () => {
561
562 it("ignores auxiliary turn completions from a different provider thread", async () => {
563 const harness = await createHarness();
556 - const now = new Date().toISOString();
564 + const now = "2026-01-01T00:00:00.000Z";
565
566 harness.emit({
567 type: "turn.started",
@@ -574,7 +582,7 @@ describe("ProviderRuntimeIngestion", () => {
582 type: "turn.completed",
583 eventId: asEventId("evt-turn-completed-aux"),
584 provider: ProviderDriverKind.make("codex"),
577 - createdAt: new Date().toISOString(),
585 + createdAt: "2026-01-01T00:00:00.000Z",
586 threadId: asThreadId("thread-1"),
587 turnId: asTurnId("turn-aux"),
588 status: "completed",
@@ -590,7 +598,7 @@ describe("ProviderRuntimeIngestion", () => {
598 type: "turn.completed",
599 eventId: asEventId("evt-turn-completed-primary"),
600 provider: ProviderDriverKind.make("codex"),
593 - createdAt: new Date().toISOString(),
601 + createdAt: "2026-01-01T00:00:00.000Z",
602 threadId: asThreadId("thread-1"),
603 turnId: asTurnId("turn-primary"),
604 status: "completed",
@@ -604,7 +612,7 @@ describe("ProviderRuntimeIngestion", () => {
612
613 it("ignores non-active turn completion when runtime omits thread id", async () => {
614 const harness = await createHarness();
607 - const now = new Date().toISOString();
615 + const now = "2026-01-01T00:00:00.000Z";
616
617 harness.emit({
618 type: "turn.started",
@@ -626,7 +634,7 @@ describe("ProviderRuntimeIngestion", () => {
634 type: "turn.completed",
635 eventId: asEventId("evt-turn-completed-guarded-other"),
636 provider: ProviderDriverKind.make("codex"),
629 - createdAt: new Date().toISOString(),
637 + createdAt: "2026-01-01T00:00:00.000Z",
638 threadId: asThreadId("thread-1"),
639 turnId: asTurnId("turn-guarded-other"),
640 status: "completed",
@@ -642,7 +650,7 @@ describe("ProviderRuntimeIngestion", () => {
650 type: "turn.completed",
651 eventId: asEventId("evt-turn-completed-guarded-main"),
652 provider: ProviderDriverKind.make("codex"),
645 - createdAt: new Date().toISOString(),
653 + createdAt: "2026-01-01T00:00:00.000Z",
654 threadId: asThreadId("thread-1"),
655 turnId: asTurnId("turn-guarded-main"),
656 status: "completed",
@@ -656,7 +664,7 @@ describe("ProviderRuntimeIngestion", () => {
664
665 it("maps canonical content delta/item completed into finalized assistant messages", async () => {
666 const harness = await createHarness();
659 - const now = new Date().toISOString();
667 + const now = "2026-01-01T00:00:00.000Z";
668
669 harness.emit({
670 type: "content.delta",
@@ -713,7 +721,7 @@ describe("ProviderRuntimeIngestion", () => {
721
722 it("uses assistant item completion detail when no assistant deltas were streamed", async () => {
723 const harness = await createHarness();
716 - const now = new Date().toISOString();
724 + const now = "2026-01-01T00:00:00.000Z";
725
726 harness.emit({
727 type: "item.completed",
@@ -745,7 +753,7 @@ describe("ProviderRuntimeIngestion", () => {
753
754 it("preserves completed tool metadata on projected tool activities", async () => {
755 const harness = await createHarness();
748 - const now = new Date().toISOString();
756 + const now = "2026-01-01T00:00:00.000Z";
757
758 harness.emit({
759 type: "item.completed",
@@ -801,7 +809,7 @@ describe("ProviderRuntimeIngestion", () => {
809
810 it("normalizes command execution activities to ran-command summaries", async () => {
811 const harness = await createHarness();
804 - const now = new Date().toISOString();
812 + const now = "2026-01-01T00:00:00.000Z";
813
814 harness.emit({
815 type: "item.completed",
@@ -843,7 +851,7 @@ describe("ProviderRuntimeIngestion", () => {
851
852 it("uses structured read-file paths when available", async () => {
853 const harness = await createHarness();
846 - const now = new Date().toISOString();
854 + const now = "2026-01-01T00:00:00.000Z";
855
856 harness.emit({
857 type: "item.completed",
@@ -885,7 +893,7 @@ describe("ProviderRuntimeIngestion", () => {
893
894 it("projects completed plan items into first-class proposed plans", async () => {
895 const harness = await createHarness();
888 - const now = new Date().toISOString();
896 + const now = "2026-01-01T00:00:00.000Z";
897
898 harness.emit({
899 type: "turn.proposed.completed",
@@ -919,7 +927,7 @@ describe("ProviderRuntimeIngestion", () => {
927 const targetThreadId = asThreadId("thread-implement");
928 const sourceTurnId = asTurnId("turn-plan-source");
929 const targetTurnId = asTurnId("turn-plan-implement");
922 - const createdAt = new Date().toISOString();
930 + const createdAt = "2026-01-01T00:00:00.000Z";
931
932 await Effect.runPromise(
933 harness.engine.dispatch({
@@ -1050,7 +1058,7 @@ describe("ProviderRuntimeIngestion", () => {
1058 },
1059 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
1060 runtimeMode: "approval-required",
1053 - createdAt: new Date().toISOString(),
1061 + createdAt: "2026-01-01T00:00:00.000Z",
1062 }),
1063 );
1064
@@ -1075,7 +1083,7 @@ describe("ProviderRuntimeIngestion", () => {
1083 type: "turn.started",
1084 eventId: asEventId("evt-plan-target-started"),
1085 provider: ProviderDriverKind.make("codex"),
1078 - createdAt: new Date().toISOString(),
1086 + createdAt: "2026-01-01T00:00:00.000Z",
1087 threadId: targetThreadId,
1088 turnId: targetTurnId,
1089 });
@@ -1106,7 +1114,7 @@ describe("ProviderRuntimeIngestion", () => {
1114 const sourceTurnId = asTurnId("turn-plan-source");
1115 const activeTurnId = asTurnId("turn-already-running");
1116 const staleTurnId = asTurnId("turn-stale-start");
1109 - const createdAt = new Date().toISOString();
1117 + const createdAt = "2026-01-01T00:00:00.000Z";
1118
1119 await Effect.runPromise(
1120 harness.engine.dispatch({
@@ -1219,7 +1227,7 @@ describe("ProviderRuntimeIngestion", () => {
1227 },
1228 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
1229 runtimeMode: "approval-required",
1222 - createdAt: new Date().toISOString(),
1230 + createdAt: "2026-01-01T00:00:00.000Z",
1231 }),
1232 );
1233
@@ -1227,7 +1235,7 @@ describe("ProviderRuntimeIngestion", () => {
1235 type: "turn.started",
1236 eventId: asEventId("evt-turn-started-stale-plan-implementation"),
1237 provider: ProviderDriverKind.make("codex"),
1230 - createdAt: new Date().toISOString(),
1238 + createdAt: "2026-01-01T00:00:00.000Z",
1239 threadId: targetThreadId,
1240 turnId: staleTurnId,
1241 });
@@ -1259,7 +1267,7 @@ describe("ProviderRuntimeIngestion", () => {
1267 const sourceTurnId = asTurnId("turn-plan-source");
1268 const expectedTurnId = asTurnId("turn-plan-implement");
1269 const replayedTurnId = asTurnId("turn-replayed");
1262 - const createdAt = new Date().toISOString();
1270 + const createdAt = "2026-01-01T00:00:00.000Z";
1271
1272 await Effect.runPromise(
1273 harness.engine.dispatch({
@@ -1381,7 +1389,7 @@ describe("ProviderRuntimeIngestion", () => {
1389 },
1390 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
1391 runtimeMode: "approval-required",
1384 - createdAt: new Date().toISOString(),
1392 + createdAt: "2026-01-01T00:00:00.000Z",
1393 }),
1394 );
1395
@@ -1399,7 +1407,7 @@ describe("ProviderRuntimeIngestion", () => {
1407 type: "turn.started",
1408 eventId: asEventId("evt-turn-started-unrelated-plan-implementation"),
1409 provider: ProviderDriverKind.make("codex"),
1402 - createdAt: new Date().toISOString(),
1410 + createdAt: "2026-01-01T00:00:00.000Z",
1411 threadId: targetThreadId,
1412 turnId: replayedTurnId,
1413 });
@@ -1420,7 +1428,7 @@ describe("ProviderRuntimeIngestion", () => {
1428
1429 it("finalizes buffered proposed-plan deltas into a first-class proposed plan on turn completion", async () => {
1430 const harness = await createHarness();
1423 - const now = new Date().toISOString();
1431 + const now = "2026-01-01T00:00:00.000Z";
1432
1433 harness.emit({
1434 type: "turn.started",
@@ -1486,7 +1494,7 @@ describe("ProviderRuntimeIngestion", () => {
1494
1495 it("buffers assistant deltas by default until completion", async () => {
1496 const harness = await createHarness();
1489 - const now = new Date().toISOString();
1497 + const now = "2026-01-01T00:00:00.000Z";
1498
1499 harness.emit({
1500 type: "turn.started",
@@ -1554,7 +1562,7 @@ describe("ProviderRuntimeIngestion", () => {
1562
1563 it("flushes and completes buffered assistant text when an approval request opens", async () => {
1564 const harness = await createHarness();
1557 - const now = new Date().toISOString();
1565 + const now = "2026-01-01T00:00:00.000Z";
1566
1567 harness.emit({
1568 type: "turn.started",
@@ -1614,7 +1622,7 @@ describe("ProviderRuntimeIngestion", () => {
1622
1623 it("flushes and completes buffered assistant text when user input is requested", async () => {
1624 const harness = await createHarness();
1617 - const now = new Date().toISOString();
1625 + const now = "2026-01-01T00:00:00.000Z";
1626
1627 harness.emit({
1628 type: "turn.started",
@@ -1980,7 +1988,7 @@ describe("ProviderRuntimeIngestion", () => {
1988
1989 it("streams assistant deltas when thread.turn.start requests streaming mode", async () => {
1990 const harness = await createHarness({ serverSettings: { enableAssistantStreaming: true } });
1983 - const now = new Date().toISOString();
1991 + const now = "2026-01-01T00:00:00.000Z";
1992
1993 await Effect.runPromise(
1994 harness.engine.dispatch({
@@ -2072,7 +2080,7 @@ describe("ProviderRuntimeIngestion", () => {
2080
2081 it("spills oversized buffered deltas and still finalizes full assistant text", async () => {
2082 const harness = await createHarness();
2075 - const now = new Date().toISOString();
2083 + const now = "2026-01-01T00:00:00.000Z";
2084 const oversizedText = "x".repeat(40_000);
2085
2086 harness.emit({
@@ -2133,7 +2141,7 @@ describe("ProviderRuntimeIngestion", () => {
2141
2142 it("does not duplicate assistant completion when item.completed is followed by turn.completed", async () => {
2143 const harness = await createHarness();
2136 - const now = new Date().toISOString();
2144 + const now = "2026-01-01T00:00:00.000Z";
2145
2146 harness.emit({
2147 type: "turn.started",
@@ -2219,7 +2227,7 @@ describe("ProviderRuntimeIngestion", () => {
2227
2228 it("maps canonical request events into approval activities with requestKind", async () => {
2229 const harness = await createHarness();
2222 - const now = new Date().toISOString();
2230 + const now = "2026-01-01T00:00:00.000Z";
2231
2232 harness.emit({
2233 type: "request.opened",
@@ -2285,7 +2293,7 @@ describe("ProviderRuntimeIngestion", () => {
2293
2294 it("maps runtime.error into errored session state", async () => {
2295 const harness = await createHarness();
2288 - const now = new Date().toISOString();
2296 + const now = "2026-01-01T00:00:00.000Z";
2297
2298 harness.emit({
2299 type: "runtime.error",
@@ -2312,7 +2320,7 @@ describe("ProviderRuntimeIngestion", () => {
2320
2321 it("records runtime.error activities from the typed payload message", async () => {
2322 const harness = await createHarness();
2315 - const now = new Date().toISOString();
2323 + const now = "2026-01-01T00:00:00.000Z";
2324
2325 harness.emit({
2326 type: "runtime.error",
@@ -2343,7 +2351,7 @@ describe("ProviderRuntimeIngestion", () => {
2351
2352 it("keeps the session running when a runtime.warning arrives during an active turn", async () => {
2353 const harness = await createHarness();
2346 - const now = new Date().toISOString();
2354 + const now = "2026-01-01T00:00:00.000Z";
2355
2356 harness.emit({
2357 type: "turn.started",
@@ -2387,7 +2395,7 @@ describe("ProviderRuntimeIngestion", () => {
2395
2396 it("maps session/thread lifecycle and item.started into session/activity projections", async () => {
2397 const harness = await createHarness();
2390 - const now = new Date().toISOString();
2398 + const now = "2026-01-01T00:00:00.000Z";
2399
2400 harness.emit({
2401 type: "session.started",
@@ -2439,7 +2447,7 @@ describe("ProviderRuntimeIngestion", () => {
2447
2448 it("consumes P1 runtime events into thread metadata, diff checkpoints, and activities", async () => {
2449 const harness = await createHarness();
2442 - const now = new Date().toISOString();
2450 + const now = "2026-01-01T00:00:00.000Z";
2451
2452 harness.emit({
2453 type: "thread.metadata.updated",
@@ -2573,7 +2581,7 @@ describe("ProviderRuntimeIngestion", () => {
2581
2582 it("projects context window updates into normalized thread activities", async () => {
2583 const harness = await createHarness();
2576 - const now = new Date().toISOString();
2584 + const now = "2026-01-01T00:00:00.000Z";
2585
2586 harness.emit({
2587 type: "thread.token-usage.updated",
@@ -2625,7 +2633,7 @@ describe("ProviderRuntimeIngestion", () => {
2633
2634 it("projects Codex camelCase token usage payloads into normalized thread activities", async () => {
2635 const harness = await createHarness();
2628 - const now = new Date().toISOString();
2636 + const now = "2026-01-01T00:00:00.000Z";
2637
2638 harness.emit({
2639 type: "thread.token-usage.updated",
@@ -2678,7 +2686,7 @@ describe("ProviderRuntimeIngestion", () => {
2686
2687 it("projects Claude usage snapshots with context window into normalized thread activities", async () => {
2688 const harness = await createHarness();
2681 - const now = new Date().toISOString();
2689 + const now = "2026-01-01T00:00:00.000Z";
2690
2691 harness.emit({
2692 type: "thread.token-usage.updated",
@@ -2722,7 +2730,7 @@ describe("ProviderRuntimeIngestion", () => {
2730
2731 it("projects compacted thread state into context compaction activities", async () => {
2732 const harness = await createHarness();
2725 - const now = new Date().toISOString();
2733 + const now = "2026-01-01T00:00:00.000Z";
2734
2735 harness.emit({
2736 type: "thread.state.changed",
@@ -2752,7 +2760,7 @@ describe("ProviderRuntimeIngestion", () => {
2760
2761 it("projects Codex task lifecycle chunks into thread activities", async () => {
2762 const harness = await createHarness();
2755 - const now = new Date().toISOString();
2763 + const now = "2026-01-01T00:00:00.000Z";
2764
2765 harness.emit({
2766 type: "task.started",
@@ -2855,7 +2863,7 @@ describe("ProviderRuntimeIngestion", () => {
2863
2864 it("projects structured user input request and resolution as thread activities", async () => {
2865 const harness = await createHarness();
2858 - const now = new Date().toISOString();
2866 + const now = "2026-01-01T00:00:00.000Z";
2867
2868 harness.emit({
2869 type: "user-input.requested",
@@ -2886,7 +2894,7 @@ describe("ProviderRuntimeIngestion", () => {
2894 type: "user-input.resolved",
2895 eventId: asEventId("evt-user-input-resolved"),
2896 provider: ProviderDriverKind.make("codex"),
2889 - createdAt: new Date().toISOString(),
2897 + createdAt: "2026-01-01T00:00:00.000Z",
2898 threadId: asThreadId("thread-1"),
2899 turnId: asTurnId("turn-user-input"),
2900 requestId: ApprovalRequestId.make("req-user-input-1"),
@@ -2928,7 +2936,7 @@ describe("ProviderRuntimeIngestion", () => {
2936
2937 it("continues processing runtime events after a single event handler failure", async () => {
2938 const harness = await createHarness();
2931 - const now = new Date().toISOString();
2939 + const now = "2026-01-01T00:00:00.000Z";
2940
2941 harness.emit({
2942 type: "content.delta",
@@ -2948,7 +2956,7 @@ describe("ProviderRuntimeIngestion", () => {
2956 type: "runtime.error",
2957 eventId: asEventId("evt-runtime-error-after-failure"),
2958 provider: ProviderDriverKind.make("codex"),
2951 - createdAt: new Date().toISOString(),
2959 + createdAt: "2026-01-01T00:00:00.000Z",
2960 threadId: asThreadId("thread-1"),
2961 turnId: asTurnId("turn-after-failure"),
2962 payload: {
apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
+7 -1
@@ -17,7 +17,13 @@ import {
17 type OrchestrationThreadActivity,
18 type ProviderRuntimeEvent,
19 } from "@t3tools/contracts";
20 -import { Cache, Cause, Duration, Effect, Layer, Option, Stream } from "effect";
20 +import * as Cache from "effect/Cache";
21 +import * as Cause from "effect/Cause";
22 +import * as Duration from "effect/Duration";
23 +import * as Effect from "effect/Effect";
24 +import * as Layer from "effect/Layer";
25 +import * as Option from "effect/Option";
26 +import * as Stream from "effect/Stream";
27 import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
28
29 import { ProviderService } from "../../provider/Services/ProviderService.ts";
apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts
+4 -1
@@ -8,7 +8,10 @@
8 *
9 * @module RuntimeReceiptBus
10 */
11 -import { Effect, Layer, PubSub, Stream } from "effect";
11 +import * as Effect from "effect/Effect";
12 +import * as Layer from "effect/Layer";
13 +import * as PubSub from "effect/PubSub";
14 +import * as Stream from "effect/Stream";
15
16 import {
17 RuntimeReceiptBus,
apps/server/src/orchestration/Layers/ThreadDeletionReactor.test.ts
+3 -1
@@ -1,5 +1,7 @@
1 import { ThreadId } from "@t3tools/contracts";
2 -import { Cause, Effect, Exit } from "effect";
2 +import * as Cause from "effect/Cause";
3 +import * as Effect from "effect/Effect";
4 +import * as Exit from "effect/Exit";
5 import { describe, expect, it } from "vitest";
6
7 import { logCleanupCauseUnlessInterrupted } from "./ThreadDeletionReactor.ts";
apps/server/src/orchestration/Layers/ThreadDeletionReactor.ts
+4 -1
@@ -1,6 +1,9 @@
1 import type { OrchestrationEvent } from "@t3tools/contracts";
2 import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
3 -import { Cause, Effect, Layer, Stream } from "effect";
3 +import * as Cause from "effect/Cause";
4 +import * as Effect from "effect/Effect";
5 +import * as Layer from "effect/Layer";
6 +import * as Stream from "effect/Stream";
7
8 import { ProviderService } from "../../provider/Services/ProviderService.ts";
9 import { TerminalManager } from "../../terminal/Services/Manager.ts";
apps/server/src/orchestration/Normalizer.ts
+3 -1
@@ -1,4 +1,6 @@
1 -import { Effect, FileSystem, Path } from "effect";
1 +import * as Effect from "effect/Effect";
2 +import * as FileSystem from "effect/FileSystem";
3 +import * as Path from "effect/Path";
4 import {
5 type ClientOrchestrationCommand,
6 type OrchestrationCommand,
apps/server/src/orchestration/Services/CheckpointReactor.ts
+3 -2
@@ -6,8 +6,9 @@
6 *
7 * @module CheckpointReactor
8 */
9 -import { Context } from "effect";
10 -import type { Effect, Scope } from "effect";
9 +import * as Context from "effect/Context";
10 +import type * as Effect from "effect/Effect";
11 +import type * as Scope from "effect/Scope";
12
13 /**
14 * CheckpointReactorShape - Service API for checkpoint reactor lifecycle.
apps/server/src/orchestration/Services/OrchestrationEngine.ts
+3 -2
@@ -11,8 +11,9 @@
11 * @module OrchestrationEngineService
12 */
13 import type { OrchestrationCommand, OrchestrationEvent } from "@t3tools/contracts";
14 -import { Context } from "effect";
15 -import type { Effect, Stream } from "effect";
14 +import * as Context from "effect/Context";
15 +import type * as Effect from "effect/Effect";
16 +import type * as Stream from "effect/Stream";
17
18 import type { OrchestrationDispatchError } from "../Errors.ts";
19 import type { OrchestrationEventStoreError } from "../../persistence/Errors.ts";
apps/server/src/orchestration/Services/OrchestrationReactor.ts
+3 -2
@@ -6,8 +6,9 @@
6 *
7 * @module OrchestrationReactor
8 */
9 -import { Context } from "effect";
10 -import type { Effect, Scope } from "effect";
9 +import * as Context from "effect/Context";
10 +import type * as Effect from "effect/Effect";
11 +import type * as Scope from "effect/Scope";
12
13 /**
14 * OrchestrationReactorShape - Service API for orchestration reactor lifecycle.
apps/server/src/orchestration/Services/ProjectionPipeline.ts
+2 -2
@@ -7,8 +7,8 @@
7 * @module OrchestrationProjectionPipeline
8 */
9 import type { OrchestrationEvent } from "@t3tools/contracts";
10 -import { Context } from "effect";
11 -import type { Effect } from "effect";
10 +import * as Context from "effect/Context";
11 +import type * as Effect from "effect/Effect";
12
13 import type { ProjectionRepositoryError } from "../../persistence/Errors.ts";
14
apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts
+3 -3
@@ -17,9 +17,9 @@ import type {
17 ProjectId,
18 ThreadId,
19 } from "@t3tools/contracts";
20 -import { Context } from "effect";
21 -import type { Option } from "effect";
22 -import type { Effect } from "effect";
20 +import * as Context from "effect/Context";
21 +import type * as Option from "effect/Option";
22 +import type * as Effect from "effect/Effect";
23
24 import type { ProjectionRepositoryError } from "../../persistence/Errors.ts";
25
apps/server/src/orchestration/Services/ProviderCommandReactor.ts
+3 -2
@@ -6,8 +6,9 @@
6 *
7 * @module ProviderCommandReactor
8 */
9 -import { Context } from "effect";
10 -import type { Effect, Scope } from "effect";
9 +import * as Context from "effect/Context";
10 +import type * as Effect from "effect/Effect";
11 +import type * as Scope from "effect/Scope";
12
13 /**
14 * ProviderCommandReactorShape - Service API for provider command reactors.
apps/server/src/orchestration/Services/ProviderRuntimeIngestion.ts
+3 -2
@@ -6,8 +6,9 @@
6 *
7 * @module ProviderRuntimeIngestionService
8 */
9 -import { Context } from "effect";
10 -import type { Effect, Scope } from "effect";
9 +import * as Context from "effect/Context";
10 +import type * as Effect from "effect/Effect";
11 +import type * as Scope from "effect/Scope";
12
13 /**
14 * ProviderRuntimeIngestionShape - Service API for runtime ingestion lifecycle.
apps/server/src/orchestration/Services/RuntimeReceiptBus.ts
+4 -2
@@ -15,8 +15,10 @@
15 * @module RuntimeReceiptBus
16 */
17 import { CheckpointRef, IsoDateTime, NonNegativeInt, ThreadId, TurnId } from "@t3tools/contracts";
18 -import { Schema, Context } from "effect";
19 -import type { Effect, Stream } from "effect";
18 +import * as Schema from "effect/Schema";
19 +import * as Context from "effect/Context";
20 +import type * as Effect from "effect/Effect";
21 +import type * as Stream from "effect/Stream";
22
23 export const CheckpointBaselineCapturedReceipt = Schema.Struct({
24 type: Schema.Literal("checkpoint.baseline.captured"),
apps/server/src/orchestration/Services/ThreadDeletionReactor.ts
+3 -2
@@ -6,8 +6,9 @@
6 *
7 * @module ThreadDeletionReactor
8 */
9 -import { Context } from "effect";
10 -import type { Effect, Scope } from "effect";
9 +import * as Context from "effect/Context";
10 +import type * as Effect from "effect/Effect";
11 +import type * as Scope from "effect/Scope";
12
13 /**
14 * ThreadDeletionReactorShape - Service API for thread deletion cleanup.
apps/server/src/orchestration/commandInvariants.test.ts
+2 -2
@@ -9,7 +9,7 @@ import {
9 type OrchestrationReadModel,
10 ProviderInstanceId,
11 } from "@t3tools/contracts";
12 -import { Effect } from "effect";
12 +import * as Effect from "effect/Effect";
13
14 import {
15 findThreadById,
@@ -19,7 +19,7 @@ import {
19 requireThreadAbsent,
20 } from "./commandInvariants.ts";
21
22 -const now = new Date().toISOString();
22 +const now = "2026-01-01T00:00:00.000Z";
23
24 const readModel: OrchestrationReadModel = {
25 snapshotSequence: 2,
apps/server/src/orchestration/commandInvariants.ts
+1 -1
@@ -6,7 +6,7 @@ import type {
6 ProjectId,
7 ThreadId,
8 } from "@t3tools/contracts";
9 -import { Effect } from "effect";
9 +import * as Effect from "effect/Effect";
10
11 import { OrchestrationCommandInvariantError } from "./Errors.ts";
12
apps/server/src/orchestration/decider.delete.test.ts
+2 -2
@@ -9,7 +9,7 @@ import {
9 type OrchestrationReadModel,
10 ProviderInstanceId,
11 } from "@t3tools/contracts";
12 -import { Effect } from "effect";
12 +import * as Effect from "effect/Effect";
13 import { describe, expect, it } from "vitest";
14
15 import { decideOrchestrationCommand } from "./decider.ts";
@@ -21,7 +21,7 @@ const asProjectId = (value: string): ProjectId => ProjectId.make(value);
21 const asThreadId = (value: string): ThreadId => ThreadId.make(value);
22
23 async function seedReadModel(): Promise<OrchestrationReadModel> {
24 - const now = new Date().toISOString();
24 + const now = "2026-01-01T00:00:00.000Z";
25 const initial = createEmptyReadModel(now);
26 const withProject = await Effect.runPromise(
27 projectEvent(initial, {
apps/server/src/orchestration/decider.projectScripts.test.ts
+6 -6
@@ -9,7 +9,7 @@ import {
9 } from "@t3tools/contracts";
10 import { createModelSelection } from "@t3tools/shared/model";
11 import { describe, expect, it } from "vitest";
12 -import { Effect } from "effect";
12 +import * as Effect from "effect/Effect";
13
14 import { decideOrchestrationCommand } from "./decider.ts";
15 import { createEmptyReadModel, projectEvent } from "./projector.ts";
@@ -20,7 +20,7 @@ const asMessageId = (value: string): MessageId => MessageId.make(value);
20
21 describe("decider project scripts", () => {
22 it("emits empty scripts on project.create", async () => {
23 - const now = new Date().toISOString();
23 + const now = "2026-01-01T00:00:00.000Z";
24 const readModel = createEmptyReadModel(now);
25
26 const result = await Effect.runPromise(
@@ -43,7 +43,7 @@ describe("decider project scripts", () => {
43 });
44
45 it("propagates scripts in project.meta.update payload", async () => {
46 - const now = new Date().toISOString();
46 + const now = "2026-01-01T00:00:00.000Z";
47 const initial = createEmptyReadModel(now);
48 const readModel = await Effect.runPromise(
49 projectEvent(initial, {
@@ -97,7 +97,7 @@ describe("decider project scripts", () => {
97 });
98
99 it("emits user message and turn-start-requested events for thread.turn.start", async () => {
100 - const now = new Date().toISOString();
100 + const now = "2026-01-01T00:00:00.000Z";
101 const initial = createEmptyReadModel(now);
102 const withProject = await Effect.runPromise(
103 projectEvent(initial, {
@@ -198,7 +198,7 @@ describe("decider project scripts", () => {
198 });
199
200 it("emits thread.runtime-mode-set from thread.runtime-mode.set", async () => {
201 - const now = new Date().toISOString();
201 + const now = "2026-01-01T00:00:00.000Z";
202 const initial = createEmptyReadModel(now);
203 const withProject = await Effect.runPromise(
204 projectEvent(initial, {
@@ -280,7 +280,7 @@ describe("decider project scripts", () => {
280 });
281
282 it("emits thread.interaction-mode-set from thread.interaction-mode.set", async () => {
283 - const now = new Date().toISOString();
283 + const now = "2026-01-01T00:00:00.000Z";
284 const initial = createEmptyReadModel(now);
285 const withProject = await Effect.runPromise(
286 projectEvent(initial, {
apps/server/src/orchestration/decider.ts
+11 -10
@@ -3,7 +3,8 @@ import type {
3 OrchestrationEvent,
4 OrchestrationReadModel,
5 } from "@t3tools/contracts";
6 -import { DateTime, Effect } from "effect";
6 +import * as DateTime from "effect/DateTime";
7 +import * as Effect from "effect/Effect";
8
9 import { OrchestrationCommandInvariantError } from "./Errors.ts";
10 import {
@@ -17,7 +18,7 @@ import {
18 } from "./commandInvariants.ts";
19 import { projectEvent } from "./projector.ts";
20
20 -const currentIso = DateTime.now.pipe(Effect.map(DateTime.formatIso));
21 +const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
22
23 function withEventBase(
24 input: Pick<OrchestrationCommand, "commandId"> & {
@@ -116,7 +117,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
117 command,
118 projectId: command.projectId,
119 });
119 - const occurredAt = yield* currentIso;
120 + const occurredAt = yield* nowIso;
121 return {
122 ...withEventBase({
123 aggregateKind: "project",
@@ -173,7 +174,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
174 });
175 }
176
176 - const occurredAt = yield* currentIso;
177 + const occurredAt = yield* nowIso;
178 return {
179 ...withEventBase({
180 aggregateKind: "project",
@@ -229,7 +230,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
230 command,
231 threadId: command.threadId,
232 });
232 - const occurredAt = yield* currentIso;
233 + const occurredAt = yield* nowIso;
234 return {
235 ...withEventBase({
236 aggregateKind: "thread",
@@ -251,7 +252,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
252 command,
253 threadId: command.threadId,
254 });
254 - const occurredAt = yield* currentIso;
255 + const occurredAt = yield* nowIso;
256 return {
257 ...withEventBase({
258 aggregateKind: "thread",
@@ -274,7 +275,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
275 command,
276 threadId: command.threadId,
277 });
277 - const occurredAt = yield* currentIso;
278 + const occurredAt = yield* nowIso;
279 return {
280 ...withEventBase({
281 aggregateKind: "thread",
@@ -296,7 +297,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
297 command,
298 threadId: command.threadId,
299 });
299 - const occurredAt = yield* currentIso;
300 + const occurredAt = yield* nowIso;
301 return {
302 ...withEventBase({
303 aggregateKind: "thread",
@@ -324,7 +325,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
325 command,
326 threadId: command.threadId,
327 });
327 - const occurredAt = yield* currentIso;
328 + const occurredAt = yield* nowIso;
329 return {
330 ...withEventBase({
331 aggregateKind: "thread",
@@ -347,7 +348,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
348 command,
349 threadId: command.threadId,
350 });
350 - const occurredAt = yield* currentIso;
351 + const occurredAt = yield* nowIso;
352 return {
353 ...withEventBase({
354 aggregateKind: "thread",
apps/server/src/orchestration/http.ts
+1 -1
@@ -4,7 +4,7 @@ import {
4 OrchestrationGetSnapshotError,
5 type OrchestrationReadModel,
6 } from "@t3tools/contracts";
7 -import { Effect } from "effect";
7 +import * as Effect from "effect/Effect";
8 import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
9
10 import { ServerAuth } from "../auth/Services/ServerAuth.ts";
apps/server/src/orchestration/projector.test.ts
+6 -6
@@ -6,7 +6,7 @@ import {
6 ThreadId,
7 type OrchestrationEvent,
8 } from "@t3tools/contracts";
9 -import { Effect } from "effect";
9 +import * as Effect from "effect/Effect";
10 import { describe, expect, it } from "vitest";
11
12 import { createEmptyReadModel, projectEvent } from "./projector.ts";
@@ -40,7 +40,7 @@ function makeEvent(input: {
40
41 describe("orchestration projector", () => {
42 it("applies thread.created events", async () => {
43 - const now = new Date().toISOString();
43 + const now = "2026-01-01T00:00:00.000Z";
44 const model = createEmptyReadModel(now);
45
46 const next = await Effect.runPromise(
@@ -100,7 +100,7 @@ describe("orchestration projector", () => {
100 });
101
102 it("fails when event payload cannot be decoded by runtime schema", async () => {
103 - const now = new Date().toISOString();
103 + const now = "2026-01-01T00:00:00.000Z";
104 const model = createEmptyReadModel(now);
105
106 await expect(
@@ -134,8 +134,8 @@ describe("orchestration projector", () => {
134 });
135
136 it("applies thread.archived and thread.unarchived events", async () => {
137 - const now = new Date().toISOString();
138 - const later = new Date(Date.parse(now) + 1_000).toISOString();
137 + const now = "2026-01-01T00:00:00.000Z";
138 + const later = "2026-01-01T00:00:01.000Z";
139 const created = await Effect.runPromise(
140 projectEvent(
141 createEmptyReadModel(now),
@@ -206,7 +206,7 @@ describe("orchestration projector", () => {
206 });
207
208 it("keeps projector forward-compatible for unhandled event types", async () => {
209 - const now = new Date().toISOString();
209 + const now = "2026-01-01T00:00:00.000Z";
210 const model = createEmptyReadModel(now);
211
212 const next = await Effect.runPromise(
apps/server/src/orchestration/projector.ts
+2 -1
@@ -5,7 +5,8 @@ import {
5 OrchestrationSession,
6 OrchestrationThread,
7 } from "@t3tools/contracts";
8 -import { Effect, Schema } from "effect";
8 +import * as Effect from "effect/Effect";
9 +import * as Schema from "effect/Schema";
10
11 import { toProjectorDecodeError, type OrchestrationProjectorDecodeError } from "./Errors.ts";
12 import {
apps/server/src/orchestration/runtimeLayer.ts
+1 -1
@@ -1,4 +1,4 @@
1 -import { Layer } from "effect";
1 +import * as Layer from "effect/Layer";
2
3 import { OrchestrationCommandReceiptRepositoryLive } from "../persistence/Layers/OrchestrationCommandReceipts.ts";
4 import { OrchestrationEventStoreLive } from "../persistence/Layers/OrchestrationEventStore.ts";
apps/server/src/os-jank.test.ts deleted
-185
@@ -1,185 +0,0 @@
1 -import { describe, expect, it, vi } from "vitest";
2 -
3 -import { fixPath } from "./os-jank.ts";
4 -
5 -describe("fixPath", () => {
6 - it("hydrates PATH on linux using the resolved login shell", () => {
7 - const env: NodeJS.ProcessEnv = {
8 - SHELL: "/bin/zsh",
9 - PATH: "/Users/test/.local/bin:/usr/bin",
10 - };
11 - const readPath = vi.fn(() => "/opt/homebrew/bin:/usr/bin");
12 -
13 - fixPath({
14 - env,
15 - platform: "linux",
16 - readPath,
17 - });
18 -
19 - expect(readPath).toHaveBeenCalledWith("/bin/zsh");
20 - expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin:/Users/test/.local/bin");
21 - });
22 -
23 - it("falls back to launchctl PATH on macOS when shell probing fails", () => {
24 - const env: NodeJS.ProcessEnv = {
25 - SHELL: "/opt/homebrew/bin/nu",
26 - PATH: "/usr/bin",
27 - };
28 - const readPath = vi
29 - .fn()
30 - .mockImplementationOnce(() => {
31 - throw new Error("unknown flag");
32 - })
33 - .mockImplementationOnce(() => undefined);
34 - const readLaunchctlPath = vi.fn(() => "/opt/homebrew/bin:/usr/bin");
35 - const logWarning = vi.fn();
36 -
37 - fixPath({
38 - env,
39 - platform: "darwin",
40 - readPath,
41 - readLaunchctlPath,
42 - userShell: "/bin/zsh",
43 - logWarning,
44 - });
45 -
46 - expect(readPath).toHaveBeenNthCalledWith(1, "/opt/homebrew/bin/nu");
47 - expect(readPath).toHaveBeenNthCalledWith(2, "/bin/zsh");
48 - expect(readLaunchctlPath).toHaveBeenCalledTimes(1);
49 - expect(logWarning).toHaveBeenCalledWith(
50 - "Failed to read PATH from login shell /opt/homebrew/bin/nu.",
51 - expect.any(Error),
52 - );
53 - expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
54 - });
55 -
56 - it("repairs PATH on Windows by merging PowerShell PATH with inherited PATH", () => {
57 - const env: NodeJS.ProcessEnv = {
58 - PATH: "C:\\Windows\\System32",
59 - APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
60 - LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
61 - USERPROFILE: "C:\\Users\\testuser",
62 - };
63 - const readWindowsEnvironment = vi.fn(() => ({
64 - PATH: "C:\\Custom\\Bin;C:\\Windows\\System32",
65 - }));
66 - const isWindowsCommandAvailable = vi.fn(() => true);
67 -
68 - fixPath({
69 - env,
70 - platform: "win32",
71 - readWindowsEnvironment,
72 - isWindowsCommandAvailable,
73 - });
74 -
75 - expect(readWindowsEnvironment).toHaveBeenCalledWith(["PATH"], { loadProfile: false });
76 - expect(env.PATH).toBe(
77 - [
78 - "C:\\Users\\testuser\\AppData\\Roaming\\npm",
79 - "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
80 - "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
81 - "C:\\Users\\testuser\\AppData\\Local\\pnpm",
82 - "C:\\Users\\testuser\\.bun\\bin",
83 - "C:\\Users\\testuser\\scoop\\shims",
84 - "C:\\Custom\\Bin",
85 - "C:\\Windows\\System32",
86 - ].join(";"),
87 - );
88 - });
89 -
90 - it("applies profile-derived fnm variables on Windows when node is missing", () => {
91 - const env: NodeJS.ProcessEnv = {
92 - PATH: "C:\\Windows\\System32",
93 - APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
94 - LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
95 - USERPROFILE: "C:\\Users\\testuser",
96 - };
97 - const readWindowsEnvironment = vi.fn(
98 - (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
99 - options?.loadProfile
100 - ? {
101 - PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
102 - FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
103 - FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
104 - }
105 - : { PATH: "C:\\Custom\\Bin;C:\\Windows\\System32" },
106 - );
107 - const isWindowsCommandAvailable = vi.fn().mockReturnValueOnce(false).mockReturnValueOnce(true);
108 -
109 - fixPath({
110 - env,
111 - platform: "win32",
112 - readWindowsEnvironment,
113 - isWindowsCommandAvailable,
114 - });
115 -
116 - expect(env.PATH).toBe(
117 - [
118 - "C:\\Profile\\Node",
119 - "C:\\Windows\\System32",
120 - "C:\\Users\\testuser\\AppData\\Roaming\\npm",
121 - "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
122 - "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
123 - "C:\\Users\\testuser\\AppData\\Local\\pnpm",
124 - "C:\\Users\\testuser\\.bun\\bin",
125 - "C:\\Users\\testuser\\scoop\\shims",
126 - "C:\\Custom\\Bin",
127 - ].join(";"),
128 - );
129 - expect(env.FNM_DIR).toBe("C:\\Users\\testuser\\AppData\\Roaming\\fnm");
130 - expect(env.FNM_MULTISHELL_PATH).toBe(
131 - "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
132 - );
133 - });
134 -
135 - it("preserves baseline PATH on Windows when the profile probe fails", () => {
136 - const env: NodeJS.ProcessEnv = {
137 - PATH: "C:\\Windows\\System32",
138 - APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
139 - USERPROFILE: "C:\\Users\\testuser",
140 - };
141 - const readWindowsEnvironment = vi.fn(
142 - (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) => {
143 - if (options?.loadProfile) {
144 - throw new Error("profile load failed");
145 - }
146 - return { PATH: "C:\\Custom\\Bin;C:\\Windows\\System32" };
147 - },
148 - );
149 - const isWindowsCommandAvailable = vi.fn(() => false);
150 -
151 - fixPath({
152 - env,
153 - platform: "win32",
154 - readWindowsEnvironment,
155 - isWindowsCommandAvailable,
156 - });
157 -
158 - expect(env.PATH).toBe(
159 - [
160 - "C:\\Users\\testuser\\AppData\\Roaming\\npm",
161 - "C:\\Users\\testuser\\.bun\\bin",
162 - "C:\\Users\\testuser\\scoop\\shims",
163 - "C:\\Custom\\Bin",
164 - "C:\\Windows\\System32",
165 - ].join(";"),
166 - );
167 - });
168 -
169 - it("does nothing on unsupported platforms", () => {
170 - const env: NodeJS.ProcessEnv = {
171 - SHELL: "C:/Program Files/Git/bin/bash.exe",
172 - PATH: "C:\\Windows\\System32",
173 - };
174 - const readPath = vi.fn(() => "/usr/local/bin:/usr/bin");
175 -
176 - fixPath({
177 - env,
178 - platform: "freebsd",
179 - readPath,
180 - });
181 -
182 - expect(readPath).not.toHaveBeenCalled();
183 - expect(env.PATH).toBe("C:\\Windows\\System32");
184 - });
185 -});
apps/server/src/os-jank.ts
+9 -6
@@ -1,5 +1,6 @@
1 -import * as OS from "node:os";
2 -import { Effect, Path } from "effect";
1 +import * as NodeOS from "node:os";
2 +import * as Effect from "effect/Effect";
3 +import * as Path from "effect/Path";
4 import {
5 readPathFromLoginShell,
6 readEnvironmentFromWindowsShell,
@@ -17,7 +18,9 @@ type WindowsCommandAvailabilityChecker = (
18 ) => boolean;
19
20 function logPathHydrationWarning(message: string, error?: unknown): void {
20 - console.warn(`[server] ${message}`, error instanceof Error ? error.message : (error ?? ""));
21 + process.stderr.write(
22 + `[server] ${message} ${error instanceof Error ? error.message : (error ?? "")}\n`,
23 + );
24 }
25
26 export function fixPath(
@@ -84,10 +87,10 @@ export function fixPath(
87 export const expandHomePath = Effect.fn(function* (input: string) {
88 const { join } = yield* Path.Path;
89 if (input === "~") {
87 - return OS.homedir();
90 + return NodeOS.homedir();
91 }
92 if (input.startsWith("~/") || input.startsWith("~\\")) {
90 - return join(OS.homedir(), input.slice(2));
93 + return join(NodeOS.homedir(), input.slice(2));
94 }
95 return input;
96 });
@@ -95,7 +98,7 @@ export const expandHomePath = Effect.fn(function* (input: string) {
98 export const resolveBaseDir = Effect.fn(function* (raw: string | undefined) {
99 const { join, resolve } = yield* Path.Path;
100 if (!raw || raw.trim().length === 0) {
98 - return join(OS.homedir(), ".t3");
101 + return join(NodeOS.homedir(), ".t3");
102 }
103 return resolve(yield* expandHomePath(raw.trim()));
104 });
apps/server/src/pathExpansion.test.ts
+1
@@ -1,3 +1,4 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 import { homedir } from "node:os";
3 import { join } from "node:path";
4 import { describe, expect, it } from "vitest";
apps/server/src/pathExpansion.ts
+1
@@ -1,3 +1,4 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 import { homedir } from "node:os";
3 import { join } from "node:path";
4
apps/server/src/persistence/Errors.ts
+2 -1
@@ -1,4 +1,5 @@
1 -import { Schema, SchemaIssue } from "effect";
1 +import * as Schema from "effect/Schema";
2 +import * as SchemaIssue from "effect/SchemaIssue";
3
4 // ===============================
5 // Core Persistence Errors
apps/server/src/persistence/Layers/AuthPairingLinks.ts
+3 -1
@@ -1,6 +1,8 @@
1 import * as SqlClient from "effect/unstable/sql/SqlClient";
2 import * as SqlSchema from "effect/unstable/sql/SqlSchema";
3 -import { Effect, Layer, Schema } from "effect";
3 +import * as Effect from "effect/Effect";
4 +import * as Layer from "effect/Layer";
5 +import * as Schema from "effect/Schema";
6
7 import {
8 toPersistenceDecodeError,
apps/server/src/persistence/Layers/AuthSessions.ts
+4 -1
@@ -1,7 +1,10 @@
1 import { AuthSessionId } from "@t3tools/contracts";
2 import * as SqlClient from "effect/unstable/sql/SqlClient";
3 import * as SqlSchema from "effect/unstable/sql/SqlSchema";
4 -import { Effect, Layer, Option, Schema } from "effect";
4 +import * as Effect from "effect/Effect";
5 +import * as Layer from "effect/Layer";
6 +import * as Option from "effect/Option";
7 +import * as Schema from "effect/Schema";
8
9 import {
10 toPersistenceDecodeError,
apps/server/src/persistence/Layers/OrchestrationCommandReceipts.ts
+2 -1
@@ -1,6 +1,7 @@
1 import * as SqlClient from "effect/unstable/sql/SqlClient";
2 import * as SqlSchema from "effect/unstable/sql/SqlSchema";
3 -import { Effect, Layer } from "effect";
3 +import * as Effect from "effect/Effect";
4 +import * as Layer from "effect/Layer";
5
6 import { toPersistenceSqlError } from "../Errors.ts";
7
apps/server/src/persistence/Layers/OrchestrationEventStore.test.ts
+6 -3
@@ -1,6 +1,9 @@
1 import { CommandId, EventId, ProjectId } from "@t3tools/contracts";
2 import { assert, it } from "@effect/vitest";
3 -import { Effect, Layer, Schema, Stream } from "effect";
3 +import * as Effect from "effect/Effect";
4 +import * as Layer from "effect/Layer";
5 +import * as Schema from "effect/Schema";
6 +import * as Stream from "effect/Stream";
7 import * as SqlClient from "effect/unstable/sql/SqlClient";
8
9 import { PersistenceDecodeError } from "../Errors.ts";
@@ -17,7 +20,7 @@ layer("OrchestrationEventStore", (it) => {
20 Effect.gen(function* () {
21 const eventStore = yield* OrchestrationEventStore;
22 const sql = yield* SqlClient.SqlClient;
20 - const now = new Date().toISOString();
23 + const now = "2026-01-01T00:00:00.000Z";
24
25 const appended = yield* eventStore.append({
26 type: "project.created",
@@ -69,7 +72,7 @@ layer("OrchestrationEventStore", (it) => {
72 Effect.gen(function* () {
73 const eventStore = yield* OrchestrationEventStore;
74 const sql = yield* SqlClient.SqlClient;
72 - const now = new Date().toISOString();
75 + const now = "2026-01-01T00:00:00.000Z";
76
77 yield* sql`
78 INSERT INTO orchestration_events (
apps/server/src/persistence/Layers/OrchestrationEventStore.ts
+4 -1
@@ -13,7 +13,10 @@ import {
13 } from "@t3tools/contracts";
14 import * as SqlClient from "effect/unstable/sql/SqlClient";
15 import * as SqlSchema from "effect/unstable/sql/SqlSchema";
16 -import { Effect, Layer, Schema, Stream } from "effect";
16 +import * as Effect from "effect/Effect";
17 +import * as Layer from "effect/Layer";
18 +import * as Schema from "effect/Schema";
19 +import * as Stream from "effect/Stream";
20
21 import {
22 toPersistenceDecodeError,
apps/server/src/persistence/Layers/ProjectionCheckpoints.ts
+5 -1
@@ -1,7 +1,11 @@
1 import { OrchestrationCheckpointFile } from "@t3tools/contracts";
2 import * as SqlClient from "effect/unstable/sql/SqlClient";
3 import * as SqlSchema from "effect/unstable/sql/SqlSchema";
4 -import { Effect, Layer, Option, Schema, Struct } from "effect";
4 +import * as Effect from "effect/Effect";
5 +import * as Layer from "effect/Layer";
6 +import * as Option from "effect/Option";
7 +import * as Schema from "effect/Schema";
8 +import * as Struct from "effect/Struct";
9
10 import { toPersistenceDecodeError, toPersistenceSqlError } from "../Errors.ts";
11 import {
apps/server/src/persistence/Layers/ProjectionPendingApprovals.ts
+2 -1
@@ -1,6 +1,7 @@
1 import * as SqlClient from "effect/unstable/sql/SqlClient";
2 import * as SqlSchema from "effect/unstable/sql/SqlSchema";
3 -import { Effect, Layer } from "effect";
3 +import * as Effect from "effect/Effect";
4 +import * as Layer from "effect/Layer";
5
6 import { toPersistenceSqlError } from "../Errors.ts";
7 import {
apps/server/src/persistence/Layers/ProjectionProjects.ts
+4 -1
@@ -1,6 +1,9 @@
1 import * as SqlClient from "effect/unstable/sql/SqlClient";
2 import * as SqlSchema from "effect/unstable/sql/SqlSchema";
3 -import { Effect, Layer, Schema, Struct } from "effect";
3 +import * as Effect from "effect/Effect";
4 +import * as Layer from "effect/Layer";
5 +import * as Schema from "effect/Schema";
6 +import * as Struct from "effect/Struct";
7
8 import { ModelSelection, ProjectScript } from "@t3tools/contracts";
9 import { toPersistenceSqlError } from "../Errors.ts";
apps/server/src/persistence/Layers/ProjectionRepositories.test.ts
+7 -3
@@ -1,6 +1,8 @@
1 import { ProjectId, ThreadId, ProviderInstanceId } from "@t3tools/contracts";
2 import { assert, it } from "@effect/vitest";
3 -import { Effect, Layer, Option } from "effect";
3 +import * as Effect from "effect/Effect";
4 +import * as Layer from "effect/Layer";
5 +import * as Option from "effect/Option";
6 import * as SqlClient from "effect/unstable/sql/SqlClient";
7
8 import { SqlitePersistenceMemory } from "./Sqlite.ts";
@@ -46,11 +48,12 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
48 `;
49 const row = rows[0];
50 if (!row) {
49 - return yield* Effect.fail(new Error("Expected projection_projects row to exist."));
51 + return yield* Effect.die("Expected projection_projects row to exist.");
52 }
53
54 assert.strictEqual(
55 row.defaultModelSelection,
56 + // @effect-diagnostics-next-line preferSchemaOverJson:off
57 JSON.stringify({
58 instanceId: ProviderInstanceId.make("codex"),
59 model: "gpt-5.4",
@@ -104,11 +107,12 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
107 `;
108 const row = rows[0];
109 if (!row) {
107 - return yield* Effect.fail(new Error("Expected projection_threads row to exist."));
110 + return yield* Effect.die("Expected projection_threads row to exist.");
111 }
112
113 assert.strictEqual(
114 row.modelSelection,
115 + // @effect-diagnostics-next-line preferSchemaOverJson:off
116 JSON.stringify({
117 instanceId: ProviderInstanceId.make("claudeAgent"),
118 model: "claude-opus-4-6",
apps/server/src/persistence/Layers/ProjectionState.ts
+3 -1
@@ -1,7 +1,9 @@
1 import { NonNegativeInt } from "@t3tools/contracts";
2 import * as SqlClient from "effect/unstable/sql/SqlClient";
3 import * as SqlSchema from "effect/unstable/sql/SqlSchema";
4 -import { Effect, Layer, Schema } from "effect";
4 +import * as Effect from "effect/Effect";
5 +import * as Layer from "effect/Layer";
6 +import * as Schema from "effect/Schema";
7
8 import { toPersistenceSqlError } from "../Errors.ts";
9
apps/server/src/persistence/Layers/ProjectionThreadActivities.ts
+4 -1
@@ -1,7 +1,10 @@
1 import * as SqlClient from "effect/unstable/sql/SqlClient";
2 import * as SqlSchema from "effect/unstable/sql/SqlSchema";
3 import { NonNegativeInt } from "@t3tools/contracts";
4 -import { Effect, Layer, Schema, Struct } from "effect";
4 +import * as Effect from "effect/Effect";
5 +import * as Layer from "effect/Layer";
6 +import * as Schema from "effect/Schema";
7 +import * as Struct from "effect/Struct";
8
9 import { toPersistenceDecodeError, toPersistenceSqlError } from "../Errors.ts";
10
apps/server/src/persistence/Layers/ProjectionThreadMessages.test.ts
+2 -1
@@ -1,6 +1,7 @@
1 import { MessageId, ThreadId } from "@t3tools/contracts";
2 import { assert, it } from "@effect/vitest";
3 -import { Effect, Layer } from "effect";
3 +import * as Effect from "effect/Effect";
4 +import * as Layer from "effect/Layer";
5
6 import { ProjectionThreadMessageRepository } from "../Services/ProjectionThreadMessages.ts";
7 import { ProjectionThreadMessageRepositoryLive } from "./ProjectionThreadMessages.ts";
apps/server/src/persistence/Layers/ProjectionThreadMessages.ts
+5 -1
@@ -1,6 +1,10 @@
1 import * as SqlClient from "effect/unstable/sql/SqlClient";
2 import * as SqlSchema from "effect/unstable/sql/SqlSchema";
3 -import { Effect, Layer, Option, Schema, Struct } from "effect";
3 +import * as Effect from "effect/Effect";
4 +import * as Layer from "effect/Layer";
5 +import * as Option from "effect/Option";
6 +import * as Schema from "effect/Schema";
7 +import * as Struct from "effect/Struct";
8 import { ChatAttachment } from "@t3tools/contracts";
9
10 import { toPersistenceSqlError } from "../Errors.ts";
apps/server/src/persistence/Layers/ProjectionThreadProposedPlans.ts
+2 -1
@@ -1,4 +1,5 @@
1 -import { Effect, Layer } from "effect";
1 +import * as Effect from "effect/Effect";
2 +import * as Layer from "effect/Layer";
3 import * as SqlClient from "effect/unstable/sql/SqlClient";
4 import * as SqlSchema from "effect/unstable/sql/SqlSchema";
5
apps/server/src/persistence/Layers/ProjectionThreadSessions.ts
+2 -1
@@ -1,6 +1,7 @@
1 import * as SqlClient from "effect/unstable/sql/SqlClient";
2 import * as SqlSchema from "effect/unstable/sql/SqlSchema";
3 -import { Effect, Layer } from "effect";
3 +import * as Effect from "effect/Effect";
4 +import * as Layer from "effect/Layer";
5
6 import { toPersistenceSqlError } from "../Errors.ts";
7
apps/server/src/persistence/Layers/ProjectionThreads.ts
+4 -1
@@ -1,6 +1,9 @@
1 import * as SqlClient from "effect/unstable/sql/SqlClient";
2 import * as SqlSchema from "effect/unstable/sql/SqlSchema";
3 -import { Effect, Layer, Schema, Struct } from "effect";
3 +import * as Effect from "effect/Effect";
4 +import * as Layer from "effect/Layer";
5 +import * as Schema from "effect/Schema";
6 +import * as Struct from "effect/Struct";
7
8 import { toPersistenceSqlError } from "../Errors.ts";
9 import {
apps/server/src/persistence/Layers/ProjectionTurns.ts
+5 -1
@@ -1,7 +1,11 @@
1 import { OrchestrationCheckpointFile } from "@t3tools/contracts";
2 import * as SqlClient from "effect/unstable/sql/SqlClient";
3 import * as SqlSchema from "effect/unstable/sql/SqlSchema";
4 -import { Effect, Layer, Option, Schema, Struct } from "effect";
4 +import * as Effect from "effect/Effect";
5 +import * as Layer from "effect/Layer";
6 +import * as Option from "effect/Option";
7 +import * as Schema from "effect/Schema";
8 +import * as Struct from "effect/Struct";
9
10 import { toPersistenceDecodeError, toPersistenceSqlError } from "../Errors.ts";
11 import {
apps/server/src/persistence/Layers/ProviderSessionRuntime.ts
+5 -1
@@ -1,7 +1,11 @@
1 import { ThreadId } from "@t3tools/contracts";
2 import * as SqlClient from "effect/unstable/sql/SqlClient";
3 import * as SqlSchema from "effect/unstable/sql/SqlSchema";
4 -import { Effect, Layer, Option, Schema, Struct } from "effect";
4 +import * as Effect from "effect/Effect";
5 +import * as Layer from "effect/Layer";
6 +import * as Option from "effect/Option";
7 +import * as Schema from "effect/Schema";
8 +import * as Struct from "effect/Struct";
9
10 import {
11 toPersistenceDecodeError,
apps/server/src/persistence/Layers/Sqlite.ts
+4 -1
@@ -1,4 +1,7 @@
1 -import { Effect, Layer, FileSystem, Path } from "effect";
1 +import * as Effect from "effect/Effect";
2 +import * as Layer from "effect/Layer";
3 +import * as FileSystem from "effect/FileSystem";
4 +import * as Path from "effect/Path";
5 import * as SqlClient from "effect/unstable/sql/SqlClient";
6
7 import { runMigrations } from "../Migrations.ts";
apps/server/src/persistence/Migrations/016_CanonicalizeModelSelections.test.ts
+9 -8
@@ -1,5 +1,6 @@
1 import { assert, it } from "@effect/vitest";
2 -import { Effect, Layer } from "effect";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 import * as SqlClient from "effect/unstable/sql/SqlClient";
5
6 import { runMigrations } from "../Migrations.ts";
@@ -264,7 +265,7 @@ layer("016_CanonicalizeModelSelections", (it) => {
265 FROM orchestration_events
266 ORDER BY rowid ASC
267 `;
267 -
268 + // @effect-diagnostics-next-line preferSchemaOverJson:off
269 assert.deepStrictEqual(JSON.parse(eventRows[0]!.payloadJson), {
270 projectId: "project-1",
271 title: "Project",
@@ -280,7 +281,7 @@ layer("016_CanonicalizeModelSelections", (it) => {
281 createdAt: "2026-01-01T00:00:00.000Z",
282 updatedAt: "2026-01-01T00:00:00.000Z",
283 });
283 -
284 + // @effect-diagnostics-next-line preferSchemaOverJson:off
285 assert.deepStrictEqual(JSON.parse(eventRows[1]!.payloadJson), {
286 projectId: "project-2",
287 title: "Fallback Project",
@@ -296,7 +297,7 @@ layer("016_CanonicalizeModelSelections", (it) => {
297 createdAt: "2026-01-01T00:00:00.000Z",
298 updatedAt: "2026-01-01T00:00:00.000Z",
299 });
299 -
300 + // @effect-diagnostics-next-line preferSchemaOverJson:off
301 assert.deepStrictEqual(JSON.parse(eventRows[2]!.payloadJson), {
302 projectId: "project-3",
303 title: "Null Model Project",
@@ -306,7 +307,7 @@ layer("016_CanonicalizeModelSelections", (it) => {
307 createdAt: "2026-01-01T00:00:00.000Z",
308 updatedAt: "2026-01-01T00:00:00.000Z",
309 });
309 -
310 + // @effect-diagnostics-next-line preferSchemaOverJson:off
311 assert.deepStrictEqual(JSON.parse(eventRows[3]!.payloadJson), {
312 threadId: "thread-1",
313 projectId: "project-1",
@@ -326,7 +327,7 @@ layer("016_CanonicalizeModelSelections", (it) => {
327 createdAt: "2026-01-01T00:00:00.000Z",
328 updatedAt: "2026-01-01T00:00:00.000Z",
329 });
329 -
330 + // @effect-diagnostics-next-line preferSchemaOverJson:off
331 assert.deepStrictEqual(JSON.parse(eventRows[4]!.payloadJson), {
332 threadId: "thread-2",
333 projectId: "project-1",
@@ -345,7 +346,7 @@ layer("016_CanonicalizeModelSelections", (it) => {
346 createdAt: "2026-01-01T00:00:00.000Z",
347 updatedAt: "2026-01-01T00:00:00.000Z",
348 });
348 -
349 + // @effect-diagnostics-next-line preferSchemaOverJson:off
350 assert.deepStrictEqual(JSON.parse(eventRows[5]!.payloadJson), {
351 threadId: "thread-1",
352 turnId: "turn-1",
@@ -359,7 +360,7 @@ layer("016_CanonicalizeModelSelections", (it) => {
360 },
361 deliveryMode: "buffered",
362 });
362 -
363 + // @effect-diagnostics-next-line preferSchemaOverJson:off
364 assert.deepStrictEqual(JSON.parse(eventRows[6]!.payloadJson), {
365 threadId: "thread-3",
366 projectId: "project-1",
apps/server/src/persistence/Migrations/019_ProjectionSnapshotLookupIndexes.test.ts
+2 -1
@@ -1,5 +1,6 @@
1 import { assert, it } from "@effect/vitest";
2 -import { Effect, Layer } from "effect";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 import * as SqlClient from "effect/unstable/sql/SqlClient";
5
6 import { runMigrations } from "../Migrations.ts";
apps/server/src/persistence/Migrations/024_BackfillProjectionThreadShellSummary.test.ts
+2 -1
@@ -1,5 +1,6 @@
1 import { assert, it } from "@effect/vitest";
2 -import { Effect, Layer } from "effect";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 import * as SqlClient from "effect/unstable/sql/SqlClient";
5
6 import { runMigrations } from "../Migrations.ts";
apps/server/src/persistence/Migrations/025_CleanupInvalidProjectionPendingApprovals.test.ts
+2 -1
@@ -1,5 +1,6 @@
1 import { assert, it } from "@effect/vitest";
2 -import { Effect, Layer } from "effect";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 import * as SqlClient from "effect/unstable/sql/SqlClient";
5
6 import { runMigrations } from "../Migrations.ts";
apps/server/src/persistence/Migrations/026_CanonicalizeModelSelectionOptions.test.ts
+2 -1
@@ -1,5 +1,6 @@
1 import { assert, it } from "@effect/vitest";
2 -import { Effect, Layer } from "effect";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 import * as SqlClient from "effect/unstable/sql/SqlClient";
5
6 import { runMigrations } from "../Migrations.ts";
apps/server/src/persistence/Migrations/027_028_ProviderInstanceIdColumns.test.ts
+2 -1
@@ -1,5 +1,6 @@
1 import { assert, it } from "@effect/vitest";
2 -import { Effect, Layer } from "effect";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 import * as SqlClient from "effect/unstable/sql/SqlClient";
5
6 import { runMigrations } from "../Migrations.ts";
apps/server/src/persistence/Migrations/029_ProjectionThreadDetailOrderingIndexes.test.ts
+2 -1
@@ -1,5 +1,6 @@
1 import { assert, it } from "@effect/vitest";
2 -import { Effect, Layer } from "effect";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 import * as SqlClient from "effect/unstable/sql/SqlClient";
5
6 import { runMigrations } from "../Migrations.ts";
apps/server/src/persistence/NodeSqliteClient.test.ts
+1 -1
@@ -1,5 +1,5 @@
1 import { assert, it } from "@effect/vitest";
2 -import { Effect } from "effect";
2 +import * as Effect from "effect/Effect";
3 import * as SqlClient from "effect/unstable/sql/SqlClient";
4
5 import * as SqliteClient from "./NodeSqliteClient.ts";
apps/server/src/persistence/Services/AuthPairingLinks.ts
+4 -2
@@ -1,5 +1,7 @@
1 -import { Option, Schema, Context } from "effect";
2 -import type { Effect } from "effect";
1 +import * as Option from "effect/Option";
2 +import * as Schema from "effect/Schema";
3 +import * as Context from "effect/Context";
4 +import type * as Effect from "effect/Effect";
5
6 import type { AuthPairingLinkRepositoryError } from "../Errors.ts";
7
apps/server/src/persistence/Services/AuthSessions.ts
+4 -2
@@ -1,6 +1,8 @@
1 import { AuthClientMetadataDeviceType, AuthSessionId } from "@t3tools/contracts";
2 -import { Option, Schema, Context } from "effect";
3 -import type { Effect } from "effect";
2 +import * as Option from "effect/Option";
3 +import * as Schema from "effect/Schema";
4 +import * as Context from "effect/Context";
5 +import type * as Effect from "effect/Effect";
6
7 import type { AuthSessionRepositoryError } from "../Errors.ts";
8
apps/server/src/persistence/Services/OrchestrationCommandReceipts.ts
+4 -2
@@ -15,8 +15,10 @@ import {
15 ProjectId,
16 ThreadId,
17 } from "@t3tools/contracts";
18 -import { Option, Schema, Context } from "effect";
19 -import type { Effect } from "effect";
18 +import * as Option from "effect/Option";
19 +import * as Schema from "effect/Schema";
20 +import * as Context from "effect/Context";
21 +import type * as Effect from "effect/Effect";
22
23 import type { OrchestrationCommandReceiptRepositoryError } from "../Errors.ts";
24
apps/server/src/persistence/Services/OrchestrationEventStore.ts
+3 -2
@@ -10,8 +10,9 @@
10 * @module OrchestrationEventStore
11 */
12 import { OrchestrationEvent } from "@t3tools/contracts";
13 -import { Context } from "effect";
14 -import type { Effect, Stream } from "effect";
13 +import * as Context from "effect/Context";
14 +import type * as Effect from "effect/Effect";
15 +import type * as Stream from "effect/Stream";
16
17 import type { OrchestrationEventStoreError } from "../Errors.ts";
18
apps/server/src/persistence/Services/ProjectionCheckpoints.ts
+4 -2
@@ -16,8 +16,10 @@ import {
16 ThreadId,
17 TurnId,
18 } from "@t3tools/contracts";
19 -import { Option, Context, Schema } from "effect";
20 -import type { Effect } from "effect";
19 +import * as Option from "effect/Option";
20 +import * as Context from "effect/Context";
21 +import * as Schema from "effect/Schema";
22 +import type * as Effect from "effect/Effect";
23
24 import type { ProjectionRepositoryError } from "../Errors.ts";
25
apps/server/src/persistence/Services/ProjectionPendingApprovals.ts
+4 -2
@@ -14,8 +14,10 @@ import {
14 ThreadId,
15 TurnId,
16 } from "@t3tools/contracts";
17 -import { Option, Schema, Context } from "effect";
18 -import type { Effect } from "effect";
17 +import * as Option from "effect/Option";
18 +import * as Schema from "effect/Schema";
19 +import * as Context from "effect/Context";
20 +import type * as Effect from "effect/Effect";
21
22 import type { ProjectionRepositoryError } from "../Errors.ts";
23
apps/server/src/persistence/Services/ProjectionProjects.ts
+4 -2
@@ -7,8 +7,10 @@
7 * @module ProjectionProjectRepository
8 */
9 import { IsoDateTime, ModelSelection, ProjectId, ProjectScript } from "@t3tools/contracts";
10 -import { Option, Schema, Context } from "effect";
11 -import type { Effect } from "effect";
10 +import * as Option from "effect/Option";
11 +import * as Schema from "effect/Schema";
12 +import * as Context from "effect/Context";
13 +import type * as Effect from "effect/Effect";
14
15 import type { ProjectionRepositoryError } from "../Errors.ts";
16
apps/server/src/persistence/Services/ProjectionState.ts
+4 -2
@@ -7,8 +7,10 @@
7 * @module ProjectionStateRepository
8 */
9 import { IsoDateTime, NonNegativeInt } from "@t3tools/contracts";
10 -import { Option, Schema, Context } from "effect";
11 -import type { Effect } from "effect";
10 +import * as Option from "effect/Option";
11 +import * as Schema from "effect/Schema";
12 +import * as Context from "effect/Context";
13 +import type * as Effect from "effect/Effect";
14
15 import type { ProjectionRepositoryError } from "../Errors.ts";
16
apps/server/src/persistence/Services/ProjectionThreadActivities.ts
+3 -2
@@ -14,8 +14,9 @@ import {
14 ThreadId,
15 TurnId,
16 } from "@t3tools/contracts";
17 -import { Schema, Context } from "effect";
18 -import type { Effect } from "effect";
17 +import * as Schema from "effect/Schema";
18 +import * as Context from "effect/Context";
19 +import type * as Effect from "effect/Effect";
20
21 import type { ProjectionRepositoryError } from "../Errors.ts";
22
apps/server/src/persistence/Services/ProjectionThreadMessages.ts
+4 -3
@@ -14,9 +14,10 @@ import {
14 TurnId,
15 IsoDateTime,
16 } from "@t3tools/contracts";
17 -import { Schema, Context } from "effect";
18 -import type { Option } from "effect";
19 -import type { Effect } from "effect";
17 +import * as Schema from "effect/Schema";
18 +import * as Context from "effect/Context";
19 +import type * as Option from "effect/Option";
20 +import type * as Effect from "effect/Effect";
21
22 import type { ProjectionRepositoryError } from "../Errors.ts";
23
apps/server/src/persistence/Services/ProjectionThreadProposedPlans.ts
+3 -2
@@ -5,8 +5,9 @@ import {
5 TrimmedNonEmptyString,
6 TurnId,
7 } from "@t3tools/contracts";
8 -import { Schema, Context } from "effect";
9 -import type { Effect } from "effect";
8 +import * as Schema from "effect/Schema";
9 +import * as Context from "effect/Context";
10 +import type * as Effect from "effect/Effect";
11
12 import type { ProjectionRepositoryError } from "../Errors.ts";
13
apps/server/src/persistence/Services/ProjectionThreadSessions.ts
+4 -2
@@ -14,8 +14,10 @@ import {
14 ThreadId,
15 TurnId,
16 } from "@t3tools/contracts";
17 -import { Option, Schema, Context } from "effect";
18 -import type { Effect } from "effect";
17 +import * as Option from "effect/Option";
18 +import * as Schema from "effect/Schema";
19 +import * as Context from "effect/Context";
20 +import type * as Effect from "effect/Effect";
21
22 import type { ProjectionRepositoryError } from "../Errors.ts";
23
apps/server/src/persistence/Services/ProjectionThreads.ts
+4 -2
@@ -16,8 +16,10 @@ import {
16 ThreadId,
17 TurnId,
18 } from "@t3tools/contracts";
19 -import { Option, Schema, Context } from "effect";
20 -import type { Effect } from "effect";
19 +import * as Option from "effect/Option";
20 +import * as Schema from "effect/Schema";
21 +import * as Context from "effect/Context";
22 +import type * as Effect from "effect/Effect";
23
24 import type { ProjectionRepositoryError } from "../Errors.ts";
25
apps/server/src/persistence/Services/ProjectionTurns.ts
+4 -2
@@ -17,8 +17,10 @@ import {
17 ThreadId,
18 TurnId,
19 } from "@t3tools/contracts";
20 -import { Option, Schema, Context } from "effect";
21 -import type { Effect } from "effect";
20 +import * as Option from "effect/Option";
21 +import * as Schema from "effect/Schema";
22 +import * as Context from "effect/Context";
23 +import type * as Effect from "effect/Effect";
24
25 import type { ProjectionRepositoryError } from "../Errors.ts";
26
apps/server/src/persistence/Services/ProviderSessionRuntime.ts
+4 -2
@@ -12,8 +12,10 @@ import {
12 RuntimeMode,
13 ThreadId,
14 } from "@t3tools/contracts";
15 -import { Option, Schema, Context } from "effect";
16 -import type { Effect } from "effect";
15 +import * as Option from "effect/Option";
16 +import * as Schema from "effect/Schema";
17 +import * as Context from "effect/Context";
18 +import type * as Effect from "effect/Effect";
19
20 import type { ProviderSessionRuntimeRepositoryError } from "../Errors.ts";
21
apps/server/src/processRunner.ts
+9 -6
@@ -1,5 +1,6 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 import { type ChildProcess as ChildProcessHandle, spawn, spawnSync } from "node:child_process";
2 -
3 +import * as NodeTimers from "node:timers";
4 export interface ProcessRunOptions {
5 cwd?: string | undefined;
6 timeoutMs?: number | undefined;
@@ -163,12 +164,14 @@ export async function runProcess(
164 let stderrTruncated = false;
165 let timedOut = false;
166 let settled = false;
166 - let forceKillTimer: ReturnType<typeof setTimeout> | null = null;
167 + let forceKillTimer: ReturnType<typeof NodeTimers.setTimeout> | null = null;
168
168 - const timeoutTimer = setTimeout(() => {
169 + // @effect-diagnostics-next-line globalTimers:off - Promise/child_process boundary; moving this runner to Effect timers is a separate refactor.
170 + const timeoutTimer = NodeTimers.setTimeout(() => {
171 timedOut = true;
172 killChild(child, "SIGTERM");
171 - forceKillTimer = setTimeout(() => {
173 + // @effect-diagnostics-next-line globalTimers:off - Promise/child_process boundary; see timeout timer above.
174 + forceKillTimer = NodeTimers.setTimeout(() => {
175 killChild(child, "SIGKILL");
176 }, 1_000);
177 }, timeoutMs);
@@ -176,9 +179,9 @@ export async function runProcess(
179 const finalize = (callback: () => void): void => {
180 if (settled) return;
181 settled = true;
179 - clearTimeout(timeoutTimer);
182 + NodeTimers.clearTimeout(timeoutTimer);
183 if (forceKillTimer) {
181 - clearTimeout(forceKillTimer);
184 + NodeTimers.clearTimeout(forceKillTimer);
185 }
186 callback();
187 };
apps/server/src/project/Layers/ProjectFaviconResolver.test.ts
+4 -1
@@ -1,6 +1,9 @@
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { it, describe, expect } from "@effect/vitest";
3 -import { Effect, FileSystem, Layer, Path } from "effect";
3 +import * as Effect from "effect/Effect";
4 +import * as FileSystem from "effect/FileSystem";
5 +import * as Layer from "effect/Layer";
6 +import * as Path from "effect/Path";
7
8 import { ProjectFaviconResolver } from "../Services/ProjectFaviconResolver.ts";
9 import { ProjectFaviconResolverLive } from "./ProjectFaviconResolver.ts";
apps/server/src/project/Layers/ProjectFaviconResolver.ts
+4 -1
@@ -1,4 +1,7 @@
1 -import { Effect, FileSystem, Layer, Path } from "effect";
1 +import * as Effect from "effect/Effect";
2 +import * as FileSystem from "effect/FileSystem";
3 +import * as Layer from "effect/Layer";
4 +import * as Path from "effect/Path";
5
6 import {
7 ProjectFaviconResolver,
apps/server/src/project/Layers/ProjectSetupScriptRunner.test.ts
+3 -1
@@ -1,5 +1,7 @@
1 import { ProjectId, type OrchestrationProject } from "@t3tools/contracts";
2 -import { Effect, Layer, Option } from "effect";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 +import * as Option from "effect/Option";
5 import { describe, expect, it, vi } from "vitest";
6
7 import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
apps/server/src/project/Layers/ProjectSetupScriptRunner.ts
+27 -3
@@ -1,12 +1,15 @@
1 import { ProjectId } from "@t3tools/contracts";
2 import { projectScriptRuntimeEnv, setupProjectScript } from "@t3tools/shared/projectScripts";
3 -import { Effect, Layer, Option } from "effect";
3 +import * as Effect from "effect/Effect";
4 +import * as Layer from "effect/Layer";
5 +import * as Option from "effect/Option";
6
7 import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
8 import { TerminalManager } from "../../terminal/Services/Manager.ts";
9 import {
10 type ProjectSetupScriptRunnerShape,
11 ProjectSetupScriptRunner,
12 + ProjectSetupScriptRunnerError,
13 } from "../Services/ProjectSetupScriptRunner.ts";
14
15 const makeProjectSetupScriptRunner = Effect.gen(function* () {
@@ -29,7 +32,9 @@ const makeProjectSetupScriptRunner = Effect.gen(function* () {
32 null;
33
34 if (!project) {
32 - return yield* Effect.fail(new Error("Project was not found for setup script execution."));
35 + return yield* new ProjectSetupScriptRunnerError({
36 + message: "Project was not found for setup script execution.",
37 + });
38 }
39
40 const script = setupProjectScript(project.scripts);
@@ -66,7 +71,26 @@ const makeProjectSetupScriptRunner = Effect.gen(function* () {
71 terminalId,
72 cwd,
73 } as const;
69 - });
74 + }).pipe(
75 + Effect.mapError((cause) => {
76 + if (
77 + typeof cause === "object" &&
78 + cause !== null &&
79 + "_tag" in cause &&
80 + cause._tag === "ProjectSetupScriptRunnerError"
81 + ) {
82 + return cause as ProjectSetupScriptRunnerError;
83 + }
84 + const message =
85 + typeof cause === "object" &&
86 + cause !== null &&
87 + "message" in cause &&
88 + typeof cause.message === "string"
89 + ? cause.message
90 + : String(cause);
91 + return new ProjectSetupScriptRunnerError({ message });
92 + }),
93 + );
94
95 return {
96 runForThread,
apps/server/src/project/Layers/RepositoryIdentityResolver.test.ts
+6 -2
@@ -1,9 +1,13 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 import { realpathSync } from "node:fs";
3
4 import * as NodeServices from "@effect/platform-node/NodeServices";
5 import { expect, it } from "@effect/vitest";
5 -import { Duration, Effect, FileSystem, Layer } from "effect";
6 -import { TestClock } from "effect/testing";
6 +import * as Duration from "effect/Duration";
7 +import * as Effect from "effect/Effect";
8 +import * as FileSystem from "effect/FileSystem";
9 +import * as Layer from "effect/Layer";
10 +import * as TestClock from "effect/testing/TestClock";
11
12 import { runProcess } from "../../processRunner.ts";
13 import { RepositoryIdentityResolver } from "../Services/RepositoryIdentityResolver.ts";
apps/server/src/project/Layers/RepositoryIdentityResolver.ts
+5 -1
@@ -1,5 +1,9 @@
1 import type { RepositoryIdentity } from "@t3tools/contracts";
2 -import { Cache, Duration, Effect, Exit, Layer } from "effect";
2 +import * as Cache from "effect/Cache";
3 +import * as Duration from "effect/Duration";
4 +import * as Effect from "effect/Effect";
5 +import * as Exit from "effect/Exit";
6 +import * as Layer from "effect/Layer";
7 import {
8 detectSourceControlProviderFromGitRemoteUrl,
9 normalizeGitRemoteUrl,
apps/server/src/project/Services/ProjectFaviconResolver.ts
+2 -2
@@ -6,8 +6,8 @@
6 *
7 * @module ProjectFaviconResolver
8 */
9 -import { Context } from "effect";
10 -import type { Effect } from "effect";
9 +import * as Context from "effect/Context";
10 +import type * as Effect from "effect/Effect";
11
12 /**
13 * ProjectFaviconResolverShape - Service API for project favicon lookup.
apps/server/src/project/Services/ProjectSetupScriptRunner.ts
+10 -3
@@ -1,5 +1,6 @@
1 -import { Context } from "effect";
2 -import type { Effect } from "effect";
1 +import * as Context from "effect/Context";
2 +import * as Data from "effect/Data";
3 +import type * as Effect from "effect/Effect";
4
5 export interface ProjectSetupScriptRunnerResultNoScript {
6 readonly status: "no-script";
@@ -25,10 +26,16 @@ export interface ProjectSetupScriptRunnerInput {
26 readonly preferredTerminalId?: string;
27 }
28
29 +export class ProjectSetupScriptRunnerError extends Data.TaggedError(
30 + "ProjectSetupScriptRunnerError",
31 +)<{
32 + readonly message: string;
33 +}> {}
34 +
35 export interface ProjectSetupScriptRunnerShape {
36 readonly runForThread: (
37 input: ProjectSetupScriptRunnerInput,
31 - ) => Effect.Effect<ProjectSetupScriptRunnerResult, Error>;
38 + ) => Effect.Effect<ProjectSetupScriptRunnerResult, ProjectSetupScriptRunnerError>;
39 }
40
41 export class ProjectSetupScriptRunner extends Context.Service<
apps/server/src/project/Services/RepositoryIdentityResolver.ts
+2 -2
@@ -1,6 +1,6 @@
1 import type { RepositoryIdentity } from "@t3tools/contracts";
2 -import { Context } from "effect";
3 -import type { Effect } from "effect";
2 +import * as Context from "effect/Context";
3 +import type * as Effect from "effect/Effect";
4
5 export interface RepositoryIdentityResolverShape {
6 readonly resolve: (cwd: string) => Effect.Effect<RepositoryIdentity | null>;
apps/server/src/provider/Drivers/ClaudeDriver.ts
+9 -2
@@ -13,7 +13,13 @@
13 * @module provider/Drivers/ClaudeDriver
14 */
15 import { ClaudeSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
16 -import { Cache, Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
16 +import * as Cache from "effect/Cache";
17 +import * as Duration from "effect/Duration";
18 +import * as Effect from "effect/Effect";
19 +import * as FileSystem from "effect/FileSystem";
20 +import * as Path from "effect/Path";
21 +import * as Schema from "effect/Schema";
22 +import * as Stream from "effect/Stream";
23 import { HttpClient } from "effect/unstable/http";
24 import { ChildProcessSpawner } from "effect/unstable/process";
25
@@ -159,7 +165,8 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
165 getSettings: Effect.succeed(effectiveConfig),
166 streamSettings: Stream.never,
167 haveSettingsChanged: () => false,
162 - initialSnapshot: (settings) => stampIdentity(makePendingClaudeProvider(settings)),
168 + initialSnapshot: (settings) =>
169 + makePendingClaudeProvider(settings).pipe(Effect.map(stampIdentity)),
170 checkProvider,
171 enrichSnapshot: ({ snapshot, publishSnapshot }) =>
172 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities).pipe(
apps/server/src/provider/Drivers/ClaudeHome.test.ts
+2 -1
@@ -2,7 +2,8 @@ import * as NodeOS from "node:os";
2
3 import * as NodeServices from "@effect/platform-node/NodeServices";
4 import { describe, expect, it } from "@effect/vitest";
5 -import { Effect, Path } from "effect";
5 +import * as Effect from "effect/Effect";
6 +import * as Path from "effect/Path";
7
8 import {
9 makeClaudeCapabilitiesCacheKey,
apps/server/src/provider/Drivers/ClaudeHome.ts
+2 -1
@@ -1,7 +1,8 @@
1 import * as NodeOS from "node:os";
2
3 import type { ClaudeSettings } from "@t3tools/contracts";
4 -import { Effect, Path } from "effect";
4 +import * as Effect from "effect/Effect";
5 +import * as Path from "effect/Path";
6
7 import { expandHomePath } from "../../pathExpansion.ts";
8
apps/server/src/provider/Drivers/CodexDriver.ts
+8 -2
@@ -22,7 +22,12 @@
22 * @module provider/Drivers/CodexDriver
23 */
24 import { CodexSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
25 -import { Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
25 +import * as Duration from "effect/Duration";
26 +import * as Effect from "effect/Effect";
27 +import * as FileSystem from "effect/FileSystem";
28 +import * as Path from "effect/Path";
29 +import * as Schema from "effect/Schema";
30 +import * as Stream from "effect/Stream";
31 import { HttpClient } from "effect/unstable/http";
32 import { ChildProcessSpawner } from "effect/unstable/process";
33
@@ -160,7 +165,8 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
165 getSettings: Effect.succeed(effectiveConfig),
166 streamSettings: Stream.never,
167 haveSettingsChanged: () => false,
163 - initialSnapshot: (settings) => stampIdentity(makePendingCodexProvider(settings)),
168 + initialSnapshot: (settings) =>
169 + makePendingCodexProvider(settings).pipe(Effect.map(stampIdentity)),
170 checkProvider,
171 enrichSnapshot: ({ snapshot, publishSnapshot }) =>
172 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities).pipe(
apps/server/src/provider/Drivers/CodexHomeLayout.test.ts
+4 -1
@@ -1,6 +1,9 @@
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { describe, expect, it } from "@effect/vitest";
3 -import { Effect, FileSystem, Path, Schema } from "effect";
3 +import * as Effect from "effect/Effect";
4 +import * as FileSystem from "effect/FileSystem";
5 +import * as Path from "effect/Path";
6 +import * as Schema from "effect/Schema";
7
8 import { CodexSettings } from "@t3tools/contracts";
9 import {
apps/server/src/provider/Drivers/CodexHomeLayout.ts
+4 -1
@@ -1,7 +1,10 @@
1 import * as NodeOS from "node:os";
2
3 import { ProviderDriverKind, type CodexSettings } from "@t3tools/contracts";
4 -import { Effect, FileSystem, Path, Schema } from "effect";
4 +import * as Effect from "effect/Effect";
5 +import * as FileSystem from "effect/FileSystem";
6 +import * as Path from "effect/Path";
7 +import * as Schema from "effect/Schema";
8 import * as PlatformError from "effect/PlatformError";
9
10 import { expandHomePath } from "../../pathExpansion.ts";
apps/server/src/provider/Drivers/CursorDriver.ts
+8 -2
@@ -13,7 +13,12 @@
13 * @module provider/Drivers/CursorDriver
14 */
15 import { CursorSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
16 -import { Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
16 +import * as Duration from "effect/Duration";
17 +import * as Effect from "effect/Effect";
18 +import * as FileSystem from "effect/FileSystem";
19 +import * as Path from "effect/Path";
20 +import * as Schema from "effect/Schema";
21 +import * as Stream from "effect/Stream";
22 import { HttpClient } from "effect/unstable/http";
23 import { ChildProcessSpawner } from "effect/unstable/process";
24
@@ -128,7 +133,8 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
133 getSettings: Effect.succeed(effectiveConfig),
134 streamSettings: Stream.never,
135 haveSettingsChanged: () => false,
131 - initialSnapshot: (settings) => stampIdentity(buildInitialCursorProviderSnapshot(settings)),
136 + initialSnapshot: (settings) =>
137 + buildInitialCursorProviderSnapshot(settings).pipe(Effect.map(stampIdentity)),
138 checkProvider,
139 // Preserve the background ACP model-capability probe that used to
140 // live on `CursorProviderLive`. Only fires when the snapshot reports
apps/server/src/provider/Drivers/OpenCodeDriver.ts
+8 -2
@@ -13,7 +13,12 @@
13 * @module provider/Drivers/OpenCodeDriver
14 */
15 import { OpenCodeSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
16 -import { Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
16 +import * as Duration from "effect/Duration";
17 +import * as Effect from "effect/Effect";
18 +import * as FileSystem from "effect/FileSystem";
19 +import * as Path from "effect/Path";
20 +import * as Schema from "effect/Schema";
21 +import * as Stream from "effect/Stream";
22 import { HttpClient } from "effect/unstable/http";
23 import { ChildProcessSpawner } from "effect/unstable/process";
24
@@ -139,7 +144,8 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
144 getSettings: Effect.succeed(effectiveConfig),
145 streamSettings: Stream.never,
146 haveSettingsChanged: () => false,
142 - initialSnapshot: (settings) => stampIdentity(makePendingOpenCodeProvider(settings)),
147 + initialSnapshot: (settings) =>
148 + makePendingOpenCodeProvider(settings).pipe(Effect.map(stampIdentity)),
149 checkProvider,
150 enrichSnapshot: ({ snapshot, publishSnapshot }) =>
151 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities).pipe(
apps/server/src/provider/Errors.ts
+1 -1
@@ -1,4 +1,4 @@
1 -import { Schema } from "effect";
1 +import * as Schema from "effect/Schema";
2
3 import type { CheckpointServiceError } from "../checkpointing/Errors.ts";
4
apps/server/src/provider/Layers/ClaudeAdapter.test.ts
+11 -2
@@ -1,3 +1,4 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3 import os from "node:os";
4 import path from "node:path";
@@ -22,7 +23,14 @@ import {
23 } from "@t3tools/contracts";
24 import { createModelSelection } from "@t3tools/shared/model";
25 import { assert, describe, it } from "@effect/vitest";
25 -import { Context, Effect, Fiber, Layer, Random, Schema, Stream } from "effect";
26 +import * as Context from "effect/Context";
27 +import * as Effect from "effect/Effect";
28 +import * as Fiber from "effect/Fiber";
29 +import * as Layer from "effect/Layer";
30 +import * as Random from "effect/Random";
31 +import * as Schema from "effect/Schema";
32 +import * as Stream from "effect/Stream";
33 +import * as TestClock from "effect/testing/TestClock";
34
35 import { attachmentRelativePath } from "../../attachmentStore.ts";
36 import { ServerConfig } from "../../config.ts";
@@ -1463,7 +1471,8 @@ describe("ClaudeAdapterLive", () => {
1471 yield* Effect.yieldNow;
1472 yield* Effect.yieldNow;
1473 yield* Effect.yieldNow;
1466 - yield* Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 50)));
1474 + yield* TestClock.adjust("50 millis");
1475 + yield* Effect.yieldNow;
1476
1477 runtimeEventsFiber.interruptUnsafe();
1478
apps/server/src/provider/Layers/ClaudeAdapter.ts
+65 -36
@@ -51,20 +51,19 @@ import {
51 getProviderOptionDescriptors,
52 resolvePromptInjectedEffort,
53 } from "@t3tools/shared/model";
54 -import {
55 - Cause,
56 - DateTime,
57 - Deferred,
58 - Effect,
59 - Exit,
60 - FileSystem,
61 - Fiber,
62 - Path,
63 - Queue,
64 - Random,
65 - Ref,
66 - Stream,
67 -} from "effect";
54 +import * as Cause from "effect/Cause";
55 +import * as DateTime from "effect/DateTime";
56 +import * as Deferred from "effect/Deferred";
57 +import * as Effect from "effect/Effect";
58 +import * as Exit from "effect/Exit";
59 +import * as FileSystem from "effect/FileSystem";
60 +import * as Fiber from "effect/Fiber";
61 +import * as Path from "effect/Path";
62 +import * as Queue from "effect/Queue";
63 +import * as Random from "effect/Random";
64 +import * as Ref from "effect/Ref";
65 +import * as Schema from "effect/Schema";
66 +import * as Stream from "effect/Stream";
67
68 import { resolveAttachmentPath } from "../../attachmentStore.ts";
69 import { ServerConfig } from "../../config.ts";
@@ -222,11 +221,22 @@ function toMessage(cause: unknown, fallback: string): string {
221 return fallback;
222 }
223
225 -function toError(cause: unknown, fallback: string): Error {
226 - return cause instanceof Error ? cause : new Error(toMessage(cause, fallback));
224 +function toProcessError(
225 + cause: unknown,
226 + fallback: string,
227 + threadId: ThreadId,
228 +): ProviderAdapterProcessError {
229 + return new ProviderAdapterProcessError({
230 + provider: PROVIDER,
231 + threadId,
232 + detail: toMessage(cause, fallback),
233 + cause,
234 + });
235 }
236
229 -function normalizeClaudeStreamMessages(cause: Cause.Cause<Error>): ReadonlyArray<string> {
237 +function normalizeClaudeStreamMessages(
238 + cause: Cause.Cause<{ readonly message: string }>,
239 +): ReadonlyArray<string> {
240 const errors = Cause.prettyErrors(cause)
241 .map((error) => error.message.trim())
242 .filter((message) => message.length > 0);
@@ -252,18 +262,23 @@ function isClaudeInterruptedMessage(message: string): boolean {
262 );
263 }
264
255 -function isClaudeInterruptedCause(cause: Cause.Cause<Error>): boolean {
265 +function isClaudeInterruptedCause(cause: Cause.Cause<{ readonly message: string }>): boolean {
266 return (
267 Cause.hasInterruptsOnly(cause) ||
268 normalizeClaudeStreamMessages(cause).some(isClaudeInterruptedMessage)
269 );
270 }
271
262 -function messageFromClaudeStreamCause(cause: Cause.Cause<Error>, fallback: string): string {
272 +function messageFromClaudeStreamCause(
273 + cause: Cause.Cause<{ readonly message: string }>,
274 + fallback: string,
275 +): string {
276 return normalizeClaudeStreamMessages(cause)[0] ?? fallback;
277 }
278
266 -function interruptionMessageFromClaudeCause(cause: Cause.Cause<Error>): string {
279 +function interruptionMessageFromClaudeCause(
280 + cause: Cause.Cause<{ readonly message: string }>,
281 +): string {
282 const message = messageFromClaudeStreamCause(cause, "Claude runtime interrupted.");
283 return isClaudeInterruptedMessage(message) ? "Claude runtime interrupted." : message;
284 }
@@ -530,7 +545,7 @@ function summarizeToolRequest(toolName: string, input: Record<string, unknown>):
545 }
546 }
547
533 - const serialized = JSON.stringify(input);
548 + const serialized = Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(input);
549 if (serialized.length <= 400) {
550 return `${toolName}: ${serialized}`;
551 }
@@ -796,7 +811,7 @@ function exitPlanCaptureKey(input: {
811
812 function tryParseJsonRecord(value: string): Record<string, unknown> | undefined {
813 try {
799 - const parsed = JSON.parse(value);
814 + const parsed = Schema.decodeUnknownSync(Schema.UnknownFromJsonString)(value);
815 return parsed && typeof parsed === "object" && !Array.isArray(parsed)
816 ? (parsed as Record<string, unknown>)
817 : undefined;
@@ -807,7 +822,7 @@ function tryParseJsonRecord(value: string): Record<string, unknown> | undefined
822
823 function toolInputFingerprint(input: Record<string, unknown>): string | undefined {
824 try {
810 - return JSON.stringify(input);
825 + return Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(input);
826 } catch {
827 return undefined;
828 }
@@ -1020,7 +1035,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
1035 return;
1036 }
1037
1023 - const observedAt = new Date().toISOString();
1038 + const observedAt = yield* nowIso;
1039 const itemId = sdkNativeItemId(message);
1040
1041 yield* nativeEventLogger.write(
@@ -1030,7 +1045,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
1045 id:
1046 "uuid" in message && typeof message.uuid === "string"
1047 ? message.uuid
1033 - : crypto.randomUUID(),
1048 + : yield* Random.nextUUIDv4,
1049 kind: "notification",
1050 provider: PROVIDER,
1051 createdAt: observedAt,
@@ -2353,9 +2368,11 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
2368 }
2369 });
2370
2356 - const runSdkStream = (context: ClaudeSessionContext): Effect.Effect<void, Error> =>
2371 + const runSdkStream = (
2372 + context: ClaudeSessionContext,
2373 + ): Effect.Effect<void, ProviderAdapterProcessError> =>
2374 Stream.fromAsyncIterable(context.query, (cause) =>
2358 - toError(cause, "Claude runtime stream failed."),
2375 + toProcessError(cause, "Claude runtime stream failed.", context.session.threadId),
2376 ).pipe(
2377 Stream.takeWhile(() => !context.stopped),
2378 Stream.runForEach((message) => handleSdkMessage(context, message)),
@@ -2363,7 +2380,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
2380
2381 const handleStreamExit = Effect.fn("handleStreamExit")(function* (
2382 context: ClaudeSessionContext,
2366 - exit: Exit.Exit<void, Error>,
2383 + exit: Exit.Exit<void, ProviderAdapterProcessError>,
2384 ) {
2385 if (context.stopped) {
2386 return;
@@ -2432,12 +2449,20 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
2449 yield* Fiber.interrupt(streamFiber);
2450 }
2451
2435 - // @effect-diagnostics-next-line tryCatchInEffectGen:off
2436 - try {
2437 - context.query.close();
2438 - } catch (cause) {
2439 - yield* emitRuntimeError(context, "Failed to close Claude runtime query.", cause);
2440 - }
2452 + yield* Effect.try({
2453 + try: () => context.query.close(),
2454 + catch: (cause) =>
2455 + new ProviderAdapterProcessError({
2456 + provider: PROVIDER,
2457 + threadId: context.session.threadId,
2458 + detail: toMessage(cause, "Failed to close Claude runtime query."),
2459 + cause,
2460 + }),
2461 + }).pipe(
2462 + Effect.catch((cause) =>
2463 + emitRuntimeError(context, "Failed to close Claude runtime query.", cause),
2464 + ),
2465 + );
2466
2467 const updatedAt = yield* nowIso;
2468 context.session = {
@@ -2916,8 +2941,12 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
2941 "claude.query.include_partial_messages": true,
2942 "claude.query.additional_directories": input.cwd ? [input.cwd] : [],
2943 "claude.query.setting_sources": [...CLAUDE_SETTING_SOURCES],
2919 - "claude.query.settings_json": JSON.stringify(settings),
2920 - "claude.query.extra_args_json": JSON.stringify(extraArgs),
2944 + "claude.query.settings_json": Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(
2945 + settings,
2946 + ),
2947 + "claude.query.extra_args_json": Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(
2948 + extraArgs,
2949 + ),
2950 "claude.query.path_to_executable": claudeBinaryPath,
2951 });
2952
apps/server/src/provider/Layers/ClaudeProvider.ts
+37 -28
@@ -6,7 +6,11 @@ import {
6 type ServerProviderModel,
7 type ServerProviderSlashCommand,
8 } from "@t3tools/contracts";
9 -import { Effect, Option, Path, Result } from "effect";
9 +import * as DateTime from "effect/DateTime";
10 +import * as Effect from "effect/Effect";
11 +import * as Option from "effect/Option";
12 +import * as Path from "effect/Path";
13 +import * as Result from "effect/Result";
14 import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
15 import {
16 createModelCapabilities,
@@ -521,7 +525,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
525 never,
526 ChildProcessSpawner.ChildProcessSpawner | Path.Path
527 > {
524 - const checkedAt = new Date().toISOString();
528 + const checkedAt = DateTime.formatIso(yield* DateTime.now);
529 const allModels = providerModelsFromSettings(
530 BUILT_IN_MODELS,
531 PROVIDER,
@@ -664,19 +668,39 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
668 });
669 });
670
667 -export const makePendingClaudeProvider = (claudeSettings: ClaudeSettings): ServerProviderDraft => {
668 - const checkedAt = new Date().toISOString();
669 - const models = providerModelsFromSettings(
670 - BUILT_IN_MODELS,
671 - PROVIDER,
672 - claudeSettings.customModels,
673 - DEFAULT_CLAUDE_MODEL_CAPABILITIES,
674 - );
671 +const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
672 +
673 +export const makePendingClaudeProvider = (
674 + claudeSettings: ClaudeSettings,
675 +): Effect.Effect<ServerProviderDraft> =>
676 + Effect.gen(function* () {
677 + const checkedAt = yield* nowIso;
678 + const models = providerModelsFromSettings(
679 + BUILT_IN_MODELS,
680 + PROVIDER,
681 + claudeSettings.customModels,
682 + DEFAULT_CLAUDE_MODEL_CAPABILITIES,
683 + );
684 +
685 + if (!claudeSettings.enabled) {
686 + return buildServerProvider({
687 + presentation: CLAUDE_PRESENTATION,
688 + enabled: false,
689 + checkedAt,
690 + models,
691 + probe: {
692 + installed: false,
693 + version: null,
694 + status: "warning",
695 + auth: { status: "unknown" },
696 + message: "Claude is disabled in T3 Code settings.",
697 + },
698 + });
699 + }
700
676 - if (!claudeSettings.enabled) {
701 return buildServerProvider({
702 presentation: CLAUDE_PRESENTATION,
679 - enabled: false,
703 + enabled: true,
704 checkedAt,
705 models,
706 probe: {
@@ -684,24 +708,9 @@ export const makePendingClaudeProvider = (claudeSettings: ClaudeSettings): Serve
708 version: null,
709 status: "warning",
710 auth: { status: "unknown" },
687 - message: "Claude is disabled in T3 Code settings.",
711 + message: "Claude provider status has not been checked in this session yet.",
712 },
713 });
690 - }
691 -
692 - return buildServerProvider({
693 - presentation: CLAUDE_PRESENTATION,
694 - enabled: true,
695 - checkedAt,
696 - models,
697 - probe: {
698 - installed: false,
699 - version: null,
700 - status: "warning",
701 - auth: { status: "unknown" },
702 - message: "Claude provider status has not been checked in this session yet.",
703 - },
714 });
705 -};
715
716 export { probeClaudeCapabilities };
apps/server/src/provider/Layers/CodexAdapter.test.ts
+28 -18
@@ -1,3 +1,4 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 import assert from "node:assert/strict";
3 import fs from "node:fs";
4 import os from "node:os";
@@ -21,7 +22,16 @@ import { createModelSelection } from "@t3tools/shared/model";
22 import * as NodeServices from "@effect/platform-node/NodeServices";
23 import { it, vi } from "@effect/vitest";
24
24 -import { Context, Effect, Exit, Fiber, Layer, Option, Queue, Schema, Scope, Stream } from "effect";
25 +import * as Context from "effect/Context";
26 +import * as Effect from "effect/Effect";
27 +import * as Exit from "effect/Exit";
28 +import * as Fiber from "effect/Fiber";
29 +import * as Layer from "effect/Layer";
30 +import * as Option from "effect/Option";
31 +import * as Queue from "effect/Queue";
32 +import * as Schema from "effect/Schema";
33 +import * as Scope from "effect/Scope";
34 +import * as Stream from "effect/Stream";
35 import * as CodexErrors from "effect-codex-app-server/errors";
36
37 import { ServerConfig } from "../../config.ts";
@@ -49,7 +59,7 @@ const asItemId = (value: string): ProviderItemId => ProviderItemId.make(value);
59
60 class FakeCodexRuntime implements CodexSessionRuntimeShape {
61 private readonly eventQueue = Effect.runSync(Queue.unbounded<ProviderEvent>());
52 - private readonly now = new Date().toISOString();
62 + private readonly now = "2026-01-01T00:00:00.000Z";
63
64 public readonly startImpl = vi.fn(() =>
65 Promise.resolve({
@@ -446,7 +456,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
456 id: asEventId("evt-msg-complete"),
457 kind: "notification",
458 provider: ProviderDriverKind.make("codex"),
449 - createdAt: new Date().toISOString(),
459 + createdAt: "2026-01-01T00:00:00.000Z",
460 method: "item/completed",
461 threadId: asThreadId("thread-1"),
462 turnId: asTurnId("turn-1"),
@@ -489,7 +499,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
499 id: asEventId("evt-plan-complete"),
500 kind: "notification",
501 provider: ProviderDriverKind.make("codex"),
492 - createdAt: new Date().toISOString(),
502 + createdAt: "2026-01-01T00:00:00.000Z",
503 method: "item/completed",
504 threadId: asThreadId("thread-1"),
505 turnId: asTurnId("turn-1"),
@@ -531,7 +541,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
541 id: asEventId("evt-plan-delta"),
542 kind: "notification",
543 provider: ProviderDriverKind.make("codex"),
534 - createdAt: new Date().toISOString(),
544 + createdAt: "2026-01-01T00:00:00.000Z",
545 method: "item/plan/delta",
546 threadId: asThreadId("thread-1"),
547 turnId: asTurnId("turn-1"),
@@ -569,7 +579,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
579 kind: "session",
580 provider: ProviderDriverKind.make("codex"),
581 threadId: asThreadId("thread-1"),
572 - createdAt: new Date().toISOString(),
582 + createdAt: "2026-01-01T00:00:00.000Z",
583 method: "session/closed",
584 message: "Session stopped",
585 };
@@ -600,7 +610,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
610 kind: "notification",
611 provider: ProviderDriverKind.make("codex"),
612 threadId: asThreadId("thread-1"),
603 - createdAt: new Date().toISOString(),
613 + createdAt: "2026-01-01T00:00:00.000Z",
614 method: "error",
615 turnId: asTurnId("turn-1"),
616 payload: {
@@ -638,7 +648,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
648 kind: "notification",
649 provider: ProviderDriverKind.make("codex"),
650 threadId: asThreadId("thread-1"),
641 - createdAt: new Date().toISOString(),
651 + createdAt: "2026-01-01T00:00:00.000Z",
652 method: "process/stderr",
653 turnId: asTurnId("turn-1"),
654 message: "The filename or extension is too long. (os error 206)",
@@ -672,7 +682,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
682 kind: "notification",
683 provider: ProviderDriverKind.make("codex"),
684 threadId: asThreadId("thread-1"),
675 - createdAt: new Date().toISOString(),
685 + createdAt: "2026-01-01T00:00:00.000Z",
686 method: "thread/realtime/started",
687 payload: {
688 threadId: "thread-1",
@@ -706,7 +716,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
716 kind: "notification",
717 provider: ProviderDriverKind.make("codex"),
718 threadId: asThreadId("thread-1"),
709 - createdAt: new Date().toISOString(),
719 + createdAt: "2026-01-01T00:00:00.000Z",
720 method: "process/stderr",
721 turnId: asTurnId("turn-1"),
722 message:
@@ -742,7 +752,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
752 kind: "notification",
753 provider: ProviderDriverKind.make("codex"),
754 threadId: asThreadId("thread-1"),
745 - createdAt: new Date().toISOString(),
755 + createdAt: "2026-01-01T00:00:00.000Z",
756 method: "serverRequest/resolved",
757 requestKind: "command",
758 requestId: ApprovalRequestId.make("req-1"),
@@ -777,7 +787,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
787 kind: "notification",
788 provider: ProviderDriverKind.make("codex"),
789 threadId: asThreadId("thread-1"),
780 - createdAt: new Date().toISOString(),
790 + createdAt: "2026-01-01T00:00:00.000Z",
791 method: "serverRequest/resolved",
792 requestKind: "file-read",
793 requestId: ApprovalRequestId.make("req-file-read-1"),
@@ -812,7 +822,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
822 kind: "notification",
823 provider: ProviderDriverKind.make("codex"),
824 threadId: asThreadId("thread-1"),
815 - createdAt: new Date().toISOString(),
825 + createdAt: "2026-01-01T00:00:00.000Z",
826 method: "item/tool/requestUserInput/answered",
827 payload: {
828 answers: {
@@ -852,7 +862,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
862 kind: "notification",
863 provider: ProviderDriverKind.make("codex"),
864 threadId: asThreadId("thread-1"),
855 - createdAt: new Date().toISOString(),
865 + createdAt: "2026-01-01T00:00:00.000Z",
866 method: "windowsSandbox/setupCompleted",
867 message: "Sandbox setup failed",
868 payload: {
@@ -897,7 +907,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
907 kind: "request",
908 provider: ProviderDriverKind.make("codex"),
909 threadId: asThreadId("thread-1"),
900 - createdAt: new Date().toISOString(),
910 + createdAt: "2026-01-01T00:00:00.000Z",
911 method: "item/tool/requestUserInput",
912 requestId: ApprovalRequestId.make("req-user-input-1"),
913 payload: {
@@ -924,7 +934,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
934 kind: "notification",
935 provider: ProviderDriverKind.make("codex"),
936 threadId: asThreadId("thread-1"),
927 - createdAt: new Date().toISOString(),
937 + createdAt: "2026-01-01T00:00:00.000Z",
938 method: "item/tool/requestUserInput/answered",
939 requestId: ApprovalRequestId.make("req-user-input-1"),
940 payload: {
@@ -965,7 +975,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
975 provider: ProviderDriverKind.make("codex"),
976 threadId: asThreadId("thread-1"),
977 turnId: asTurnId("turn-1"),
968 - createdAt: new Date().toISOString(),
978 + createdAt: "2026-01-01T00:00:00.000Z",
979 method: "thread/tokenUsage/updated",
980 payload: {
981 threadId: "thread-1",
@@ -1147,7 +1157,7 @@ it.effect("flushes managed native logs when the adapter layer shuts down", () =>
1157 kind: "notification",
1158 provider: ProviderDriverKind.make("codex"),
1159 threadId: asThreadId("thread-logger"),
1150 - createdAt: new Date().toISOString(),
1160 + createdAt: "2026-01-01T00:00:00.000Z",
1161 method: "process/stderr",
1162 message: "native flush test",
1163 } satisfies ProviderEvent);
apps/server/src/provider/Layers/CodexAdapter.ts
+8 -1
@@ -24,7 +24,14 @@ import {
24 ThreadId,
25 ProviderSendTurnInput,
26 } from "@t3tools/contracts";
27 -import { Effect, Exit, Fiber, FileSystem, Queue, Schema, Scope, Stream } from "effect";
27 +import * as Effect from "effect/Effect";
28 +import * as Exit from "effect/Exit";
29 +import * as Fiber from "effect/Fiber";
30 +import * as FileSystem from "effect/FileSystem";
31 +import * as Queue from "effect/Queue";
32 +import * as Schema from "effect/Schema";
33 +import * as Scope from "effect/Scope";
34 +import * as Stream from "effect/Stream";
35 import { ChildProcessSpawner } from "effect/unstable/process";
36 import * as CodexErrors from "effect-codex-app-server/errors";
37 import * as EffectCodexSchema from "effect-codex-app-server/schema";
apps/server/src/provider/Layers/CodexProvider.ts
+33 -23
@@ -1,4 +1,11 @@
1 -import { DateTime, Duration, Effect, Layer, Option, Result, Schema, Types } from "effect";
1 +import * as DateTime from "effect/DateTime";
2 +import * as Duration from "effect/Duration";
3 +import * as Effect from "effect/Effect";
4 +import * as Layer from "effect/Layer";
5 +import * as Option from "effect/Option";
6 +import * as Result from "effect/Result";
7 +import * as Schema from "effect/Schema";
8 +import * as Types from "effect/Types";
9 import { ChildProcessSpawner } from "effect/unstable/process";
10 import * as CodexClient from "effect-codex-app-server/client";
11 import * as CodexSchema from "effect-codex-app-server/schema";
@@ -325,14 +332,33 @@ const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvi
332 capabilities: null,
333 }));
334
328 -const makePendingCodexProvider = (codexSettings: CodexSettings): ServerProviderDraft => {
329 - const checkedAt = new Date().toISOString();
330 - const models = emptyCodexModelsFromSettings(codexSettings);
335 +const makePendingCodexProvider = (
336 + codexSettings: CodexSettings,
337 +): Effect.Effect<ServerProviderDraft> =>
338 + Effect.gen(function* () {
339 + const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
340 + const models = emptyCodexModelsFromSettings(codexSettings);
341 +
342 + if (!codexSettings.enabled) {
343 + return buildServerProvider({
344 + presentation: CODEX_PRESENTATION,
345 + enabled: false,
346 + checkedAt,
347 + models,
348 + skills: [],
349 + probe: {
350 + installed: false,
351 + version: null,
352 + status: "warning",
353 + auth: { status: "unknown" },
354 + message: "Codex is disabled in T3 Code settings.",
355 + },
356 + });
357 + }
358
332 - if (!codexSettings.enabled) {
359 return buildServerProvider({
360 presentation: CODEX_PRESENTATION,
335 - enabled: false,
361 + enabled: true,
362 checkedAt,
363 models,
364 skills: [],
@@ -341,26 +367,10 @@ const makePendingCodexProvider = (codexSettings: CodexSettings): ServerProviderD
367 version: null,
368 status: "warning",
369 auth: { status: "unknown" },
344 - message: "Codex is disabled in T3 Code settings.",
370 + message: "Codex provider status has not been checked in this session yet.",
371 },
372 });
347 - }
348 -
349 - return buildServerProvider({
350 - presentation: CODEX_PRESENTATION,
351 - enabled: true,
352 - checkedAt,
353 - models,
354 - skills: [],
355 - probe: {
356 - installed: false,
357 - version: null,
358 - status: "warning",
359 - auth: { status: "unknown" },
360 - message: "Codex provider status has not been checked in this session yet.",
361 - },
373 });
363 -};
374
375 function accountProbeStatus(account: CodexAppServerProviderSnapshot["account"]): {
376 readonly status: Exclude<ServerProviderState, "disabled">;
apps/server/src/provider/Layers/CodexSessionRuntime.test.ts
+2 -1
@@ -1,6 +1,7 @@
1 import assert from "node:assert/strict";
2
3 -import { Effect, Schema } from "effect";
3 +import * as Effect from "effect/Effect";
4 +import * as Schema from "effect/Schema";
5 import { describe, it } from "vitest";
6 import { ThreadId } from "@t3tools/contracts";
7 import * as CodexErrors from "effect-codex-app-server/errors";
apps/server/src/provider/Layers/CodexSessionRuntime.ts
+30 -14
@@ -17,7 +17,17 @@ import {
17 TurnId,
18 } from "@t3tools/contracts";
19 import { normalizeModelSlug } from "@t3tools/shared/model";
20 -import { Deferred, Effect, Exit, Layer, Queue, Ref, Scope, Random, Schema, Stream } from "effect";
20 +import * as DateTime from "effect/DateTime";
21 +import * as Deferred from "effect/Deferred";
22 +import * as Effect from "effect/Effect";
23 +import * as Exit from "effect/Exit";
24 +import * as Layer from "effect/Layer";
25 +import * as Queue from "effect/Queue";
26 +import * as Ref from "effect/Ref";
27 +import * as Scope from "effect/Scope";
28 +import * as Random from "effect/Random";
29 +import * as Schema from "effect/Schema";
30 +import * as Stream from "effect/Stream";
31 import * as SchemaIssue from "effect/SchemaIssue";
32 import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
33 import * as CodexClient from "effect-codex-app-server/client";
@@ -653,11 +663,14 @@ function updateSession(
663 sessionRef: Ref.Ref<ProviderSession>,
664 updates: Partial<ProviderSession>,
665 ): Effect.Effect<void> {
656 - return Ref.update(sessionRef, (session) => ({
657 - ...session,
658 - ...updates,
659 - updatedAt: new Date().toISOString(),
660 - }));
666 + return Effect.gen(function* () {
667 + const updatedAt = DateTime.formatIso(yield* DateTime.now);
668 + yield* Ref.update(sessionRef, (session) => ({
669 + ...session,
670 + ...updates,
671 + updatedAt,
672 + }));
673 + });
674 }
675
676 function parseThreadSnapshot(
@@ -724,7 +737,9 @@ export const makeCodexSessionRuntime = (
737 Effect.provide(clientContext),
738 );
739 const serverNotifications = yield* Queue.unbounded<CodexServerNotification>();
740 + const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
741
742 + const sessionCreatedAt = yield* nowIso;
743 const initialSession = {
744 provider: PROVIDER,
745 ...(options.providerInstanceId ? { providerInstanceId: options.providerInstanceId } : {}),
@@ -734,22 +749,23 @@ export const makeCodexSessionRuntime = (
749 ...(options.model ? { model: options.model } : {}),
750 threadId: options.threadId,
751 ...(options.resumeCursor !== undefined ? { resumeCursor: options.resumeCursor } : {}),
737 - createdAt: new Date().toISOString(),
738 - updatedAt: new Date().toISOString(),
752 + createdAt: sessionCreatedAt,
753 + updatedAt: sessionCreatedAt,
754 } satisfies ProviderSession;
755 const sessionRef = yield* Ref.make<ProviderSession>(initialSession);
756 const offerEvent = (event: ProviderEvent) => Queue.offer(events, event).pipe(Effect.asVoid);
757
758 const emitEvent = (event: Omit<ProviderEvent, "id" | "provider" | "createdAt">) =>
744 - Effect.flatMap(Random.nextUUIDv4, (id) =>
745 - offerEvent({
759 + Effect.gen(function* () {
760 + const id = yield* Random.nextUUIDv4;
761 + return yield* offerEvent({
762 id: EventId.make(id),
763 provider: PROVIDER,
764 ...(options.providerInstanceId ? { providerInstanceId: options.providerInstanceId } : {}),
749 - createdAt: new Date().toISOString(),
765 + createdAt: yield* nowIso,
766 ...event,
751 - }),
752 - );
767 + });
768 + });
769 const emitSessionEvent = (method: string, message: string) =>
770 emitEvent({
771 kind: "session",
@@ -1177,7 +1193,7 @@ export const makeCodexSessionRuntime = (
1193 cwd: opened.cwd,
1194 model: opened.model,
1195 resumeCursor: { threadId: providerThreadId },
1180 - updatedAt: new Date().toISOString(),
1196 + updatedAt: yield* nowIso,
1197 } satisfies ProviderSession;
1198 yield* Ref.set(sessionRef, session);
1199 yield* emitSessionEvent("session/ready", "Codex App Server session ready.");
apps/server/src/provider/Layers/CursorAdapter.test.ts
+14 -6
@@ -1,3 +1,4 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 import * as path from "node:path";
3 import * as os from "node:os";
4 import { chmod, mkdtemp, readFile, writeFile } from "node:fs/promises";
@@ -5,7 +6,13 @@ import { fileURLToPath } from "node:url";
6
7 import * as NodeServices from "@effect/platform-node/NodeServices";
8 import { assert, it } from "@effect/vitest";
8 -import { Context, Deferred, Effect, Fiber, Layer, Schema, Stream } from "effect";
9 +import * as Context from "effect/Context";
10 +import * as Deferred from "effect/Deferred";
11 +import * as Effect from "effect/Effect";
12 +import * as Fiber from "effect/Fiber";
13 +import * as Layer from "effect/Layer";
14 +import * as Schema from "effect/Schema";
15 +import * as Stream from "effect/Stream";
16 import { createModelSelection } from "@t3tools/shared/model";
17
18 import {
@@ -98,7 +105,7 @@ async function waitForFileContent(filePath: string, attempts = 40) {
105 return raw;
106 }
107 } catch {}
101 - await new Promise((resolve) => setTimeout(resolve, 50));
108 + await Effect.runPromise(Effect.yieldNow);
109 }
110 throw new Error(`Timed out waiting for file content at ${filePath}`);
111 }
@@ -113,10 +120,11 @@ async function waitForFileContent(filePath: string, attempts = 40) {
120 // tests assumed.
121 const makeResolveCursorSettings = Effect.gen(function* () {
122 const serverSettings = yield* ServerSettingsService;
116 - // @effect-diagnostics effect/returnEffectInGen:off
117 - return serverSettings.getSettings.pipe(
118 - Effect.map((snapshot) => snapshot.providers.cursor),
119 - Effect.orDie,
123 + return yield* Effect.succeed(
124 + serverSettings.getSettings.pipe(
125 + Effect.map((snapshot) => snapshot.providers.cursor),
126 + Effect.orDie,
127 + ),
128 );
129 });
130
apps/server/src/provider/Layers/CursorAdapter.ts
+23 -21
@@ -3,7 +3,6 @@
3 *
4 * @module CursorAdapterLive
5 */
6 -import * as nodePath from "node:path";
6
7 import {
8 ApprovalRequestId,
@@ -22,21 +21,21 @@ import {
21 type ThreadId,
22 TurnId,
23 } from "@t3tools/contracts";
25 -import {
26 - DateTime,
27 - Deferred,
28 - Effect,
29 - Exit,
30 - Fiber,
31 - FileSystem,
32 - Option,
33 - PubSub,
34 - Random,
35 - Scope,
36 - Semaphore,
37 - Stream,
38 - SynchronizedRef,
39 -} from "effect";
24 +import * as DateTime from "effect/DateTime";
25 +import * as Deferred from "effect/Deferred";
26 +import * as Effect from "effect/Effect";
27 +import * as Exit from "effect/Exit";
28 +import * as Fiber from "effect/Fiber";
29 +import * as FileSystem from "effect/FileSystem";
30 +import * as Option from "effect/Option";
31 +import * as Path from "effect/Path";
32 +import * as PubSub from "effect/PubSub";
33 +import * as Random from "effect/Random";
34 +import * as Schema from "effect/Schema";
35 +import * as Scope from "effect/Scope";
36 +import * as Semaphore from "effect/Semaphore";
37 +import * as Stream from "effect/Stream";
38 +import * as SynchronizedRef from "effect/SynchronizedRef";
39 import { ChildProcessSpawner } from "effect/unstable/process";
40 import type * as EffectAcpSchema from "effect-acp/schema";
41
@@ -306,6 +305,7 @@ export function makeCursorAdapter(
305 return Effect.gen(function* () {
306 const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("cursor");
307 const fileSystem = yield* FileSystem.FileSystem;
308 + const path = yield* Path.Path;
309 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
310 const serverConfig = yield* Effect.service(ServerConfig);
311 const nativeEventLogger =
@@ -358,12 +358,12 @@ export function makeCursorAdapter(
358 ) =>
359 Effect.gen(function* () {
360 if (!nativeEventLogger) return;
361 - const observedAt = new Date().toISOString();
361 + const observedAt = yield* nowIso;
362 yield* nativeEventLogger.write(
363 {
364 observedAt,
365 event: {
366 - id: crypto.randomUUID(),
366 + id: yield* Random.nextUUIDv4,
367 kind: "notification",
368 provider: PROVIDER,
369 createdAt: observedAt,
@@ -390,7 +390,7 @@ export function makeCursorAdapter(
390 method: string,
391 ) =>
392 Effect.gen(function* () {
393 - const fingerprint = `${ctx.activeTurnId ?? "no-turn"}:${JSON.stringify(payload)}`;
393 + const fingerprint = `${ctx.activeTurnId ?? "no-turn"}:${Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(payload)}`;
394 if (ctx.lastPlanFingerprint === fingerprint) {
395 return;
396 }
@@ -460,7 +460,7 @@ export function makeCursorAdapter(
460 });
461 }
462
463 - const cwd = nodePath.resolve(input.cwd.trim());
463 + const cwd = path.resolve(input.cwd.trim());
464 const cursorModelSelection =
465 input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;
466 const existing = sessions.get(input.threadId);
@@ -638,7 +638,9 @@ export function makeCursorAdapter(
638 turnId: ctx?.activeTurnId,
639 requestId: runtimeRequestId,
640 permissionRequest,
641 - detail: permissionRequest.detail ?? JSON.stringify(params).slice(0, 2000),
641 + detail:
642 + permissionRequest.detail ??
643 + Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(params).slice(0, 2000),
644 args: params,
645 source: "acp.jsonrpc",
646 method: "session/request_permission",
apps/server/src/provider/Layers/CursorProvider.test.ts
+14 -4
@@ -1,7 +1,9 @@
1 import * as NodeOS from "node:os";
2
3 import * as NodeServices from "@effect/platform-node/NodeServices";
4 -import { Effect, FileSystem, Path } from "effect";
4 +import * as Effect from "effect/Effect";
5 +import * as FileSystem from "effect/FileSystem";
6 +import * as Path from "effect/Path";
7 import { describe, expect, it } from "vitest";
8 import type * as EffectAcpSchema from "effect-acp/schema";
9 import type { CursorSettings, ServerProviderModel } from "@t3tools/contracts";
@@ -68,12 +70,16 @@ const makeMockAgentWrapper = Effect.fn("makeMockAgentWrapper")(function* (
70 prefix: "cursor-provider-mock-",
71 });
72 const wrapperPath = path.join(dir, "fake-agent.sh");
73 + // @effect-diagnostics-next-line preferSchemaOverJson:off
74 + const bunCommand = JSON.stringify("bun");
75 + // @effect-diagnostics-next-line preferSchemaOverJson:off
76 + const mockAgentPathJson = JSON.stringify(mockAgentPath);
77 const envExports = Object.entries(extraEnv ?? {})
78 .map(([key, value]) => `export ${key}=${JSON.stringify(value)}`)
79 .join("\n");
80 const script = `#!/bin/sh
81 ${envExports}
76 -exec ${JSON.stringify("bun")} ${JSON.stringify(mockAgentPath)} "$@"
82 +exec ${bunCommand} ${mockAgentPathJson} "$@"
83 `;
84 yield* fileSystem.writeFileString(wrapperPath, script);
85 yield* fileSystem.chmod(wrapperPath, 0o755);
@@ -89,13 +95,17 @@ const makeMockAgentWithAboutWrapper = Effect.fn("makeMockAgentWithAboutWrapper")
95 prefix: "cursor-provider-about-mock-",
96 });
97 const wrapperPath = path.join(dir, "fake-agent.sh");
98 + // @effect-diagnostics-next-line preferSchemaOverJson:off
99 + const bunCommand = JSON.stringify("bun");
100 + // @effect-diagnostics-next-line preferSchemaOverJson:off
101 + const mockAgentPathJson = JSON.stringify(mockAgentPath);
102 const script = `#!/bin/sh
103 if [ "$1" = "about" ]; then
104 printf 'CLI Version 2026.04.09-f2b0fcd\\n'
105 printf 'User Email cursor@example.com\\n'
106 exit 0
107 fi
98 -exec ${JSON.stringify("bun")} ${JSON.stringify(mockAgentPath)} "$@"
108 +exec ${bunCommand} ${mockAgentPathJson} "$@"
109 `;
110 yield* fileSystem.writeFileString(wrapperPath, script);
111 yield* fileSystem.chmod(wrapperPath, 0o755);
@@ -118,7 +128,7 @@ const waitForFileContent = Effect.fn("waitForFileContent")(function* (
128 }
129 yield* Effect.sleep("50 millis");
130 }
121 - return yield* Effect.fail(new Error(`Timed out waiting for file content at ${filePath}`));
131 + return yield* Effect.die(`Timed out waiting for file content at ${filePath}`);
132 });
133
134 const makeProviderStatusEnvFixture = Effect.fn("makeProviderStatusEnvFixture")(function* () {
apps/server/src/provider/Layers/CursorProvider.ts
+35 -26
@@ -1,5 +1,4 @@
1 -import * as nodeOs from "node:os";
2 -
1 +import * as NodeOs from "node:os";
2 import type {
3 CursorSettings,
4 ModelCapabilities,
@@ -11,7 +10,15 @@ import type {
10 } from "@t3tools/contracts";
11 import { ProviderDriverKind } from "@t3tools/contracts";
12 import type * as EffectAcpSchema from "effect-acp/schema";
14 -import { Cause, Effect, Exit, FileSystem, Layer, Option, Path, Result } from "effect";
13 +import * as Cause from "effect/Cause";
14 +import * as DateTime from "effect/DateTime";
15 +import * as Effect from "effect/Effect";
16 +import * as Exit from "effect/Exit";
17 +import * as FileSystem from "effect/FileSystem";
18 +import * as Layer from "effect/Layer";
19 +import * as Option from "effect/Option";
20 +import * as Path from "effect/Path";
21 +import * as Result from "effect/Result";
22 import { HttpClient } from "effect/unstable/http";
23 import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
24 import {
@@ -58,38 +65,40 @@ export const CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES = {
65
66 export function buildInitialCursorProviderSnapshot(
67 cursorSettings: CursorSettings,
61 -): ServerProviderDraft {
62 - const checkedAt = new Date().toISOString();
63 - const models = getCursorFallbackModels(cursorSettings);
68 +): Effect.Effect<ServerProviderDraft> {
69 + return Effect.gen(function* () {
70 + const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
71 + const models = getCursorFallbackModels(cursorSettings);
72 +
73 + if (!cursorSettings.enabled) {
74 + return buildServerProvider({
75 + presentation: CURSOR_PRESENTATION,
76 + enabled: false,
77 + checkedAt,
78 + models,
79 + probe: {
80 + installed: false,
81 + version: null,
82 + status: "warning",
83 + auth: { status: "unknown" },
84 + message: "Cursor is disabled in T3 Code settings.",
85 + },
86 + });
87 + }
88
65 - if (!cursorSettings.enabled) {
89 return buildServerProvider({
90 presentation: CURSOR_PRESENTATION,
68 - enabled: false,
91 + enabled: true,
92 checkedAt,
93 models,
94 probe: {
72 - installed: false,
95 + installed: true,
96 version: null,
97 status: "warning",
98 auth: { status: "unknown" },
76 - message: "Cursor is disabled in T3 Code settings.",
99 + message: "Checking Cursor Agent availability...",
100 },
101 });
79 - }
80 -
81 - return buildServerProvider({
82 - presentation: CURSOR_PRESENTATION,
83 - enabled: true,
84 - checkedAt,
85 - models,
86 - probe: {
87 - installed: true,
88 - version: null,
89 - status: "warning",
90 - auth: { status: "unknown" },
91 - message: "Checking Cursor Agent availability...",
92 - },
102 });
103 }
104
@@ -854,7 +863,7 @@ function isCursorAboutJsonFormatUnsupported(result: CommandResult): boolean {
863 const readCursorCliConfigChannel = Effect.fn("readCursorCliConfigChannel")(function* () {
864 const fileSystem = yield* FileSystem.FileSystem;
865 const path = yield* Path.Path;
857 - const configPath = path.join(nodeOs.homedir(), ".cursor", "cli-config.json");
866 + const configPath = path.join(NodeOs.homedir(), ".cursor", "cli-config.json");
867 const raw = yield* fileSystem.readFileString(configPath).pipe(Effect.orElseSucceed(() => ""));
868 return parseCursorCliConfigChannel(raw);
869 });
@@ -1085,7 +1094,7 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
1094 never,
1095 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
1096 > {
1088 - const checkedAt = new Date().toISOString();
1097 + const checkedAt = DateTime.formatIso(yield* DateTime.now);
1098 const fallbackModels = getCursorFallbackModels(cursorSettings);
1099
1100 if (!cursorSettings.enabled) {
apps/server/src/provider/Layers/EventNdjsonLogger.test.ts
+2 -1
@@ -1,10 +1,11 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 import fs from "node:fs";
3 import os from "node:os";
4 import path from "node:path";
5
6 import { ThreadId } from "@t3tools/contracts";
7 import { assert, describe, it } from "@effect/vitest";
7 -import { Effect } from "effect";
8 +import * as Effect from "effect/Effect";
9
10 import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
11
apps/server/src/provider/Layers/EventNdjsonLogger.ts
+6 -1
@@ -1,3 +1,4 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 /**
3 * Provider event logger helper.
4 *
@@ -10,7 +11,11 @@ import path from "node:path";
11
12 import type { ThreadId } from "@t3tools/contracts";
13 import { RotatingFileSink } from "@t3tools/shared/logging";
13 -import { Effect, Exit, Logger, Scope, SynchronizedRef } from "effect";
14 +import * as Effect from "effect/Effect";
15 +import * as Exit from "effect/Exit";
16 +import * as Logger from "effect/Logger";
17 +import * as Scope from "effect/Scope";
18 +import * as SynchronizedRef from "effect/SynchronizedRef";
19
20 import { toSafeThreadAttachmentSegment } from "../../attachmentStore.ts";
21
apps/server/src/provider/Layers/OpenCodeAdapter.test.ts
+14 -6
@@ -1,8 +1,16 @@
1 import assert from "node:assert/strict";
2 -
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 import { it } from "@effect/vitest";
5 -import { Context, Effect, Exit, Fiber, Layer, Option, Schema, Scope, Stream } from "effect";
4 +import * as Context from "effect/Context";
5 +import * as Effect from "effect/Effect";
6 +import * as Exit from "effect/Exit";
7 +import * as Fiber from "effect/Fiber";
8 +import * as Layer from "effect/Layer";
9 +import * as Option from "effect/Option";
10 +import * as Schema from "effect/Schema";
11 +import * as Scope from "effect/Scope";
12 +import * as Stream from "effect/Stream";
13 +import * as TestClock from "effect/testing/TestClock";
14 import { beforeEach } from "vitest";
15
16 import {
@@ -216,8 +224,8 @@ beforeEach(() => {
224 runtimeMock.reset();
225 });
226
219 -const sleep = (ms: number) =>
220 - Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, ms)));
227 +const advanceTestClock = (ms: number) =>
228 + TestClock.adjust(`${ms} millis`).pipe(Effect.andThen(Effect.yieldNow));
229
230 it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
231 it.effect("reuses a configured OpenCode server URL instead of spawning a local server", () =>
@@ -648,7 +656,7 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
656 threadId: asThreadId("thread-native-log"),
657 runtimeMode: "full-access",
658 });
651 - yield* sleep(10);
659 + yield* advanceTestClock(10);
660 return started;
661 }).pipe(Effect.provide(adapterLayer));
662
@@ -736,7 +744,7 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
744 threadId: asThreadId("thread-native-log-failure"),
745 runtimeMode: "full-access",
746 });
739 - yield* sleep(10);
747 + yield* advanceTestClock(10);
748 return {
749 sessions: yield* adapter.listSessions(),
750 closeCallsDuringRun: [...runtimeMock.state.closeCalls],
apps/server/src/provider/Layers/OpenCodeAdapter.ts
+52 -39
@@ -12,7 +12,15 @@ import {
12 TurnId,
13 type UserInputQuestion,
14 } from "@t3tools/contracts";
15 -import { Cause, Effect, Exit, Queue, Random, Ref, Scope, Stream } from "effect";
15 +import * as Cause from "effect/Cause";
16 +import * as DateTime from "effect/DateTime";
17 +import * as Effect from "effect/Effect";
18 +import * as Exit from "effect/Exit";
19 +import * as Queue from "effect/Queue";
20 +import * as Random from "effect/Random";
21 +import * as Ref from "effect/Ref";
22 +import * as Scope from "effect/Scope";
23 +import * as Stream from "effect/Stream";
24 import type { OpencodeClient, Part, PermissionRequest, QuestionRequest } from "@opencode-ai/sdk/v2";
25 import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
26
@@ -40,6 +48,7 @@ import {
48 toOpenCodeQuestionAnswers,
49 type OpenCodeServerConnection,
50 } from "../opencodeRuntime.ts";
51 +import * as Option from "effect/Option";
52
53 const PROVIDER = ProviderDriverKind.make("opencode");
54
@@ -95,9 +104,7 @@ export interface OpenCodeAdapterLiveOptions {
104 readonly nativeEventLogger?: EventNdjsonLogger;
105 }
106
98 -function nowIso(): string {
99 - return new Date().toISOString();
100 -}
107 +const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
108
109 /**
110 * Map a tagged OpenCodeRuntimeError produced by {@link runOpenCodeSdk} into
@@ -140,12 +147,14 @@ const buildEventBase = (input: {
147 "eventId" | "provider" | "threadId" | "createdAt" | "turnId" | "itemId" | "requestId" | "raw"
148 >
149 > =>
143 - Random.nextUUIDv4.pipe(
144 - Effect.map((uuid) => ({
150 + Effect.gen(function* () {
151 + const uuid = yield* Random.nextUUIDv4;
152 + const createdAt = input.createdAt ?? (yield* nowIso);
153 + return {
154 eventId: EventId.make(uuid),
155 provider: PROVIDER,
156 threadId: input.threadId,
148 - createdAt: input.createdAt ?? nowIso(),
157 + createdAt,
158 ...(input.turnId ? { turnId: input.turnId } : {}),
159 ...(input.itemId ? { itemId: RuntimeItemId.make(input.itemId) } : {}),
160 ...(input.requestId ? { requestId: RuntimeRequestId.make(input.requestId) } : {}),
@@ -157,8 +166,8 @@ const buildEventBase = (input: {
166 },
167 }
168 : {}),
160 - })),
161 - );
169 + };
170 + });
171
172 function toToolLifecycleItemType(toolName: string): ToolLifecycleItemType {
173 const normalized = toolName.toLowerCase();
@@ -347,12 +356,13 @@ export function appendOpenCodeAssistantTextDelta(
356 };
357 }
358
350 -function isoFromEpochMs(value: number | undefined): string | undefined {
351 - if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
352 - return undefined;
353 - }
354 - return new Date(value).toISOString();
355 -}
359 +const isoFromEpochMs = (value: number) =>
360 + DateTime.make(value).pipe(
361 + Option.match({
362 + onNone: () => undefined,
363 + onSome: DateTime.formatIso,
364 + }),
365 + );
366
367 function messageRoleForPart(
368 context: OpenCodeSessionContext,
@@ -408,21 +418,24 @@ function updateProviderSession(
418 readonly clearActiveTurnId?: boolean;
419 readonly clearLastError?: boolean;
420 },
411 -): ProviderSession {
412 - const nextSession = {
413 - ...context.session,
414 - ...patch,
415 - updatedAt: nowIso(),
416 - } as ProviderSession & Record<string, unknown>;
417 - const mutableSession = nextSession as Record<string, unknown>;
418 - if (options?.clearActiveTurnId) {
419 - delete mutableSession.activeTurnId;
420 - }
421 - if (options?.clearLastError) {
422 - delete mutableSession.lastError;
423 - }
424 - context.session = nextSession;
425 - return nextSession;
421 +): Effect.Effect<ProviderSession> {
422 + return Effect.gen(function* () {
423 + const updatedAt = yield* nowIso;
424 + const nextSession = {
425 + ...context.session,
426 + ...patch,
427 + updatedAt,
428 + } as ProviderSession & Record<string, unknown>;
429 + const mutableSession = nextSession as Record<string, unknown>;
430 + if (options?.clearActiveTurnId) {
431 + delete mutableSession.activeTurnId;
432 + }
433 + if (options?.clearLastError) {
434 + delete mutableSession.lastError;
435 + }
436 + context.session = nextSession;
437 + return nextSession;
438 + });
439 }
440
441 const stopOpenCodeContext = Effect.fn("stopOpenCodeContext")(function* (
@@ -592,8 +605,8 @@ export function makeOpenCodeAdapter(
605 turnId,
606 itemId: part.id,
607 createdAt:
595 - part.type === "text" || part.type === "reasoning"
596 - ? isoFromEpochMs(part.time?.start)
608 + (part.type === "text" || part.type === "reasoning") && part.time !== undefined
609 + ? isoFromEpochMs(part.time.start)
610 : undefined,
611 raw,
612 })),
@@ -642,7 +655,7 @@ export function makeOpenCodeAdapter(
655
656 const turnId = context.activeTurnId;
657 yield* writeNativeEventBestEffort(context.session.threadId, {
645 - observedAt: nowIso(),
658 + observedAt: yield* nowIso,
659 event: {
660 provider: PROVIDER,
661 threadId: context.session.threadId,
@@ -863,7 +876,7 @@ export function makeOpenCodeAdapter(
876
877 case "session.status": {
878 if (event.properties.status.type === "busy") {
866 - updateProviderSession(context, {
879 + yield* updateProviderSession(context, {
880 status: "running",
881 activeTurnId: turnId,
882 });
@@ -887,7 +900,7 @@ export function makeOpenCodeAdapter(
900
901 if (event.properties.status.type === "idle" && turnId) {
902 context.activeTurnId = undefined;
890 - updateProviderSession(context, { status: "ready" }, { clearActiveTurnId: true });
903 + yield* updateProviderSession(context, { status: "ready" }, { clearActiveTurnId: true });
904 yield* emit({
905 ...(yield* buildEventBase({
906 threadId: context.session.threadId,
@@ -907,7 +920,7 @@ export function makeOpenCodeAdapter(
920 const message = sessionErrorMessage(event.properties.error);
921 const activeTurnId = context.activeTurnId;
922 context.activeTurnId = undefined;
910 - updateProviderSession(
923 + yield* updateProviderSession(
924 context,
925 {
926 status: "error",
@@ -1084,7 +1097,7 @@ export function makeOpenCodeAdapter(
1097 return raceWinner.session;
1098 }
1099
1087 - const createdAt = nowIso();
1100 + const createdAt = yield* nowIso;
1101 const session: ProviderSession = {
1102 provider: PROVIDER,
1103 providerInstanceId: boundInstanceId,
@@ -1185,7 +1198,7 @@ export function makeOpenCodeAdapter(
1198 context.activeTurnId = turnId;
1199 context.activeAgent = agent ?? (input.interactionMode === "plan" ? "plan" : undefined);
1200 context.activeVariant = variant;
1188 - updateProviderSession(
1201 + yield* updateProviderSession(
1202 context,
1203 {
1204 status: "running",
@@ -1223,7 +1236,7 @@ export function makeOpenCodeAdapter(
1236 context.activeTurnId = undefined;
1237 context.activeAgent = undefined;
1238 context.activeVariant = undefined;
1226 - updateProviderSession(
1239 + yield* updateProviderSession(
1240 context,
1241 {
1242 status: "ready",
apps/server/src/provider/Layers/OpenCodeProvider.test.ts
+3 -1
@@ -2,7 +2,9 @@ import assert from "node:assert/strict";
2
3 import * as NodeServices from "@effect/platform-node/NodeServices";
4 import { it } from "@effect/vitest";
5 -import { Effect, Layer, Schema } from "effect";
5 +import * as Effect from "effect/Effect";
6 +import * as Layer from "effect/Layer";
7 +import * as Schema from "effect/Schema";
8 import { beforeEach } from "vitest";
9
10 import { OpenCodeSettings } from "@t3tools/contracts";
apps/server/src/provider/Layers/OpenCodeProvider.ts
+35 -31
@@ -4,7 +4,10 @@ import {
4 type OpenCodeSettings,
5 type ServerProviderModel,
6 } from "@t3tools/contracts";
7 -import { Cause, Data, Effect } from "effect";
7 +import * as Cause from "effect/Cause";
8 +import * as Data from "effect/Data";
9 +import * as DateTime from "effect/DateTime";
10 +import * as Effect from "effect/Effect";
11
12 import { createModelCapabilities } from "@t3tools/shared/model";
13 import {
@@ -249,19 +252,38 @@ function flattenOpenCodeModels(input: OpenCodeInventory): ReadonlyArray<ServerPr
252
253 export const makePendingOpenCodeProvider = (
254 openCodeSettings: OpenCodeSettings,
252 -): ServerProviderDraft => {
253 - const checkedAt = new Date().toISOString();
254 - const models = providerModelsFromSettings(
255 - [],
256 - PROVIDER,
257 - openCodeSettings.customModels,
258 - DEFAULT_OPENCODE_MODEL_CAPABILITIES,
259 - );
255 +): Effect.Effect<ServerProviderDraft> =>
256 + Effect.gen(function* () {
257 + const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
258 + const models = providerModelsFromSettings(
259 + [],
260 + PROVIDER,
261 + openCodeSettings.customModels,
262 + DEFAULT_OPENCODE_MODEL_CAPABILITIES,
263 + );
264 +
265 + if (!openCodeSettings.enabled) {
266 + return buildServerProvider({
267 + presentation: OPENCODE_PRESENTATION,
268 + enabled: false,
269 + checkedAt,
270 + models,
271 + probe: {
272 + installed: false,
273 + version: null,
274 + status: "warning",
275 + auth: { status: "unknown" },
276 + message:
277 + openCodeSettings.serverUrl.trim().length > 0
278 + ? "OpenCode is disabled in T3 Code settings. A server URL is configured."
279 + : "OpenCode is disabled in T3 Code settings.",
280 + },
281 + });
282 + }
283
261 - if (!openCodeSettings.enabled) {
284 return buildServerProvider({
285 presentation: OPENCODE_PRESENTATION,
264 - enabled: false,
286 + enabled: true,
287 checkedAt,
288 models,
289 probe: {
@@ -269,28 +291,10 @@ export const makePendingOpenCodeProvider = (
291 version: null,
292 status: "warning",
293 auth: { status: "unknown" },
272 - message:
273 - openCodeSettings.serverUrl.trim().length > 0
274 - ? "OpenCode is disabled in T3 Code settings. A server URL is configured."
275 - : "OpenCode is disabled in T3 Code settings.",
294 + message: "OpenCode provider status has not been checked in this session yet.",
295 },
296 });
278 - }
279 -
280 - return buildServerProvider({
281 - presentation: OPENCODE_PRESENTATION,
282 - enabled: true,
283 - checkedAt,
284 - models,
285 - probe: {
286 - installed: false,
287 - version: null,
288 - status: "warning",
289 - auth: { status: "unknown" },
290 - message: "OpenCode provider status has not been checked in this session yet.",
291 - },
297 });
293 -};
298
299 export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatus")(function* (
300 openCodeSettings: OpenCodeSettings,
@@ -298,7 +302,7 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
302 environment: NodeJS.ProcessEnv = process.env,
303 ): Effect.fn.Return<ServerProviderDraft, never, OpenCodeRuntime> {
304 const openCodeRuntime = yield* OpenCodeRuntime;
301 - const checkedAt = new Date().toISOString();
305 + const checkedAt = DateTime.formatIso(yield* DateTime.now);
306 const customModels = openCodeSettings.customModels;
307 const isExternalServer = openCodeSettings.serverUrl.trim().length > 0;
308
apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts
+4 -1
@@ -5,7 +5,10 @@ import {
5 } from "@t3tools/contracts";
6 import { it, assert, vi } from "@effect/vitest";
7
8 -import { Effect, Layer, PubSub, Stream } from "effect";
8 +import * as Effect from "effect/Effect";
9 +import * as Layer from "effect/Layer";
10 +import * as PubSub from "effect/PubSub";
11 +import * as Stream from "effect/Stream";
12
13 import type { ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
14 import type { CodexAdapterShape } from "../Services/CodexAdapter.ts";
apps/server/src/provider/Layers/ProviderAdapterRegistry.ts
+2 -1
@@ -20,7 +20,8 @@ import {
20 ProviderInstanceId,
21 type ProviderDriverKind,
22 } from "@t3tools/contracts";
23 -import { Effect, Layer } from "effect";
23 +import * as Effect from "effect/Effect";
24 +import * as Layer from "effect/Layer";
25
26 import { ProviderUnsupportedError } from "../Errors.ts";
27 import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
apps/server/src/provider/Layers/ProviderEventLoggers.ts
+3 -1
@@ -27,7 +27,9 @@
27 *
28 * @module provider/Layers/ProviderEventLoggers
29 */
30 -import { Context, Effect, Layer } from "effect";
30 +import * as Context from "effect/Context";
31 +import * as Effect from "effect/Effect";
32 +import * as Layer from "effect/Layer";
33
34 import { ServerConfig } from "../../config.ts";
35 import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
apps/server/src/provider/Layers/ProviderInstanceRegistryHydration.ts
+3 -1
@@ -47,7 +47,9 @@ import {
47 type ProviderInstanceConfigMap,
48 ServerSettings,
49 } from "@t3tools/contracts";
50 -import { Effect, Layer, Stream } from "effect";
50 +import * as Effect from "effect/Effect";
51 +import * as Layer from "effect/Layer";
52 +import * as Stream from "effect/Stream";
53
54 import { ServerSettingsService } from "../../serverSettings.ts";
55 import { BUILT_IN_DRIVERS, type BuiltInDriversEnv } from "../builtInDrivers.ts";
apps/server/src/provider/Layers/ProviderInstanceRegistryLive.test.ts
+2 -1
@@ -33,7 +33,8 @@ import {
33 type ProviderInstanceConfigMap,
34 ProviderInstanceId,
35 } from "@t3tools/contracts";
36 -import { Effect, Layer } from "effect";
36 +import * as Effect from "effect/Effect";
37 +import * as Layer from "effect/Layer";
38 import { HttpClient, HttpClientResponse } from "effect/unstable/http";
39
40 import { ServerConfig } from "../../config.ts";
apps/server/src/provider/Layers/ProviderInstanceRegistryLive.ts
+13 -4
@@ -40,7 +40,16 @@ import {
40 type ProviderDriverKind,
41 type ServerProvider,
42 } from "@t3tools/contracts";
43 -import { Context, Effect, Equal, Exit, Layer, PubSub, Ref, Schema, Scope, Stream } from "effect";
43 +import * as Context from "effect/Context";
44 +import * as Effect from "effect/Effect";
45 +import * as Equal from "effect/Equal";
46 +import * as Exit from "effect/Exit";
47 +import * as Layer from "effect/Layer";
48 +import * as PubSub from "effect/PubSub";
49 +import * as Ref from "effect/Ref";
50 +import * as Schema from "effect/Schema";
51 +import * as Scope from "effect/Scope";
52 +import * as Stream from "effect/Stream";
53
54 import { buildUnavailableProviderSnapshot } from "../unavailableProviderSnapshot.ts";
55 import {
@@ -115,7 +124,7 @@ const buildEntry = <R>(input: {
124 if (!driver) {
125 return {
126 kind: "unavailable" as const,
118 - snapshot: buildUnavailableProviderSnapshot({
127 + snapshot: yield* buildUnavailableProviderSnapshot({
128 driverKind: entry.driver,
129 instanceId,
130 displayName: entry.displayName,
@@ -137,7 +146,7 @@ const buildEntry = <R>(input: {
146 });
147 return {
148 kind: "unavailable" as const,
140 - snapshot: buildUnavailableProviderSnapshot({
149 + snapshot: yield* buildUnavailableProviderSnapshot({
150 driverKind: entry.driver,
151 instanceId,
152 displayName: entry.displayName,
@@ -175,7 +184,7 @@ const buildEntry = <R>(input: {
184 yield* Scope.close(childScope, Exit.void).pipe(Effect.ignore);
185 return {
186 kind: "unavailable" as const,
178 - snapshot: buildUnavailableProviderSnapshot({
187 + snapshot: yield* buildUnavailableProviderSnapshot({
188 driverKind: entry.driver,
189 instanceId,
190 displayName: entry.displayName,
apps/server/src/provider/Layers/ProviderRegistry.test.ts
+23 -26
@@ -1,6 +1,15 @@
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 -import { describe, it, assert, live } from "@effect/vitest";
3 -import { Effect, Exit, Layer, PubSub, Ref, Schema, Scope, Sink, Stream } from "effect";
2 +import { describe, it, assert } from "@effect/vitest";
3 +import * as Effect from "effect/Effect";
4 +import * as Exit from "effect/Exit";
5 +import * as Layer from "effect/Layer";
6 +import * as PubSub from "effect/PubSub";
7 +import * as Ref from "effect/Ref";
8 +import * as Schema from "effect/Schema";
9 +import * as Scope from "effect/Scope";
10 +import * as Sink from "effect/Sink";
11 +import * as Stream from "effect/Stream";
12 +import * as TestClock from "effect/testing/TestClock";
13 import * as CodexErrors from "effect-codex-app-server/errors";
14 import {
15 ClaudeSettings,
@@ -696,7 +705,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
705 attempt < 50 && cachedProvider?.checkedAt !== refreshedProvider.checkedAt;
706 attempt += 1
707 ) {
699 - yield* Effect.sleep("10 millis");
708 + yield* TestClock.adjust("10 millis");
709 + yield* Effect.yieldNow;
710 cachedProvider = yield* readProviderStatusCache(filePath);
711 }
712
@@ -840,8 +850,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
850 const changes = yield* PubSub.unbounded<void>();
851 const instancesRef = yield* Ref.make<ReadonlyArray<ProviderInstance>>([codexInstance]);
852 const failNextList = yield* Ref.make(false);
843 - const wait = (millis: number) =>
844 - Effect.promise<void>(() => new Promise((resolve) => setTimeout(resolve, millis)));
853 + const wait = () => Effect.yieldNow;
854 const instanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, {
855 getInstance: (instanceId) =>
856 Ref.get(instancesRef).pipe(
@@ -892,7 +901,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
901 !providers.some((provider) => provider.instanceId === claudeInstanceId);
902 attempt += 1
903 ) {
895 - yield* wait(10);
904 + yield* wait();
905 providers = yield* registry.getProviders;
906 }
907
@@ -917,7 +926,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
926 // assertions below fail.
927 it.effect("propagates real Codex probe failures to the aggregator at boot", () =>
928 Effect.gen(function* () {
920 - const missingBinary = `t3code_codex_missing_${process.pid}_${Date.now()}`;
929 + const missingBinary = `t3code_codex_missing_`;
930 const serverSettings = yield* makeMutableServerSettingsService(
931 Schema.decodeSync(ServerSettings)(
932 deepMerge(DEFAULT_SERVER_SETTINGS, {
@@ -1013,20 +1022,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
1022 // rebuilt instance's refresh (previous bug mode), the aggregator
1023 // keeps the old snapshot and this test fails.
1024 //
1016 - // `live` (imported from `@effect/vitest`) is used instead of
1017 - // `it.effect` so real timers coordinate the fibres that drive the
1018 - // settings → reconcile → sync pipeline. Under `it.effect`'s
1019 - // TestClock, `Effect.sleep` blocks until `TestClock.adjust`, which
1020 - // would require this test to reach into the internals of the
1021 - // reconcile pipeline to advance it step by step.
1022 - //
1023 - // The nested `it` handed to `it.layer(…, (it) => …)` is the
1024 - // `MethodsNonLive` variant and therefore lacks `.live`; the
1025 - // top-level `live` export from `@effect/vitest` is the equivalent.
1026 - live("re-probes when settings change the codex binaryPath", () =>
1025 + it.effect("re-probes when settings change the codex binaryPath", () =>
1026 Effect.gen(function* () {
1028 - const firstMissing = `t3code_codex_first_${process.pid}_${Date.now()}`;
1029 - const secondMissing = `t3code_codex_second_${process.pid}_${Date.now()}`;
1027 + const firstMissing = `t3code_codex_first_`;
1028 + const secondMissing = `t3code_codex_second_`;
1029 const serverSettings = yield* makeMutableServerSettingsService(
1030 Schema.decodeSync(ServerSettings)(
1031 deepMerge(DEFAULT_SERVER_SETTINGS, {
@@ -1093,11 +1092,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
1092 },
1093 });
1094
1096 - // Poll with real timers (via `it.live`) until `checkedAt`
1097 - // advances or we hit a generous 3-second ceiling. Anything
1098 - // slower than that is a regression — the real probe fails
1099 - // fast on ENOENT, and the reconcile + sync pipeline is
1100 - // purely in-process.
1095 + // Poll with TestClock until `checkedAt` advances or we hit a
1096 + // generous virtual 3-second ceiling.
1097 const refreshed = yield* Effect.gen(function* () {
1098 for (let attempts = 0; attempts < 60; attempts += 1) {
1099 const providers = yield* registry.getProviders;
@@ -1105,7 +1101,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
1101 if (codex !== undefined && codex.checkedAt !== initialCheckedAt) {
1102 return providers;
1103 }
1108 - yield* Effect.sleep("50 millis");
1104 + yield* TestClock.adjust("50 millis");
1105 + yield* Effect.yieldNow;
1106 }
1107 return yield* registry.getProviders;
1108 });
apps/server/src/provider/Layers/ProviderRegistry.ts
+9 -1
@@ -29,7 +29,15 @@ import {
29 type ServerProvider,
30 type ServerProviderUpdateState,
31 } from "@t3tools/contracts";
32 -import { Cause, Effect, Equal, FileSystem, Layer, Path, PubSub, Ref, Stream } from "effect";
32 +import * as Cause from "effect/Cause";
33 +import * as Effect from "effect/Effect";
34 +import * as Equal from "effect/Equal";
35 +import * as FileSystem from "effect/FileSystem";
36 +import * as Layer from "effect/Layer";
37 +import * as Path from "effect/Path";
38 +import * as PubSub from "effect/PubSub";
39 +import * as Ref from "effect/Ref";
40 +import * as Stream from "effect/Stream";
41 import * as Semaphore from "effect/Semaphore";
42
43 import { ServerConfig } from "../../config.ts";
apps/server/src/provider/Layers/ProviderService.test.ts
+31 -20
@@ -1,3 +1,4 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 import fs from "node:fs";
3 import os from "node:os";
4 import path from "node:path";
@@ -21,7 +22,17 @@ import {
22 import { createModelSelection } from "@t3tools/shared/model";
23 import { it, assert, vi } from "@effect/vitest";
24
24 -import { Effect, Exit, Fiber, Layer, Metric, Option, PubSub, Ref, Scope, Stream } from "effect";
25 +import * as Effect from "effect/Effect";
26 +import * as Exit from "effect/Exit";
27 +import * as Fiber from "effect/Fiber";
28 +import * as Layer from "effect/Layer";
29 +import * as Metric from "effect/Metric";
30 +import * as Option from "effect/Option";
31 +import * as PubSub from "effect/PubSub";
32 +import * as Ref from "effect/Ref";
33 +import * as Scope from "effect/Scope";
34 +import * as Stream from "effect/Stream";
35 +import * as TestClock from "effect/testing/TestClock";
36 import * as SqlClient from "effect/unstable/sql/SqlClient";
37
38 import {
@@ -83,7 +94,7 @@ function makeFakeCodexAdapter(provider: ProviderDriverKind = CODEX_DRIVER) {
94
95 const startSession = vi.fn((input: ProviderSessionStartInput) =>
96 Effect.sync(() => {
86 - const now = new Date().toISOString();
97 + const now = "2026-01-01T00:00:00.000Z";
98 const session: ProviderSession = {
99 provider,
100 ...(input.providerInstanceId !== undefined
@@ -246,8 +257,8 @@ function makeFakeCodexAdapter(provider: ProviderDriverKind = CODEX_DRIVER) {
257 };
258 }
259
249 -const sleep = (ms: number) =>
250 - Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, ms)));
260 +const advanceTestClock = (ms: number) =>
261 + TestClock.adjust(`${ms} millis`).pipe(Effect.andThen(Effect.yieldNow));
262
263 const hasMetricSnapshot = (
264 snapshots: ReadonlyArray<Metric.Metric.Snapshot>,
@@ -572,18 +583,18 @@ it.effect("ProviderServiceLive writes canonical events to the emitting thread se
583
584 yield* Effect.gen(function* () {
585 yield* ProviderService;
575 - yield* sleep(10);
586 + yield* advanceTestClock(10);
587 codex.emit({
588 eventId: asEventId("evt-canonical-thread-segment"),
589 provider: ProviderDriverKind.make("codex"),
590 threadId: asThreadId("thread-canonical-thread-segment"),
580 - createdAt: new Date().toISOString(),
591 + createdAt: "2026-01-01T00:00:00.000Z",
592 type: "turn.completed",
593 payload: {
594 state: "completed",
595 },
596 });
586 - yield* sleep(20);
597 + yield* advanceTestClock(20);
598 }).pipe(Effect.provide(providerLayer));
599
600 assert.equal(canonicalEvents.length, 1);
@@ -704,7 +715,7 @@ it.effect(
715 ...existing,
716 status: "ready",
717 resumeCursor: updatedResumeCursor,
707 - updatedAt: new Date(Date.now() + 1_000).toISOString(),
718 + updatedAt: "2026-01-01T00:00:01.000Z",
719 }));
720 return session;
721 }).pipe(Effect.provide(firstProviderLayer));
@@ -1403,20 +1414,20 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
1414 const consumer = yield* Stream.runForEach(provider.streamEvents, (event) =>
1415 Ref.update(eventsRef, (current) => [...current, event]),
1416 ).pipe(Effect.forkChild);
1406 - yield* sleep(50);
1417 + yield* advanceTestClock(50);
1418
1419 const completedEvent: LegacyProviderRuntimeEvent = {
1420 type: "turn.completed",
1421 eventId: asEventId("evt-1"),
1422 provider: ProviderDriverKind.make("codex"),
1412 - createdAt: new Date().toISOString(),
1423 + createdAt: "2026-01-01T00:00:00.000Z",
1424 threadId: session.threadId,
1425 turnId: asTurnId("turn-1"),
1426 status: "completed",
1427 };
1428
1429 fanout.codex.emit(completedEvent);
1419 - yield* sleep(50);
1430 + yield* advanceTestClock(50);
1431
1432 const events = yield* Ref.get(eventsRef);
1433 yield* Fiber.interrupt(consumer);
@@ -1450,13 +1461,13 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
1461 Stream.runForEach((event) => Ref.update(receivedRef, (current) => [...current, event])),
1462 Effect.forkChild,
1463 );
1453 - yield* sleep(50);
1464 + yield* advanceTestClock(50);
1465
1466 fanout.codex.emit({
1467 type: "tool.started",
1468 eventId: asEventId("evt-seq-1"),
1469 provider: ProviderDriverKind.make("codex"),
1459 - createdAt: new Date().toISOString(),
1470 + createdAt: "2026-01-01T00:00:00.000Z",
1471 threadId: session.threadId,
1472 turnId: asTurnId("turn-1"),
1473 toolKind: "command",
@@ -1466,7 +1477,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
1477 type: "tool.completed",
1478 eventId: asEventId("evt-seq-2"),
1479 provider: ProviderDriverKind.make("codex"),
1469 - createdAt: new Date().toISOString(),
1480 + createdAt: "2026-01-01T00:00:00.000Z",
1481 threadId: session.threadId,
1482 turnId: asTurnId("turn-1"),
1483 toolKind: "command",
@@ -1476,7 +1487,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
1487 type: "turn.completed",
1488 eventId: asEventId("evt-seq-3"),
1489 provider: ProviderDriverKind.make("codex"),
1479 - createdAt: new Date().toISOString(),
1490 + createdAt: "2026-01-01T00:00:00.000Z",
1491 threadId: session.threadId,
1492 turnId: asTurnId("turn-1"),
1493 status: "completed",
@@ -1515,14 +1526,14 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
1526 Stream.runForEach(() => Effect.fail("listener crash")),
1527 Effect.forkChild,
1528 );
1518 - yield* sleep(50);
1529 + yield* advanceTestClock(50);
1530
1531 const events: ReadonlyArray<LegacyProviderRuntimeEvent> = [
1532 {
1533 type: "tool.completed",
1534 eventId: asEventId("evt-ordered-1"),
1535 provider: ProviderDriverKind.make("codex"),
1525 - createdAt: new Date().toISOString(),
1536 + createdAt: "2026-01-01T00:00:00.000Z",
1537 threadId: session.threadId,
1538 turnId: asTurnId("turn-1"),
1539 toolKind: "command",
@@ -1533,7 +1544,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
1544 type: "message.delta",
1545 eventId: asEventId("evt-ordered-2"),
1546 provider: ProviderDriverKind.make("codex"),
1536 - createdAt: new Date().toISOString(),
1547 + createdAt: "2026-01-01T00:00:00.000Z",
1548 threadId: session.threadId,
1549 turnId: asTurnId("turn-1"),
1550 delta: "hello",
@@ -1542,7 +1553,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
1553 type: "turn.completed",
1554 eventId: asEventId("evt-ordered-3"),
1555 provider: ProviderDriverKind.make("codex"),
1545 - createdAt: new Date().toISOString(),
1556 + createdAt: "2026-01-01T00:00:00.000Z",
1557 threadId: session.threadId,
1558 turnId: asTurnId("turn-1"),
1559 status: "completed",
@@ -1758,7 +1769,7 @@ validation.layer("ProviderServiceLive validation", (it) => {
1769
1770 validation.codex.startSession.mockImplementationOnce((input: ProviderSessionStartInput) =>
1771 Effect.sync(() => {
1761 - const now = new Date().toISOString();
1772 + const now = "2026-01-01T00:00:00.000Z";
1773 return {
1774 provider: ProviderDriverKind.make("codex"),
1775 status: "ready",
apps/server/src/provider/Layers/ProviderService.ts
+37 -20
@@ -24,7 +24,16 @@ import {
24 type ProviderRuntimeEvent,
25 type ProviderSession,
26 } from "@t3tools/contracts";
27 -import { Cause, Effect, Layer, Option, PubSub, Ref, Schema, SchemaIssue, Stream } from "effect";
27 +import * as Cause from "effect/Cause";
28 +import * as DateTime from "effect/DateTime";
29 +import * as Effect from "effect/Effect";
30 +import * as Layer from "effect/Layer";
31 +import * as Option from "effect/Option";
32 +import * as PubSub from "effect/PubSub";
33 +import * as Ref from "effect/Ref";
34 +import * as Schema from "effect/Schema";
35 +import * as SchemaIssue from "effect/SchemaIssue";
36 +import * as Stream from "effect/Stream";
37
38 import {
39 increment,
@@ -199,6 +208,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
208 const registry = yield* ProviderAdapterRegistry;
209 const directory = yield* ProviderSessionDirectory;
210 const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
211 + const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
212
213 const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
214 Effect.succeed(event).pipe(
@@ -655,7 +665,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
665 ...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
666 activeTurnId: turn.turnId,
667 lastRuntimeEvent: "provider.sendTurn",
658 - lastRuntimeEventAt: new Date().toISOString(),
668 + lastRuntimeEventAt: yield* nowIso,
669 },
670 });
671 yield* analytics.record("provider.turn.sent", {
@@ -977,27 +987,34 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
987 ),
988 ).pipe(Effect.map((sessionsByAdapter) => sessionsByAdapter.flatMap((sessions) => sessions)));
989 yield* Effect.forEach(activeSessions, (session) =>
980 - upsertSessionBinding(session, session.threadId, {
981 - lastRuntimeEvent: "provider.stopAll",
982 - lastRuntimeEventAt: new Date().toISOString(),
983 - }),
990 + Effect.flatMap(nowIso, (lastRuntimeEventAt) =>
991 + upsertSessionBinding(session, session.threadId, {
992 + lastRuntimeEvent: "provider.stopAll",
993 + lastRuntimeEventAt,
994 + }),
995 + ),
996 ).pipe(Effect.asVoid);
997 yield* Effect.forEach(currentAdapters, ([, adapter]) => adapter.stopAll()).pipe(Effect.asVoid);
998 const bindings = yield* directory.listBindings().pipe(Effect.orElseSucceed(() => []));
987 - yield* Effect.forEach(bindings, (binding) => {
988 - const providerInstanceId = dieOnMissingBindingInstanceId("ProviderService.stopAll", binding);
989 - return directory.upsert({
990 - threadId: binding.threadId,
991 - provider: binding.provider,
992 - providerInstanceId,
993 - status: "stopped",
994 - runtimePayload: {
995 - activeTurnId: null,
996 - lastRuntimeEvent: "provider.stopAll",
997 - lastRuntimeEventAt: new Date().toISOString(),
998 - },
999 - });
1000 - }).pipe(Effect.asVoid);
999 + yield* Effect.forEach(bindings, (binding) =>
1000 + Effect.gen(function* () {
1001 + const providerInstanceId = dieOnMissingBindingInstanceId(
1002 + "ProviderService.stopAll",
1003 + binding,
1004 + );
1005 + return yield* directory.upsert({
1006 + threadId: binding.threadId,
1007 + provider: binding.provider,
1008 + providerInstanceId,
1009 + status: "stopped",
1010 + runtimePayload: {
1011 + activeTurnId: null,
1012 + lastRuntimeEvent: "provider.stopAll",
1013 + lastRuntimeEventAt: yield* nowIso,
1014 + },
1015 + });
1016 + }),
1017 + ).pipe(Effect.asVoid);
1018 yield* analytics.record("provider.sessions.stopped_all", {
1019 sessionCount: threadIds.length,
1020 });
apps/server/src/provider/Layers/ProviderSessionDirectory.test.ts
+5 -2
@@ -1,3 +1,4 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 import fs from "node:fs";
3 import os from "node:os";
4 import path from "node:path";
@@ -6,7 +7,9 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
7 import { ProviderDriverKind, ThreadId } from "@t3tools/contracts";
8 import { it, assert } from "@effect/vitest";
9 import { assertSome } from "@effect/vitest/utils";
9 -import { Effect, Layer, Option } from "effect";
10 +import * as Effect from "effect/Effect";
11 +import * as Layer from "effect/Layer";
12 +import * as Option from "effect/Option";
13 import * as SqlClient from "effect/unstable/sql/SqlClient";
14
15 import {
@@ -209,7 +212,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
212 adapterKey: "claudeAgent",
213 runtimeMode: "full-access",
214 status: "running",
212 - lastSeenAt: new Date().toISOString(),
215 + lastSeenAt: "2026-01-01T00:00:00.000Z",
216 resumeCursor: null,
217 runtimePayload: null,
218 });
apps/server/src/provider/Layers/ProviderSessionDirectory.ts
+6 -2
@@ -1,5 +1,9 @@
1 import { defaultInstanceIdForDriver, ProviderDriverKind, type ThreadId } from "@t3tools/contracts";
2 -import { Effect, Layer, Option, Schema } from "effect";
2 +import * as DateTime from "effect/DateTime";
3 +import * as Effect from "effect/Effect";
4 +import * as Layer from "effect/Layer";
5 +import * as Option from "effect/Option";
6 +import * as Schema from "effect/Schema";
7
8 import type { ProviderSessionRuntime } from "../../persistence/Services/ProviderSessionRuntime.ts";
9 import { ProviderSessionRuntimeRepository } from "../../persistence/Services/ProviderSessionRuntime.ts";
@@ -110,7 +114,7 @@ const makeProviderSessionDirectory = Effect.gen(function* () {
114 });
115 }
116
113 - const now = new Date().toISOString();
117 + const now = DateTime.formatIso(yield* DateTime.now);
118 const providerChanged =
119 existingRuntime !== undefined && existingRuntime.providerName !== binding.provider;
120 const providerInstanceId =
apps/server/src/provider/Layers/ProviderSessionReaper.test.ts
+26 -14
@@ -6,7 +6,15 @@ import {
6 ProviderDriverKind,
7 ProviderInstanceId,
8 } from "@t3tools/contracts";
9 -import { Effect, Exit, Layer, ManagedRuntime, Option, Scope, Stream } from "effect";
9 +import * as Clock from "effect/Clock";
10 +import * as DateTime from "effect/DateTime";
11 +import * as Effect from "effect/Effect";
12 +import * as Exit from "effect/Exit";
13 +import * as Layer from "effect/Layer";
14 +import * as ManagedRuntime from "effect/ManagedRuntime";
15 +import * as Option from "effect/Option";
16 +import * as Scope from "effect/Scope";
17 +import * as Stream from "effect/Stream";
18 import { afterEach, describe, expect, it, vi } from "vitest";
19
20 import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
@@ -28,21 +36,25 @@ async function waitFor(
36 predicate: () => boolean | Promise<boolean>,
37 timeoutMs = 2_000,
38 ): Promise<void> {
31 - const deadline = Date.now() + timeoutMs;
39 + const deadline = (await Effect.runPromise(Clock.currentTimeMillis)) + timeoutMs;
40 const poll = async (): Promise<void> => {
41 if (await predicate()) {
42 return;
43 }
36 - if (Date.now() >= deadline) {
44 + if ((await Effect.runPromise(Clock.currentTimeMillis)) >= deadline) {
45 throw new Error("Timed out waiting for expectation.");
46 }
39 - await new Promise((resolve) => setTimeout(resolve, 10));
47 + await Effect.runPromise(Effect.yieldNow);
48 return poll();
49 };
50
51 return poll();
52 }
53
54 +const drainFibers = Effect.forEach(Array.from({ length: 10 }), () => Effect.yieldNow, {
55 + discard: true,
56 +});
57 +
58 const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
59
60 function makeReadModel(
@@ -59,7 +71,7 @@ function makeReadModel(
71 } | null;
72 }>,
73 ) {
62 - const now = new Date().toISOString();
74 + const now = "2026-01-01T00:00:00.000Z";
75 const projectId = ProjectId.make("project-provider-session-reaper");
76
77 return {
@@ -207,7 +219,7 @@ describe("ProviderSessionReaper", () => {
219
220 it("reaps stale persisted sessions without active turns", async () => {
221 const threadId = ThreadId.make("thread-reaper-stale");
210 - const now = new Date().toISOString();
222 + const now = "2026-01-01T00:00:00.000Z";
223 const harness = await createHarness({
224 readModel: makeReadModel([
225 {
@@ -255,7 +267,7 @@ describe("ProviderSessionReaper", () => {
267 it("skips stale sessions when the thread still has an active turn", async () => {
268 const threadId = ThreadId.make("thread-reaper-active-turn");
269 const turnId = TurnId.make("turn-reaper-active");
258 - const now = new Date().toISOString();
270 + const now = "2026-01-01T00:00:00.000Z";
271 const harness = await createHarness({
272 readModel: makeReadModel([
273 {
@@ -293,7 +305,7 @@ describe("ProviderSessionReaper", () => {
305 const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
306 scope = await Effect.runPromise(Scope.make("sequential"));
307 await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
296 - await new Promise((resolve) => setTimeout(resolve, 50));
308 + await Effect.runPromise(drainFibers);
309
310 expect(harness.stopSession).not.toHaveBeenCalled();
311 const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
@@ -302,7 +314,7 @@ describe("ProviderSessionReaper", () => {
314
315 it("does not reap sessions that are still within the inactivity threshold", async () => {
316 const threadId = ThreadId.make("thread-reaper-fresh");
305 - const now = new Date().toISOString();
317 + const now = DateTime.formatIso(await Effect.runPromise(DateTime.now));
318 const harness = await createHarness({
319 readModel: makeReadModel([
320 {
@@ -340,7 +352,7 @@ describe("ProviderSessionReaper", () => {
352 const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
353 scope = await Effect.runPromise(Scope.make("sequential"));
354 await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
343 - await new Promise((resolve) => setTimeout(resolve, 50));
355 + await Effect.runPromise(drainFibers);
356
357 expect(harness.stopSession).not.toHaveBeenCalled();
358 const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
@@ -349,7 +361,7 @@ describe("ProviderSessionReaper", () => {
361
362 it("skips persisted sessions that are already marked stopped", async () => {
363 const threadId = ThreadId.make("thread-reaper-stopped");
352 - const now = new Date().toISOString();
364 + const now = "2026-01-01T00:00:00.000Z";
365 const harness = await createHarness({
366 readModel: makeReadModel([
367 {
@@ -387,7 +399,7 @@ describe("ProviderSessionReaper", () => {
399 const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
400 scope = await Effect.runPromise(Scope.make("sequential"));
401 await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
390 - await new Promise((resolve) => setTimeout(resolve, 50));
402 + await Effect.runPromise(drainFibers);
403
404 expect(harness.stopSession).not.toHaveBeenCalled();
405 const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
@@ -397,7 +409,7 @@ describe("ProviderSessionReaper", () => {
409 it("continues reaping other sessions when one stop attempt fails", async () => {
410 const failedThreadId = ThreadId.make("thread-reaper-stop-failure");
411 const reapedThreadId = ThreadId.make("thread-reaper-stop-success");
400 - const now = new Date().toISOString();
412 + const now = "2026-01-01T00:00:00.000Z";
413 const harness = await createHarness({
414 readModel: makeReadModel([
415 {
@@ -483,7 +495,7 @@ describe("ProviderSessionReaper", () => {
495 it("continues reaping other sessions when one stop attempt defects", async () => {
496 const defectThreadId = ThreadId.make("thread-reaper-stop-defect");
497 const reapedThreadId = ThreadId.make("thread-reaper-stop-after-defect");
486 - const now = new Date().toISOString();
498 + const now = "2026-01-01T00:00:00.000Z";
499 const harness = await createHarness({
500 readModel: makeReadModel([
501 {
apps/server/src/provider/Layers/ProviderSessionReaper.ts
+7 -2
@@ -1,4 +1,9 @@
1 -import { Duration, Effect, Layer, Option, Schedule } from "effect";
1 +import * as Clock from "effect/Clock";
2 +import * as Duration from "effect/Duration";
3 +import * as Effect from "effect/Effect";
4 +import * as Layer from "effect/Layer";
5 +import * as Option from "effect/Option";
6 +import * as Schedule from "effect/Schedule";
7
8 import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
9 import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
@@ -30,7 +35,7 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =
35
36 const sweep = Effect.gen(function* () {
37 const bindings = yield* directory.listBindings();
33 - const now = Date.now();
38 + const now = yield* Clock.currentTimeMillis;
39 let reapedCount = 0;
40
41 for (const binding of bindings) {
apps/server/src/provider/Layers/scopedSafeTeardown.test.ts
+3 -1
@@ -1,5 +1,7 @@
1 import { it } from "@effect/vitest";
2 -import { Cause, Effect, Exit } from "effect";
2 +import * as Cause from "effect/Cause";
3 +import * as Effect from "effect/Effect";
4 +import * as Exit from "effect/Exit";
5 import { describe, expect } from "vitest";
6
7 import { scopedSafeTeardown } from "./scopedSafeTeardown.ts";
apps/server/src/provider/Layers/scopedSafeTeardown.ts
+3 -1
@@ -34,7 +34,9 @@
34 *
35 * @module provider/Layers/scopedSafeTeardown
36 */
37 -import { Effect, Exit, Scope } from "effect";
37 +import * as Effect from "effect/Effect";
38 +import * as Exit from "effect/Exit";
39 +import * as Scope from "effect/Scope";
40
41 /**
42 * Run `effect` with a freshly made `Scope.Scope`, guaranteeing that
apps/server/src/provider/ProviderDriver.ts
+3 -1
@@ -26,7 +26,9 @@ import type {
26 ProviderInstanceEnvironment,
27 ProviderInstanceId,
28 } from "@t3tools/contracts";
29 -import type { Effect, Schema, Scope } from "effect";
29 +import type * as Effect from "effect/Effect";
30 +import type * as Schema from "effect/Schema";
31 +import type * as Scope from "effect/Scope";
32
33 import type { TextGenerationShape } from "../textGeneration/TextGeneration.ts";
34 import type { ProviderAdapterError, ProviderDriverError } from "./Errors.ts";
apps/server/src/provider/Services/ProviderAdapter.ts
+2 -2
@@ -20,8 +20,8 @@ import type {
20 ProviderTurnStartResult,
21 TurnId,
22 } from "@t3tools/contracts";
23 -import type { Effect } from "effect";
24 -import type { Stream } from "effect";
23 +import type * as Effect from "effect/Effect";
24 +import type * as Stream from "effect/Stream";
25
26 export type ProviderSessionModelSwitchMode = "in-session" | "unsupported";
27
apps/server/src/provider/Services/ProviderAdapterRegistry.ts
+5 -2
@@ -20,8 +20,11 @@
20 * @module ProviderAdapterRegistry
21 */
22 import type { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
23 -import { Context } from "effect";
24 -import type { Effect, PubSub, Scope, Stream } from "effect";
23 +import * as Context from "effect/Context";
24 +import type * as Effect from "effect/Effect";
25 +import type * as PubSub from "effect/PubSub";
26 +import type * as Scope from "effect/Scope";
27 +import type * as Stream from "effect/Stream";
28
29 import type { ProviderAdapterError, ProviderUnsupportedError } from "../Errors.ts";
30 import type { ProviderAdapterShape } from "./ProviderAdapter.ts";
apps/server/src/provider/Services/ProviderInstanceRegistry.ts
+5 -2
@@ -18,8 +18,11 @@
18 * @module provider/Services/ProviderInstanceRegistry
19 */
20 import type { ProviderInstanceId, ServerProvider } from "@t3tools/contracts";
21 -import { Context } from "effect";
22 -import type { Effect, PubSub, Scope, Stream } from "effect";
21 +import * as Context from "effect/Context";
22 +import type * as Effect from "effect/Effect";
23 +import type * as PubSub from "effect/PubSub";
24 +import type * as Scope from "effect/Scope";
25 +import type * as Stream from "effect/Stream";
26
27 import type { ProviderInstance } from "../ProviderDriver.ts";
28
apps/server/src/provider/Services/ProviderInstanceRegistryMutator.ts
+2 -2
@@ -29,8 +29,8 @@
29 * @module provider/Services/ProviderInstanceRegistryMutator
30 */
31 import type { ProviderInstanceConfigMap } from "@t3tools/contracts";
32 -import { Context } from "effect";
33 -import type { Effect } from "effect";
32 +import * as Context from "effect/Context";
33 +import type * as Effect from "effect/Effect";
34
35 export interface ProviderInstanceRegistryMutatorShape {
36 /**
apps/server/src/provider/Services/ProviderRegistry.ts
+3 -2
@@ -12,8 +12,9 @@ import type {
12 ServerProvider,
13 ServerProviderUpdateState,
14 } from "@t3tools/contracts";
15 -import { Context } from "effect";
16 -import type { Effect, Stream } from "effect";
15 +import * as Context from "effect/Context";
16 +import type * as Effect from "effect/Effect";
17 +import type * as Stream from "effect/Stream";
18 import type { ProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
19
20 export type ProviderMaintenanceActionKind = "update";
apps/server/src/provider/Services/ProviderService.ts
+3 -2
@@ -24,8 +24,9 @@ import type {
24 ThreadId,
25 ProviderTurnStartResult,
26 } from "@t3tools/contracts";
27 -import { Context } from "effect";
28 -import type { Effect, Stream } from "effect";
27 +import * as Context from "effect/Context";
28 +import type * as Effect from "effect/Effect";
29 +import type * as Stream from "effect/Stream";
30
31 import type { ProviderServiceError } from "../Errors.ts";
32 import type { ProviderAdapterCapabilities } from "./ProviderAdapter.ts";
apps/server/src/provider/Services/ProviderSessionDirectory.ts
+3 -2
@@ -5,8 +5,9 @@ import type {
5 RuntimeMode,
6 ThreadId,
7 } from "@t3tools/contracts";
8 -import { Option, Context } from "effect";
9 -import type { Effect } from "effect";
8 +import * as Option from "effect/Option";
9 +import * as Context from "effect/Context";
10 +import type * as Effect from "effect/Effect";
11
12 import type {
13 ProviderSessionDirectoryPersistenceError,
apps/server/src/provider/Services/ProviderSessionReaper.ts
+3 -2
@@ -1,5 +1,6 @@
1 -import { Context } from "effect";
2 -import type { Effect, Scope } from "effect";
1 +import * as Context from "effect/Context";
2 +import type * as Effect from "effect/Effect";
3 +import type * as Scope from "effect/Scope";
4
5 export interface ProviderSessionReaperShape {
6 /**
apps/server/src/provider/Services/ServerProvider.ts
+2 -1
@@ -1,5 +1,6 @@
1 import type { ServerProvider } from "@t3tools/contracts";
2 -import type { Effect, Stream } from "effect";
2 +import type * as Effect from "effect/Effect";
3 +import type * as Stream from "effect/Stream";
4 import type { ProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
5
6 export interface ServerProviderShape {
apps/server/src/provider/acp/AcpAdapterSupport.ts
+1 -1
@@ -3,7 +3,7 @@ import {
3 type ProviderDriverKind,
4 type ThreadId,
5 } from "@t3tools/contracts";
6 -import { Schema } from "effect";
6 +import * as Schema from "effect/Schema";
7 import * as EffectAcpErrors from "effect-acp/errors";
8
9 import {
apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts
+3 -1
@@ -1,3 +1,4 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 import * as path from "node:path";
3 import * as os from "node:os";
4 import { fileURLToPath } from "node:url";
@@ -5,7 +6,8 @@ import { mkdtempSync, readFileSync, rmSync } from "node:fs";
6
7 import * as NodeServices from "@effect/platform-node/NodeServices";
8 import { it } from "@effect/vitest";
8 -import { Effect, Stream } from "effect";
9 +import * as Effect from "effect/Effect";
10 +import * as Stream from "effect/Stream";
11 import { describe, expect } from "vitest";
12
13 import { AcpSessionRuntime, type AcpSessionRequestLogEvent } from "./AcpSessionRuntime.ts";
apps/server/src/provider/acp/AcpNativeLogging.ts
+6 -3
@@ -1,5 +1,8 @@
1 import type { ProviderDriverKind, ThreadId } from "@t3tools/contracts";
2 -import { Cause, Effect } from "effect";
2 +import * as Cause from "effect/Cause";
3 +import * as DateTime from "effect/DateTime";
4 +import * as Effect from "effect/Effect";
5 +import * as Random from "effect/Random";
6 import type * as EffectAcpProtocol from "effect-acp/protocol";
7
8 import type { EventNdjsonLogger } from "../Layers/EventNdjsonLogger.ts";
@@ -14,12 +17,12 @@ function writeNativeAcpLog(input: {
17 }): Effect.Effect<void, never> {
18 return Effect.gen(function* () {
19 if (!input.nativeEventLogger) return;
17 - const observedAt = new Date().toISOString();
20 + const observedAt = DateTime.formatIso(yield* DateTime.now);
21 yield* input.nativeEventLogger.write(
22 {
23 observedAt,
24 event: {
22 - id: crypto.randomUUID(),
25 + id: yield* Random.nextUUIDv4,
26 kind: input.kind,
27 provider: input.provider,
28 createdAt: observedAt,
apps/server/src/provider/acp/AcpSessionRuntime.ts
+15 -5
@@ -1,4 +1,14 @@
1 -import { Cause, Deferred, Effect, Exit, Layer, Queue, Ref, Scope, Context, Stream } from "effect";
1 +import * as Cause from "effect/Cause";
2 +import * as Deferred from "effect/Deferred";
3 +import * as Effect from "effect/Effect";
4 +import * as Exit from "effect/Exit";
5 +import * as Layer from "effect/Layer";
6 +import * as Queue from "effect/Queue";
7 +import * as Ref from "effect/Ref";
8 +import * as Scope from "effect/Scope";
9 +import * as Context from "effect/Context";
10 +import * as Schema from "effect/Schema";
11 +import * as Stream from "effect/Stream";
12 import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
13 import * as EffectAcpClient from "effect-acp/client";
14 import * as EffectAcpErrors from "effect-acp/errors";
@@ -248,7 +258,7 @@ const makeAcpSessionRuntime = (
258 }
259 return yield* new EffectAcpErrors.AcpTransportError({
260 detail: "ACP session runtime has not been started",
251 - cause: new Error("ACP session runtime has not been started"),
261 + cause: "ACP session runtime has not been started",
262 });
263 });
264
@@ -267,7 +277,7 @@ const makeAcpSessionRuntime = (
277 }
278 return yield* new EffectAcpErrors.AcpRequestError({
279 code: -32602,
270 - errorMessage: `Invalid value ${JSON.stringify(value)} for session config option "${configOption.id}": expected boolean`,
280 + errorMessage: `Invalid value ${Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(value)} for session config option "${configOption.id}": expected boolean`,
281 data: {
282 configId: configOption.id,
283 expectedType: "boolean",
@@ -278,7 +288,7 @@ const makeAcpSessionRuntime = (
288 if (typeof value !== "string") {
289 return yield* new EffectAcpErrors.AcpRequestError({
290 code: -32602,
281 - errorMessage: `Invalid value ${JSON.stringify(value)} for session config option "${configOption.id}": expected string`,
291 + errorMessage: `Invalid value ${Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(value)} for session config option "${configOption.id}": expected string`,
292 data: {
293 configId: configOption.id,
294 expectedType: "string",
@@ -292,7 +302,7 @@ const makeAcpSessionRuntime = (
302 }
303 return yield* new EffectAcpErrors.AcpRequestError({
304 code: -32602,
295 - errorMessage: `Invalid value ${JSON.stringify(value)} for session config option "${configOption.id}": expected one of ${allowedValues.join(", ")}`,
305 + errorMessage: `Invalid value ${Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(value)} for session config option "${configOption.id}": expected one of ${allowedValues.join(", ")}`,
306 data: {
307 configId: configOption.id,
308 allowedValues,
apps/server/src/provider/acp/CursorAcpCliProbe.test.ts
+12 -7
@@ -4,7 +4,8 @@
4 */
5 import * as NodeServices from "@effect/platform-node/NodeServices";
6 import { it } from "@effect/vitest";
7 -import { Effect } from "effect";
7 +import * as Console from "effect/Console";
8 +import * as Effect from "effect/Effect";
9 import { describe, expect } from "vitest";
10 import type * as EffectAcpSchema from "effect-acp/schema";
11
@@ -44,12 +45,14 @@ describe.runIf(process.env.T3_CURSOR_ACP_PROBE === "1")("Cursor ACP CLI probe",
45 const runtime = yield* AcpSessionRuntime;
46 const started = yield* runtime.start();
47 const result = started.sessionSetupResult;
47 - console.log("session/new result:", JSON.stringify(result, null, 2));
48 + // @effect-diagnostics-next-line preferSchemaOverJson:off
49 + yield* Console.log("session/new result:", JSON.stringify(result, null, 2));
50
51 expect(typeof started.sessionId).toBe("string");
52
53 const configOptions = result.configOptions;
52 - console.log("session/new configOptions:", JSON.stringify(configOptions, null, 2));
54 + // @effect-diagnostics-next-line preferSchemaOverJson:off
55 + yield* Console.log("session/new configOptions:", JSON.stringify(configOptions, null, 2));
56
57 if (Array.isArray(configOptions)) {
58 const modelConfig = configOptions.find((opt) => opt.category === "model");
@@ -59,9 +62,11 @@ describe.runIf(process.env.T3_CURSOR_ACP_PROBE === "1")("Cursor ACP CLI probe",
62 opt.category === "model_option" ||
63 opt.category === "model_config",
64 );
62 - console.log("Model config option:", JSON.stringify(modelConfig, null, 2));
63 - console.log(
65 + // @effect-diagnostics-next-line preferSchemaOverJson:off
66 + yield* Console.log("Model config option:", JSON.stringify(modelConfig, null, 2));
67 + yield* Console.log(
68 "Parameterized model config options:",
69 + // @effect-diagnostics-next-line preferSchemaOverJson:off
70 JSON.stringify(parameterizedOptions, null, 2),
71 );
72 expect(modelConfig).toBeDefined();
@@ -107,8 +112,8 @@ describe.runIf(process.env.T3_CURSOR_ACP_PROBE === "1")("Cursor ACP CLI probe",
112
113 const setResult: EffectAcpSchema.SetSessionConfigOptionResponse =
114 yield* runtime.setConfigOption(modelConfigId, "gpt-5.4");
110 -
111 - console.log("session/set_config_option result:", JSON.stringify(setResult, null, 2));
115 + // @effect-diagnostics-next-line preferSchemaOverJson:off
116 + yield* Console.log("session/set_config_option result:", JSON.stringify(setResult, null, 2));
117
118 if (Array.isArray(setResult.configOptions)) {
119 const modelConfig = setResult.configOptions.find((opt) => opt.category === "model");
apps/server/src/provider/acp/CursorAcpExtension.ts
+1 -1
@@ -3,7 +3,7 @@
3 * Additional reference provided by the Cursor team: https://anysphere.enterprise.slack.com/files/U068SSJE141/F0APT1HSZRP/cursor-acp-extension-method-schemas.md
4 */
5 import type { UserInputQuestion } from "@t3tools/contracts";
6 -import { Schema } from "effect";
6 +import * as Schema from "effect/Schema";
7
8 const CursorAskQuestionOption = Schema.Struct({
9 id: Schema.String,
apps/server/src/provider/acp/CursorAcpSupport.test.ts
+4 -6
@@ -1,4 +1,4 @@
1 -import { Effect } from "effect";
1 +import * as Effect from "effect/Effect";
2 import type * as EffectAcpSchema from "effect-acp/schema";
3 import { describe, expect, it } from "vitest";
4
@@ -105,11 +105,9 @@ describe("applyCursorAcpModelSelection", () => {
105 { id: "fastMode", value: true },
106 ],
107 mapError: ({ step, configId, cause }) =>
108 - new Error(
109 - step === "set-config-option"
110 - ? `failed to set config option ${configId}: ${cause.message}`
111 - : `failed to set model: ${cause.message}`,
112 - ),
108 + step === "set-config-option"
109 + ? `failed to set config option ${configId}: ${cause.message}`
110 + : `failed to set model: ${cause.message}`,
111 }),
112 );
113
apps/server/src/provider/acp/CursorAcpSupport.ts
+3 -1
@@ -1,5 +1,7 @@
1 import { type CursorSettings, type ProviderOptionSelection } from "@t3tools/contracts";
2 -import { Effect, Layer, Scope } from "effect";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 +import * as Scope from "effect/Scope";
5 import { ChildProcessSpawner } from "effect/unstable/process";
6 import type * as EffectAcpErrors from "effect-acp/errors";
7
apps/server/src/provider/builtInProviderCatalog.ts
+1 -1
@@ -1,5 +1,5 @@
1 import type { ProviderDriverKind, ProviderInstanceId, ServerProvider } from "@t3tools/contracts";
2 -import type { Stream } from "effect";
2 +import type * as Stream from "effect/Stream";
3 import type { ServerProviderShape } from "./Services/ServerProvider.ts";
4
5 export type ProviderSnapshotSource = {
apps/server/src/provider/makeManagedServerProvider.test.ts
+10 -5
@@ -1,7 +1,12 @@
1 import { describe, it, assert } from "@effect/vitest";
2 import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";
3 import { createModelCapabilities } from "@t3tools/shared/model";
4 -import { Deferred, Effect, Fiber, PubSub, Ref, Stream } from "effect";
4 +import * as Deferred from "effect/Deferred";
5 +import * as Effect from "effect/Effect";
6 +import * as Fiber from "effect/Fiber";
7 +import * as PubSub from "effect/PubSub";
8 +import * as Ref from "effect/Ref";
9 +import * as Stream from "effect/Stream";
10
11 import { makeManagedServerProvider } from "./makeManagedServerProvider.ts";
12
@@ -108,7 +113,7 @@ describe("makeManagedServerProvider", () => {
113 getSettings: Effect.succeed({ enabled: true }),
114 streamSettings: Stream.empty,
115 haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
111 - initialSnapshot: () => initialSnapshot,
116 + initialSnapshot: () => Effect.succeed(initialSnapshot),
117 checkProvider: Ref.update(checkCalls, (count) => count + 1).pipe(
118 Effect.flatMap(() => Deferred.await(releaseCheck)),
119 Effect.as(refreshedSnapshot),
@@ -150,7 +155,7 @@ describe("makeManagedServerProvider", () => {
155 getSettings: Ref.get(settingsRef),
156 streamSettings: Stream.fromPubSub(settingsChanges),
157 haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
153 - initialSnapshot: () => initialSnapshot,
158 + initialSnapshot: () => Effect.succeed(initialSnapshot),
159 checkProvider: Ref.updateAndGet(checkCalls, (count) => count + 1).pipe(
160 Effect.flatMap((count) =>
161 count === 1
@@ -192,7 +197,7 @@ describe("makeManagedServerProvider", () => {
197 getSettings: Effect.succeed({ enabled: true }),
198 streamSettings: Stream.empty,
199 haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
195 - initialSnapshot: () => initialSnapshot,
200 + initialSnapshot: () => Effect.succeed(initialSnapshot),
201 checkProvider: Deferred.await(releaseCheck).pipe(Effect.as(refreshedSnapshot)),
202 enrichSnapshot: ({ publishSnapshot }) =>
203 Deferred.await(releaseEnrichment).pipe(
@@ -233,7 +238,7 @@ describe("makeManagedServerProvider", () => {
238 getSettings: Effect.succeed({ enabled: true }),
239 streamSettings: Stream.empty,
240 haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
236 - initialSnapshot: () => initialSnapshot,
241 + initialSnapshot: () => Effect.succeed(initialSnapshot),
242 checkProvider: Ref.updateAndGet(refreshCount, (count) => count + 1).pipe(
243 Effect.flatMap((count) =>
244 count === 1
apps/server/src/provider/makeManagedServerProvider.ts
+10 -3
@@ -1,5 +1,12 @@
1 import type { ServerProvider } from "@t3tools/contracts";
2 -import { Duration, Effect, Equal, Fiber, PubSub, Ref, Scope, Stream } from "effect";
2 +import * as Duration from "effect/Duration";
3 +import * as Effect from "effect/Effect";
4 +import * as Equal from "effect/Equal";
5 +import * as Fiber from "effect/Fiber";
6 +import * as PubSub from "effect/PubSub";
7 +import * as Ref from "effect/Ref";
8 +import * as Scope from "effect/Scope";
9 +import * as Stream from "effect/Stream";
10 import * as Semaphore from "effect/Semaphore";
11
12 import type { ServerProviderShape } from "./Services/ServerProvider.ts";
@@ -17,7 +24,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
24 readonly getSettings: Effect.Effect<Settings>;
25 readonly streamSettings: Stream.Stream<Settings>;
26 readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean;
20 - readonly initialSnapshot: (settings: Settings) => ServerProvider;
27 + readonly initialSnapshot: (settings: Settings) => Effect.Effect<ServerProvider>;
28 readonly checkProvider: Effect.Effect<ServerProvider, ServerSettingsError>;
29 readonly enrichSnapshot?: (input: {
30 readonly settings: Settings;
@@ -33,7 +40,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
40 PubSub.shutdown,
41 );
42 const initialSettings = yield* input.getSettings;
36 - const initialSnapshot = input.initialSnapshot(initialSettings);
43 + const initialSnapshot = yield* input.initialSnapshot(initialSettings);
44 const snapshotStateRef = yield* Ref.make<ProviderSnapshotState>({
45 snapshot: initialSnapshot,
46 enrichmentGeneration: 0,
apps/server/src/provider/opencodeRuntime.ts
+19 -20
@@ -11,27 +11,26 @@ import {
11 type QuestionAnswer,
12 type QuestionRequest,
13 } from "@opencode-ai/sdk/v2";
14 -import {
15 - Cause,
16 - Context,
17 - Data,
18 - Deferred,
19 - Effect,
20 - Exit,
21 - Fiber,
22 - Layer,
23 - Option,
24 - Predicate as P,
25 - Ref,
26 - Result,
27 - Scope,
28 - Stream,
29 -} from "effect";
14 +import * as Cause from "effect/Cause";
15 +import * as Context from "effect/Context";
16 +import * as Data from "effect/Data";
17 +import * as Deferred from "effect/Deferred";
18 +import * as Effect from "effect/Effect";
19 +import * as Exit from "effect/Exit";
20 +import * as Fiber from "effect/Fiber";
21 +import * as Layer from "effect/Layer";
22 +import * as Option from "effect/Option";
23 +import * as P from "effect/Predicate";
24 +import * as Ref from "effect/Ref";
25 +import * as Result from "effect/Result";
26 +import * as Scope from "effect/Scope";
27 +import * as Schema from "effect/Schema";
28 +import * as Stream from "effect/Stream";
29 import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
30
31 import { isWindowsCommandNotFound } from "../processRunner.ts";
32 import { collectStreamAsString } from "./providerSnapshot.ts";
34 -import { NetService } from "@t3tools/shared/Net";
33 +import * as NetService from "@t3tools/shared/Net";
34
35 const OPENCODE_SERVER_READY_PREFIX = "opencode server listening";
36 const DEFAULT_OPENCODE_SERVER_TIMEOUT_MS = 5_000;
@@ -66,7 +65,7 @@ export function openCodeRuntimeErrorDetail(cause: unknown): string {
65 const status = (anyCause.response as { status?: number } | undefined)?.status;
66 const body = anyCause.error ?? anyCause.data ?? anyCause.body;
67 try {
69 - return `status=${status ?? "?"} body=${JSON.stringify(body ?? cause)}`;
68 + return `status=${status ?? "?"} body=${Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(body ?? cause)}`;
69 } catch {
70 /* fall through */
71 }
@@ -270,7 +269,7 @@ function ensureRuntimeError(
269
270 const makeOpenCodeRuntime = Effect.gen(function* () {
271 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
273 - const netService = yield* NetService;
272 + const netService = yield* NetService.NetService;
273
274 const runOpenCodeCommand: OpenCodeRuntimeShape["runOpenCodeCommand"] = (input) =>
275 Effect.gen(function* () {
@@ -337,7 +336,7 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
336 shell: process.platform === "win32",
337 env: {
338 ...(input.environment ?? process.env),
340 - OPENCODE_CONFIG_CONTENT: JSON.stringify({}),
339 + OPENCODE_CONFIG_CONTENT: Schema.encodeUnknownSync(Schema.UnknownFromJsonString)({}),
340 },
341 }),
342 )
apps/server/src/provider/providerMaintenance.test.ts
+3 -1
@@ -1,10 +1,12 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 import { afterEach, describe, expect, it } from "@effect/vitest";
3 import { chmodSync, mkdirSync, symlinkSync, writeFileSync } from "node:fs";
4 import * as NodeServices from "@effect/platform-node/NodeServices";
5 import os from "node:os";
6 import path from "node:path";
7 import { ProviderDriverKind } from "@t3tools/contracts";
7 -import { Effect, Random } from "effect";
8 +import * as Effect from "effect/Effect";
9 +import * as Random from "effect/Random";
10 import {
11 clearLatestProviderVersionCacheForTests,
12 createProviderVersionAdvisory,
apps/server/src/provider/providerMaintenance.ts
+5 -1
@@ -4,7 +4,11 @@ import {
4 type ServerProviderVersionAdvisory,
5 } from "@t3tools/contracts";
6 import { resolveCommandPath } from "@t3tools/shared/shell";
7 -import { DateTime, Effect, FileSystem, Option, Schema } from "effect";
7 +import * as DateTime from "effect/DateTime";
8 +import * as Effect from "effect/Effect";
9 +import * as FileSystem from "effect/FileSystem";
10 +import * as Option from "effect/Option";
11 +import * as Schema from "effect/Schema";
12 import { HttpClient, HttpClientRequest } from "effect/unstable/http";
13
14 import { compareCliVersions } from "./cliVersion.ts";
apps/server/src/provider/providerMaintenanceCommandCoordinator.ts
+2 -1
@@ -1,4 +1,5 @@
1 -import { Effect, Ref } from "effect";
1 +import * as Effect from "effect/Effect";
2 +import * as Ref from "effect/Ref";
3 import * as Semaphore from "effect/Semaphore";
4
5 export interface ProviderMaintenanceCommandCoordinatorShape<E> {
apps/server/src/provider/providerMaintenanceRunner.test.ts
+9 -1
@@ -6,7 +6,15 @@ import {
6 type ServerProviderUpdateState,
7 } from "@t3tools/contracts";
8 import { ServerProviderUpdateError } from "@t3tools/contracts";
9 -import { Cause, Effect, Exit, Fiber, Layer, Ref, Schema, Sink, Stream } from "effect";
9 +import * as Cause from "effect/Cause";
10 +import * as Effect from "effect/Effect";
11 +import * as Exit from "effect/Exit";
12 +import * as Fiber from "effect/Fiber";
13 +import * as Layer from "effect/Layer";
14 +import * as Ref from "effect/Ref";
15 +import * as Schema from "effect/Schema";
16 +import * as Sink from "effect/Sink";
17 +import * as Stream from "effect/Stream";
18 import { HttpClient, HttpClientResponse } from "effect/unstable/http";
19 import { ChildProcessSpawner } from "effect/unstable/process";
20
apps/server/src/provider/providerMaintenanceRunner.ts
+23 -3
@@ -7,7 +7,16 @@ import {
7 type ServerProviderUpdatedPayload,
8 type ServerProviderUpdateState,
9 } from "@t3tools/contracts";
10 -import { Cause, Context, DateTime, Duration, Effect, Layer, Option, Ref, Schema } from "effect";
10 +import * as Cause from "effect/Cause";
11 +import * as Context from "effect/Context";
12 +import * as Data from "effect/Data";
13 +import * as DateTime from "effect/DateTime";
14 +import * as Duration from "effect/Duration";
15 +import * as Effect from "effect/Effect";
16 +import * as Layer from "effect/Layer";
17 +import * as Option from "effect/Option";
18 +import * as Ref from "effect/Ref";
19 +import * as Schema from "effect/Schema";
20 import { HttpClient } from "effect/unstable/http";
21 import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
22
@@ -45,6 +54,11 @@ export class ProviderMaintenanceRunner extends Context.Service<
54 ProviderMaintenanceRunnerShape
55 >()("t3/provider/ProviderMaintenanceRunner") {}
56
57 +class ProviderMaintenanceCommandError extends Data.TaggedError("ProviderMaintenanceCommandError")<{
58 + readonly message: string;
59 + readonly cause?: unknown;
60 +}> {}
61 +
62 interface VerifiedProviderRefresh {
63 readonly providers: ReadonlyArray<ServerProvider>;
64 readonly verifiedProviders: ReadonlyArray<ServerProvider>;
@@ -65,7 +79,10 @@ const runProviderMaintenanceCommandWithSpawner = Effect.fn("ProviderMaintenanceR
79 .pipe(
80 Effect.mapError(
81 (cause) =>
68 - new Error(`Failed to run update command ${input.command}: ${cause.message}`),
82 + new ProviderMaintenanceCommandError({
83 + message: `Failed to run update command ${input.command}: ${cause.message}`,
84 + cause,
85 + }),
86 ),
87 );
88 yield* Effect.addFinalizer(() => child.kill().pipe(Effect.ignore));
@@ -86,7 +103,10 @@ const runProviderMaintenanceCommandWithSpawner = Effect.fn("ProviderMaintenanceR
103 ).pipe(
104 Effect.mapError(
105 (cause) =>
89 - new Error(cause instanceof Error ? cause.message : "Update command failed to run."),
106 + new ProviderMaintenanceCommandError({
107 + message: cause instanceof Error ? cause.message : "Update command failed to run.",
108 + cause,
109 + }),
110 ),
111 );
112
apps/server/src/provider/providerSnapshot.ts
+11 -3
@@ -8,7 +8,9 @@ import type {
8 ServerProviderModel,
9 ServerProviderState,
10 } from "@t3tools/contracts";
11 -import { Effect, Stream } from "effect";
11 +import * as Effect from "effect/Effect";
12 +import * as Data from "effect/Data";
13 +import * as Stream from "effect/Stream";
14 import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
15 import { normalizeModelSlug } from "@t3tools/shared/model";
16 import { isWindowsCommandNotFound } from "../processRunner.ts";
@@ -25,6 +27,12 @@ export interface CommandResult {
27 readonly code: number;
28 }
29
30 +export class ProviderCommandExecutionError extends Data.TaggedError(
31 + "ProviderCommandExecutionError",
32 +)<{
33 + readonly message: string;
34 +}> {}
35 +
36 export interface ProviderProbeResult {
37 readonly installed: boolean;
38 readonly version: string | null;
@@ -47,7 +55,7 @@ export function nonEmptyTrimmed(value: string | undefined): string | undefined {
55 return trimmed.length > 0 ? trimmed : undefined;
56 }
57
50 -export function isCommandMissingCause(error: Error): boolean {
58 +export function isCommandMissingCause(error: { readonly message: string }): boolean {
59 const lower = error.message.toLowerCase();
60 return lower.includes("enoent") || lower.includes("notfound");
61 }
@@ -67,7 +75,7 @@ export const spawnAndCollect = (binaryPath: string, command: ChildProcess.Comman
75
76 const result: CommandResult = { stdout, stderr, code: exitCode };
77 if (isWindowsCommandNotFound(exitCode, stderr)) {
70 - return yield* Effect.fail(new Error(`spawn ${binaryPath} ENOENT`));
78 + return yield* new ProviderCommandExecutionError({ message: `spawn ${binaryPath} ENOENT` });
79 }
80 return result;
81 }).pipe(Effect.scoped);
apps/server/src/provider/providerStatusCache.test.ts
+2 -1
@@ -7,7 +7,8 @@ import {
7 } from "@t3tools/contracts";
8 import { createModelCapabilities } from "@t3tools/shared/model";
9 import { assert, it } from "@effect/vitest";
10 -import { Effect, FileSystem } from "effect";
10 +import * as Effect from "effect/Effect";
11 +import * as FileSystem from "effect/FileSystem";
12
13 import {
14 hydrateCachedProvider,
apps/server/src/provider/providerStatusCache.ts
+5 -1
@@ -4,7 +4,11 @@ import {
4 type ServerProvider,
5 ServerProvider as ServerProviderSchema,
6 } from "@t3tools/contracts";
7 -import { Cause, Effect, FileSystem, Path, Schema } from "effect";
7 +import * as Cause from "effect/Cause";
8 +import * as Effect from "effect/Effect";
9 +import * as FileSystem from "effect/FileSystem";
10 +import * as Path from "effect/Path";
11 +import * as Schema from "effect/Schema";
12
13 import { writeFileStringAtomically } from "../atomicWrite.ts";
14
apps/server/src/provider/testUtils/providerAdapterRegistryMock.ts
+5 -1
@@ -18,7 +18,11 @@ import {
18 ProviderDriverKind,
19 type ProviderInstanceId,
20 } from "@t3tools/contracts";
21 -import { Effect, PubSub, Record, Result, Stream } from "effect";
21 +import * as Effect from "effect/Effect";
22 +import * as PubSub from "effect/PubSub";
23 +import * as Record from "effect/Record";
24 +import * as Result from "effect/Result";
25 +import * as Stream from "effect/Stream";
26
27 import { ProviderUnsupportedError, type ProviderAdapterError } from "../Errors.ts";
28 import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts";
apps/server/src/provider/unavailableProviderSnapshot.ts
+36 -29
@@ -15,6 +15,8 @@ import {
15 type ProviderInstanceId,
16 type ServerProvider,
17 } from "@t3tools/contracts";
18 +import * as DateTime from "effect/DateTime";
19 +import * as Effect from "effect/Effect";
20
21 import { buildServerProvider } from "./providerSnapshot.ts";
22
@@ -25,12 +27,15 @@ export interface UnavailableProviderSnapshotInput {
27 readonly accentColor?: string | undefined;
28 readonly reason: string;
29 /**
28 - * Optional override for `checkedAt`. Defaulted to `new Date()` so callers
30 + * Optional override for `checkedAt`. Defaulted to the current Effect
31 + * `DateTime` so callers
32 * (notably tests) don't have to pass it.
33 */
34 readonly checkedAt?: string;
35 }
36
37 +const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
38 +
39 /**
40 * Produce a `ServerProvider` snapshot representing a configured instance
41 * whose driver the running build does not implement. The result is safe
@@ -39,34 +44,36 @@ export interface UnavailableProviderSnapshotInput {
44 */
45 export function buildUnavailableProviderSnapshot(
46 input: UnavailableProviderSnapshotInput,
42 -): ServerProvider {
43 - const checkedAt = input.checkedAt ?? new Date().toISOString();
44 - const displayName = input.displayName?.trim() || (input.driverKind as string);
47 +): Effect.Effect<ServerProvider> {
48 + return Effect.gen(function* () {
49 + const checkedAt = input.checkedAt ?? (yield* nowIso);
50 + const displayName = input.displayName?.trim() || (input.driverKind as string);
51
46 - const base = buildServerProvider({
47 - presentation: { displayName },
48 - enabled: false,
49 - checkedAt,
50 - models: [],
51 - skills: [],
52 - probe: {
53 - installed: false,
54 - version: null,
55 - status: "error",
56 - auth: { status: "unknown" },
57 - message: input.reason,
58 - },
59 - });
52 + const base = buildServerProvider({
53 + presentation: { displayName },
54 + enabled: false,
55 + checkedAt,
56 + models: [],
57 + skills: [],
58 + probe: {
59 + installed: false,
60 + version: null,
61 + status: "error",
62 + auth: { status: "unknown" },
63 + message: input.reason,
64 + },
65 + });
66
61 - return {
62 - ...base,
63 - instanceId: input.instanceId,
64 - ...(input.accentColor ? { accentColor: input.accentColor } : {}),
65 - driver:
66 - typeof input.driverKind === "string"
67 - ? ProviderDriverKind.make(input.driverKind)
68 - : input.driverKind,
69 - availability: "unavailable",
70 - unavailableReason: input.reason,
71 - };
67 + return {
68 + ...base,
69 + instanceId: input.instanceId,
70 + ...(input.accentColor ? { accentColor: input.accentColor } : {}),
71 + driver:
72 + typeof input.driverKind === "string"
73 + ? ProviderDriverKind.make(input.driverKind)
74 + : input.driverKind,
75 + availability: "unavailable",
76 + unavailableReason: input.reason,
77 + };
78 + });
79 }
apps/server/src/server.test.ts
+59 -51
@@ -27,18 +27,17 @@ import {
27 } from "@t3tools/contracts";
28 import { assert, it } from "@effect/vitest";
29 import { assertFailure, assertInclude, assertTrue } from "@effect/vitest/utils";
30 -import {
31 - Deferred,
32 - DateTime,
33 - Duration,
34 - Effect,
35 - FileSystem,
36 - Layer,
37 - ManagedRuntime,
38 - Option,
39 - Path,
40 - Stream,
41 -} from "effect";
30 +import * as Clock from "effect/Clock";
31 +import * as Deferred from "effect/Deferred";
32 +import * as DateTime from "effect/DateTime";
33 +import * as Duration from "effect/Duration";
34 +import * as Effect from "effect/Effect";
35 +import * as FileSystem from "effect/FileSystem";
36 +import * as Layer from "effect/Layer";
37 +import * as ManagedRuntime from "effect/ManagedRuntime";
38 +import * as Option from "effect/Option";
39 +import * as Path from "effect/Path";
40 +import * as Stream from "effect/Stream";
41 import { ChildProcessSpawner } from "effect/unstable/process";
42 import {
43 FetchHttpClient,
@@ -92,6 +91,7 @@ import {
91 import { ProjectFaviconResolverLive } from "./project/Layers/ProjectFaviconResolver.ts";
92 import {
93 ProjectSetupScriptRunner,
94 + ProjectSetupScriptRunnerError,
95 type ProjectSetupScriptRunnerShape,
96 } from "./project/Services/ProjectSetupScriptRunner.ts";
97 import {
@@ -116,6 +116,7 @@ import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
116 import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";
117 import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
118 import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
119 +import * as Data from "effect/Data";
120
121 const defaultProjectId = ProjectId.make("project-default");
122 const defaultThreadId = ThreadId.make("thread-default");
@@ -137,7 +138,7 @@ const testEnvironmentDescriptor = {
138 },
139 };
140 const makeDefaultOrchestrationReadModel = () => {
140 - const now = new Date().toISOString();
141 + const now = "2026-01-01T00:00:00.000Z";
142 return {
143 snapshotSequence: 0,
144 updatedAt: now,
@@ -181,7 +182,7 @@ const makeDefaultOrchestrationReadModel = () => {
182 const makeDefaultOrchestrationThreadShell = (
183 overrides: Partial<OrchestrationThreadShell> = {},
184 ): OrchestrationThreadShell => {
184 - const now = new Date().toISOString();
185 + const now = "2026-01-01T00:00:00.000Z";
186 return {
187 id: defaultThreadId,
188 projectId: defaultProjectId,
@@ -302,15 +303,13 @@ const makeBrowserOtlpPayload = (spanName: string) =>
303 yield* Effect.promise(() => runtime.dispose());
304 }
305
305 - const request = yield* Effect.promise(() =>
306 - Promise.race([
307 - collector.firstRequest,
308 - new Promise<never>((_, reject) => {
309 - setTimeout(() => reject(new Error("Timed out waiting for OTLP trace export")), 1_000);
310 - }),
311 - ]),
306 + const request = yield* Effect.raceFirst(
307 + Effect.promise(() => collector.firstRequest).pipe(Effect.orDie),
308 + Effect.sleep(Duration.seconds(1)).pipe(
309 + Effect.andThen(Effect.die(new Error("Timed out waiting for OTLP trace export"))),
310 + ),
311 );
313 -
312 + // @effect-diagnostics-next-line preferSchemaOverJson:off
313 return JSON.parse(request.body) as OtlpTracer.TraceData;
314 });
315
@@ -629,7 +628,7 @@ const buildAppUnderTest = (options?: {
628 snapshotSequence: 0,
629 projects: [],
630 threads: [],
632 - updatedAt: new Date(0).toISOString(),
631 + updatedAt: "1970-01-01T00:00:00.000Z",
632 }),
633 getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
634 getProjectShellById: () => Effect.succeed(Option.none()),
@@ -823,17 +822,23 @@ const bootstrapBearerSession = (credential = defaultDesktopBootstrapToken) =>
822 };
823 });
824
825 +class AuthenticationGetterError extends Data.TaggedError("AuthenticationGetterError")<{
826 + readonly message: string;
827 +}> {}
828 +
829 const getAuthenticatedSessionCookieHeader = (credential = defaultDesktopBootstrapToken) =>
830 Effect.gen(function* () {
831 const { response, cookie } = yield* bootstrapBrowserSession(credential);
832 if (!response.ok) {
830 - return yield* Effect.fail(
831 - new Error(`Expected bootstrap session response to succeed, got ${response.status}`),
832 - );
833 + return yield* new AuthenticationGetterError({
834 + message: `Expected bootstrap session response to succeed, got ${response.status}`,
835 + });
836 }
837
838 if (!cookie) {
836 - return yield* Effect.fail(new Error("Expected bootstrap session response to set a cookie."));
839 + return yield* new AuthenticationGetterError({
840 + message: "Expected bootstrap session response to set a cookie.",
841 + });
842 }
843
844 return cookie.split(";")[0] ?? cookie;
@@ -843,15 +848,15 @@ const getAuthenticatedBearerSessionToken = (credential = defaultDesktopBootstrap
848 Effect.gen(function* () {
849 const { response, body } = yield* bootstrapBearerSession(credential);
850 if (!response.ok) {
846 - return yield* Effect.fail(
847 - new Error(`Expected bearer bootstrap response to succeed, got ${response.status}`),
848 - );
851 + return yield* new AuthenticationGetterError({
852 + message: `Expected bearer bootstrap response to succeed, got ${response.status}`,
853 + });
854 }
855
856 if (!body.sessionToken) {
852 - return yield* Effect.fail(
853 - new Error("Expected bearer bootstrap response to include a session token."),
854 - );
857 + return yield* new AuthenticationGetterError({
858 + message: "Expected bearer bootstrap response to include a session token.",
859 + });
860 }
861
862 return body.sessionToken;
@@ -1758,6 +1763,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
1763 "content-type": "application/json",
1764 origin: "http://localhost:5733",
1765 },
1766 + // @effect-diagnostics-next-line preferSchemaOverJson:off
1767 body: HttpBody.text(JSON.stringify(payload), "application/json"),
1768 });
1769
@@ -1803,6 +1809,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
1809 ]);
1810 assert.deepEqual(upstreamRequests, [
1811 {
1812 + // @effect-diagnostics-next-line preferSchemaOverJson:off
1813 body: JSON.stringify(payload),
1814 contentType: "application/json",
1815 },
@@ -1875,6 +1882,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
1882 cookie: yield* getAuthenticatedSessionCookieHeader(),
1883 "content-type": "application/json",
1884 },
1885 + // @effect-diagnostics-next-line preferSchemaOverJson:off
1886 body: HttpBody.text(JSON.stringify(payload), "application/json"),
1887 });
1888
@@ -2182,7 +2190,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
2190 version: 1 as const,
2191 sequence: 2,
2192 type: "ready" as const,
2185 - payload: { at: new Date().toISOString(), environment: testEnvironmentDescriptor },
2193 + payload: { at: "2026-01-01T00:00:00.000Z", environment: testEnvironmentDescriptor },
2194 });
2195
2196 yield* buildAppUnderTest({
@@ -2370,7 +2378,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
2378 instanceId: ProviderInstanceId.make("codex"),
2379 model: "gpt-5-codex",
2380 },
2373 - createdAt: new Date().toISOString(),
2381 + createdAt: "2026-01-01T00:00:00.000Z",
2382 }),
2383 ),
2384 );
@@ -2913,11 +2921,11 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
2921 });
2922
2923 const wsUrl = yield* getWsServerUrl("/ws");
2916 - const startedAt = Date.now();
2924 + const startedAt = yield* Clock.currentTimeMillis;
2925 const result = yield* Effect.scoped(
2926 withWsRpcClient(wsUrl, (client) => client[WS_METHODS.vcsPull]({ cwd: "/tmp/repo" })),
2927 );
2920 - const elapsedMs = Date.now() - startedAt;
2928 + const elapsedMs = (yield* Clock.currentTimeMillis) - startedAt;
2929
2930 assert.equal(result.status, "pulled");
2931 assertTrue(elapsedMs < 1_000);
@@ -2982,7 +2990,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
2990 });
2991
2992 const wsUrl = yield* getWsServerUrl("/ws");
2985 - const startedAt = Date.now();
2993 + const startedAt = yield* Clock.currentTimeMillis;
2994 yield* Effect.scoped(
2995 withWsRpcClient(wsUrl, (client) =>
2996 client[WS_METHODS.gitRunStackedAction]({
@@ -2992,7 +3000,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
3000 }).pipe(Stream.runCollect),
3001 ),
3002 );
2995 - const elapsedMs = Date.now() - startedAt;
3003 + const elapsedMs = (yield* Clock.currentTimeMillis) - startedAt;
3004
3005 assertTrue(elapsedMs < 1_000);
3006 }).pipe(Effect.provide(NodeHttpServer.layerTest)),
@@ -3079,7 +3087,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
3087
3088 it.effect("routes websocket rpc orchestration methods", () =>
3089 Effect.gen(function* () {
3082 - const now = new Date().toISOString();
3090 + const now = "2026-01-01T00:00:00.000Z";
3091 const snapshot = {
3092 snapshotSequence: 1,
3093 updatedAt: now,
@@ -3292,7 +3300,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
3300 const threadId = ThreadId.make("thread-archive");
3301 const effects: string[] = [];
3302 const dispatchedCommands: Array<OrchestrationCommand> = [];
3295 - const now = new Date().toISOString();
3303 + const now = "2026-01-01T00:00:00.000Z";
3304
3305 yield* buildAppUnderTest({
3306 layers: {
@@ -3363,7 +3371,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
3371 const threadId = ThreadId.make("thread-archive-precheck");
3372 const effects: string[] = [];
3373 const dispatchedCommands: Array<OrchestrationCommand> = [];
3366 - const now = new Date().toISOString();
3374 + const now = "2026-01-01T00:00:00.000Z";
3375 let archived = false;
3376
3377 yield* buildAppUnderTest({
@@ -3494,7 +3502,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
3502 const threadId = ThreadId.make("thread-archive-stopped-session");
3503 const effects: string[] = [];
3504 const dispatchedCommands: Array<OrchestrationCommand> = [];
3497 - const now = new Date().toISOString();
3505 + const now = "2026-01-01T00:00:00.000Z";
3506
3507 yield* buildAppUnderTest({
3508 layers: {
@@ -3560,7 +3568,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
3568 const threadId = ThreadId.make("thread-archive-stop-failure");
3569 const effects: string[] = [];
3570 const dispatchedCommands: Array<OrchestrationCommand> = [];
3563 - const now = new Date().toISOString();
3571 + const now = "2026-01-01T00:00:00.000Z";
3572
3573 yield* buildAppUnderTest({
3574 layers: {
@@ -3637,7 +3645,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
3645 const threadId = ThreadId.make("thread-archive-stop-defect");
3646 const effects: string[] = [];
3647 const dispatchedCommands: Array<OrchestrationCommand> = [];
3640 - const now = new Date().toISOString();
3648 + const now = "2026-01-01T00:00:00.000Z";
3649
3650 yield* buildAppUnderTest({
3651 layers: {
@@ -3769,7 +3777,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
3777 },
3778 });
3779
3772 - const createdAt = new Date().toISOString();
3780 + const createdAt = "2026-01-01T00:00:00.000Z";
3781 const wsUrl = yield* getWsServerUrl("/ws");
3782 const response = yield* Effect.scoped(
3783 withWsRpcClient(wsUrl, (client) =>
@@ -3864,7 +3872,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
3872 );
3873 const runForThread = vi.fn(
3874 (_: Parameters<ProjectSetupScriptRunnerShape["runForThread"]>[0]) =>
3867 - Effect.fail(new Error("pty unavailable")),
3875 + Effect.fail(new ProjectSetupScriptRunnerError({ message: "pty unavailable" })),
3876 );
3877
3878 yield* buildAppUnderTest({
@@ -3886,7 +3894,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
3894 },
3895 });
3896
3889 - const createdAt = new Date().toISOString();
3897 + const createdAt = "2026-01-01T00:00:00.000Z";
3898 const wsUrl = yield* getWsServerUrl("/ws");
3899 const response = yield* Effect.scoped(
3900 withWsRpcClient(wsUrl, (client) =>
@@ -4003,7 +4011,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
4011 },
4012 });
4013
4006 - const createdAt = new Date().toISOString();
4014 + const createdAt = "2026-01-01T00:00:00.000Z";
4015 const wsUrl = yield* getWsServerUrl("/ws");
4016 const response = yield* Effect.scoped(
4017 withWsRpcClient(wsUrl, (client) =>
@@ -4087,7 +4095,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
4095 },
4096 });
4097
4090 - const createdAt = new Date().toISOString();
4098 + const createdAt = "2026-01-01T00:00:00.000Z";
4099 const wsUrl = yield* getWsServerUrl("/ws");
4100 const result = yield* Effect.scoped(
4101 withWsRpcClient(wsUrl, (client) =>
@@ -4149,7 +4157,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
4157 history: "",
4158 exitCode: null,
4159 exitSignal: null,
4152 - updatedAt: new Date().toISOString(),
4160 + updatedAt: "2026-01-01T00:00:00.000Z",
4161 };
4162
4163 yield* buildAppUnderTest({
apps/server/src/server.ts
+5 -8
@@ -1,4 +1,5 @@
1 -import { Effect, Layer } from "effect";
1 +import * as Effect from "effect/Effect";
2 +import * as Layer from "effect/Layer";
3 import { FetchHttpClient, HttpRouter, HttpServer } from "effect/unstable/http";
4
5 import { ServerConfig } from "./config.ts";
@@ -86,7 +87,7 @@ import {
87 orchestrationDispatchRouteLayer,
88 orchestrationSnapshotRouteLayer,
89 } from "./orchestration/http.ts";
89 -import { NetService } from "@t3tools/shared/Net";
90 +import * as NetService from "@t3tools/shared/Net";
91 import { disableTailscaleServe, ensureTailscaleServe } from "@t3tools/tailscale";
92
93 const PtyAdapterLive = Layer.unwrap(
@@ -333,7 +334,7 @@ export const makeServerLayer = Layer.unwrap(
334 return;
335 }
336
336 - const state = makePersistedServerRuntimeState({
337 + const state = yield* makePersistedServerRuntimeState({
338 config,
339 port: address.port,
340 });
@@ -418,8 +419,4 @@ export const makeServerLayer = Layer.unwrap(
419 );
420
421 // Important: Only `ServerConfig` should be provided by the CLI layer!!! Don't let other requirements leak into the launch layer.
421 -export const runServer = Layer.launch(makeServerLayer) satisfies Effect.Effect<
422 - never,
423 - any,
424 - ServerConfig
425 ->;
422 +export const runServer = Layer.launch(makeServerLayer);
apps/server/src/serverLifecycleEvents.test.ts
+3 -2
@@ -1,7 +1,8 @@
1 import { EnvironmentId } from "@t3tools/contracts";
2 import { assert, it } from "@effect/vitest";
3 import { assertTrue } from "@effect/vitest/utils";
4 -import { Effect, Option } from "effect";
4 +import * as Effect from "effect/Effect";
5 +import * as Option from "effect/Option";
6
7 import { ServerLifecycleEvents, ServerLifecycleEventsLive } from "./serverLifecycleEvents.ts";
8
@@ -37,7 +38,7 @@ it.effect(
38 version: 1,
39 type: "ready",
40 payload: {
40 - at: new Date().toISOString(),
41 + at: "2026-01-01T00:00:00.000Z",
42 environment,
43 },
44 })
apps/server/src/serverLifecycleEvents.ts
+6 -1
@@ -1,5 +1,10 @@
1 import type { ServerLifecycleStreamEvent } from "@t3tools/contracts";
2 -import { Effect, Layer, PubSub, Ref, Context, Stream } from "effect";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 +import * as PubSub from "effect/PubSub";
5 +import * as Ref from "effect/Ref";
6 +import * as Context from "effect/Context";
7 +import * as Stream from "effect/Stream";
8
9 type LifecycleEventInput =
10 | Omit<Extract<ServerLifecycleStreamEvent, { type: "welcome" }>, "sequence">
apps/server/src/serverLogger.ts
+4 -1
@@ -1,4 +1,7 @@
1 -import { Effect, Logger, References, Layer } from "effect";
1 +import * as Effect from "effect/Effect";
2 +import * as Logger from "effect/Logger";
3 +import * as References from "effect/References";
4 +import * as Layer from "effect/Layer";
5
6 import { ServerConfig } from "./config.ts";
7
apps/server/src/serverRuntimeStartup.test.ts
+6 -1
@@ -1,7 +1,12 @@
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { DEFAULT_MODEL, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
3 import { assert, it } from "@effect/vitest";
4 -import { Deferred, Effect, Fiber, Option, Ref, Stream } from "effect";
4 +import * as Deferred from "effect/Deferred";
5 +import * as Effect from "effect/Effect";
6 +import * as Fiber from "effect/Fiber";
7 +import * as Option from "effect/Option";
8 +import * as Ref from "effect/Ref";
9 +import * as Stream from "effect/Stream";
10
11 import { ServerConfig } from "./config.ts";
12 import {
apps/server/src/serverRuntimeStartup.ts
+16 -17
@@ -7,20 +7,19 @@ import {
7 ProviderInstanceId,
8 ThreadId,
9 } from "@t3tools/contracts";
10 -import {
11 - Data,
12 - Deferred,
13 - Effect,
14 - Exit,
15 - Layer,
16 - Option,
17 - Path,
18 - Queue,
19 - Ref,
20 - Scope,
21 - Context,
22 - Console,
23 -} from "effect";
10 +import * as Data from "effect/Data";
11 +import * as Deferred from "effect/Deferred";
12 +import * as Effect from "effect/Effect";
13 +import * as Exit from "effect/Exit";
14 +import * as Layer from "effect/Layer";
15 +import * as Option from "effect/Option";
16 +import * as Path from "effect/Path";
17 +import * as Queue from "effect/Queue";
18 +import * as Ref from "effect/Ref";
19 +import * as Scope from "effect/Scope";
20 +import * as Context from "effect/Context";
21 +import * as Console from "effect/Console";
22 +import * as DateTime from "effect/DateTime";
23
24 import { ServerConfig } from "./config.ts";
25 import { Keybindings } from "./keybindings.ts";
@@ -188,7 +187,7 @@ export const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {
187 let nextProjectDefaultModelSelection: ModelSelection;
188
189 if (Option.isNone(existingProject)) {
191 - const createdAt = new Date().toISOString();
190 + const createdAt = DateTime.formatIso(yield* DateTime.now);
191 nextProjectId = ProjectId.make(crypto.randomUUID());
192 const bootstrapProjectTitle = path.basename(serverConfig.cwd) || "project";
193 nextProjectDefaultModelSelection = getAutoBootstrapDefaultModelSelection();
@@ -210,7 +209,7 @@ export const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {
209 const existingThreadId =
210 yield* projectionReadModelQuery.getFirstActiveThreadIdByProjectId(nextProjectId);
211 if (Option.isNone(existingThreadId)) {
213 - const createdAt = new Date().toISOString();
212 + const createdAt = DateTime.formatIso(yield* DateTime.now);
213 const createdThreadId = ThreadId.make(crypto.randomUUID());
214 yield* orchestrationEngine.dispatch({
215 type: "thread.create",
@@ -423,7 +422,7 @@ export const makeServerRuntimeStartup = Effect.gen(function* () {
422 version: 1,
423 type: "ready",
424 payload: {
426 - at: new Date().toISOString(),
425 + at: DateTime.formatIso(yield* DateTime.now),
426 environment: yield* serverEnvironment.getDescriptor,
427 },
428 }),
apps/server/src/serverRuntimeState.ts
+14 -9
@@ -1,4 +1,8 @@
1 -import { Effect, FileSystem, Option, Schema } from "effect";
1 +import * as DateTime from "effect/DateTime";
2 +import * as Effect from "effect/Effect";
3 +import * as FileSystem from "effect/FileSystem";
4 +import * as Option from "effect/Option";
5 +import * as Schema from "effect/Schema";
6
7 import { writeFileStringAtomically } from "./atomicWrite.ts";
8 import { type ServerConfigShape } from "./config.ts";
@@ -30,14 +34,15 @@ const runtimeOriginForConfig = (
34 export const makePersistedServerRuntimeState = (input: {
35 readonly config: Pick<ServerConfigShape, "host">;
36 readonly port: number;
33 -}): PersistedServerRuntimeState => ({
34 - version: 1,
35 - pid: process.pid,
36 - ...(input.config.host ? { host: input.config.host } : {}),
37 - port: input.port,
38 - origin: runtimeOriginForConfig(input.config, input.port),
39 - startedAt: new Date().toISOString(),
40 -});
37 +}): Effect.Effect<PersistedServerRuntimeState> =>
38 + Effect.map(DateTime.now, (now) => ({
39 + version: 1,
40 + pid: process.pid,
41 + ...(input.config.host ? { host: input.config.host } : {}),
42 + port: input.port,
43 + origin: runtimeOriginForConfig(input.config, input.port),
44 + startedAt: DateTime.formatIso(now),
45 + }));
46
47 export const persistServerRuntimeState = (input: {
48 readonly path: string;
apps/server/src/serverSettings.test.ts
+6 -1
@@ -8,7 +8,10 @@ import {
8 } from "@t3tools/contracts";
9 import { createModelSelection } from "@t3tools/shared/model";
10 import { assert, it } from "@effect/vitest";
11 -import { Effect, FileSystem, Layer, Schema } from "effect";
11 +import * as Effect from "effect/Effect";
12 +import * as FileSystem from "effect/FileSystem";
13 +import * as Layer from "effect/Layer";
14 +import * as Schema from "effect/Schema";
15 import { ServerConfig } from "./config.ts";
16 import { ServerSettingsLive, ServerSettingsService } from "./serverSettings.ts";
17
@@ -439,6 +442,7 @@ it.layer(NodeServices.layer)("server settings", (it) => {
442 assert.equal(next.providers.codex.binaryPath, "/opt/homebrew/bin/codex");
443
444 const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
445 + // @effect-diagnostics-next-line preferSchemaOverJson:off
446 assert.deepEqual(JSON.parse(raw), {
447 addProjectBaseDirectory: "~/Development",
448 observability: {
@@ -490,6 +494,7 @@ it.layer(NodeServices.layer)("server settings", (it) => {
494
495 const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
496 assert.notInclude(raw, "sk-or-secret");
497 + // @effect-diagnostics-next-line preferSchemaOverJson:off
498 assert.deepEqual(JSON.parse(raw).providerInstances.codex_personal.environment, [
499 {
500 name: "OPENROUTER_API_KEY",
apps/server/src/serverSettings.ts
+17 -19
@@ -24,25 +24,23 @@ import {
24 ServerSettingsError,
25 type ServerSettingsPatch,
26 } from "@t3tools/contracts";
27 -import {
28 - Cache,
29 - Deferred,
30 - Duration,
31 - Effect,
32 - Exit,
33 - FileSystem,
34 - Layer,
35 - Path,
36 - Equal,
37 - PubSub,
38 - Ref,
39 - Schema,
40 - SchemaIssue,
41 - Scope,
42 - Context,
43 - Stream,
44 - Cause,
45 -} from "effect";
27 +import * as Cache from "effect/Cache";
28 +import * as Deferred from "effect/Deferred";
29 +import * as Duration from "effect/Duration";
30 +import * as Effect from "effect/Effect";
31 +import * as Exit from "effect/Exit";
32 +import * as FileSystem from "effect/FileSystem";
33 +import * as Layer from "effect/Layer";
34 +import * as Path from "effect/Path";
35 +import * as Equal from "effect/Equal";
36 +import * as PubSub from "effect/PubSub";
37 +import * as Ref from "effect/Ref";
38 +import * as Schema from "effect/Schema";
39 +import * as SchemaIssue from "effect/SchemaIssue";
40 +import * as Scope from "effect/Scope";
41 +import * as Context from "effect/Context";
42 +import * as Stream from "effect/Stream";
43 +import * as Cause from "effect/Cause";
44 import * as Semaphore from "effect/Semaphore";
45 import { writeFileStringAtomically } from "./atomicWrite.ts";
46 import { ServerConfig } from "./config.ts";
apps/server/src/sourceControl/AzureDevOpsCli.test.ts
+9 -3
@@ -1,8 +1,10 @@
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { assert, it, afterEach, describe, expect, vi } from "@effect/vitest";
3 -import { Effect, FileSystem, Layer, Option } from "effect";
3 +import * as Effect from "effect/Effect";
4 +import * as FileSystem from "effect/FileSystem";
5 +import * as Layer from "effect/Layer";
6 +import * as Option from "effect/Option";
7 import { ChildProcessSpawner } from "effect/unstable/process";
5 -import type { VcsError } from "@t3tools/contracts";
8
9 import * as VcsProcess from "../vcs/VcsProcess.ts";
10 import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
@@ -35,6 +37,7 @@ describe("AzureDevOpsCli.layer", () => {
37 mockRun.mockReturnValueOnce(
38 Effect.succeed(
39 processOutput(
40 + // @effect-diagnostics-next-line preferSchemaOverJson:off
41 JSON.stringify({
42 pullRequestId: 42,
43 title: "Add Azure provider",
@@ -91,6 +94,7 @@ describe("AzureDevOpsCli.layer", () => {
94 mockRun.mockReturnValueOnce(
95 Effect.succeed(
96 processOutput(
97 + // @effect-diagnostics-next-line preferSchemaOverJson:off
98 JSON.stringify([
99 {
100 pullRequestId: 7,
@@ -149,6 +153,7 @@ describe("AzureDevOpsCli.layer", () => {
153 mockRun.mockReturnValueOnce(
154 Effect.succeed(
155 processOutput(
156 + // @effect-diagnostics-next-line preferSchemaOverJson:off
157 JSON.stringify({
158 name: "repo",
159 webUrl: "https://dev.azure.com/acme/project/_git/repo",
@@ -181,6 +186,7 @@ describe("AzureDevOpsCli.layer", () => {
186 mockRun.mockReturnValueOnce(
187 Effect.succeed(
188 processOutput(
189 + // @effect-diagnostics-next-line preferSchemaOverJson:off
190 JSON.stringify({
191 name: "repo",
192 webUrl: "https://dev.azure.com/acme/project/_git/repo",
@@ -231,7 +237,7 @@ describe("AzureDevOpsCli.layer", () => {
237 it.effect("creates pull requests using the body file as the Azure description", () =>
238 Effect.gen(function* () {
239 const fileSystem = yield* FileSystem.FileSystem;
234 - const bodyFile = `/tmp/t3code-azure-devops-cli-${Date.now()}.md`;
240 + const bodyFile = `/tmp/t3code-azure-devops-cli-.md`;
241 yield* fileSystem.writeFileString(bodyFile, "Generated body");
242 mockRun.mockReturnValueOnce(Effect.succeed(processOutput("{}")));
243
apps/server/src/sourceControl/AzureDevOpsCli.ts
+6 -1
@@ -1,4 +1,9 @@
1 -import { Context, Effect, Layer, Result, Schema, SchemaIssue } from "effect";
1 +import * as Context from "effect/Context";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 +import * as Result from "effect/Result";
5 +import * as Schema from "effect/Schema";
6 +import * as SchemaIssue from "effect/SchemaIssue";
7 import {
8 TrimmedNonEmptyString,
9 type SourceControlRepositoryVisibility,
apps/server/src/sourceControl/AzureDevOpsSourceControlProvider.test.ts
+3 -1
@@ -1,5 +1,7 @@
1 import { assert, it } from "@effect/vitest";
2 -import { Effect, Layer, Option } from "effect";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 +import * as Option from "effect/Option";
5
6 import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
7 import * as AzureDevOpsSourceControlProvider from "./AzureDevOpsSourceControlProvider.ts";
apps/server/src/sourceControl/AzureDevOpsSourceControlProvider.ts
+7 -6
@@ -1,4 +1,5 @@
1 -import { Effect, Layer } from "effect";
1 +import * as Effect from "effect/Effect";
2 +import * as Layer from "effect/Layer";
3 import { SourceControlProviderError, type ChangeRequest } from "@t3tools/contracts";
4
5 import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
@@ -30,7 +31,7 @@ function parseAzureAuth(input: SourceControlProviderDiscovery.SourceControlAuthP
31 });
32 }
33
33 - if (account && account.length > 0) {
34 + if (account !== undefined && account.length > 0) {
35 return SourceControlProviderDiscovery.providerAuth({
36 status: "authenticated",
37 account,
@@ -90,7 +91,7 @@ export const make = Effect.fn("makeAzureDevOpsSourceControlProvider")(function*
91 .listPullRequests({
92 cwd: input.cwd,
93 headSelector: input.headSelector,
93 - ...(source ? { source } : {}),
94 + ...(source !== undefined ? { source } : {}),
95 state: input.state,
96 ...(input.limit !== undefined ? { limit: input.limit } : {}),
97 })
@@ -111,8 +112,8 @@ export const make = Effect.fn("makeAzureDevOpsSourceControlProvider")(function*
112 cwd: input.cwd,
113 baseBranch: input.baseRefName,
114 headSelector: input.headSelector,
114 - ...(source ? { source } : {}),
115 - ...(input.target ? { target: input.target } : {}),
115 + ...(source !== undefined ? { source } : {}),
116 + ...(input.target !== undefined ? { target: input.target } : {}),
117 title: input.title,
118 bodyFile: input.bodyFile,
119 })
@@ -135,7 +136,7 @@ export const make = Effect.fn("makeAzureDevOpsSourceControlProvider")(function*
136 .checkoutPullRequest({
137 cwd: input.cwd,
138 reference: input.reference,
138 - ...(input.context ? { remoteName: input.context.remoteName } : {}),
139 + ...(input.context !== undefined ? { remoteName: input.context.remoteName } : {}),
140 })
141 .pipe(Effect.mapError((error) => providerError("checkoutChangeRequest", error))),
142 });
apps/server/src/sourceControl/BitbucketApi.test.ts
+8 -1
@@ -1,6 +1,11 @@
1 import { assert, it, vi } from "@effect/vitest";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 -import { ConfigProvider, DateTime, Effect, FileSystem, Layer, Option } from "effect";
3 +import * as ConfigProvider from "effect/ConfigProvider";
4 +import * as DateTime from "effect/DateTime";
5 +import * as Effect from "effect/Effect";
6 +import * as FileSystem from "effect/FileSystem";
7 +import * as Layer from "effect/Layer";
8 +import * as Option from "effect/Option";
9 import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
10
11 import * as BitbucketApi from "./BitbucketApi.ts";
@@ -423,6 +428,7 @@ it.effect("creates repositories through the Bitbucket REST API", () => {
428 assert.ok(request);
429 const rawBody = (request.body as { readonly body?: Uint8Array }).body;
430 assert.ok(rawBody);
431 + // @effect-diagnostics-next-line preferSchemaOverJson:off
432 assert.deepStrictEqual(JSON.parse(new TextDecoder().decode(rawBody)), {
433 scm: "git",
434 is_private: true,
@@ -458,6 +464,7 @@ it.effect("creates pull requests using the official REST payload shape", () => {
464 assert.ok(request);
465 const rawBody = (request.body as { readonly body?: Uint8Array }).body;
466 assert.ok(rawBody);
467 + // @effect-diagnostics-next-line preferSchemaOverJson:off
468 assert.deepStrictEqual(JSON.parse(new TextDecoder().decode(rawBody)), {
469 title: "Provider PR",
470 description: "PR body",
apps/server/src/sourceControl/BitbucketApi.ts
+7 -1
@@ -1,4 +1,10 @@
1 -import { Config, Context, Effect, FileSystem, Layer, Option, Schema } from "effect";
1 +import * as Config from "effect/Config";
2 +import * as Context from "effect/Context";
3 +import * as Effect from "effect/Effect";
4 +import * as FileSystem from "effect/FileSystem";
5 +import * as Layer from "effect/Layer";
6 +import * as Option from "effect/Option";
7 +import * as Schema from "effect/Schema";
8 import {
9 TrimmedNonEmptyString,
10 type SourceControlProviderAuth,
apps/server/src/sourceControl/BitbucketSourceControlProvider.test.ts
+3 -1
@@ -1,5 +1,7 @@
1 import { assert, it } from "@effect/vitest";
2 -import { Effect, Layer, Option } from "effect";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 +import * as Option from "effect/Option";
5
6 import * as BitbucketApi from "./BitbucketApi.ts";
7 import * as BitbucketSourceControlProvider from "./BitbucketSourceControlProvider.ts";
apps/server/src/sourceControl/BitbucketSourceControlProvider.ts
+3 -1
@@ -1,4 +1,6 @@
1 -import { Effect, Layer, Option } from "effect";
1 +import * as Effect from "effect/Effect";
2 +import * as Layer from "effect/Layer";
3 +import * as Option from "effect/Option";
4 import { SourceControlProviderError, type ChangeRequest } from "@t3tools/contracts";
5
6 import * as BitbucketApi from "./BitbucketApi.ts";
apps/server/src/sourceControl/GitHubCli.test.ts
+7 -2
@@ -1,7 +1,8 @@
1 import { assert, it, afterEach, describe, expect, vi } from "@effect/vitest";
2 -import { Effect, Layer } from "effect";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 import { ChildProcessSpawner } from "effect/unstable/process";
4 -import { VcsProcessExitError, type VcsError } from "@t3tools/contracts";
5 +import { VcsProcessExitError } from "@t3tools/contracts";
6
7 import * as VcsProcess from "../vcs/VcsProcess.ts";
8 import * as GitHubCli from "./GitHubCli.ts";
@@ -34,6 +35,7 @@ describe("GitHubCli.layer", () => {
35 mockRun.mockReturnValueOnce(
36 Effect.succeed(
37 processOutput(
38 + // @effect-diagnostics-next-line preferSchemaOverJson:off
39 JSON.stringify({
40 number: 42,
41 title: "Add PR thread creation",
@@ -92,6 +94,7 @@ describe("GitHubCli.layer", () => {
94 mockRun.mockReturnValueOnce(
95 Effect.succeed(
96 processOutput(
97 + // @effect-diagnostics-next-line preferSchemaOverJson:off
98 JSON.stringify({
99 number: 42,
100 title: " Add PR thread creation \n",
@@ -137,6 +140,7 @@ describe("GitHubCli.layer", () => {
140 mockRun.mockReturnValueOnce(
141 Effect.succeed(
142 processOutput(
143 + // @effect-diagnostics-next-line preferSchemaOverJson:off
144 JSON.stringify([
145 {
146 number: 0,
@@ -187,6 +191,7 @@ describe("GitHubCli.layer", () => {
191 mockRun.mockReturnValueOnce(
192 Effect.succeed(
193 processOutput(
194 + // @effect-diagnostics-next-line preferSchemaOverJson:off
195 JSON.stringify({
196 nameWithOwner: "octocat/codething-mvp",
197 url: "https://github.com/octocat/codething-mvp",
apps/server/src/sourceControl/GitHubCli.ts
+6 -1
@@ -1,4 +1,9 @@
1 -import { Context, Effect, Layer, Result, Schema, SchemaIssue } from "effect";
1 +import * as Context from "effect/Context";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 +import * as Result from "effect/Result";
5 +import * as Schema from "effect/Schema";
6 +import * as SchemaIssue from "effect/SchemaIssue";
7
8 import {
9 TrimmedNonEmptyString,
apps/server/src/sourceControl/GitHubSourceControlProvider.test.ts
+4 -1
@@ -1,5 +1,8 @@
1 import { assert, it } from "@effect/vitest";
2 -import { DateTime, Effect, Layer, Option } from "effect";
2 +import * as DateTime from "effect/DateTime";
3 +import * as Effect from "effect/Effect";
4 +import * as Layer from "effect/Layer";
5 +import * as Option from "effect/Option";
6 import { ChildProcessSpawner } from "effect/unstable/process";
7
8 import * as VcsProcess from "../vcs/VcsProcess.ts";
apps/server/src/sourceControl/GitHubSourceControlProvider.ts
+5 -1
@@ -1,4 +1,8 @@
1 -import { Effect, Layer, Option, Result, Schema } from "effect";
1 +import * as Effect from "effect/Effect";
2 +import * as Layer from "effect/Layer";
3 +import * as Option from "effect/Option";
4 +import * as Result from "effect/Result";
5 +import * as Schema from "effect/Schema";
6 import {
7 SourceControlProviderError,
8 type ChangeRequest,
apps/server/src/sourceControl/GitLabCli.test.ts
+15 -2
@@ -1,5 +1,6 @@
1 import { assert, it, afterEach, expect, vi } from "@effect/vitest";
2 -import { Effect, Layer } from "effect";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 import { ChildProcessSpawner } from "effect/unstable/process";
5
6 import { VcsProcessExitError } from "@t3tools/contracts";
@@ -38,6 +39,7 @@ layer("GitLabCli.layer", (it) => {
39 mockedRun.mockReturnValueOnce(
40 Effect.succeed(
41 processOutput(
42 + // @effect-diagnostics-next-line preferSchemaOverJson:off
43 JSON.stringify({
44 iid: 42,
45 title: "Add MR thread creation",
@@ -89,6 +91,7 @@ layer("GitLabCli.layer", (it) => {
91 mockedRun.mockReturnValueOnce(
92 Effect.succeed(
93 processOutput(
94 + // @effect-diagnostics-next-line preferSchemaOverJson:off
95 JSON.stringify([
96 {
97 iid: 0,
@@ -154,6 +157,7 @@ layer("GitLabCli.layer", (it) => {
157 mockedRun.mockReturnValueOnce(
158 Effect.succeed(
159 processOutput(
160 + // @effect-diagnostics-next-line preferSchemaOverJson:off
161 JSON.stringify({
162 path_with_namespace: "octocat/t3code",
163 web_url: "https://gitlab.com/octocat/t3code",
@@ -219,10 +223,19 @@ layer("GitLabCli.layer", (it) => {
223 it.effect("creates repositories under an explicit namespace", () =>
224 Effect.gen(function* () {
225 mockedRun
222 - .mockReturnValueOnce(Effect.succeed(processOutput(JSON.stringify({ id: 1234 }))))
226 +
227 + .mockReturnValueOnce(
228 + Effect.succeed(
229 + processOutput(
230 + // @effect-diagnostics-next-line preferSchemaOverJson:off
231 + JSON.stringify({ id: 1234 }),
232 + ),
233 + ),
234 + )
235 .mockReturnValueOnce(
236 Effect.succeed(
237 processOutput(
238 + // @effect-diagnostics-next-line preferSchemaOverJson:off
239 JSON.stringify({
240 path_with_namespace: "octocat/t3code",
241 web_url: "https://gitlab.com/octocat/t3code",
apps/server/src/sourceControl/GitLabCli.ts
+8 -1
@@ -1,4 +1,11 @@
1 -import { Context, Effect, Layer, Option, Result, Schema, SchemaIssue, type DateTime } from "effect";
1 +import * as Context from "effect/Context";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 +import * as Option from "effect/Option";
5 +import * as Result from "effect/Result";
6 +import * as Schema from "effect/Schema";
7 +import * as SchemaIssue from "effect/SchemaIssue";
8 +import type * as DateTime from "effect/DateTime";
9
10 import { TrimmedNonEmptyString, type SourceControlRepositoryVisibility } from "@t3tools/contracts";
11
apps/server/src/sourceControl/GitLabSourceControlProvider.test.ts
+3 -1
@@ -1,5 +1,7 @@
1 import { assert, it } from "@effect/vitest";
2 -import { Effect, Layer, Option } from "effect";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 +import * as Option from "effect/Option";
5
6 import * as GitLabCli from "./GitLabCli.ts";
7 import * as GitLabSourceControlProvider from "./GitLabSourceControlProvider.ts";
apps/server/src/sourceControl/GitLabSourceControlProvider.ts
+3 -1
@@ -1,4 +1,6 @@
1 -import { Effect, Layer, Option } from "effect";
1 +import * as Effect from "effect/Effect";
2 +import * as Layer from "effect/Layer";
3 +import * as Option from "effect/Option";
4 import { SourceControlProviderError, type ChangeRequest } from "@t3tools/contracts";
5
6 import * as GitLabCli from "./GitLabCli.ts";
apps/server/src/sourceControl/SourceControlDiscovery.test.ts
+3 -1
@@ -1,6 +1,8 @@
1 import { assert, it } from "@effect/vitest";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 -import { Effect, Layer, Option } from "effect";
3 +import * as Effect from "effect/Effect";
4 +import * as Layer from "effect/Layer";
5 +import * as Option from "effect/Option";
6 import { ChildProcessSpawner } from "effect/unstable/process";
7 import { VcsProcessSpawnError } from "@t3tools/contracts";
8
apps/server/src/sourceControl/SourceControlDiscovery.ts
+4 -1
@@ -3,7 +3,10 @@ import {
3 type VcsDiscoveryItem,
4 type VcsDriverKind,
5 } from "@t3tools/contracts";
6 -import { Context, Effect, Layer, Option } from "effect";
6 +import * as Context from "effect/Context";
7 +import * as Effect from "effect/Effect";
8 +import * as Layer from "effect/Layer";
9 +import * as Option from "effect/Option";
10
11 import { ServerConfig } from "../config.ts";
12 import * as VcsProcess from "../vcs/VcsProcess.ts";
apps/server/src/sourceControl/SourceControlProvider.ts
+2 -1
@@ -1,4 +1,5 @@
1 -import { Context, Effect } from "effect";
1 +import * as Context from "effect/Context";
2 +import * as Effect from "effect/Effect";
3 import type {
4 ChangeRequest,
5 ChangeRequestState,
apps/server/src/sourceControl/SourceControlProviderDiscovery.ts
+2 -1
@@ -3,7 +3,8 @@ import type {
3 SourceControlProviderDiscoveryItem,
4 SourceControlProviderKind,
5 } from "@t3tools/contracts";
6 -import { Effect, Option } from "effect";
6 +import * as Effect from "effect/Effect";
7 +import * as Option from "effect/Option";
8
9 import type * as VcsProcess from "../vcs/VcsProcess.ts";
10
apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts
+4 -1
@@ -1,6 +1,9 @@
1 import { assert, it } from "@effect/vitest";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 -import { DateTime, Effect, Layer, Option } from "effect";
3 +import * as DateTime from "effect/DateTime";
4 +import * as Effect from "effect/Effect";
5 +import * as Layer from "effect/Layer";
6 +import * as Option from "effect/Option";
7
8 import { ServerConfig } from "../config.ts";
9 import type * as VcsDriver from "../vcs/VcsDriver.ts";
apps/server/src/sourceControl/SourceControlProviderRegistry.ts
+6 -1
@@ -1,4 +1,9 @@
1 -import { Cache, Context, Duration, Effect, Exit, Layer } from "effect";
1 +import * as Cache from "effect/Cache";
2 +import * as Context from "effect/Context";
3 +import * as Duration from "effect/Duration";
4 +import * as Effect from "effect/Effect";
5 +import * as Exit from "effect/Exit";
6 +import * as Layer from "effect/Layer";
7 import {
8 SourceControlProviderError,
9 type SourceControlProviderDiscoveryItem,
apps/server/src/sourceControl/SourceControlRepositoryService.test.ts
+3 -1
@@ -1,6 +1,8 @@
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { assert, it } from "@effect/vitest";
3 -import { Effect, FileSystem, Layer } from "effect";
3 +import * as Effect from "effect/Effect";
4 +import * as FileSystem from "effect/FileSystem";
5 +import * as Layer from "effect/Layer";
6 import { ChildProcessSpawner } from "effect/unstable/process";
7
8 import { GitCommandError, type SourceControlProviderError } from "@t3tools/contracts";
apps/server/src/sourceControl/SourceControlRepositoryService.ts
+6 -1
@@ -1,5 +1,10 @@
1 import * as NodeOS from "node:os";
2 -import { Context, Effect, FileSystem, Layer, Path, Schema } from "effect";
2 +import * as Context from "effect/Context";
3 +import * as Effect from "effect/Effect";
4 +import * as FileSystem from "effect/FileSystem";
5 +import * as Layer from "effect/Layer";
6 +import * as Path from "effect/Path";
7 +import * as Schema from "effect/Schema";
8
9 import {
10 SourceControlRepositoryError,
apps/server/src/sourceControl/azureDevOpsPullRequests.ts
+6 -1
@@ -1,4 +1,9 @@
1 -import { Cause, DateTime, Exit, Option, Result, Schema } from "effect";
1 +import * as Cause from "effect/Cause";
2 +import * as DateTime from "effect/DateTime";
3 +import * as Exit from "effect/Exit";
4 +import * as Option from "effect/Option";
5 +import * as Result from "effect/Result";
6 +import * as Schema from "effect/Schema";
7 import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
8 import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson";
9
apps/server/src/sourceControl/bitbucketPullRequests.ts
+3 -1
@@ -1,4 +1,6 @@
1 -import { DateTime, Option, Schema } from "effect";
1 +import * as DateTime from "effect/DateTime";
2 +import * as Option from "effect/Option";
3 +import * as Schema from "effect/Schema";
4 import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
5
6 export interface NormalizedBitbucketPullRequestRecord {
apps/server/src/sourceControl/gitHubPullRequests.ts
+6 -1
@@ -1,4 +1,9 @@
1 -import { Cause, DateTime, Exit, Option, Result, Schema } from "effect";
1 +import * as Cause from "effect/Cause";
2 +import * as DateTime from "effect/DateTime";
3 +import * as Exit from "effect/Exit";
4 +import * as Option from "effect/Option";
5 +import * as Result from "effect/Result";
6 +import * as Schema from "effect/Schema";
7 import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
8 import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson";
9
apps/server/src/sourceControl/gitLabMergeRequests.ts
+6 -1
@@ -1,4 +1,9 @@
1 -import { Cause, DateTime, Exit, Option, Result, Schema } from "effect";
1 +import * as Cause from "effect/Cause";
2 +import * as DateTime from "effect/DateTime";
3 +import * as Exit from "effect/Exit";
4 +import * as Option from "effect/Option";
5 +import * as Result from "effect/Result";
6 +import * as Schema from "effect/Schema";
7 import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
8 import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson";
9
apps/server/src/startupAccess.ts
+1 -1
@@ -1,7 +1,7 @@
1 import { networkInterfaces } from "node:os";
2
3 import { QrCode } from "@t3tools/shared/qrCode";
4 -import { Effect } from "effect";
4 +import * as Effect from "effect/Effect";
5 import { HttpServer } from "effect/unstable/http";
6
7 import { ServerConfig } from "./config.ts";
apps/server/src/stream/collectUint8StreamText.test.ts
+2 -1
@@ -1,5 +1,6 @@
1 import { assert, describe, it } from "@effect/vitest";
2 -import { Effect, Stream } from "effect";
2 +import * as Effect from "effect/Effect";
3 +import * as Stream from "effect/Stream";
4
5 import { collectUint8StreamText } from "./collectUint8StreamText.ts";
6
apps/server/src/stream/collectUint8StreamText.ts
+2 -1
@@ -1,4 +1,5 @@
1 -import { Effect, Stream } from "effect";
1 +import * as Effect from "effect/Effect";
2 +import * as Stream from "effect/Stream";
3
4 export interface CollectedUint8StreamText {
5 readonly text: string;
apps/server/src/telemetry/Identify.ts
+5 -1
@@ -1,4 +1,8 @@
1 -import { Effect, FileSystem, Path, Random, Schema } from "effect";
1 +import * as Effect from "effect/Effect";
2 +import * as FileSystem from "effect/FileSystem";
3 +import * as Path from "effect/Path";
4 +import * as Random from "effect/Random";
5 +import * as Schema from "effect/Schema";
6 import * as Crypto from "node:crypto";
7 import { homedir } from "node:os";
8 import { ServerConfig } from "../config.ts";
apps/server/src/telemetry/Layers/AnalyticsService.test.ts
+3 -1
@@ -1,7 +1,9 @@
1 import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 import { assert, it } from "@effect/vitest";
4 -import { ConfigProvider, Effect, Layer } from "effect";
4 +import * as ConfigProvider from "effect/ConfigProvider";
5 +import * as Effect from "effect/Effect";
6 +import * as Layer from "effect/Layer";
7 import * as HttpServer from "effect/unstable/http/HttpServer";
8 import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
9 import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
apps/server/src/telemetry/Layers/AnalyticsService.ts
+5 -1
@@ -7,7 +7,11 @@
7 * @module AnalyticsServiceLive
8 */
9
10 -import { Config, DateTime, Effect, Layer, Ref } from "effect";
10 +import * as Config from "effect/Config";
11 +import * as DateTime from "effect/DateTime";
12 +import * as Effect from "effect/Effect";
13 +import * as Layer from "effect/Layer";
14 +import * as Ref from "effect/Ref";
15 import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
16
17 import { ServerConfig } from "../../config.ts";
apps/server/src/telemetry/Services/AnalyticsService.ts
+3 -1
@@ -6,7 +6,9 @@
6 *
7 * @module AnalyticsService
8 */
9 -import { Effect, Layer, Context } from "effect";
9 +import * as Effect from "effect/Effect";
10 +import * as Layer from "effect/Layer";
11 +import * as Context from "effect/Context";
12
13 export interface AnalyticsServiceShape {
14 /**
apps/server/src/terminal/Layers/BunPTY.ts
+2 -1
@@ -1,4 +1,5 @@
1 -import { Effect, Layer } from "effect";
1 +import * as Effect from "effect/Effect";
2 +import * as Layer from "effect/Layer";
3 import { PtyAdapter } from "../Services/PTY.ts";
4 import type { PtyAdapterShape, PtyExitEvent, PtyProcess } from "../Services/PTY.ts";
5
apps/server/src/terminal/Layers/Manager.test.ts
+31 -38
@@ -1,5 +1,3 @@
1 -import path from "node:path";
2 -
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { assert, it } from "@effect/vitest";
3 import {
@@ -8,20 +6,19 @@ import {
6 type TerminalOpenInput,
7 type TerminalRestartInput,
8 } from "@t3tools/contracts";
11 -import {
12 - Duration,
13 - Effect,
14 - Encoding,
15 - Exit,
16 - Fiber,
17 - FileSystem,
18 - Option,
19 - PlatformError,
20 - Ref,
21 - Schedule,
22 - Scope,
23 -} from "effect";
24 -import { TestClock } from "effect/testing";
9 +import * as Cause from "effect/Cause";
10 +import * as Duration from "effect/Duration";
11 +import * as Effect from "effect/Effect";
12 +import * as Encoding from "effect/Encoding";
13 +import * as Exit from "effect/Exit";
14 +import * as Fiber from "effect/Fiber";
15 +import * as FileSystem from "effect/FileSystem";
16 +import * as Path from "effect/Path";
17 +import * as PlatformError from "effect/PlatformError";
18 +import * as Ref from "effect/Ref";
19 +import * as Schedule from "effect/Schedule";
20 +import * as Scope from "effect/Scope";
21 +import * as TestClock from "effect/testing/TestClock";
22 import { expect } from "vitest";
23
24 import type { TerminalManagerShape } from "../Services/Manager.ts";
@@ -130,20 +127,11 @@ class FakePtyAdapter implements PtyAdapterShape {
127 const waitFor = <E, R>(
128 predicate: Effect.Effect<boolean, E, R>,
129 timeout: Duration.Input = 800,
133 -): Effect.Effect<void, Error | E, R> =>
130 +): Effect.Effect<void, E | Cause.TimeoutError, R> =>
131 predicate.pipe(
135 - Effect.filterOrFail(
136 - (done) => done,
137 - () => new Error("Condition not met"),
138 - ),
132 + Effect.filter((done) => done),
133 Effect.retry(Schedule.spaced("15 millis")),
140 - Effect.timeoutOption(timeout),
141 - Effect.flatMap((result) =>
142 - Option.match(result, {
143 - onNone: () => Effect.fail(new Error("Timed out waiting for condition")),
144 - onSome: () => Effect.void,
145 - }),
146 - ),
134 + Effect.timeout(timeout),
135 );
136
137 function openInput(overrides: Partial<TerminalOpenInput> = {}): TerminalOpenInput {
@@ -181,7 +169,7 @@ function multiTerminalHistoryLogName(threadId: string, terminalId: string): stri
169 }
170
171 function historyLogPath(logsDir: string, threadId = "thread-1"): string {
184 - return path.join(logsDir, historyLogName(threadId));
172 + return joinPath(logsDir, historyLogName(threadId));
173 }
174
175 function multiTerminalHistoryLogPath(
@@ -189,7 +177,11 @@ function multiTerminalHistoryLogPath(
177 threadId = "thread-1",
178 terminalId = "default",
179 ): string {
192 - return path.join(logsDir, multiTerminalHistoryLogName(threadId, terminalId));
180 + return joinPath(logsDir, multiTerminalHistoryLogName(threadId, terminalId));
181 +}
182 +
183 +function joinPath(...segments: ReadonlyArray<string>): string {
184 + return segments.join("/");
185 }
186
187 interface CreateManagerOptions {
@@ -217,12 +209,13 @@ const createManager = (
209 ): Effect.Effect<
210 ManagerFixture,
211 PlatformError.PlatformError,
220 - FileSystem.FileSystem | Scope.Scope
212 + FileSystem.FileSystem | Path.Path | Scope.Scope
213 > =>
214 Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) =>
215 Effect.gen(function* () {
216 + const pathService = yield* Path.Path;
217 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-terminal-" });
225 - const logsDir = path.join(baseDir, "userdata", "logs", "terminals");
218 + const logsDir = pathService.join(baseDir, "userdata", "logs", "terminals");
219 const ptyAdapter = options.ptyAdapter ?? new FakePtyAdapter();
220
221 const manager = yield* makeTerminalManagerWithOptions({
@@ -302,8 +295,8 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
295 if (process.platform === "win32") return;
296
297 const { manager, baseDir } = yield* createManager();
305 - const blockedRoot = path.join(baseDir, "blocked-root");
306 - const blockedCwd = path.join(blockedRoot, "cwd");
298 + const blockedRoot = joinPath(baseDir, "blocked-root");
299 + const blockedCwd = joinPath(blockedRoot, "cwd");
300 yield* makeDirectory(blockedCwd);
301 yield* chmod(blockedRoot, 0o000);
302
@@ -441,8 +434,8 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
434 it.effect("propagates explicit worktree metadata through snapshots and lifecycle events", () =>
435 Effect.gen(function* () {
436 const { manager, getEvents, baseDir } = yield* createManager();
444 - const firstWorktreePath = path.join(baseDir, "worktrees", "feature-a");
445 - const secondWorktreePath = path.join(baseDir, "worktrees", "feature-b");
437 + const firstWorktreePath = joinPath(baseDir, "worktrees", "feature-a");
438 + const secondWorktreePath = joinPath(baseDir, "worktrees", "feature-b");
439 yield* makeDirectory(firstWorktreePath);
440 yield* makeDirectory(secondWorktreePath);
441 const startedSnapshot = yield* manager.open(
@@ -478,7 +471,7 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
471 it.effect("preserves worktree metadata when reopening an exited session", () =>
472 Effect.gen(function* () {
473 const { manager, ptyAdapter, getEvents, baseDir } = yield* createManager();
481 - const worktreePath = path.join(baseDir, "worktrees", "feature-a");
474 + const worktreePath = joinPath(baseDir, "worktrees", "feature-a");
475 yield* makeDirectory(worktreePath);
476
477 yield* manager.open(
@@ -816,7 +809,7 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
809 it.effect("migrates legacy transcript filenames to terminal-scoped history path on open", () =>
810 Effect.gen(function* () {
811 const { manager, logsDir } = yield* createManager();
819 - const legacyPath = path.join(logsDir, "thread-1.log");
812 + const legacyPath = joinPath(logsDir, "thread-1.log");
813 const nextPath = historyLogPath(logsDir);
814 yield* writeFileString(legacyPath, "legacy-line\n");
815
apps/server/src/terminal/Layers/Manager.ts
+61 -40
@@ -1,5 +1,3 @@
1 -import path from "node:path";
2 -
1 import {
2 DEFAULT_TERMINAL_ID,
3 type TerminalEvent,
@@ -7,20 +5,20 @@ import {
5 type TerminalSessionStatus,
6 } from "@t3tools/contracts";
7 import { makeKeyedCoalescingWorker } from "@t3tools/shared/KeyedCoalescingWorker";
10 -import {
11 - Effect,
12 - Encoding,
13 - Equal,
14 - Exit,
15 - Fiber,
16 - FileSystem,
17 - Layer,
18 - Option,
19 - Schema,
20 - Scope,
21 - Semaphore,
22 - SynchronizedRef,
23 -} from "effect";
8 +import * as Effect from "effect/Effect";
9 +import * as Encoding from "effect/Encoding";
10 +import * as Equal from "effect/Equal";
11 +import * as Exit from "effect/Exit";
12 +import * as Fiber from "effect/Fiber";
13 +import * as FileSystem from "effect/FileSystem";
14 +import * as DateTime from "effect/DateTime";
15 +import * as Layer from "effect/Layer";
16 +import * as Option from "effect/Option";
17 +import * as Path from "effect/Path";
18 +import * as Schema from "effect/Schema";
19 +import * as Scope from "effect/Scope";
20 +import * as Semaphore from "effect/Semaphore";
21 +import * as SynchronizedRef from "effect/SynchronizedRef";
22
23 import { ServerConfig } from "../../config.ts";
24 import {
@@ -213,15 +211,25 @@ function normalizeShellCommand(
211 return firstToken.replace(/^['"]|['"]$/g, "");
212 }
213
214 +function basename(command: string, platform: NodeJS.Platform): string {
215 + const normalized = platform === "win32" ? command.replaceAll("/", "\\") : command;
216 + const separator = platform === "win32" ? "\\" : "/";
217 + return normalized.slice(normalized.lastIndexOf(separator) + 1);
218 +}
219 +
220 +function joinWindowsPath(...segments: ReadonlyArray<string>): string {
221 + return segments
222 + .filter((segment) => segment.length > 0)
223 + .join("\\")
224 + .replace(/\\+/g, "\\");
225 +}
226 +
227 function shellCandidateFromCommand(
228 command: string | null,
229 platform: NodeJS.Platform = process.platform,
230 ): ShellCandidate | null {
231 if (!command || command.length === 0) return null;
221 - const shellName =
222 - platform === "win32"
223 - ? path.win32.basename(command).toLowerCase()
224 - : path.basename(command).toLowerCase();
232 + const shellName = basename(command, platform).toLowerCase();
233 if (platform === "win32" && (shellName === "pwsh.exe" || shellName === "powershell.exe")) {
234 return { shell: command, args: ["-NoLogo"] };
235 }
@@ -236,7 +244,7 @@ function windowsSystemRoot(env: NodeJS.ProcessEnv): string {
244 }
245
246 function windowsPowerShellPath(env: NodeJS.ProcessEnv): string {
239 - return path.win32.join(
247 + return joinWindowsPath(
248 windowsSystemRoot(env),
249 "System32",
250 "WindowsPowerShell",
@@ -246,7 +254,7 @@ function windowsPowerShellPath(env: NodeJS.ProcessEnv): string {
254 }
255
256 function windowsCmdPath(env: NodeJS.ProcessEnv): string {
249 - return path.win32.join(windowsSystemRoot(env), "System32", "cmd.exe");
257 + return joinWindowsPath(windowsSystemRoot(env), "System32", "cmd.exe");
258 }
259
260 function formatShellCandidate(candidate: ShellCandidate): string {
@@ -714,8 +722,10 @@ const makeTerminalManager = Effect.fn("makeTerminalManager")(function* () {
722 export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWithOptions")(
723 function* (options: TerminalManagerOptions) {
724 const fileSystem = yield* FileSystem.FileSystem;
725 + const path = yield* Path.Path;
726 const context = yield* Effect.context<never>();
727 const runFork = Effect.runForkWith(context);
728 + const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
729
730 const logsDir = options.logsDir;
731 const historyLineLimit = options.historyLineLimit ?? DEFAULT_HISTORY_LINE_LIMIT;
@@ -1160,6 +1170,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
1170 expectedPid: number,
1171 ) {
1172 while (true) {
1173 + const updatedAt = yield* nowIso;
1174 const action: DrainProcessEventAction = yield* Effect.sync(() => {
1175 if (session.pid !== expectedPid || !session.process || session.status !== "running") {
1176 session.pendingProcessEvents = [];
@@ -1194,7 +1205,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
1205 historyLineLimit,
1206 );
1207 }
1197 - session.updatedAt = new Date().toISOString();
1208 + session.updatedAt = updatedAt;
1209
1210 return {
1211 type: "output",
@@ -1221,7 +1232,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
1232 session.exitSignal = Number.isInteger(nextEvent.event.signal)
1233 ? nextEvent.event.signal
1234 : null;
1224 - session.updatedAt = new Date().toISOString();
1235 + session.updatedAt = updatedAt;
1236
1237 return {
1238 type: "exit",
@@ -1242,22 +1253,24 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
1253 yield* queuePersist(action.threadId, action.terminalId, action.history);
1254 }
1255
1256 + const createdAt = yield* nowIso;
1257 yield* publishEvent({
1258 type: "output",
1259 threadId: action.threadId,
1260 terminalId: action.terminalId,
1249 - createdAt: new Date().toISOString(),
1261 + createdAt,
1262 data: action.data,
1263 });
1264 continue;
1265 }
1266
1267 yield* clearKillFiber(action.process);
1268 + const createdAt = yield* nowIso;
1269 yield* publishEvent({
1270 type: "exited",
1271 threadId: action.threadId,
1272 terminalId: action.terminalId,
1260 - createdAt: new Date().toISOString(),
1273 + createdAt,
1274 exitCode: action.exitCode,
1275 exitSignal: action.exitSignal,
1276 });
@@ -1272,6 +1285,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
1285 const process = session.process;
1286 if (!process) return;
1287
1288 + const updatedAt = yield* nowIso;
1289 yield* modifyManagerState((state) => {
1290 cleanupProcessHandles(session);
1291 session.process = null;
@@ -1282,7 +1296,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
1296 session.pendingProcessEvents = [];
1297 session.pendingProcessEventIndex = 0;
1298 session.processEventDrainRunning = false;
1285 - session.updatedAt = new Date().toISOString();
1299 + session.updatedAt = updatedAt;
1300 return [undefined, state] as const;
1301 });
1302
@@ -1361,6 +1375,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
1375 "terminal.cwd": input.cwd,
1376 });
1377
1378 + const startingAt = yield* nowIso;
1379 yield* modifyManagerState((state) => {
1380 session.status = "starting";
1381 session.cwd = input.cwd;
@@ -1373,7 +1388,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
1388 session.pendingProcessEvents = [];
1389 session.pendingProcessEventIndex = 0;
1390 session.processEventDrainRunning = false;
1376 - session.updatedAt = new Date().toISOString();
1391 + session.updatedAt = startingAt;
1392 return [undefined, state] as const;
1393 });
1394
@@ -1404,11 +1419,12 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
1419 runFork(drainProcessEvents(session, processPid));
1420 });
1421
1422 + const startedAt = yield* nowIso;
1423 yield* modifyManagerState((state) => {
1424 session.process = ptyProcess;
1425 session.pid = processPid;
1426 session.status = "running";
1411 - session.updatedAt = new Date().toISOString();
1427 + session.updatedAt = startedAt;
1428 session.unsubscribeData = unsubscribeData;
1429 session.unsubscribeExit = unsubscribeExit;
1430 return [undefined, state] as const;
@@ -1418,7 +1434,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
1434 type: eventType,
1435 threadId: session.threadId,
1436 terminalId: session.terminalId,
1421 - createdAt: new Date().toISOString(),
1437 + createdAt: startedAt,
1438 snapshot: snapshot(session),
1439 });
1440 }),
@@ -1436,6 +1452,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
1452 yield* startKillEscalation(ptyProcess, session.threadId, session.terminalId);
1453 }
1454
1455 + const failedAt = yield* nowIso;
1456 yield* modifyManagerState((state) => {
1457 session.status = "error";
1458 session.pid = null;
@@ -1446,7 +1463,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
1463 session.pendingProcessEvents = [];
1464 session.pendingProcessEventIndex = 0;
1465 session.processEventDrainRunning = false;
1449 - session.updatedAt = new Date().toISOString();
1466 + session.updatedAt = failedAt;
1467 return [undefined, state] as const;
1468 });
1469
@@ -1457,7 +1474,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
1474 type: "error",
1475 threadId: session.threadId,
1476 terminalId: session.terminalId,
1460 - createdAt: new Date().toISOString(),
1477 + createdAt: failedAt,
1478 message,
1479 });
1480 yield* Effect.logError("failed to start terminal", {
@@ -1529,6 +1546,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
1546 return;
1547 }
1548
1549 + const updatedAt = yield* nowIso;
1550 const event = yield* modifyManagerState((state) => {
1551 const liveSession: Option.Option<TerminalSessionState> = Option.fromNullishOr(
1552 state.sessions.get(toSessionKey(session.threadId, session.terminalId)),
@@ -1543,14 +1561,14 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
1561 }
1562
1563 liveSession.value.hasRunningSubprocess = hasRunningSubprocess.value;
1546 - liveSession.value.updatedAt = new Date().toISOString();
1564 + liveSession.value.updatedAt = updatedAt;
1565
1566 return [
1567 Option.some({
1568 type: "activity" as const,
1569 threadId: liveSession.value.threadId,
1570 terminalId: liveSession.value.terminalId,
1553 - createdAt: new Date().toISOString(),
1571 + createdAt: updatedAt,
1572 hasRunningSubprocess: hasRunningSubprocess.value,
1573 }),
1574 state,
@@ -1629,6 +1647,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
1647 const history = yield* readHistory(input.threadId, terminalId);
1648 const cols = input.cols ?? DEFAULT_OPEN_COLS;
1649 const rows = input.rows ?? DEFAULT_OPEN_ROWS;
1650 + const createdAt = yield* nowIso;
1651 const session: TerminalSessionState = {
1652 threadId: input.threadId,
1653 terminalId,
@@ -1643,7 +1662,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
1662 processEventDrainRunning: false,
1663 exitCode: null,
1664 exitSignal: null,
1646 - updatedAt: new Date().toISOString(),
1665 + updatedAt: createdAt,
1666 cols,
1667 rows,
1668 process: null,
@@ -1734,7 +1753,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
1753 if (liveSession.cols !== targetCols || liveSession.rows !== targetRows) {
1754 liveSession.cols = targetCols;
1755 liveSession.rows = targetRows;
1737 - liveSession.updatedAt = new Date().toISOString();
1756 + liveSession.updatedAt = yield* nowIso;
1757 liveSession.process.resize(targetCols, targetRows);
1758 }
1759
@@ -1768,7 +1787,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
1787 }
1788 session.cols = input.cols;
1789 session.rows = input.rows;
1771 - session.updatedAt = new Date().toISOString();
1790 + session.updatedAt = yield* nowIso;
1791 yield* Effect.sync(() => process.resize(input.cols, input.rows));
1792 });
1793
@@ -1783,13 +1802,14 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
1802 session.pendingProcessEvents = [];
1803 session.pendingProcessEventIndex = 0;
1804 session.processEventDrainRunning = false;
1786 - session.updatedAt = new Date().toISOString();
1805 + const clearedAt = yield* nowIso;
1806 + session.updatedAt = clearedAt;
1807 yield* persistHistory(input.threadId, terminalId, session.history);
1808 yield* publishEvent({
1809 type: "cleared",
1810 threadId: input.threadId,
1811 terminalId,
1792 - createdAt: new Date().toISOString(),
1812 + createdAt: clearedAt,
1813 });
1814 }),
1815 );
@@ -1808,6 +1828,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
1828 if (Option.isNone(existingSession)) {
1829 const cols = input.cols ?? DEFAULT_OPEN_COLS;
1830 const rows = input.rows ?? DEFAULT_OPEN_ROWS;
1831 + const createdAt = yield* nowIso;
1832 session = {
1833 threadId: input.threadId,
1834 terminalId,
@@ -1822,7 +1843,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
1843 processEventDrainRunning: false,
1844 exitCode: null,
1845 exitSignal: null,
1825 - updatedAt: new Date().toISOString(),
1846 + updatedAt: createdAt,
1847 cols,
1848 rows,
1849 process: null,
apps/server/src/terminal/Layers/NodePTY.test.ts
+3 -1
@@ -1,4 +1,6 @@
1 -import { FileSystem, Path, Effect } from "effect";
1 +import * as FileSystem from "effect/FileSystem";
2 +import * as Path from "effect/Path";
3 +import * as Effect from "effect/Effect";
4 import { assert, it } from "@effect/vitest";
5
6 import { ensureNodePtySpawnHelperExecutable } from "./NodePTY.ts";
apps/server/src/terminal/Layers/NodePTY.ts
+4 -1
@@ -1,6 +1,9 @@
1 import { createRequire } from "node:module";
2
3 -import { Effect, FileSystem, Layer, Path } from "effect";
3 +import * as Effect from "effect/Effect";
4 +import * as FileSystem from "effect/FileSystem";
5 +import * as Layer from "effect/Layer";
6 +import * as Path from "effect/Path";
7 import { PtyAdapter } from "../Services/PTY.ts";
8 import {
9 PtySpawnError,
apps/server/src/terminal/Services/Manager.ts
+2 -1
@@ -23,7 +23,8 @@ import {
23 TerminalWriteInput,
24 } from "@t3tools/contracts";
25 import type { PtyProcess } from "./PTY.ts";
26 -import { Effect, Context } from "effect";
26 +import * as Effect from "effect/Effect";
27 +import * as Context from "effect/Context";
28
29 export {
30 TerminalCwdError,
apps/server/src/terminal/Services/PTY.ts
+3 -1
@@ -6,7 +6,9 @@
6 *
7 * @module PtyAdapter
8 */
9 -import { Effect, Schema, Context } from "effect";
9 +import * as Effect from "effect/Effect";
10 +import * as Schema from "effect/Schema";
11 +import * as Context from "effect/Context";
12
13 /**
14 * PtyError - Error type for PTY adapter operations.
apps/server/src/textGeneration/ClaudeTextGeneration.test.ts
+6 -1
@@ -1,7 +1,11 @@
1 import { ClaudeSettings, ProviderInstanceId } from "@t3tools/contracts";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 import { it } from "@effect/vitest";
4 -import { Effect, FileSystem, Layer, Path, Schema } from "effect";
4 +import * as Effect from "effect/Effect";
5 +import * as FileSystem from "effect/FileSystem";
6 +import * as Layer from "effect/Layer";
7 +import * as Path from "effect/Path";
8 +import * as Schema from "effect/Schema";
9 import { createModelSelection } from "@t3tools/shared/model";
10 import { expect } from "vitest";
11
@@ -287,6 +291,7 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGeneration", (it) => {
291 const claudeHome = path.join(process.cwd(), ".claude-work-test");
292 return yield* withFakeClaudeEnv(
293 {
294 + // @effect-diagnostics-next-line preferSchemaOverJson:off
295 output: JSON.stringify({
296 structured_output: {
297 title: "Use Claude home",
apps/server/src/textGeneration/ClaudeTextGeneration.ts
+10 -3
@@ -7,7 +7,10 @@
7 *
8 * @module ClaudeTextGeneration
9 */
10 -import { Effect, Option, Schema, Stream } from "effect";
10 +import * as Effect from "effect/Effect";
11 +import * as Option from "effect/Option";
12 +import * as Schema from "effect/Schema";
13 +import * as Stream from "effect/Stream";
14 import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
15
16 import { type ClaudeSettings, type ModelSelection } from "@t3tools/contracts";
@@ -93,7 +96,9 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
96 outputSchemaJson: S;
97 modelSelection: ModelSelection;
98 }): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
96 - const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
99 + const jsonSchemaStr = Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(
100 + toJsonSchemaObject(outputSchemaJson),
101 + );
102 const caps = getClaudeModelCapabilities(modelSelection.model);
103 const descriptors = getProviderOptionDescriptors({
104 caps,
@@ -126,7 +131,9 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
131 "--model",
132 resolveClaudeApiModelId(modelSelection),
133 ...(cliEffort ? ["--effort", cliEffort] : []),
129 - ...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []),
134 + ...(Object.keys(settings).length > 0
135 + ? ["--settings", Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(settings)]
136 + : []),
137 "--dangerously-skip-permissions",
138 ],
139 {
apps/server/src/textGeneration/CodexTextGeneration.test.ts
+15 -5
@@ -1,6 +1,11 @@
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { it } from "@effect/vitest";
3 -import { Effect, FileSystem, Layer, Path, Result, Schema } from "effect";
3 +import * as Effect from "effect/Effect";
4 +import * as FileSystem from "effect/FileSystem";
5 +import * as Layer from "effect/Layer";
6 +import * as Path from "effect/Path";
7 +import * as Result from "effect/Result";
8 +import * as Schema from "effect/Schema";
9 import { createModelSelection } from "@t3tools/shared/model";
10 import { expect } from "vitest";
11
@@ -113,6 +118,7 @@ function makeFakeCodexBinary(
118 : []),
119 ...(input.stdinMustContain !== undefined
120 ? [
121 + // @effect-diagnostics-next-line preferSchemaOverJson:off
122 `if ! printf "%s" "$stdin_content" | grep -F -- ${JSON.stringify(input.stdinMustContain)} >/dev/null; then`,
123 ' printf "%s\\n" "stdin missing expected content" >&2',
124 ` exit 3`,
@@ -121,6 +127,7 @@ function makeFakeCodexBinary(
127 : []),
128 ...(input.stdinMustNotContain !== undefined
129 ? [
130 + // @effect-diagnostics-next-line preferSchemaOverJson:off
131 `if printf "%s" "$stdin_content" | grep -F -- ${JSON.stringify(input.stdinMustNotContain)} >/dev/null; then`,
132 ' printf "%s\\n" "stdin contained forbidden content" >&2',
133 ` exit 4`,
@@ -128,7 +135,10 @@ function makeFakeCodexBinary(
135 ]
136 : []),
137 ...(input.stderr !== undefined
131 - ? [`printf "%s\\n" ${JSON.stringify(input.stderr)} >&2`]
138 + ? [
139 + // @effect-diagnostics-next-line preferSchemaOverJson:off
140 + `printf "%s\\n" ${JSON.stringify(input.stderr)} >&2`,
141 + ]
142 : []),
143 'if [ -n "$output_path" ]; then',
144 " cat > \"$output_path\" <<'__T3CODE_FAKE_CODEX_OUTPUT__'",
@@ -415,7 +425,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
425 const fs = yield* FileSystem.FileSystem;
426 const path = yield* Path.Path;
427 const { attachmentsDir } = yield* ServerConfig;
418 - const attachmentId = `thread-branch-image-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
428 + const attachmentId = "thread-branch-image-attachment";
429 const attachmentPath = path.join(attachmentsDir, `${attachmentId}.png`);
430 yield* fs.makeDirectory(attachmentsDir, { recursive: true });
431 yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
@@ -453,7 +463,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
463 const fs = yield* FileSystem.FileSystem;
464 const path = yield* Path.Path;
465 const { attachmentsDir } = yield* ServerConfig;
456 - const attachmentId = `thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
466 + const attachmentId = "thread-1-attachment";
467 const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);
468 yield* fs.makeDirectory(attachmentsDir, { recursive: true });
469 yield* fs.writeFile(imagePath, Buffer.from("hello"));
@@ -502,7 +512,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
512 const fs = yield* FileSystem.FileSystem;
513 const path = yield* Path.Path;
514 const { attachmentsDir } = yield* ServerConfig;
505 - const missingAttachmentId = `thread-missing-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
515 + const missingAttachmentId = "thread-missing-attachment";
516 const missingPath = path.join(attachmentsDir, `${missingAttachmentId}.png`);
517 yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));
518
apps/server/src/textGeneration/CodexTextGeneration.ts
+9 -2
@@ -1,4 +1,11 @@
1 -import { Effect, FileSystem, Option, Path, Random, Schema, Scope, Stream } from "effect";
1 +import * as Effect from "effect/Effect";
2 +import * as FileSystem from "effect/FileSystem";
3 +import * as Option from "effect/Option";
4 +import * as Path from "effect/Path";
5 +import * as Random from "effect/Random";
6 +import * as Schema from "effect/Schema";
7 +import * as Scope from "effect/Scope";
8 +import * as Stream from "effect/Stream";
9 import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
10
11 import { type CodexSettings, type ModelSelection } from "@t3tools/contracts";
@@ -152,7 +159,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
159 const schemaPath = yield* writeTempFile(
160 operation,
161 "codex-schema",
155 - JSON.stringify(toJsonSchemaObject(outputSchemaJson)),
162 + Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(toJsonSchemaObject(outputSchemaJson)),
163 );
164 const outputPath = yield* writeTempFile(operation, "codex-output", "");
165
apps/server/src/textGeneration/CursorTextGeneration.test.ts
+16 -9
@@ -1,3 +1,4 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 import * as path from "node:path";
3 import * as os from "node:os";
4 import { fileURLToPath } from "node:url";
@@ -5,7 +6,11 @@ import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync
6
7 import * as NodeServices from "@effect/platform-node/NodeServices";
8 import { it } from "@effect/vitest";
8 -import { Effect, Layer, Schema } from "effect";
9 +import * as Clock from "effect/Clock";
10 +import * as Effect from "effect/Effect";
11 +import * as Exit from "effect/Exit";
12 +import * as Layer from "effect/Layer";
13 +import * as Schema from "effect/Schema";
14 import { createModelSelection } from "@t3tools/shared/model";
15 import { expect } from "vitest";
16
@@ -67,17 +72,19 @@ function withFakeAcpAgent<A, E, R>(
72 }
73
74 function waitForFileContent(path: string): Effect.Effect<string> {
70 - return Effect.promise(async () => {
71 - const deadline = Date.now() + 5_000;
75 + return Effect.gen(function* () {
76 + const deadline = (yield* Clock.currentTimeMillis) + 5_000;
77 for (;;) {
73 - try {
74 - return readFileSync(path, "utf8");
75 - } catch (error) {
76 - if (Date.now() >= deadline) {
77 - throw error instanceof Error ? error : new Error(String(error));
78 + const result = yield* Effect.exit(Effect.sync(() => readFileSync(path, "utf8")));
79 + if (Exit.isSuccess(result)) {
80 + return result.value;
81 + }
82 + {
83 + if ((yield* Clock.currentTimeMillis) >= deadline) {
84 + return yield* Effect.die(result.cause);
85 }
86 }
80 - await new Promise((resolve) => setTimeout(resolve, 25));
87 + yield* Effect.sleep(25);
88 }
89 });
90 }
apps/server/src/textGeneration/CursorTextGeneration.ts
+4 -1
@@ -1,4 +1,7 @@
1 -import { Effect, Option, Ref, Schema } from "effect";
1 +import * as Effect from "effect/Effect";
2 +import * as Option from "effect/Option";
3 +import * as Ref from "effect/Ref";
4 +import * as Schema from "effect/Schema";
5 import { ChildProcessSpawner } from "effect/unstable/process";
6
7 import { type CursorSettings, type ModelSelection } from "@t3tools/contracts";
apps/server/src/textGeneration/OpenCodeTextGeneration.test.ts
+6 -3
@@ -1,9 +1,12 @@
1 import { OpenCodeSettings, ProviderInstanceId } from "@t3tools/contracts";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 import { it } from "@effect/vitest";
4 -import { Duration, Effect, Layer, Schema } from "effect";
5 -import { TestClock } from "effect/testing";
6 -import { NetService } from "@t3tools/shared/Net";
4 +import * as Duration from "effect/Duration";
5 +import * as Effect from "effect/Effect";
6 +import * as Layer from "effect/Layer";
7 +import * as Schema from "effect/Schema";
8 +import * as TestClock from "effect/testing/TestClock";
9 +import * as NetService from "@t3tools/shared/Net";
10 import { beforeEach, expect } from "vitest";
11
12 import { ServerConfig } from "../config.ts";
apps/server/src/textGeneration/OpenCodeTextGeneration.ts
+5 -1
@@ -1,4 +1,8 @@
1 -import { Effect, Exit, Fiber, Schema, Scope } from "effect";
1 +import * as Effect from "effect/Effect";
2 +import * as Exit from "effect/Exit";
3 +import * as Fiber from "effect/Fiber";
4 +import * as Schema from "effect/Schema";
5 +import * as Scope from "effect/Scope";
6 import * as Semaphore from "effect/Semaphore";
7
8 import {
apps/server/src/textGeneration/TextGeneration.test.ts
+4 -1
@@ -1,5 +1,8 @@
1 import { it } from "@effect/vitest";
2 -import { Effect, PubSub, Result, Stream } from "effect";
2 +import * as Effect from "effect/Effect";
3 +import * as PubSub from "effect/PubSub";
4 +import * as Result from "effect/Result";
5 +import * as Stream from "effect/Stream";
6 import { describe, expect } from "vitest";
7
8 import { ProviderInstanceId } from "@t3tools/contracts";
apps/server/src/textGeneration/TextGeneration.ts
+3 -1
@@ -1,4 +1,6 @@
1 -import { Context, Effect, Layer } from "effect";
1 +import * as Context from "effect/Context";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 import type { ChatAttachment, ModelSelection, ProviderInstanceId } from "@t3tools/contracts";
5 import { TextGenerationError } from "@t3tools/contracts";
6
apps/server/src/textGeneration/TextGenerationPolicy.ts
+1 -1
@@ -1,4 +1,4 @@
1 -import { Schema } from "effect";
1 +import * as Schema from "effect/Schema";
2
3 export const TextGenerationPolicyKind = Schema.Literals([
4 "default",
apps/server/src/textGeneration/TextGenerationPrompts.ts
+1 -1
@@ -6,7 +6,7 @@
6 *
7 * @module textGenerationPrompts
8 */
9 -import { Schema } from "effect";
9 +import * as Schema from "effect/Schema";
10 import type { ChatAttachment } from "@t3tools/contracts";
11
12 import { limitSection } from "./TextGenerationUtils.ts";
apps/server/src/textGeneration/TextGenerationUtils.ts
+1 -1
@@ -1,4 +1,4 @@
1 -import { Schema } from "effect";
1 +import * as Schema from "effect/Schema";
2
3 import { TextGenerationError } from "@t3tools/contracts";
4
apps/server/src/vcs/GitVcsDriver.test.ts
+5 -1
@@ -1,5 +1,9 @@
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 -import { Effect, FileSystem, Layer, Path, PlatformError } from "effect";
2 +import * as Effect from "effect/Effect";
3 +import * as FileSystem from "effect/FileSystem";
4 +import * as Layer from "effect/Layer";
5 +import * as Path from "effect/Path";
6 +import * as PlatformError from "effect/PlatformError";
7 import { ChildProcessSpawner } from "effect/unstable/process";
8 import { assert, it } from "@effect/vitest";
9
apps/server/src/vcs/GitVcsDriver.ts
+5 -1
@@ -1,4 +1,8 @@
1 -import { Context, DateTime, Effect, Layer, Option } from "effect";
1 +import * as Context from "effect/Context";
2 +import * as DateTime from "effect/DateTime";
3 +import * as Effect from "effect/Effect";
4 +import * as Layer from "effect/Layer";
5 +import * as Option from "effect/Option";
6 import { ChildProcessSpawner } from "effect/unstable/process";
7
8 import {
apps/server/src/vcs/GitVcsDriverCore.test.ts
+6 -1
@@ -1,6 +1,11 @@
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { assert, it, describe } from "@effect/vitest";
3 -import { Effect, FileSystem, Layer, Path, PlatformError, Scope } from "effect";
3 +import * as Effect from "effect/Effect";
4 +import * as FileSystem from "effect/FileSystem";
5 +import * as Layer from "effect/Layer";
6 +import * as Path from "effect/Path";
7 +import * as PlatformError from "effect/PlatformError";
8 +import * as Scope from "effect/Scope";
9
10 import { GitCommandError } from "@t3tools/contracts";
11 import { ServerConfig } from "../config.ts";
apps/server/src/vcs/GitVcsDriverCore.ts
+16 -18
@@ -1,21 +1,19 @@
1 -import {
2 - Cache,
3 - Data,
4 - DateTime,
5 - Duration,
6 - Effect,
7 - Exit,
8 - FileSystem,
9 - Option,
10 - Path,
11 - PlatformError,
12 - Ref,
13 - Result,
14 - Schema,
15 - Scope,
16 - Semaphore,
17 - Stream,
18 -} from "effect";
1 +import * as Cache from "effect/Cache";
2 +import * as Data from "effect/Data";
3 +import * as DateTime from "effect/DateTime";
4 +import * as Duration from "effect/Duration";
5 +import * as Effect from "effect/Effect";
6 +import * as Exit from "effect/Exit";
7 +import * as FileSystem from "effect/FileSystem";
8 +import * as Option from "effect/Option";
9 +import * as Path from "effect/Path";
10 +import * as PlatformError from "effect/PlatformError";
11 +import * as Ref from "effect/Ref";
12 +import * as Result from "effect/Result";
13 +import * as Schema from "effect/Schema";
14 +import * as Scope from "effect/Scope";
15 +import * as Semaphore from "effect/Semaphore";
16 +import * as Stream from "effect/Stream";
17 import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
18
19 import { GitCommandError, type VcsRef } from "@t3tools/contracts";
apps/server/src/vcs/VcsDriver.ts
+2 -1
@@ -1,4 +1,5 @@
1 -import { Context, type Effect } from "effect";
1 +import * as Context from "effect/Context";
2 +import type * as Effect from "effect/Effect";
3
4 import type {
5 VcsDriverCapabilities,
apps/server/src/vcs/VcsDriverRegistry.test.ts
+2 -1
@@ -1,5 +1,6 @@
1 import { assert, it, describe } from "@effect/vitest";
2 -import { Effect, Layer } from "effect";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 import { ChildProcessSpawner } from "effect/unstable/process";
5
6 import * as VcsProcess from "./VcsProcess.ts";
apps/server/src/vcs/VcsDriverRegistry.ts
+6 -1
@@ -1,4 +1,9 @@
1 -import { Cache, Context, Duration, Effect, Exit, Layer } from "effect";
1 +import * as Cache from "effect/Cache";
2 +import * as Context from "effect/Context";
3 +import * as Duration from "effect/Duration";
4 +import * as Effect from "effect/Effect";
5 +import * as Exit from "effect/Exit";
6 +import * as Layer from "effect/Layer";
7
8 import type { VcsDriverKind, VcsError, VcsRepositoryIdentity } from "@t3tools/contracts";
9 import { VcsUnsupportedOperationError } from "@t3tools/contracts";
apps/server/src/vcs/VcsProcess.ts
+8 -1
@@ -1,4 +1,11 @@
1 -import { Duration, Context, Effect, Layer, Option, PlatformError, Sink, Stream } from "effect";
1 +import * as Duration from "effect/Duration";
2 +import * as Context from "effect/Context";
3 +import * as Effect from "effect/Effect";
4 +import * as Layer from "effect/Layer";
5 +import * as Option from "effect/Option";
6 +import * as PlatformError from "effect/PlatformError";
7 +import * as Sink from "effect/Sink";
8 +import * as Stream from "effect/Stream";
9 import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
10
11 import {
apps/server/src/vcs/VcsProjectConfig.test.ts
+5 -1
@@ -1,6 +1,9 @@
1 import { assert, it, describe } from "@effect/vitest";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 -import { Effect, FileSystem, Layer, Path } from "effect";
3 +import * as Effect from "effect/Effect";
4 +import * as FileSystem from "effect/FileSystem";
5 +import * as Layer from "effect/Layer";
6 +import * as Path from "effect/Path";
7
8 import * as VcsProjectConfig from "./VcsProjectConfig.ts";
9
@@ -38,6 +41,7 @@ describe("VcsProjectConfig", () => {
41 yield* fileSystem.makeDirectory(nested, { recursive: true });
42 yield* fileSystem.writeFileString(
43 path.join(configDir, "vcs.json"),
44 + // @effect-diagnostics-next-line preferSchemaOverJson:off
45 JSON.stringify({ vcs: { kind: "jj" } }),
46 );
47
apps/server/src/vcs/VcsProjectConfig.ts
+6 -1
@@ -1,4 +1,9 @@
1 -import { Context, Effect, FileSystem, Layer, Path, Schema } from "effect";
1 +import * as Context from "effect/Context";
2 +import * as Effect from "effect/Effect";
3 +import * as FileSystem from "effect/FileSystem";
4 +import * as Layer from "effect/Layer";
5 +import * as Path from "effect/Path";
6 +import * as Schema from "effect/Schema";
7
8 import { VcsDriverKind, type VcsDriverKind as VcsDriverKindType } from "@t3tools/contracts";
9
apps/server/src/vcs/VcsProvisioningService.test.ts
+4 -1
@@ -1,5 +1,8 @@
1 import { assert, it } from "@effect/vitest";
2 -import { DateTime, Effect, Layer, Option } from "effect";
2 +import * as DateTime from "effect/DateTime";
3 +import * as Effect from "effect/Effect";
4 +import * as Layer from "effect/Layer";
5 +import * as Option from "effect/Option";
6 import { ChildProcessSpawner } from "effect/unstable/process";
7
8 import * as VcsDriver from "./VcsDriver.ts";
apps/server/src/vcs/VcsProvisioningService.ts
+3 -1
@@ -1,4 +1,6 @@
1 -import { Context, Effect, Layer } from "effect";
1 +import * as Context from "effect/Context";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4
5 import {
6 type VcsDriverKind,
apps/server/src/vcs/VcsStatusBroadcaster.test.ts
+13 -2
@@ -1,6 +1,14 @@
1 import { assert, it, describe } from "@effect/vitest";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 -import { Deferred, Effect, Exit, FileSystem, Layer, Option, Path, Scope, Stream } from "effect";
3 +import * as Deferred from "effect/Deferred";
4 +import * as Effect from "effect/Effect";
5 +import * as Exit from "effect/Exit";
6 +import * as FileSystem from "effect/FileSystem";
7 +import * as Layer from "effect/Layer";
8 +import * as Option from "effect/Option";
9 +import * as Path from "effect/Path";
10 +import * as Scope from "effect/Scope";
11 +import * as Stream from "effect/Stream";
12 import type {
13 VcsStatusLocalResult,
14 VcsStatusRemoteResult,
@@ -46,6 +54,7 @@ function makeTestLayer(state: {
54 remoteInvalidationCalls: number;
55 }) {
56 return VcsStatusBroadcaster.layer.pipe(
57 + Layer.provideMerge(NodeServices.layer),
58 Layer.provide(
59 Layer.mock(GitWorkflowService.GitWorkflowService)({
60 localStatus: () =>
@@ -185,6 +194,7 @@ describe("VcsStatusBroadcaster", () => {
194 remoteInvalidationCalls: 0,
195 };
196 const testLayer = VcsStatusBroadcaster.layer.pipe(
197 + Layer.provideMerge(NodeServices.layer),
198 Layer.provide(
199 Layer.mock(GitWorkflowService.GitWorkflowService)({
200 localStatus: (input) =>
@@ -231,7 +241,7 @@ describe("VcsStatusBroadcaster", () => {
241 assert.deepStrictEqual(seenCwds, [realPath, realPath]);
242 assert.equal(state.localStatusCalls, 1);
243 assert.equal(state.remoteStatusCalls, 1);
234 - }).pipe(Effect.provide(Layer.mergeAll(testLayer, NodeServices.layer)));
244 + }).pipe(Effect.provide(testLayer));
245 });
246
247 it.effect("streams a local snapshot first and remote updates later", () => {
@@ -286,6 +296,7 @@ describe("VcsStatusBroadcaster", () => {
296 let remoteInterruptedDeferred: Deferred.Deferred<void, never> | null = null;
297 let remoteStartedDeferred: Deferred.Deferred<void, never> | null = null;
298 const testLayer = VcsStatusBroadcaster.layer.pipe(
299 + Layer.provideMerge(NodeServices.layer),
300 Layer.provide(
301 Layer.mock(GitWorkflowService.GitWorkflowService)({
302 localStatus: () =>
apps/server/src/vcs/VcsStatusBroadcaster.ts
+24 -26
@@ -1,18 +1,15 @@
1 -import { realpathSync } from "node:fs";
2 -
3 -import {
4 - Context,
5 - Duration,
6 - Effect,
7 - Exit,
8 - Fiber,
9 - Layer,
10 - PubSub,
11 - Ref,
12 - Scope,
13 - Stream,
14 - SynchronizedRef,
15 -} from "effect";
1 +import * as Context from "effect/Context";
2 +import * as Duration from "effect/Duration";
3 +import * as Effect from "effect/Effect";
4 +import * as Exit from "effect/Exit";
5 +import * as Fiber from "effect/Fiber";
6 +import * as FileSystem from "effect/FileSystem";
7 +import * as Layer from "effect/Layer";
8 +import * as PubSub from "effect/PubSub";
9 +import * as Ref from "effect/Ref";
10 +import * as Scope from "effect/Scope";
11 +import * as Stream from "effect/Stream";
12 +import * as SynchronizedRef from "effect/SynchronizedRef";
13 import type {
14 GitManagerServiceError,
15 VcsStatusInput,
@@ -69,18 +66,17 @@ function fingerprintStatusPart(status: unknown): string {
66 return JSON.stringify(status);
67 }
68
72 -function normalizeCwd(cwd: string): string {
73 - try {
74 - return realpathSync.native(cwd);
75 - } catch {
76 - return cwd;
77 - }
78 -}
69 +const normalizeCwd = (cwd: string) =>
70 + Effect.service(FileSystem.FileSystem).pipe(
71 + Effect.flatMap((fs) => fs.realPath(cwd)),
72 + Effect.orElseSucceed(() => cwd),
73 + );
74
75 export const layer = Layer.effect(
76 VcsStatusBroadcaster,
77 Effect.gen(function* () {
78 const workflow = yield* GitWorkflowService.GitWorkflowService;
79 + const fs = yield* FileSystem.FileSystem;
80 const changesPubSub = yield* Effect.acquireRelease(
81 PubSub.unbounded<VcsStatusChange>(),
82 (pubsub) => PubSub.shutdown(pubsub),
@@ -195,10 +191,12 @@ export const layer = Layer.effect(
191 },
192 );
193
194 + const withFileSystem = Effect.provideService(FileSystem.FileSystem, fs);
195 +
196 const getStatus: VcsStatusBroadcasterShape["getStatus"] = Effect.fn(
197 "VcsStatusBroadcaster.getStatus",
198 )(function* (input) {
201 - const cwd = normalizeCwd(input.cwd);
199 + const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
200 const [local, remote] = yield* Effect.all([
201 getOrLoadLocalStatus(cwd),
202 getOrLoadRemoteStatus(cwd),
@@ -209,7 +207,7 @@ export const layer = Layer.effect(
207 const refreshLocalStatus: VcsStatusBroadcasterShape["refreshLocalStatus"] = Effect.fn(
208 "VcsStatusBroadcaster.refreshLocalStatus",
209 )(function* (rawCwd) {
212 - const cwd = normalizeCwd(rawCwd);
210 + const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
211 yield* workflow.invalidateLocalStatus(cwd);
212 const local = yield* workflow.localStatus({ cwd });
213 return yield* updateCachedLocalStatus(cwd, local, { publish: true });
@@ -226,7 +224,7 @@ export const layer = Layer.effect(
224 const refreshStatus: VcsStatusBroadcasterShape["refreshStatus"] = Effect.fn(
225 "VcsStatusBroadcaster.refreshStatus",
226 )(function* (rawCwd) {
229 - const cwd = normalizeCwd(rawCwd);
227 + const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
228 const [local, remote] = yield* Effect.all([
229 refreshLocalStatus(cwd),
230 refreshRemoteStatus(cwd),
@@ -312,7 +310,7 @@ export const layer = Layer.effect(
310 const streamStatus: VcsStatusBroadcasterShape["streamStatus"] = (input) =>
311 Stream.unwrap(
312 Effect.gen(function* () {
315 - const cwd = normalizeCwd(input.cwd);
313 + const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
314 const subscription = yield* PubSub.subscribe(changesPubSub);
315 const initialLocal = yield* getOrLoadLocalStatus(cwd);
316 const initialRemote = (yield* getCachedStatus(cwd))?.remote?.value ?? null;
apps/server/src/vcs/testing/VcsDriverContractHarness.ts
+8 -10
@@ -1,14 +1,12 @@
1 import { assert, it, describe } from "@effect/vitest";
2 -import {
3 - Effect,
4 - FileSystem,
5 - Layer,
6 - Path,
7 - type PlatformError,
8 - type Scope,
9 - DateTime,
10 - Option,
11 -} from "effect";
2 +import * as Effect from "effect/Effect";
3 +import * as FileSystem from "effect/FileSystem";
4 +import * as Layer from "effect/Layer";
5 +import * as Path from "effect/Path";
6 +import type * as PlatformError from "effect/PlatformError";
7 +import type * as Scope from "effect/Scope";
8 +import * as DateTime from "effect/DateTime";
9 +import * as Option from "effect/Option";
10
11 import type { VcsDriverKind } from "@t3tools/contracts";
12 import * as VcsDriver from "../VcsDriver.ts";
apps/server/src/workspace/Layers/WorkspaceEntries.test.ts
+38 -7
@@ -1,8 +1,13 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 import fsPromises from "node:fs/promises";
2 -
3 import * as NodeServices from "@effect/platform-node/NodeServices";
4 import { it, afterEach, describe, expect, vi } from "@effect/vitest";
5 -import { Effect, FileSystem, Layer, Path, PlatformError } from "effect";
5 +import * as Effect from "effect/Effect";
6 +import * as Fiber from "effect/Fiber";
7 +import * as FileSystem from "effect/FileSystem";
8 +import * as Layer from "effect/Layer";
9 +import * as Path from "effect/Path";
10 +import * as PlatformError from "effect/PlatformError";
11
12 import { ServerConfig } from "../../config.ts";
13 import * as VcsDriverRegistry from "../../vcs/VcsDriverRegistry.ts";
@@ -222,25 +227,37 @@ it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
227 yield* writeTextFile(cwd, "src/components/Composer.tsx");
228
229 let rootReadCount = 0;
230 + let releaseRootRead: (() => void) | undefined;
231 + const rootReadGate = new Promise<void>((resolve) => {
232 + releaseRootRead = resolve;
233 + });
234 const originalReaddir = fsPromises.readdir.bind(fsPromises);
235 vi.spyOn(fsPromises, "readdir").mockImplementation((async (
236 ...args: Parameters<typeof fsPromises.readdir>
237 ) => {
238 if (args[0] === cwd) {
239 rootReadCount += 1;
231 - await new Promise((resolve) => setTimeout(resolve, 20));
240 + await rootReadGate;
241 }
242 return originalReaddir(...args);
243 }) as typeof fsPromises.readdir);
244
236 - yield* Effect.all(
245 + const searches = yield* Effect.all(
246 [
247 searchWorkspaceEntries({ cwd, query: "", limit: 100 }),
248 searchWorkspaceEntries({ cwd, query: "comp", limit: 100 }),
249 searchWorkspaceEntries({ cwd, query: "src", limit: 100 }),
250 ],
251 { concurrency: "unbounded" },
243 - );
252 + ).pipe(Effect.forkScoped);
253 + for (let attempt = 0; attempt < 50; attempt += 1) {
254 + if (rootReadCount > 0) {
255 + break;
256 + }
257 + yield* Effect.yieldNow;
258 + }
259 + releaseRootRead?.();
260 + yield* Fiber.join(searches);
261
262 expect(rootReadCount).toBe(1);
263 }),
@@ -257,6 +274,10 @@ it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
274
275 let activeReads = 0;
276 let peakReads = 0;
277 + let releaseReads: (() => void) | undefined;
278 + const readsGate = new Promise<void>((resolve) => {
279 + releaseReads = resolve;
280 + });
281 const originalReaddir = fsPromises.readdir.bind(fsPromises);
282 vi.spyOn(fsPromises, "readdir").mockImplementation((async (
283 ...args: Parameters<typeof fsPromises.readdir>
@@ -265,7 +286,7 @@ it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
286 if (typeof target === "string" && target.startsWith(cwd)) {
287 activeReads += 1;
288 peakReads = Math.max(peakReads, activeReads);
268 - await new Promise((resolve) => setTimeout(resolve, 4));
289 + await readsGate;
290 try {
291 return await originalReaddir(...args);
292 } finally {
@@ -275,7 +296,17 @@ it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
296 return originalReaddir(...args);
297 }) as typeof fsPromises.readdir);
298
278 - yield* searchWorkspaceEntries({ cwd, query: "", limit: 200 });
299 + const search = yield* searchWorkspaceEntries({ cwd, query: "", limit: 200 }).pipe(
300 + Effect.forkScoped,
301 + );
302 + for (let attempt = 0; attempt < 50; attempt += 1) {
303 + if (activeReads > 0) {
304 + break;
305 + }
306 + yield* Effect.yieldNow;
307 + }
308 + releaseReads?.();
309 + yield* Fiber.join(search);
310
311 expect(peakReads).toBeLessThanOrEqual(32);
312 }),
apps/server/src/workspace/Layers/WorkspaceEntries.ts
+8 -1
@@ -1,8 +1,15 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 import * as OS from "node:os";
3 import fsPromises from "node:fs/promises";
4 import type { Dirent } from "node:fs";
5
5 -import { Cache, DateTime, Duration, Effect, Exit, Layer, Path } from "effect";
6 +import * as Cache from "effect/Cache";
7 +import * as DateTime from "effect/DateTime";
8 +import * as Duration from "effect/Duration";
9 +import * as Effect from "effect/Effect";
10 +import * as Exit from "effect/Exit";
11 +import * as Layer from "effect/Layer";
12 +import * as Path from "effect/Path";
13
14 import { type FilesystemBrowseInput, type ProjectEntry } from "@t3tools/contracts";
15 import { isExplicitRelativePath, isWindowsAbsolutePath } from "@t3tools/shared/path";
apps/server/src/workspace/Layers/WorkspaceFileSystem.test.ts
+4 -1
@@ -1,6 +1,9 @@
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { it, describe, expect } from "@effect/vitest";
3 -import { Effect, FileSystem, Layer, Path } from "effect";
3 +import * as Effect from "effect/Effect";
4 +import * as FileSystem from "effect/FileSystem";
5 +import * as Layer from "effect/Layer";
6 +import * as Path from "effect/Path";
7
8 import { ServerConfig } from "../../config.ts";
9 import * as VcsDriverRegistry from "../../vcs/VcsDriverRegistry.ts";
apps/server/src/workspace/Layers/WorkspaceFileSystem.ts
+4 -1
@@ -1,4 +1,7 @@
1 -import { Effect, FileSystem, Layer, Path } from "effect";
1 +import * as Effect from "effect/Effect";
2 +import * as FileSystem from "effect/FileSystem";
3 +import * as Layer from "effect/Layer";
4 +import * as Path from "effect/Path";
5
6 import {
7 WorkspaceFileSystem,
apps/server/src/workspace/Layers/WorkspacePaths.test.ts
+4 -1
@@ -1,6 +1,9 @@
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { it, describe, expect } from "@effect/vitest";
3 -import { Effect, FileSystem, Layer, Path } from "effect";
3 +import * as Effect from "effect/Effect";
4 +import * as FileSystem from "effect/FileSystem";
5 +import * as Layer from "effect/Layer";
6 +import * as Path from "effect/Path";
7
8 import { WorkspacePaths } from "../Services/WorkspacePaths.ts";
9 import { WorkspacePathsLive } from "./WorkspacePaths.ts";
apps/server/src/workspace/Layers/WorkspacePaths.ts
+4 -1
@@ -1,5 +1,8 @@
1 import * as OS from "node:os";
2 -import { Effect, FileSystem, Layer, Path } from "effect";
2 +import * as Effect from "effect/Effect";
3 +import * as FileSystem from "effect/FileSystem";
4 +import * as Layer from "effect/Layer";
5 +import * as Path from "effect/Path";
6
7 import {
8 WorkspacePaths,
apps/server/src/workspace/Services/WorkspaceEntries.ts
+3 -2
@@ -6,8 +6,9 @@
6 *
7 * @module WorkspaceEntries
8 */
9 -import { Schema, Context } from "effect";
10 -import type { Effect } from "effect";
9 +import * as Schema from "effect/Schema";
10 +import * as Context from "effect/Context";
11 +import type * as Effect from "effect/Effect";
12
13 import type {
14 FilesystemBrowseInput,
apps/server/src/workspace/Services/WorkspaceFileSystem.ts
+3 -2
@@ -6,8 +6,9 @@
6 *
7 * @module WorkspaceFileSystem
8 */
9 -import { Schema, Context } from "effect";
10 -import type { Effect } from "effect";
9 +import * as Schema from "effect/Schema";
10 +import * as Context from "effect/Context";
11 +import type * as Effect from "effect/Effect";
12
13 import type { ProjectWriteFileInput, ProjectWriteFileResult } from "@t3tools/contracts";
14 import { WorkspacePathOutsideRootError } from "./WorkspacePaths.ts";
apps/server/src/workspace/Services/WorkspacePaths.ts
+3 -2
@@ -6,8 +6,9 @@
6 *
7 * @module WorkspacePaths
8 */
9 -import { Schema, Context } from "effect";
10 -import type { Effect } from "effect";
9 +import * as Schema from "effect/Schema";
10 +import * as Context from "effect/Context";
11 +import type * as Effect from "effect/Effect";
12
13 export class WorkspaceRootNotExistsError extends Schema.TaggedErrorClass<WorkspaceRootNotExistsError>()(
14 "WorkspaceRootNotExistsError",
apps/server/src/ws.ts
+89 -75
@@ -1,4 +1,13 @@
1 -import { Cause, Duration, Effect, Layer, Option, Queue, Ref, Schema, Stream } from "effect";
1 +import * as Cause from "effect/Cause";
2 +import * as DateTime from "effect/DateTime";
3 +import * as Duration from "effect/Duration";
4 +import * as Effect from "effect/Effect";
5 +import * as Layer from "effect/Layer";
6 +import * as Option from "effect/Option";
7 +import * as Queue from "effect/Queue";
8 +import * as Ref from "effect/Ref";
9 +import * as Schema from "effect/Schema";
10 +import * as Stream from "effect/Stream";
11 import {
12 type AuthAccessStreamEvent,
13 AuthSessionId,
@@ -78,6 +87,8 @@ import {
87 } from "./auth/Services/SessionCredentialService.ts";
88 import { respondToAuthError } from "./auth/http.ts";
89
90 +const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
91 +
92 function isThreadDetailEvent(event: OrchestrationEvent): event is Extract<
93 OrchestrationEvent,
94 {
@@ -378,83 +389,86 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
389 readonly scriptId: string;
390 readonly scriptName: string;
391 readonly terminalId: string;
381 - }) => {
382 - const payload = {
383 - scriptId: input.scriptId,
384 - scriptName: input.scriptName,
385 - terminalId: input.terminalId,
386 - worktreePath: input.worktreePath,
387 - };
388 - return Effect.all([
389 - appendSetupScriptActivity({
390 - threadId: command.threadId,
391 - kind: "setup-script.requested",
392 - summary: "Starting setup script",
393 - createdAt: input.requestedAt,
394 - payload,
395 - tone: "info",
396 - }),
397 - appendSetupScriptActivity({
398 - threadId: command.threadId,
399 - kind: "setup-script.started",
400 - summary: "Setup script started",
401 - createdAt: new Date().toISOString(),
402 - payload,
403 - tone: "info",
404 - }),
405 - ]).pipe(
406 - Effect.asVoid,
407 - Effect.catch((error) =>
408 - Effect.logWarning(
409 - "bootstrap turn start launched setup script but failed to record setup activity",
410 - {
411 - threadId: command.threadId,
412 - worktreePath: input.worktreePath,
413 - scriptId: input.scriptId,
414 - terminalId: input.terminalId,
415 - detail: error.message,
416 - },
392 + }) =>
393 + Effect.gen(function* () {
394 + const startedAt = yield* nowIso;
395 + const payload = {
396 + scriptId: input.scriptId,
397 + scriptName: input.scriptName,
398 + terminalId: input.terminalId,
399 + worktreePath: input.worktreePath,
400 + };
401 + yield* Effect.all([
402 + appendSetupScriptActivity({
403 + threadId: command.threadId,
404 + kind: "setup-script.requested",
405 + summary: "Starting setup script",
406 + createdAt: input.requestedAt,
407 + payload,
408 + tone: "info",
409 + }),
410 + appendSetupScriptActivity({
411 + threadId: command.threadId,
412 + kind: "setup-script.started",
413 + summary: "Setup script started",
414 + createdAt: startedAt,
415 + payload,
416 + tone: "info",
417 + }),
418 + ]).pipe(
419 + Effect.asVoid,
420 + Effect.catch((error) =>
421 + Effect.logWarning(
422 + "bootstrap turn start launched setup script but failed to record setup activity",
423 + {
424 + threadId: command.threadId,
425 + worktreePath: input.worktreePath,
426 + scriptId: input.scriptId,
427 + terminalId: input.terminalId,
428 + detail: error.message,
429 + },
430 + ),
431 ),
418 - ),
419 - );
420 - };
432 + );
433 + });
434
435 const runSetupProgram = () =>
423 - bootstrap?.runSetupScript && targetWorktreePath
424 - ? (() => {
425 - const worktreePath = targetWorktreePath;
426 - const requestedAt = new Date().toISOString();
427 - return projectSetupScriptRunner
428 - .runForThread({
429 - threadId: command.threadId,
430 - ...(targetProjectId ? { projectId: targetProjectId } : {}),
431 - ...(targetProjectCwd ? { projectCwd: targetProjectCwd } : {}),
432 - worktreePath,
433 - })
434 - .pipe(
435 - Effect.matchEffect({
436 - onFailure: (error) =>
437 - recordSetupScriptLaunchFailure({
438 - error,
439 - requestedAt,
440 - worktreePath,
441 - }),
442 - onSuccess: (setupResult) => {
443 - if (setupResult.status !== "started") {
444 - return Effect.void;
445 - }
446 - return recordSetupScriptStarted({
447 - requestedAt,
448 - worktreePath,
449 - scriptId: setupResult.scriptId,
450 - scriptName: setupResult.scriptName,
451 - terminalId: setupResult.terminalId,
452 - });
453 - },
436 + Effect.gen(function* () {
437 + if (!bootstrap?.runSetupScript || !targetWorktreePath) {
438 + return;
439 + }
440 + const worktreePath = targetWorktreePath;
441 + const requestedAt = yield* nowIso;
442 + yield* projectSetupScriptRunner
443 + .runForThread({
444 + threadId: command.threadId,
445 + ...(targetProjectId ? { projectId: targetProjectId } : {}),
446 + ...(targetProjectCwd ? { projectCwd: targetProjectCwd } : {}),
447 + worktreePath,
448 + })
449 + .pipe(
450 + Effect.matchEffect({
451 + onFailure: (error) =>
452 + recordSetupScriptLaunchFailure({
453 + error,
454 + requestedAt,
455 + worktreePath,
456 }),
455 - );
456 - })()
457 - : Effect.void;
457 + onSuccess: (setupResult) => {
458 + if (setupResult.status !== "started") {
459 + return Effect.void;
460 + }
461 + return recordSetupScriptStarted({
462 + requestedAt,
463 + worktreePath,
464 + scriptId: setupResult.scriptId,
465 + scriptName: setupResult.scriptName,
466 + terminalId: setupResult.terminalId,
467 + });
468 + },
469 + }),
470 + );
471 + });
472
473 const bootstrapProgram = Effect.gen(function* () {
474 if (bootstrap?.createThread) {
@@ -597,7 +611,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
611 `session-stop-for-archive:${normalizedCommand.commandId}`,
612 ),
613 threadId: normalizedCommand.threadId,
600 - createdAt: new Date().toISOString(),
614 + createdAt: yield* nowIso,
615 });
616
617 yield* dispatchNormalizedCommand(stopCommand);
apps/server/tsconfig.json
+1 -15
@@ -3,21 +3,7 @@
3 "compilerOptions": {
4 "composite": true,
5 "types": ["node", "bun"],
6 - "lib": ["ESNext", "esnext.disposable"],
7 - "plugins": [
8 - {
9 - "name": "@effect/language-service",
10 - "namespaceImportPackages": ["@effect/platform-node"],
11 - "diagnosticSeverity": {
12 - "importFromBarrel": "error",
13 - "anyUnknownInErrorContext": "warning",
14 - "instanceOfSchema": "warning",
15 - "deterministicKeys": "warning",
16 - "preferSchemaOverJson": "off",
17 - "globalErrorInEffectFailure": "off"
18 - }
19 - }
20 - ]
6 + "lib": ["ESNext", "esnext.disposable"]
7 },
8 "include": ["src", "tsdown.config.ts", "scripts", "integration", "../../scripts/lib"]
9 }
apps/web/src/components/BranchToolbar.logic.ts
+1 -1
@@ -1,5 +1,5 @@
1 import type { EnvironmentId, VcsRef, ProjectId } from "@t3tools/contracts";
2 -import { Schema } from "effect";
2 +import * as Schema from "effect/Schema";
3 export {
4 dedupeRemoteBranchesWithLocalMatches,
5 deriveLocalBranchNameFromRemoteRef,
apps/web/src/components/ChatView.browser.tsx
+1 -1
@@ -22,7 +22,7 @@ import {
22 import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime";
23 import { createModelCapabilities, createModelSelection } from "@t3tools/shared/model";
24 import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
25 -import { Option } from "effect";
25 +import * as Option from "effect/Option";
26 import { HttpResponse, http, ws } from "msw";
27 import { setupWorker } from "msw/browser";
28 import { page } from "vitest/browser";
apps/web/src/components/ChatView.logic.ts
+1 -1
@@ -10,7 +10,7 @@ import {
10 } from "@t3tools/contracts";
11 import { type ChatMessage, type SessionPhase, type Thread, type ThreadSession } from "../types";
12 import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
13 -import { Schema } from "effect";
13 +import * as Schema from "effect/Schema";
14 import { selectThreadByRef, useStore } from "../store";
15 import {
16 filterTerminalContextsWithText,
apps/web/src/components/CommandPalette.tsx
+1 -1
@@ -13,7 +13,7 @@ import {
13 } from "@t3tools/contracts";
14 import { useQuery, useQueryClient } from "@tanstack/react-query";
15 import { useNavigate, useParams } from "@tanstack/react-router";
16 -import { Option } from "effect";
16 +import * as Option from "effect/Option";
17 import {
18 ArrowDownIcon,
19 ArrowLeftIcon,
apps/web/src/components/GitActionsControl.tsx
+1 -1
@@ -12,7 +12,7 @@ import type {
12 } from "@t3tools/contracts";
13 import { useIsMutating, useMutation, useQueryClient } from "@tanstack/react-query";
14 import { useNavigate } from "@tanstack/react-router";
15 -import { Option } from "effect";
15 +import * as Option from "effect/Option";
16 import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
17 import { flushSync } from "react-dom";
18 import {
apps/web/src/components/settings/ConnectionsSettings.tsx
+1 -1
@@ -17,7 +17,7 @@ import {
17 type DesktopServerExposureState,
18 type EnvironmentId,
19 } from "@t3tools/contracts";
20 -import { DateTime } from "effect";
20 +import * as DateTime from "effect/DateTime";
21
22 import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
23 import { cn } from "../../lib/utils";
apps/web/src/components/settings/DiagnosticsSettings.tsx
+2 -1
@@ -9,7 +9,8 @@ import {
9 } from "lucide-react";
10 import { useCallback, useMemo, useState, type ReactNode } from "react";
11 import type { ServerProcessDiagnosticsEntry, ServerProcessSignal } from "@t3tools/contracts";
12 -import { DateTime, Option } from "effect";
12 +import * as DateTime from "effect/DateTime";
13 +import * as Option from "effect/Option";
14
15 import { ensureLocalApi } from "../../localApi";
16 import { cn } from "../../lib/utils";
apps/web/src/components/settings/ProviderSettingsForm.tsx
+1 -1
@@ -1,7 +1,7 @@
1 "use client";
2
3 import { useMemo, type ReactNode } from "react";
4 -import { Schema } from "effect";
4 +import * as Schema from "effect/Schema";
5 import type {
6 ProviderSettingsFormAnnotation,
7 ProviderSettingsFormControl,
apps/web/src/components/settings/SettingsPanels.browser.tsx
+3 -2
@@ -16,7 +16,8 @@ import {
16 type ServerProvider,
17 type SourceControlDiscoveryResult,
18 } from "@t3tools/contracts";
19 -import { DateTime, Option } from "effect";
19 +import * as DateTime from "effect/DateTime";
20 +import * as Option from "effect/Option";
21 import { page } from "vitest/browser";
22 import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
23 import { render } from "vitest-browser-react";
@@ -261,7 +262,7 @@ function createOutdatedProvider(driver: string): ServerProvider {
262 }
263
264 function makeUtc(value: string) {
264 - return DateTime.makeUnsafe(Date.parse(value));
265 + return DateTime.makeUnsafe(value);
266 }
267
268 function makePairingLink(input: {
apps/web/src/components/settings/SettingsPanels.tsx
+1 -1
@@ -14,7 +14,7 @@ import {
14 import { scopeThreadRef } from "@t3tools/client-runtime";
15 import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
16 import { createModelSelection } from "@t3tools/shared/model";
17 -import { Equal } from "effect";
17 +import * as Equal from "effect/Equal";
18 import { APP_VERSION } from "../../branding";
19 import {
20 canCheckForUpdate,
apps/web/src/components/settings/SourceControlSettings.tsx
+1 -1
@@ -1,5 +1,5 @@
1 import { GitPullRequestIcon, RefreshCwIcon } from "lucide-react";
2 -import { Option } from "effect";
2 +import * as Option from "effect/Option";
3 import { type ReactNode } from "react";
4 import type {
5 SourceControlProviderKind,
apps/web/src/components/settings/providerDriverMeta.ts
+1 -1
@@ -5,7 +5,7 @@ import {
5 OpenCodeSettings,
6 ProviderDriverKind,
7 } from "@t3tools/contracts";
8 -import type { Schema } from "effect";
8 +import type * as Schema from "effect/Schema";
9 import { ClaudeAI, CursorIcon, type Icon, OpenAI, OpenCodeIcon } from "../Icons";
10
11 type ProviderSettingsSchema = {
apps/web/src/components/ui/sidebar.tsx
+1 -1
@@ -19,7 +19,7 @@ import { Skeleton } from "~/components/ui/skeleton";
19 import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
20 import { useIsMobile } from "~/hooks/useMediaQuery";
21 import { getLocalStorageItem, setLocalStorageItem } from "~/hooks/useLocalStorage";
22 -import { Schema } from "effect";
22 +import * as Schema from "effect/Schema";
23
24 const SIDEBAR_COOKIE_NAME = "sidebar_state";
25 const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
apps/web/src/environments/primary/auth.ts
+2 -1
@@ -16,7 +16,8 @@ import {
16 } from "../../pairingUrl";
17
18 import { resolvePrimaryEnvironmentHttpUrl } from "./target";
19 -import { Data, Predicate } from "effect";
19 +import * as Data from "effect/Data";
20 +import * as Predicate from "effect/Predicate";
21
22 export class BootstrapHttpError extends Data.TaggedError("BootstrapHttpError")<{
23 readonly message: string;
apps/web/src/hooks/useSettings.ts
+1 -1
@@ -19,7 +19,7 @@ import {
19 UnifiedSettings,
20 } from "@t3tools/contracts/settings";
21 import { ensureLocalApi } from "~/localApi";
22 -import { Struct } from "effect";
22 +import * as Struct from "effect/Struct";
23 import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
24 import { applySettingsUpdated, getServerConfig, useServerSettings } from "~/rpc/serverState";
25
apps/web/src/lib/gitStatusState.ts
+1 -1
@@ -4,7 +4,7 @@ import {
4 type GitManagerServiceError,
5 type VcsStatusResult,
6 } from "@t3tools/contracts";
7 -import { Cause } from "effect";
7 +import * as Cause from "effect/Cause";
8 import { Atom } from "effect/unstable/reactivity";
9 import { useEffect } from "react";
10
apps/web/src/lib/processDiagnosticsState.ts
+3 -1
@@ -1,6 +1,8 @@
1 import { useAtomValue } from "@effect/atom-react";
2 import type { ServerProcessDiagnosticsResult } from "@t3tools/contracts";
3 -import { Cause, Effect, Option } from "effect";
3 +import * as Cause from "effect/Cause";
4 +import * as Effect from "effect/Effect";
5 +import * as Option from "effect/Option";
6 import { AsyncResult, Atom } from "effect/unstable/reactivity";
7 import { useCallback } from "react";
8
apps/web/src/lib/projectScriptKeybindings.ts
+1 -1
@@ -4,7 +4,7 @@ import {
4 type KeybindingRule,
5 type ResolvedKeybindingsConfig,
6 } from "@t3tools/contracts";
7 -import { Schema } from "effect";
7 +import * as Schema from "effect/Schema";
8
9 export const PROJECT_SCRIPT_KEYBINDING_INVALID_MESSAGE = "Invalid keybinding.";
10
apps/web/src/lib/providerReactQuery.ts
+2 -1
@@ -5,7 +5,8 @@ import {
5 ThreadId,
6 } from "@t3tools/contracts";
7 import { queryOptions } from "@tanstack/react-query";
8 -import { Option, Schema } from "effect";
8 +import * as Option from "effect/Option";
9 +import * as Schema from "effect/Schema";
10 import { ensureEnvironmentApi } from "../environmentApi";
11
12 interface CheckpointDiffQueryInput {
apps/web/src/lib/sourceControlDiscoveryState.ts
+1 -1
@@ -7,7 +7,7 @@ import {
7 sourceControlDiscoveryStateAtom,
8 } from "@t3tools/client-runtime";
9 import { EnvironmentId, type SourceControlDiscoveryResult } from "@t3tools/contracts";
10 -import { Effect } from "effect";
10 +import * as Effect from "effect/Effect";
11 import { Atom } from "effect/unstable/reactivity";
12
13 import { readPrimaryEnvironmentDescriptor } from "../environments/primary";
apps/web/src/lib/traceDiagnosticsState.ts
+3 -1
@@ -1,6 +1,8 @@
1 import { useAtomValue } from "@effect/atom-react";
2 import type { ServerTraceDiagnosticsResult } from "@t3tools/contracts";
3 -import { Cause, Effect, Option } from "effect";
3 +import * as Cause from "effect/Cause";
4 +import * as Effect from "effect/Effect";
5 +import * as Option from "effect/Option";
6 import { AsyncResult, Atom } from "effect/unstable/reactivity";
7 import { useCallback } from "react";
8
apps/web/src/observability/clientTracing.ts
+5 -1
@@ -1,4 +1,8 @@
1 -import { Exit, Layer, ManagedRuntime, Scope, Tracer } from "effect";
1 +import * as Exit from "effect/Exit";
2 +import * as Layer from "effect/Layer";
3 +import * as ManagedRuntime from "effect/ManagedRuntime";
4 +import * as Scope from "effect/Scope";
5 +import * as Tracer from "effect/Tracer";
6 import { FetchHttpClient, HttpClient } from "effect/unstable/http";
7 import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
8
apps/web/src/projectScripts.ts
+1 -1
@@ -4,7 +4,7 @@ import {
4 type KeybindingCommand,
5 type ProjectScript,
6 } from "@t3tools/contracts";
7 -import { Schema } from "effect";
7 +import * as Schema from "effect/Schema";
8
9 function normalizeScriptId(value: string): string {
10 const cleaned = value
apps/web/src/rpc/protocol.ts
+4 -1
@@ -1,5 +1,8 @@
1 import { WsRpcGroup } from "@t3tools/contracts";
2 -import { Duration, Effect, Layer, Schedule } from "effect";
2 +import * as Duration from "effect/Duration";
3 +import * as Effect from "effect/Effect";
4 +import * as Layer from "effect/Layer";
5 +import * as Schedule from "effect/Schedule";
6 import { RpcClient, RpcSerialization } from "effect/unstable/rpc";
7 import * as Socket from "effect/unstable/socket/Socket";
8
apps/web/src/rpc/wsRpcClient.ts
+2 -1
@@ -10,7 +10,8 @@ import {
10 WS_METHODS,
11 } from "@t3tools/contracts";
12 import { applyGitStatusStreamEvent } from "@t3tools/shared/git";
13 -import { Effect, Stream } from "effect";
13 +import * as Effect from "effect/Effect";
14 +import * as Stream from "effect/Stream";
15
16 import { type WsRpcProtocolClient } from "./protocol";
17 import { resetWsReconnectBackoff } from "./wsConnectionState";
apps/web/src/rpc/wsTransport.test.ts
+1 -1
@@ -1,5 +1,5 @@
1 import { DEFAULT_SERVER_SETTINGS, WS_METHODS } from "@t3tools/contracts";
2 -import { Stream } from "effect";
2 +import * as Stream from "effect/Stream";
3 import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4
5 import {
apps/web/src/rpc/wsTransport.ts
+9 -11
@@ -1,14 +1,12 @@
1 -import {
2 - Cause,
3 - Duration,
4 - Effect,
5 - Exit,
6 - Layer,
7 - ManagedRuntime,
8 - Option,
9 - Scope,
10 - Stream,
11 -} from "effect";
1 +import * as Cause from "effect/Cause";
2 +import * as Duration from "effect/Duration";
3 +import * as Effect from "effect/Effect";
4 +import * as Exit from "effect/Exit";
5 +import * as Layer from "effect/Layer";
6 +import * as ManagedRuntime from "effect/ManagedRuntime";
7 +import * as Option from "effect/Option";
8 +import * as Scope from "effect/Scope";
9 +import * as Stream from "effect/Stream";
10 import { RpcClient } from "effect/unstable/rpc";
11
12 import { ClientTracingLive } from "../observability/clientTracing";
apps/web/src/store.ts
+1 -1
@@ -20,7 +20,7 @@ import type {
20 } from "@t3tools/contracts";
21 import { isProviderDriverKind, ProviderDriverKind } from "@t3tools/contracts";
22 import type { ThreadId, TurnId } from "@t3tools/contracts";
23 -import { Schema } from "effect";
23 +import * as Schema from "effect/Schema";
24 import { resolveModelSlugForProvider } from "@t3tools/shared/model";
25 import { create } from "zustand";
26 import {
apps/web/test/wsRpcHarness.ts
+5 -1
@@ -1,5 +1,9 @@
1 -import { Effect, Exit, PubSub, Scope, Stream } from "effect";
1 import { ORCHESTRATION_WS_METHODS, WS_METHODS, WsRpcGroup } from "@t3tools/contracts";
2 +import * as Effect from "effect/Effect";
3 +import * as Exit from "effect/Exit";
4 +import * as PubSub from "effect/PubSub";
5 +import * as Scope from "effect/Scope";
6 +import * as Stream from "effect/Stream";
7 import { RpcMessage, RpcSerialization, RpcServer } from "effect/unstable/rpc";
8
9 type RpcServerInstance = RpcServer.RpcServer<any>;
apps/web/tsconfig.json
+13 -3
@@ -15,12 +15,22 @@
15 "plugins": [
16 {
17 "name": "@effect/language-service",
18 - "namespaceImportPackages": ["@effect/platform-node"],
18 + "namespaceImportPackages": ["@effect/platform-node", "effect"],
19 "diagnosticSeverity": {
20 "importFromBarrel": "error",
21 "anyUnknownInErrorContext": "error",
22 - "instanceOfSchema": "warning",
23 - "deterministicKeys": "warning"
22 + "unsafeEffectTypeAssertion": "error",
23 + "instanceOfSchema": "error",
24 + "deterministicKeys": "error",
25 + "strictEffectProvide": "off",
26 + "missingEffectServiceDependency": "error",
27 + "leakingRequirements": "error",
28 + "globalErrorInEffectCatch": "error",
29 + "globalErrorInEffectFailure": "error",
30 + "unknownInEffectCatch": "error",
31 + "strictBooleanExpressions": "off",
32 + "preferSchemaOverJson": "error",
33 + "schemaSyncInEffect": "error"
34 }
35 }
36 ]
bun.lock
+1
@@ -201,6 +201,7 @@
201 },
202 "devDependencies": {
203 "@effect/language-service": "catalog:",
204 + "@effect/platform-node": "catalog:",
205 "@effect/vitest": "catalog:",
206 "@types/node": "catalog:",
207 "typescript": "catalog:",
packages/client-runtime/tsconfig.json
+1 -14
@@ -1,18 +1,5 @@
1 {
2 "extends": "../../tsconfig.base.json",
3 - "compilerOptions": {
4 - "plugins": [
5 - {
6 - "name": "@effect/language-service",
7 - "namespaceImportPackages": ["@effect/platform-node", "effect"],
8 - "diagnosticSeverity": {
9 - "importFromBarrel": "error",
10 - "anyUnknownInErrorContext": "error",
11 - "instanceOfSchema": "warning",
12 - "deterministicKeys": "warning"
13 - }
14 - }
15 - ]
16 - },
3 + "compilerOptions": {},
4 "include": ["src"]
5 }
packages/contracts/src/model.ts
+2 -2
@@ -99,10 +99,10 @@ function coerceLegacyOptionsObjectToArray(
99 const entries: Array<ProviderOptionSelection> = [];
100 for (const [rawKey, rawValue] of Object.entries(record)) {
101 const id = typeof rawKey === "string" ? rawKey.trim() : "";
102 - if (!id) continue;
102 + if (id.length === 0) continue;
103 if (typeof rawValue === "string") {
104 const trimmed = rawValue.trim();
105 - if (trimmed) entries.push({ id, value: trimmed });
105 + if (trimmed.length > 0) entries.push({ id, value: trimmed });
106 } else if (typeof rawValue === "boolean") {
107 entries.push({ id, value: rawValue });
108 }
packages/contracts/src/terminal.test.ts
+10 -6
@@ -164,6 +164,8 @@ describe("TerminalCloseInput", () => {
164 });
165
166 describe("TerminalSessionSnapshot", () => {
167 + const isoTimestamp = "2026-01-01T00:00:00.000Z";
168 +
169 it("accepts running snapshots", () => {
170 expect(
171 decodes(TerminalSessionSnapshot, {
@@ -176,20 +178,22 @@ describe("TerminalSessionSnapshot", () => {
178 history: "hello\n",
179 exitCode: null,
180 exitSignal: null,
179 - updatedAt: new Date().toISOString(),
181 + updatedAt: isoTimestamp,
182 }),
183 ).toBe(true);
184 });
185 });
186
187 describe("TerminalEvent", () => {
188 + const isoTimestamp = "2026-01-01T00:00:00.000Z";
189 +
190 it("accepts output events", () => {
191 expect(
192 decodes(TerminalEvent, {
193 type: "output",
194 threadId: "thread-1",
195 terminalId: DEFAULT_TERMINAL_ID,
192 - createdAt: new Date().toISOString(),
196 + createdAt: isoTimestamp,
197 data: "line\n",
198 }),
199 ).toBe(true);
@@ -201,7 +205,7 @@ describe("TerminalEvent", () => {
205 type: "exited",
206 threadId: "thread-1",
207 terminalId: DEFAULT_TERMINAL_ID,
204 - createdAt: new Date().toISOString(),
208 + createdAt: isoTimestamp,
209 exitCode: 0,
210 exitSignal: null,
211 }),
@@ -214,7 +218,7 @@ describe("TerminalEvent", () => {
218 type: "activity",
219 threadId: "thread-1",
220 terminalId: DEFAULT_TERMINAL_ID,
217 - createdAt: new Date().toISOString(),
221 + createdAt: isoTimestamp,
222 hasRunningSubprocess: true,
223 }),
224 ).toBe(true);
@@ -226,7 +230,7 @@ describe("TerminalEvent", () => {
230 type: "started",
231 threadId: "thread-1",
232 terminalId: DEFAULT_TERMINAL_ID,
229 - createdAt: new Date().toISOString(),
233 + createdAt: isoTimestamp,
234 snapshot: {
235 threadId: "thread-1",
236 terminalId: DEFAULT_TERMINAL_ID,
@@ -237,7 +241,7 @@ describe("TerminalEvent", () => {
241 history: "",
242 exitCode: null,
243 exitSignal: null,
240 - updatedAt: new Date().toISOString(),
244 + updatedAt: isoTimestamp,
245 },
246 }),
247 ).toBe(true);
packages/contracts/src/terminal.ts
+5 -2
@@ -170,10 +170,13 @@ export class TerminalCwdError extends Schema.TaggedErrorClass<TerminalCwdError>(
170 return `Terminal cwd does not exist: ${this.cwd}`;
171 }
172 const causeMessage =
173 - this.cause && typeof this.cause === "object" && "message" in this.cause
173 + this.cause !== undefined &&
174 + this.cause !== null &&
175 + typeof this.cause === "object" &&
176 + "message" in this.cause
177 ? this.cause.message
178 : undefined;
176 - return causeMessage
179 + return typeof causeMessage === "string" && causeMessage.length > 0
180 ? `Failed to access terminal cwd: ${this.cwd} (${causeMessage})`
181 : `Failed to access terminal cwd: ${this.cwd}`;
182 }
packages/contracts/tsconfig.json
+1 -14
@@ -1,18 +1,5 @@
1 {
2 "extends": "../../tsconfig.base.json",
3 - "compilerOptions": {
4 - "plugins": [
5 - {
6 - "name": "@effect/language-service",
7 - "namespaceImportPackages": ["@effect/platform-node", "effect"],
8 - "diagnosticSeverity": {
9 - "importFromBarrel": "error",
10 - "anyUnknownInErrorContext": "error",
11 - "instanceOfSchema": "warning",
12 - "deterministicKeys": "warning"
13 - }
14 - }
15 - ]
16 - },
3 + "compilerOptions": {},
4 "include": ["src"]
5 }
packages/effect-acp/test/examples/cursor-acp-client.example.ts
+3 -3
@@ -48,7 +48,7 @@ const program = Effect.gen(function* () {
48 version: "0.0.0",
49 },
50 });
51 - yield* Console.log("initialized", JSON.stringify(initialized, null, 4));
51 + yield* Console.log("initialized", initialized);
52
53 const session = yield* acp.agent.createSession({
54 cwd: process.cwd(),
@@ -61,7 +61,7 @@ const program = Effect.gen(function* () {
61 value: "claude-opus-4-6",
62 });
63
64 - yield* Console.log("config", JSON.stringify(config, null, 4));
64 + yield* Console.log("config", config);
65
66 const result = yield* acp.agent.prompt({
67 sessionId: session.sessionId,
@@ -73,7 +73,7 @@ const program = Effect.gen(function* () {
73 ],
74 });
75
76 - yield* Console.log("prompt result", JSON.stringify(result));
76 + yield* Console.log("prompt result", result);
77 yield* acp.agent.cancel({ sessionId: session.sessionId });
78 }).pipe(Effect.provide(acpLayer));
79 });
packages/effect-acp/tsconfig.json
+1 -14
@@ -1,18 +1,5 @@
1 {
2 "extends": "../../tsconfig.base.json",
3 - "compilerOptions": {
4 - "plugins": [
5 - {
6 - "name": "@effect/language-service",
7 - "namespaceImportPackages": ["@effect/platform-node", "effect"],
8 - "diagnosticSeverity": {
9 - "importFromBarrel": "error",
10 - "anyUnknownInErrorContext": "error",
11 - "instanceOfSchema": "warning",
12 - "deterministicKeys": "warning"
13 - }
14 - }
15 - ]
16 - },
3 + "compilerOptions": {},
4 "include": ["src", "scripts", "test"]
5 }
packages/effect-codex-app-server/src/client.ts
+20 -20
@@ -17,6 +17,8 @@ import {
17 } from "./_internal/shared.ts";
18 import { makeChildStdio, makeTerminationError } from "./_internal/stdio.ts";
19
20 +const DEFAULT_APP_SERVER_FORCE_KILL_AFTER = "2 seconds" as const;
21 +
22 export interface CodexAppServerClientOptions {
23 readonly logIncoming?: boolean;
24 readonly logOutgoing?: boolean;
@@ -273,26 +275,24 @@ export const layerCommand = (
275 > =>
276 Layer.effect(
277 CodexAppServerClient,
276 - Effect.acquireRelease(
277 - Effect.gen(function* () {
278 - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
279 - const command = ChildProcess.make(options.command, [...(options.args ?? [])], {
280 - ...(options.cwd ? { cwd: options.cwd } : {}),
281 - ...(options.env ? { env: { ...process.env, ...options.env } } : {}),
282 - shell: process.platform === "win32",
283 - });
284 - return yield* spawner.spawn(command).pipe(
285 - Effect.mapError(
286 - (cause) =>
287 - new CodexError.CodexAppServerSpawnError({
288 - command: [options.command, ...(options.args ?? [])].join(" "),
289 - cause,
290 - }),
291 - ),
292 - );
293 - }),
294 - (handle) => handle.kill().pipe(Effect.orDie),
295 - ).pipe(
278 + Effect.gen(function* () {
279 + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
280 + const command = ChildProcess.make(options.command, [...(options.args ?? [])], {
281 + ...(options.cwd ? { cwd: options.cwd } : {}),
282 + ...(options.env ? { env: { ...process.env, ...options.env } } : {}),
283 + forceKillAfter: DEFAULT_APP_SERVER_FORCE_KILL_AFTER,
284 + shell: process.platform === "win32",
285 + });
286 + return yield* spawner.spawn(command).pipe(
287 + Effect.mapError(
288 + (cause) =>
289 + new CodexError.CodexAppServerSpawnError({
290 + command: [options.command, ...(options.args ?? [])].join(" "),
291 + cause,
292 + }),
293 + ),
294 + );
295 + }).pipe(
296 Effect.flatMap((handle) =>
297 make(makeChildStdio(handle), options, makeTerminationError(handle)),
298 ),
packages/effect-codex-app-server/test/examples/codex-app-server-probe.ts
+3 -3
@@ -45,17 +45,17 @@ const program = Effect.gen(function* () {
45 optOutNotificationMethods: null,
46 },
47 });
48 - yield* Console.log("initialize", JSON.stringify(initialized, null, 2));
48 + yield* Console.log("initialize", initialized);
49
50 yield* client.notify("initialized", undefined);
51
52 const account = yield* client.request("account/read", {});
53 - yield* Console.log("account/read", JSON.stringify(account, null, 2));
53 + yield* Console.log("account/read", account);
54
55 const skills = yield* client.request("skills/list", {
56 cwds: [process.cwd()],
57 });
58 - yield* Console.log("skills/list", JSON.stringify(skills, null, 2));
58 + yield* Console.log("skills/list", skills);
59 }).pipe(Effect.provide(codexLayer));
60 });
61
packages/effect-codex-app-server/tsconfig.json
+1 -14
@@ -1,18 +1,5 @@
1 {
2 "extends": "../../tsconfig.base.json",
3 - "compilerOptions": {
4 - "plugins": [
5 - {
6 - "name": "@effect/language-service",
7 - "namespaceImportPackages": ["@effect/platform-node", "effect"],
8 - "diagnosticSeverity": {
9 - "importFromBarrel": "error",
10 - "anyUnknownInErrorContext": "error",
11 - "instanceOfSchema": "warning",
12 - "deterministicKeys": "warning"
13 - }
14 - }
15 - ]
16 - },
3 + "compilerOptions": {},
4 "include": ["src", "scripts", "test"]
5 }
packages/shared/package.json
+1
@@ -95,6 +95,7 @@
95 },
96 "devDependencies": {
97 "@effect/language-service": "catalog:",
98 + "@effect/platform-node": "catalog:",
99 "@effect/vitest": "catalog:",
100 "@types/node": "catalog:",
101 "typescript": "catalog:",
packages/shared/src/Net.test.ts
+12 -10
@@ -3,7 +3,7 @@ import * as NodeNet from "node:net";
3 import { assert, describe, it } from "@effect/vitest";
4 import * as Effect from "effect/Effect";
5
6 -import * as Net from "./Net.ts";
6 +import * as NetService from "./Net.ts";
7
8 const closeServer = (server: NodeNet.Server) =>
9 Effect.sync(() => {
@@ -19,19 +19,21 @@ const getPort = (server: NodeNet.Server): number => {
19 return typeof address === "object" && address !== null ? address.port : 0;
20 };
21
22 -const openServer = (host?: string): Effect.Effect<NodeNet.Server, Net.NetError> =>
23 - Effect.callback<NodeNet.Server, Net.NetError>((resume) => {
22 +const openServer = (host?: string): Effect.Effect<NodeNet.Server, NetService.NetError> =>
23 + Effect.callback<NodeNet.Server, NetService.NetError>((resume) => {
24 const server = NodeNet.createServer();
25 let settled = false;
26
27 - const settle = (effect: Effect.Effect<NodeNet.Server, Net.NetError>) => {
27 + const settle = (effect: Effect.Effect<NodeNet.Server, NetService.NetError>) => {
28 if (settled) return;
29 settled = true;
30 resume(effect);
31 };
32
33 server.once("error", (cause) => {
34 - settle(Effect.fail(new Net.NetError({ message: "Failed to open test server", cause })));
34 + settle(
35 + Effect.fail(new NetService.NetError({ message: "Failed to open test server", cause })),
36 + );
37 });
38
39 if (host) {
@@ -43,11 +45,11 @@ const openServer = (host?: string): Effect.Effect<NodeNet.Server, Net.NetError>
45 return closeServer(server);
46 });
47
46 -it.layer(Net.NetService.layer)("NetService", (it) => {
48 +it.layer(NetService.layer)("NetService", (it) => {
49 describe("Net helpers", () => {
50 it.effect("reserveLoopbackPort returns a positive loopback port", () =>
51 Effect.gen(function* () {
50 - const net = yield* Net.NetService;
52 + const net = yield* NetService.NetService;
53 const port = yield* net.reserveLoopbackPort();
54
55 assert.ok(port > 0);
@@ -59,7 +61,7 @@ it.layer(Net.NetService.layer)("NetService", (it) => {
61 openServer("127.0.0.1"),
62 (server) =>
63 Effect.gen(function* () {
62 - const net = yield* Net.NetService;
64 + const net = yield* NetService.NetService;
65 const port = getPort(server);
66
67 const available = yield* net.isPortAvailableOnLoopback(port);
@@ -71,7 +73,7 @@ it.layer(Net.NetService.layer)("NetService", (it) => {
73
74 it.effect("findAvailablePort returns preferred when it is free", () =>
75 Effect.gen(function* () {
74 - const net = yield* Net.NetService;
76 + const net = yield* NetService.NetService;
77 const preferred = yield* net.reserveLoopbackPort();
78
79 const resolved = yield* net.findAvailablePort(preferred);
@@ -84,7 +86,7 @@ it.layer(Net.NetService.layer)("NetService", (it) => {
86 openServer(),
87 (server) =>
88 Effect.gen(function* () {
87 - const net = yield* Net.NetService;
89 + const net = yield* NetService.NetService;
90 const preferred = getPort(server);
91
92 const resolved = yield* net.findAvailablePort(preferred);
packages/shared/src/Net.ts
+16 -19
@@ -4,22 +4,21 @@ import * as Data from "effect/Data";
4 import * as Effect from "effect/Effect";
5 import * as Layer from "effect/Layer";
6 import * as Context from "effect/Context";
7 +import * as Predicate from "effect/Predicate";
8
9 export class NetError extends Data.TaggedError("NetError")<{
10 readonly message: string;
11 readonly cause?: unknown;
12 }> {}
13
13 -function isErrnoExceptionWithCode(cause: unknown): cause is {
14 +const isErrnoExceptionWithCode = (
15 + cause: unknown,
16 +): cause is {
17 readonly code: string;
15 -} {
16 - return (
17 - typeof cause === "object" &&
18 - cause !== null &&
19 - "code" in cause &&
20 - typeof (cause as { readonly code: unknown }).code === "string"
21 - );
22 -}
18 +} =>
19 + Predicate.isObject(cause) &&
20 + Predicate.hasProperty(cause, "code") &&
21 + Predicate.isString(cause.code);
22
23 const closeServer = (server: NodeNet.Server) => {
24 try {
@@ -85,6 +84,13 @@ export interface NetServiceShape {
84 readonly findAvailablePort: (preferred: number) => Effect.Effect<number, NetError>;
85 }
86
87 +/**
88 + * NetService - Service tag for startup networking helpers.
89 + */
90 +export class NetService extends Context.Service<NetService, NetServiceShape>()(
91 + "@t3tools/shared/Net/NetService",
92 +) {}
93 +
94 export const make = () => {
95 /**
96 * Returns true when a TCP server can bind to {host, port}.
@@ -175,13 +181,4 @@ export const make = () => {
181 } satisfies NetServiceShape;
182 };
183
178 -/**
179 - * NetService - Service tag for startup networking helpers.
180 - */
181 -export class NetService extends Context.Service<NetService, NetServiceShape>()(
182 - "@t3tools/shared/Net/NetService",
183 -) {
184 - static readonly layer = Layer.sync(NetService, make);
185 -}
186 -
187 -export const layer = NetService.layer;
184 +export const layer = Layer.sync(NetService, make);
packages/shared/src/logging.ts
+1
@@ -1,3 +1,4 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 import fs from "node:fs";
3 import path from "node:path";
4
packages/shared/src/observability.test.ts
+108 -114
@@ -1,11 +1,10 @@
1 -import fs from "node:fs";
2 -import os from "node:os";
3 -import path from "node:path";
4 -
1 import { assert, describe, it } from "@effect/vitest";
2 +import * as NodeServices from "@effect/platform-node/NodeServices";
3 import * as Effect from "effect/Effect";
4 +import * as FileSystem from "effect/FileSystem";
5 import * as Layer from "effect/Layer";
6 import * as Logger from "effect/Logger";
7 +import * as Path from "effect/Path";
8 import * as References from "effect/References";
9 import * as Schema from "effect/Schema";
10 import * as Tracer from "effect/Tracer";
@@ -57,13 +56,14 @@ const makeRecord = (name: string, suffix = ""): TraceRecord => ({
56 },
57 });
58
60 -const readTraceRecords = (tracePath: string) =>
61 - fs
62 - .readFileSync(tracePath, "utf8")
59 +const readTraceRecords = Effect.fn("readTraceRecords")(function* (tracePath: string) {
60 + const fileSystem = yield* FileSystem.FileSystem;
61 + return (yield* fileSystem.readFileString(tracePath))
62 .trim()
63 .split("\n")
64 .filter((line) => line.length > 0)
65 .map((line) => decodeTraceRecordLine(line));
66 +});
67
68 const makeTestLayer = (tracePath: string) =>
69 Layer.mergeAll(
@@ -106,9 +106,11 @@ describe("observability", () => {
106 });
107
108 it("normalizes invalid dates without throwing", () => {
109 + // @effect-diagnostics-next-line globalDate:off
110 + const invalidDate = new Date("not-a-real-date");
111 assert.deepStrictEqual(
112 compactTraceAttributes({
111 - invalidDate: new Date("not-a-real-date"),
113 + invalidDate,
114 }),
115 {
116 invalidDate: "Invalid Date",
@@ -119,122 +121,116 @@ describe("observability", () => {
121 it.effect("flushes buffered trace records on close", () =>
122 Effect.scoped(
123 Effect.gen(function* () {
122 - const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-trace-sink-"));
124 + const fileSystem = yield* FileSystem.FileSystem;
125 + const path = yield* Path.Path;
126 + const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
127 const tracePath = path.join(tempDir, "shared.trace.ndjson");
128
125 - try {
126 - const sink = yield* makeTraceSink({
127 - filePath: tracePath,
128 - maxBytes: 1024,
129 - maxFiles: 2,
130 - batchWindowMs: 10_000,
131 - });
132 -
133 - sink.push(makeRecord("alpha"));
134 - sink.push(makeRecord("beta"));
135 - yield* sink.close();
136 -
137 - const lines = readTraceRecords(tracePath);
138 -
139 - assert.equal(lines.length, 2);
140 - assert.equal(lines[0]?.name, "alpha");
141 - assert.equal(lines[1]?.name, "beta");
142 - } finally {
143 - fs.rmSync(tempDir, { recursive: true, force: true });
144 - }
145 - }),
129 + const sink = yield* makeTraceSink({
130 + filePath: tracePath,
131 + maxBytes: 1024,
132 + maxFiles: 2,
133 + batchWindowMs: 10_000,
134 + });
135 +
136 + sink.push(makeRecord("alpha"));
137 + sink.push(makeRecord("beta"));
138 + yield* sink.close();
139 +
140 + const lines = yield* readTraceRecords(tracePath);
141 +
142 + assert.equal(lines.length, 2);
143 + assert.equal(lines[0]?.name, "alpha");
144 + assert.equal(lines[1]?.name, "beta");
145 + }).pipe(Effect.provide(NodeServices.layer)),
146 ),
147 );
148
149 it.effect("rotates the trace file when the configured max size is exceeded", () =>
150 Effect.scoped(
151 Effect.gen(function* () {
152 - const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-trace-sink-"));
152 + const fileSystem = yield* FileSystem.FileSystem;
153 + const path = yield* Path.Path;
154 + const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
155 const tracePath = path.join(tempDir, "shared.trace.ndjson");
156
155 - try {
156 - const sink = yield* makeTraceSink({
157 - filePath: tracePath,
158 - maxBytes: 180,
159 - maxFiles: 2,
160 - batchWindowMs: 10_000,
161 - });
162 -
163 - for (let index = 0; index < 8; index += 1) {
164 - sink.push(makeRecord("rotate", `${index}-${"x".repeat(48)}`));
165 - yield* sink.flush;
166 - }
167 - yield* sink.close();
168 -
169 - const matchingFiles = fs
170 - .readdirSync(tempDir)
171 - .filter(
172 - (entry) =>
173 - entry === "shared.trace.ndjson" || entry.startsWith("shared.trace.ndjson."),
174 - )
175 - .toSorted();
176 -
177 - assert.equal(
178 - matchingFiles.some((entry) => entry === "shared.trace.ndjson.1"),
179 - true,
180 - );
181 - assert.equal(
182 - matchingFiles.some((entry) => entry === "shared.trace.ndjson.3"),
183 - false,
184 - );
185 - } finally {
186 - fs.rmSync(tempDir, { recursive: true, force: true });
157 + const sink = yield* makeTraceSink({
158 + filePath: tracePath,
159 + maxBytes: 180,
160 + maxFiles: 2,
161 + batchWindowMs: 10_000,
162 + });
163 +
164 + for (let index = 0; index < 8; index += 1) {
165 + sink.push(makeRecord("rotate", `${index}-${"x".repeat(48)}`));
166 + yield* sink.flush;
167 }
188 - }),
168 + yield* sink.close();
169 +
170 + const matchingFiles = (yield* fileSystem.readDirectory(tempDir))
171 + .filter(
172 + (entry) => entry === "shared.trace.ndjson" || entry.startsWith("shared.trace.ndjson."),
173 + )
174 + .toSorted();
175 +
176 + assert.equal(
177 + matchingFiles.some((entry) => entry === "shared.trace.ndjson.1"),
178 + true,
179 + );
180 + assert.equal(
181 + matchingFiles.some((entry) => entry === "shared.trace.ndjson.3"),
182 + false,
183 + );
184 + }).pipe(Effect.provide(NodeServices.layer)),
185 ),
186 );
187
188 it.effect("drops only the invalid trace record when serialization fails", () =>
189 Effect.scoped(
190 Effect.gen(function* () {
195 - const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-trace-sink-"));
191 + const fileSystem = yield* FileSystem.FileSystem;
192 + const path = yield* Path.Path;
193 + const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
194 const tracePath = path.join(tempDir, "shared.trace.ndjson");
195
198 - try {
199 - const sink = yield* makeTraceSink({
200 - filePath: tracePath,
201 - maxBytes: 1024,
202 - maxFiles: 2,
203 - batchWindowMs: 10_000,
204 - });
205 -
206 - const circular: Array<unknown> = [];
207 - circular.push(circular);
208 -
209 - sink.push(makeRecord("alpha"));
210 - sink.push({
211 - ...makeRecord("invalid"),
212 - attributes: {
213 - circular,
214 - },
215 - } as TraceRecord);
216 - sink.push(makeRecord("beta"));
217 - yield* sink.close();
218 -
219 - const lines = readTraceRecords(tracePath);
220 -
221 - assert.deepStrictEqual(
222 - lines.map((line) => line.name),
223 - ["alpha", "beta"],
224 - );
225 - } finally {
226 - fs.rmSync(tempDir, { recursive: true, force: true });
227 - }
228 - }),
196 + const sink = yield* makeTraceSink({
197 + filePath: tracePath,
198 + maxBytes: 1024,
199 + maxFiles: 2,
200 + batchWindowMs: 10_000,
201 + });
202 +
203 + const circular: Array<unknown> = [];
204 + circular.push(circular);
205 +
206 + sink.push(makeRecord("alpha"));
207 + sink.push({
208 + ...makeRecord("invalid"),
209 + attributes: {
210 + circular,
211 + },
212 + } as TraceRecord);
213 + sink.push(makeRecord("beta"));
214 + yield* sink.close();
215 +
216 + const lines = yield* readTraceRecords(tracePath);
217 +
218 + assert.deepStrictEqual(
219 + lines.map((line) => line.name),
220 + ["alpha", "beta"],
221 + );
222 + }).pipe(Effect.provide(NodeServices.layer)),
223 ),
224 );
225
226 it.effect("writes nested spans to disk and captures log messages as span events", () =>
233 - Effect.gen(function* () {
234 - const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-local-tracer-"));
235 - const tracePath = path.join(tempDir, "shared.trace.ndjson");
227 + Effect.scoped(
228 + Effect.gen(function* () {
229 + const fileSystem = yield* FileSystem.FileSystem;
230 + const path = yield* Path.Path;
231 + const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-local-tracer-" });
232 + const tracePath = path.join(tempDir, "shared.trace.ndjson");
233
237 - try {
234 yield* Effect.scoped(
235 Effect.gen(function* () {
236 const program = Effect.gen(function* () {
@@ -254,7 +250,7 @@ describe("observability", () => {
250 }),
251 );
252
257 - const records = readTraceRecords(tracePath);
253 + const records = yield* readTraceRecords(tracePath);
254 assert.equal(records.length, 2);
255
256 const parent = records.find((record) => record.name === "parent-span");
@@ -281,18 +277,18 @@ describe("observability", () => {
277 child.events.some((event) => event.attributes["effect.logLevel"] === "INFO"),
278 true,
279 );
284 - } finally {
285 - fs.rmSync(tempDir, { recursive: true, force: true });
286 - }
287 - }),
280 + }).pipe(Effect.provide(NodeServices.layer)),
281 + ),
282 );
283
284 it.effect("serializes interrupted spans with an interrupted exit status", () =>
291 - Effect.gen(function* () {
292 - const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-local-tracer-"));
293 - const tracePath = path.join(tempDir, "shared.trace.ndjson");
285 + Effect.scoped(
286 + Effect.gen(function* () {
287 + const fileSystem = yield* FileSystem.FileSystem;
288 + const path = yield* Path.Path;
289 + const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-local-tracer-" });
290 + const tracePath = path.join(tempDir, "shared.trace.ndjson");
291
295 - try {
292 yield* Effect.scoped(
293 Effect.exit(
294 Effect.interrupt.pipe(
@@ -302,13 +298,11 @@ describe("observability", () => {
298 ),
299 );
300
305 - const records = readTraceRecords(tracePath);
301 + const records = yield* readTraceRecords(tracePath);
302 assert.equal(records.length, 1);
303 assert.equal(records[0]?.name, "interrupt-span");
304 assert.equal(records[0]?.exit?._tag, "Interrupted");
309 - } finally {
310 - fs.rmSync(tempDir, { recursive: true, force: true });
311 - }
312 - }),
305 + }).pipe(Effect.provide(NodeServices.layer)),
306 + ),
307 );
308 });
packages/shared/src/schemaJson.ts
+18
@@ -84,6 +84,10 @@ export const fromLenientJsonString = new SchemaTransformation.Transformation(
84 SchemaGetter.stringifyJson(),
85 );
86
87 +export const prettyJsonString = SchemaGetter.parseJson<string>().compose(
88 + SchemaGetter.stringifyJson({ space: 2 }),
89 +);
90 +
91 /**
92 * Build a schema that decodes a lenient JSON string into `A`.
93 *
@@ -92,3 +96,17 @@ export const fromLenientJsonString = new SchemaTransformation.Transformation(
96 */
97 export const fromLenientJson = <S extends Schema.Top>(schema: S) =>
98 Schema.String.pipe(Schema.decodeTo(schema, fromLenientJsonString));
99 +
100 +/**
101 + * Build a JSON string schema that encodes with stable 2-space formatting.
102 + *
103 + * Decode behavior matches `Schema.fromJsonString(schema)`. Encode behavior
104 + * keeps the transformation schema-based while preserving human-readable JSON.
105 + */
106 +export const fromJsonStringPretty = <S extends Schema.Top>(schema: S) =>
107 + Schema.fromJsonString(schema).pipe(
108 + Schema.encode({
109 + decode: prettyJsonString,
110 + encode: prettyJsonString,
111 + }),
112 + );
packages/shared/src/shell.ts
+1
@@ -1,3 +1,4 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 import * as NodeOS from "node:os";
3 import { execFileSync } from "node:child_process";
4 import { accessSync, constants, statSync } from "node:fs";
packages/shared/tsconfig.json
+1 -14
@@ -1,18 +1,5 @@
1 {
2 "extends": "../../tsconfig.base.json",
3 - "compilerOptions": {
4 - "plugins": [
5 - {
6 - "name": "@effect/language-service",
7 - "namespaceImportPackages": ["@effect/platform-node", "effect"],
8 - "diagnosticSeverity": {
9 - "importFromBarrel": "error",
10 - "anyUnknownInErrorContext": "error",
11 - "instanceOfSchema": "warning",
12 - "deterministicKeys": "warning"
13 - }
14 - }
15 - ]
16 - },
3 + "compilerOptions": {},
4 "include": ["src"]
5 }
packages/ssh/src/command.test.ts
+1 -1
@@ -7,7 +7,7 @@ import * as Layer from "effect/Layer";
7 import * as Result from "effect/Result";
8 import * as Sink from "effect/Sink";
9 import * as Stream from "effect/Stream";
10 -import { TestClock } from "effect/testing";
10 +import * as TestClock from "effect/testing/TestClock";
11 import { ChildProcessSpawner } from "effect/unstable/process";
12
13 import {
packages/ssh/src/tunnel.test.ts
+4 -4
@@ -1,6 +1,6 @@
1 import { assert, describe, it } from "@effect/vitest";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 -import { NetService } from "@t3tools/shared/Net";
3 +import * as NetService from "@t3tools/shared/Net";
4 import * as Duration from "effect/Duration";
5 import * as Effect from "effect/Effect";
6 import * as Fiber from "effect/Fiber";
@@ -8,7 +8,7 @@ import * as Layer from "effect/Layer";
8 import * as Result from "effect/Result";
9 import * as Sink from "effect/Sink";
10 import * as Stream from "effect/Stream";
11 -import { TestClock } from "effect/testing";
11 +import * as TestClock from "effect/testing/TestClock";
12 import { HttpClient, HttpClientResponse } from "effect/unstable/http";
13 import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
14
@@ -74,7 +74,7 @@ const testHttpClient = HttpClient.make((request) =>
74
75 const hangingHttpClient = HttpClient.make(() => Effect.never);
76
77 -const testNetService = NetService.of({
77 +const testNetService = NetService.NetService.of({
78 canListenOnHost: () => Effect.succeed(true),
79 isPortAvailableOnLoopback: () => Effect.succeed(true),
80 reserveLoopbackPort: () => Effect.succeed(41_773),
@@ -270,7 +270,7 @@ describe("ssh tunnel scripts", () => {
270 NodeServices.layer,
271 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
272 Layer.succeed(HttpClient.HttpClient, testHttpClient),
273 - Layer.succeed(NetService, testNetService),
273 + Layer.succeed(NetService.NetService, testNetService),
274 SshPasswordPrompt.disabledLayer,
275 SshEnvironmentManager.layer(),
276 );
packages/ssh/src/tunnel.ts
+6 -6
@@ -2,7 +2,7 @@ import type {
2 DesktopSshEnvironmentBootstrap,
3 DesktopSshEnvironmentTarget,
4 } from "@t3tools/contracts";
5 -import { type NetError, NetService } from "@t3tools/shared/Net";
5 +import * as NetService from "@t3tools/shared/Net";
6 import { fromLenientJson } from "@t3tools/shared/schemaJson";
7 import * as Context from "effect/Context";
8 import * as Deferred from "effect/Deferred";
@@ -82,7 +82,7 @@ type SshEnvironmentEffectContext =
82 | FileSystem.FileSystem
83 | Path.Path
84 | HttpClient.HttpClient
85 - | NetService
85 + | NetService.NetService
86 | SshPasswordPrompt;
87
88 type SshEnvironmentEffectError =
@@ -92,7 +92,7 @@ type SshEnvironmentEffectError =
92 | SshPairingError
93 | SshReadinessError
94 | SshPasswordPromptError
95 - | NetError;
95 + | NetService.NetError;
96
97 function makeSshTunnelCancelledError(target: DesktopSshEnvironmentTarget): SshCommandError {
98 return new SshCommandError({
@@ -903,7 +903,7 @@ export const fetchLoopbackSshJson = Effect.fn("ssh/tunnel.fetchLoopbackSshJson")
903 });
904
905 const reserveLocalTunnelPort = Effect.fn("ssh/tunnel.reserveLocalTunnelPort")(function* () {
906 - const net = yield* NetService;
906 + const net = yield* NetService.NetService;
907 return yield* net.reserveLoopbackPort();
908 });
909
@@ -923,7 +923,7 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
923 | FileSystem.FileSystem
924 | Path.Path
925 | HttpClient.HttpClient
926 - | NetService
926 + | NetService.NetService
927 | Scope.Scope
928 > {
929 const hostSpec = yield* buildSshHostSpecEffect(input.resolvedTarget);
@@ -1076,7 +1076,7 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
1076 ),
1077 Effect.tapError((cause) =>
1078 Effect.gen(function* () {
1079 - const net = yield* NetService;
1079 + const net = yield* NetService.NetService;
1080 const processRunningExit = yield* Effect.exit(child.isRunning);
1081 const localPortAvailableExit = yield* Effect.exit(
1082 net.canListenOnHost(input.localPort, "127.0.0.1"),
packages/ssh/tsconfig.json
+1 -14
@@ -1,18 +1,5 @@
1 {
2 "extends": "../../tsconfig.base.json",
3 - "compilerOptions": {
4 - "plugins": [
5 - {
6 - "name": "@effect/language-service",
7 - "namespaceImportPackages": ["@effect/platform-node", "effect"],
8 - "diagnosticSeverity": {
9 - "importFromBarrel": "error",
10 - "anyUnknownInErrorContext": "error",
11 - "instanceOfSchema": "warning",
12 - "deterministicKeys": "warning"
13 - }
14 - }
15 - ]
16 - },
3 + "compilerOptions": {},
4 "include": ["src"]
5 }
packages/tailscale/tsconfig.json
+1 -13
@@ -1,17 +1,5 @@
1 {
2 "extends": "../../tsconfig.base.json",
3 - "compilerOptions": {
4 - "plugins": [
5 - {
6 - "name": "@effect/language-service",
7 - "diagnosticSeverity": {
8 - "importFromBarrel": "error",
9 - "anyUnknownInErrorContext": "warning",
10 - "instanceOfSchema": "warning",
11 - "deterministicKeys": "warning"
12 - }
13 - }
14 - ]
15 - },
3 + "compilerOptions": {},
4 "include": ["src"]
5 }
scripts/apply-web-brand-assets.ts
+4 -1
@@ -2,7 +2,10 @@
2
3 import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
4 import * as NodeServices from "@effect/platform-node/NodeServices";
5 -import { Effect, FileSystem, Option, Path } from "effect";
5 +import * as Effect from "effect/Effect";
6 +import * as FileSystem from "effect/FileSystem";
7 +import * as Option from "effect/Option";
8 +import * as Path from "effect/Path";
9 import { Argument, Command } from "effect/unstable/cli";
10 import { resolveWebIconOverrides, type WebAssetBrand } from "./lib/brand-assets.ts";
11
scripts/build-desktop-artifact.test.ts
+3 -1
@@ -1,6 +1,8 @@
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { assert, it } from "@effect/vitest";
3 -import { ConfigProvider, Effect, Option } from "effect";
3 +import * as ConfigProvider from "effect/ConfigProvider";
4 +import * as Effect from "effect/Effect";
5 +import * as Option from "effect/Option";
6
7 import {
8 resolveBuildOptions,
scripts/build-desktop-artifact.ts
+10 -12
@@ -10,18 +10,16 @@ import { resolveCatalogDependencies } from "./lib/resolve-catalog.ts";
10
11 import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
12 import * as NodeServices from "@effect/platform-node/NodeServices";
13 -import {
14 - Config,
15 - Data,
16 - Effect,
17 - FileSystem,
18 - Layer,
19 - Logger,
20 - Option,
21 - Path,
22 - Schema,
23 - Stream,
24 -} from "effect";
13 +import * as Config from "effect/Config";
14 +import * as Data from "effect/Data";
15 +import * as Effect from "effect/Effect";
16 +import * as FileSystem from "effect/FileSystem";
17 +import * as Layer from "effect/Layer";
18 +import * as Logger from "effect/Logger";
19 +import * as Option from "effect/Option";
20 +import * as Path from "effect/Path";
21 +import * as Schema from "effect/Schema";
22 +import * as Stream from "effect/Stream";
23 import { Command, Flag } from "effect/unstable/cli";
24 import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
25
scripts/dev-runner.test.ts
+2 -1
@@ -1,7 +1,8 @@
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import * as NodeOS from "node:os";
3 import { assert, describe, it } from "@effect/vitest";
4 -import { Effect, Path } from "effect";
4 +import * as Effect from "effect/Effect";
5 +import * as Path from "effect/Path";
6
7 import {
8 checkPortAvailabilityOnHosts,
scripts/dev-runner.ts
+16 -8
@@ -4,8 +4,16 @@ import * as NodeOS from "node:os";
4
5 import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
6 import * as NodeServices from "@effect/platform-node/NodeServices";
7 -import { NetService } from "@t3tools/shared/Net";
8 -import { Config, Data, Effect, Hash, Layer, Logger, Option, Path, Schema } from "effect";
7 +import * as NetService from "@t3tools/shared/Net";
8 +import * as Config from "effect/Config";
9 +import * as Data from "effect/Data";
10 +import * as Effect from "effect/Effect";
11 +import * as Hash from "effect/Hash";
12 +import * as Layer from "effect/Layer";
13 +import * as Logger from "effect/Logger";
14 +import * as Option from "effect/Option";
15 +import * as Path from "effect/Path";
16 +import * as Schema from "effect/Schema";
17 import { Argument, Command, Flag } from "effect/unstable/cli";
18 import { ChildProcess } from "effect/unstable/process";
19
@@ -238,22 +246,22 @@ export function checkPortAvailabilityOnHosts<R>(
246 });
247 }
248
241 -const defaultCheckPortAvailability: PortAvailabilityCheck<NetService> = (port) =>
249 +const defaultCheckPortAvailability: PortAvailabilityCheck<NetService.NetService> = (port) =>
250 Effect.gen(function* () {
243 - const net = yield* NetService;
251 + const net = yield* NetService.NetService;
252 return yield* checkPortAvailabilityOnHosts(port, DEV_PORT_PROBE_HOSTS, (candidatePort, host) =>
253 net.canListenOnHost(candidatePort, host),
254 );
255 });
256
249 -interface FindFirstAvailableOffsetInput<R = NetService> {
257 +interface FindFirstAvailableOffsetInput<R = NetService.NetService> {
258 readonly startOffset: number;
259 readonly requireServerPort: boolean;
260 readonly requireWebPort: boolean;
261 readonly checkPortAvailability?: PortAvailabilityCheck<R>;
262 }
263
256 -export function findFirstAvailableOffset<R = NetService>({
264 +export function findFirstAvailableOffset<R = NetService.NetService>({
265 startOffset,
266 requireServerPort,
267 requireWebPort,
@@ -300,7 +308,7 @@ export function findFirstAvailableOffset<R = NetService>({
308 });
309 }
310
303 -interface ResolveModePortOffsetsInput<R = NetService> {
311 +interface ResolveModePortOffsetsInput<R = NetService.NetService> {
312 readonly mode: DevMode;
313 readonly startOffset: number;
314 readonly hasExplicitServerPort: boolean;
@@ -308,7 +316,7 @@ interface ResolveModePortOffsetsInput<R = NetService> {
316 readonly checkPortAvailability?: PortAvailabilityCheck<R>;
317 }
318
311 -export function resolveModePortOffsets<R = NetService>({
319 +export function resolveModePortOffsets<R = NetService.NetService>({
320 mode,
321 startOffset,
322 hasExplicitServerPort,
scripts/merge-update-manifests.test.ts
+3 -1
@@ -1,6 +1,8 @@
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { assert, describe, it } from "@effect/vitest";
3 -import { Effect, FileSystem, Path } from "effect";
3 +import * as Effect from "effect/Effect";
4 +import * as FileSystem from "effect/FileSystem";
5 +import * as Path from "effect/Path";
6 import { Command, CliError } from "effect/unstable/cli";
7
8 import {
scripts/merge-update-manifests.ts
+5 -1
@@ -2,7 +2,11 @@
2
3 import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
4 import * as NodeServices from "@effect/platform-node/NodeServices";
5 -import { Effect, FileSystem, Option, Path, Schema } from "effect";
5 +import * as Effect from "effect/Effect";
6 +import * as FileSystem from "effect/FileSystem";
7 +import * as Option from "effect/Option";
8 +import * as Path from "effect/Path";
9 +import * as Schema from "effect/Schema";
10 import { Argument, Command, Flag } from "effect/unstable/cli";
11
12 import {
scripts/mock-update-server.test.ts
+5 -2
@@ -1,7 +1,10 @@
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 -import { NodeHttpServer } from "@effect/platform-node";
2 +import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
3 import { assert, it } from "@effect/vitest";
4 -import { Effect, FileSystem, Layer, Path } from "effect";
4 +import * as Effect from "effect/Effect";
5 +import * as FileSystem from "effect/FileSystem";
6 +import * as Layer from "effect/Layer";
7 +import * as Path from "effect/Path";
8 import { HttpClient, HttpRouter } from "effect/unstable/http";
9
10 import { makeMockUpdateRouteLayer } from "./mock-update-server.ts";
scripts/mock-update-server.ts
+8 -2
@@ -1,8 +1,14 @@
1 +// @effect-diagnostics-next-line nodeBuiltinImport:off - NodeHttpServer.layer takes `NodeHttp.createServer` as arg
2 import * as NodeHttp from "node:http";
3
3 -import { NodeHttpServer, NodeRuntime } from "@effect/platform-node";
4 +import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
5 +import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
6 import * as NodeServices from "@effect/platform-node/NodeServices";
5 -import { Config, Effect, FileSystem, Layer, Path } from "effect";
7 +import * as Config from "effect/Config";
8 +import * as Effect from "effect/Effect";
9 +import * as FileSystem from "effect/FileSystem";
10 +import * as Layer from "effect/Layer";
11 +import * as Path from "effect/Path";
12 import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
13
14 interface MockUpdateServerConfig {
scripts/notify-discord-release.ts
+7 -1
@@ -2,7 +2,13 @@
2
3 import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
4 import * as NodeServices from "@effect/platform-node/NodeServices";
5 -import { Config, Data, DateTime, Effect, Layer, Logger, Schema } from "effect";
5 +import * as Config from "effect/Config";
6 +import * as Data from "effect/Data";
7 +import * as DateTime from "effect/DateTime";
8 +import * as Effect from "effect/Effect";
9 +import * as Layer from "effect/Layer";
10 +import * as Logger from "effect/Logger";
11 +import * as Schema from "effect/Schema";
12 import { Argument, Command, Flag } from "effect/unstable/cli";
13 import {
14 FetchHttpClient,
scripts/release-smoke.ts
+4 -1
@@ -1,3 +1,4 @@
1 +// @effect-diagnostics nodeBuiltinImport:off
2 import { execFileSync } from "node:child_process";
3 import {
4 cpSync,
@@ -11,6 +12,8 @@ import {
12 import { tmpdir } from "node:os";
13 import { dirname, join, resolve } from "node:path";
14 import { fileURLToPath } from "node:url";
15 +import * as Console from "effect/Console";
16 +import * as Effect from "effect/Effect";
17
18 const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
19
@@ -389,7 +392,7 @@ try {
392 "Windows release smoke unexpectedly removed the x64 builder debug fixture.",
393 );
394
392 - console.log("Release smoke checks passed.");
395 + Effect.runSync(Console.log("Release smoke checks passed."));
396 } finally {
397 rmSync(tempRoot, { recursive: true, force: true });
398 }
scripts/resolve-nightly-release.ts
+8 -2
@@ -2,7 +2,13 @@
2
3 import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
4 import * as NodeServices from "@effect/platform-node/NodeServices";
5 -import { Config, Effect, FileSystem, Option, Path, Schema } from "effect";
5 +import * as Console from "effect/Console";
6 +import * as Config from "effect/Config";
7 +import * as Effect from "effect/Effect";
8 +import * as FileSystem from "effect/FileSystem";
9 +import * as Option from "effect/Option";
10 +import * as Path from "effect/Path";
11 +import * as Schema from "effect/Schema";
12 import { Command, Flag } from "effect/unstable/cli";
13
14 interface NightlyReleaseMetadata {
@@ -93,7 +99,7 @@ const writeOutput = Effect.fn("writeOutput")(function* (
99 yield* fs.writeFileString(githubOutputPath, serialized, { flag: "a" });
100 } else {
101 for (const [key, value] of entries) {
96 - console.log(`${key}=${value}`);
102 + yield* Console.log(`${key}=${value}`);
103 }
104 }
105 });
scripts/resolve-previous-release-tag.ts
+7 -1
@@ -2,7 +2,13 @@
2
3 import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
4 import * as NodeServices from "@effect/platform-node/NodeServices";
5 -import { Array, Config, Effect, FileSystem, Schema, Stream, String } from "effect";
5 +import * as Array from "effect/Array";
6 +import * as Config from "effect/Config";
7 +import * as Effect from "effect/Effect";
8 +import * as FileSystem from "effect/FileSystem";
9 +import * as Schema from "effect/Schema";
10 +import * as Stream from "effect/Stream";
11 +import * as String from "effect/String";
12 import { Command, Flag } from "effect/unstable/cli";
13 import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
14
scripts/tsconfig.json
+1 -6
@@ -3,12 +3,7 @@
3 "compilerOptions": {
4 "composite": true,
5 "types": ["node"],
6 - "lib": ["ESNext", "esnext.disposable"],
7 - "plugins": [
8 - {
9 - "name": "@effect/language-service"
10 - }
11 - ]
6 + "lib": ["ESNext", "esnext.disposable"]
7 },
8 "include": ["**/*.ts"]
9 }
scripts/update-release-package-versions.test.ts
+11 -13
@@ -1,8 +1,14 @@
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { assert, it } from "@effect/vitest";
3 -import { ConfigProvider, Effect, FileSystem, Layer, Path, Schema, SchemaGetter } from "effect";
3 +import * as ConfigProvider from "effect/ConfigProvider";
4 +import * as Effect from "effect/Effect";
5 +import * as FileSystem from "effect/FileSystem";
6 +import * as Layer from "effect/Layer";
7 +import * as Path from "effect/Path";
8 +import * as Schema from "effect/Schema";
9 import { Command, CliError } from "effect/unstable/cli";
10 import * as TestConsole from "effect/testing/TestConsole";
11 +import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
12
13 import {
14 releasePackageFiles,
@@ -13,17 +19,9 @@ import {
19 const ScriptTestLayer = Layer.mergeAll(NodeServices.layer, TestConsole.layer);
20 const runCli = Command.runWith(updateReleasePackageVersionsCommand, { version: "0.0.0" });
21 const PackageJsonSchema = Schema.Record(Schema.String, Schema.Unknown);
16 -const PrettyJsonString = SchemaGetter.parseJson<string>().compose(
17 - SchemaGetter.stringifyJson({ space: 2 }),
18 -);
19 -const PackageJsonPrettyJson = Schema.fromJsonString(PackageJsonSchema).pipe(
20 - Schema.encode({
21 - decode: PrettyJsonString,
22 - encode: PrettyJsonString,
23 - }),
24 -);
25 -const decodePackageJson = Schema.decodeUnknownEffect(PackageJsonPrettyJson);
26 -const encodePackageJson = Schema.encodeSync(PackageJsonPrettyJson);
22 +const PackageJsonPrettyJson = fromJsonStringPretty(PackageJsonSchema);
23 +const decodePackageJson = Schema.decodeEffect(PackageJsonPrettyJson);
24 +const encodePackageJson = Schema.encodeEffect(PackageJsonPrettyJson);
25
26 const writePackageJsonFixtures = Effect.fn("writePackageJsonFixtures")(function* (
27 rootDir: string,
@@ -37,7 +35,7 @@ const writePackageJsonFixtures = Effect.fn("writePackageJsonFixtures")(function*
35 yield* fs.makeDirectory(path.dirname(filePath), { recursive: true });
36 yield* fs.writeFileString(
37 filePath,
40 - `${encodePackageJson({
38 + `${yield* encodePackageJson({
39 name: relativePath,
40 version,
41 private: true,
scripts/update-release-package-versions.ts
+9 -10
@@ -2,8 +2,15 @@
2
3 import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
4 import * as NodeServices from "@effect/platform-node/NodeServices";
5 -import { Config, Console, Effect, FileSystem, Option, Path, Schema, SchemaGetter } from "effect";
5 +import * as Config from "effect/Config";
6 +import * as Console from "effect/Console";
7 +import * as Effect from "effect/Effect";
8 +import * as FileSystem from "effect/FileSystem";
9 +import * as Option from "effect/Option";
10 +import * as Path from "effect/Path";
11 +import * as Schema from "effect/Schema";
12 import { Argument, Command, Flag } from "effect/unstable/cli";
13 +import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
14
15 export const releasePackageFiles = [
16 "apps/server/package.json",
@@ -17,15 +24,7 @@ interface UpdateReleasePackageVersionsOptions {
24 }
25
26 const PackageJsonSchema = Schema.Record(Schema.String, Schema.Unknown);
20 -const PrettyJsonString = SchemaGetter.parseJson<string>().compose(
21 - SchemaGetter.stringifyJson({ space: 2 }),
22 -);
23 -const PackageJsonPrettyJson = Schema.fromJsonString(PackageJsonSchema).pipe(
24 - Schema.encode({
25 - decode: PrettyJsonString,
26 - encode: PrettyJsonString,
27 - }),
28 -);
27 +const PackageJsonPrettyJson = fromJsonStringPretty(PackageJsonSchema);
28 const decodePackageJson = Schema.decodeUnknownEffect(PackageJsonPrettyJson);
29 const encodePackageJson = Schema.encodeSync(PackageJsonPrettyJson);
30
tsconfig.base.json
+34 -1
@@ -17,6 +17,39 @@
17 "skipLibCheck": true,
18 "allowSyntheticDefaultImports": true,
19 "esModuleInterop": true,
20 - "resolveJsonModule": true
20 + "resolveJsonModule": true,
21 + "plugins": [
22 + {
23 + "name": "@effect/language-service",
24 + "namespaceImportPackages": ["@effect/platform-node", "effect"],
25 + "diagnosticSeverity": {
26 + "importFromBarrel": "error",
27 + "anyUnknownInErrorContext": "error",
28 + "unsafeEffectTypeAssertion": "error",
29 + "instanceOfSchema": "error",
30 + "deterministicKeys": "error",
31 + "strictEffectProvide": "off",
32 + "missingEffectServiceDependency": "error",
33 + "leakingRequirements": "error",
34 + "globalErrorInEffectCatch": "error",
35 + "globalErrorInEffectFailure": "error",
36 + "unknownInEffectCatch": "error",
37 + "strictBooleanExpressions": "off",
38 + "preferSchemaOverJson": "error",
39 + "schemaSyncInEffect": "error",
40 + "cryptoRandomUUID": "error",
41 + "cryptoRandomUUIDInEffect": "error",
42 + "nodeBuiltinImport": "error",
43 + "globalDate": "error",
44 + "globalDateInEffect": "error",
45 + "globalConsole": "error",
46 + "globalConsoleInEffect": "error",
47 + "globalRandom": "error",
48 + "globalRandomInEffect": "error",
49 + "globalTimers": "error",
50 + "globalTimersInEffect": "error"
51 + }
52 + }
53 + ]
54 }
55 }