Open History to see the last commit
1import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
2import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability";
3// @effect-diagnostics nodeBuiltinImport:off - CLI integration uses temporary Node paths.
4import * as NodeFS from "node:fs";
5import * as NodeOS from "node:os";
6import * as NodePath from "node:path";
7
8import * as NodeServices from "@effect/platform-node/NodeServices";
9import { assert, it } from "@effect/vitest";
10import {
11 CommandId,
12 EnvironmentInternalError,
13 EventId,
14 ProviderInstanceId,
15 ThreadId,
16 type OrchestrationV2AppThread,
17 type ProjectId,
18} from "@t3tools/contracts";
19import * as NetService from "@t3tools/shared/Net";
20import * as DateTime from "effect/DateTime";
21import * as Effect from "effect/Effect";
22import * as FileSystem from "effect/FileSystem";
23import * as Layer from "effect/Layer";
24import * as References from "effect/References";
25import * as Stream from "effect/Stream";
26import { Command } from "effect/cli";
27
28import { cli } from "../binCli.ts";
29import * as ServerConfig from "../config.ts";
30import * as EventSink from "../orchestration-v2/EventSink.ts";
31import * as EventStore from "../orchestration-v2/EventStore.ts";
32import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
33import * as RuntimeLayer from "../orchestration-v2/runtimeLayer.ts";
34import * as SqlitePersistence from "../persistence/Sqlite.ts";
35import * as ProjectEnrichmentService from "../project/ProjectEnrichmentService.ts";
36import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
37import * as ProjectService from "../project/ProjectService.ts";
38import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
39import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
40import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
41import {
42 ProjectLiveServerDeclaredResponseError,
43 ProjectLiveServerRequestError,
44 projectCommandErrorFromLiveServerRequest,
45} from "./project.ts";
46
47const layerCliRuntime = Layer.mergeAll(NodeServices.layer, NetService.layer);
48const runCli = (args: ReadonlyArray<string>) =>
49 Command.runWith(cli, { version: "0.0.0" })(args).pipe(Effect.provide(layerCliRuntime));
50
51const makeConfig = (baseDir: string) =>
52 Effect.gen(function* () {
53 const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, undefined);
54 return {
55 logLevel: "Info",
56 traceMinLevel: "Info",
57 traceTimingEnabled: true,
58 traceBatchWindowMs: 200,
59 traceMaxBytes: 10 * 1024 * 1024,
60 traceMaxFiles: 10,
61 otelEnvironment: OtelEnvironment.none,
62 otlpTracesUrl: undefined,
63 otlpMetricsUrl: undefined,
64 otlpLogsUrl: undefined,
65 otlpTracesExport: DEFAULT_SIGNAL_EXPORT,
66 otlpMetricsExport: DEFAULT_SIGNAL_EXPORT,
67 otlpLogsExport: DEFAULT_SIGNAL_EXPORT,
68 mode: "web",
69 port: 0,
70 host: "127.0.0.1",
71 cwd: process.cwd(),
72 baseDir,
73 ...derivedPaths,
74 staticDir: undefined,
75 devUrl: undefined,
76 devAllowedOrigins: [],
77 noBrowser: true,
78 startupPresentation: "browser",
79 desktopBootstrapToken: undefined,
80 autoBootstrapProjectFromCwd: false,
81 logWebSocketEvents: false,
82 tailscaleServeEnabled: false,
83 tailscaleServePort: 443,
84 } satisfies ServerConfig.ServerConfig["Service"];
85 });
86
87const readProjects = (baseDir: string) =>
88 Effect.gen(function* () {
89 const config = yield* makeConfig(baseDir);
90 const layer = RuntimeLayer.layerProjectService.pipe(
91 Layer.provideMerge(ProjectEnrichmentService.layer),
92 Layer.provideMerge(RepositoryIdentityResolver.layer),
93 Layer.provideMerge(ProjectFaviconResolver.layer),
94 Layer.provideMerge(T3ProjectFileLoader.layer),
95 Layer.provideMerge(WorkspacePaths.layer),
96 Layer.provideMerge(SqlitePersistence.layerConfig),
97 Layer.provideMerge(NodeServices.layer),
98 Layer.provide(ServerConfig.layer(config)),
99 Layer.provide(Layer.succeed(References.MinimumLogLevel, config.logLevel)),
100 );
101 return yield* ProjectService.ProjectService.pipe(
102 Effect.flatMap((projects) => projects.snapshot),
103 Effect.provide(layer),
104 );
105 });
106
107it("maps declared server failures into structural project command errors", () => {
108 const cause = new EnvironmentInternalError({
109 code: "internal_error",
110 reason: "access_token_issuance_failed",
111 traceId: "trace-123",
112 });
113
114 const error = projectCommandErrorFromLiveServerRequest(cause);
115
116 assert.instanceOf(error, ProjectLiveServerDeclaredResponseError);
117 assert.strictEqual(error.operation, "callLiveServer");
118 assert.strictEqual(error.code, "internal_error");
119 assert.strictEqual(error.traceId, "trace-123");
120 assert.strictEqual(error.message, "Server request failed (internal_error, trace trace-123).");
121 assert.strictEqual(error.cause, cause);
122});
123
124it("preserves unexpected server failures without deriving the message from them", () => {
125 const cause = new Error("credential abc123 was rejected");
126
127 const error = projectCommandErrorFromLiveServerRequest(cause);
128
129 assert.instanceOf(error, ProjectLiveServerRequestError);
130 assert.strictEqual(error.operation, "callLiveServer");
131 assert.strictEqual(error.message, "Failed to call the running server.");
132 assert.strictEqual(error.cause, cause);
133});
134
135it.effect("adds, renames, and removes projects through the V2 project CLI domain", () =>
136 Effect.gen(function* () {
137 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-v2-project-cli-"));
138 const workspaceRoot = NodeFS.mkdtempSync(
139 NodePath.join(NodeOS.tmpdir(), "t3-v2-project-workspace-"),
140 );
141
142 yield* runCli(["project", "add", workspaceRoot, "--title", "Alpha", "--base-dir", baseDir]);
143 const added = (yield* readProjects(baseDir)).projects[0];
144 assert.equal(added?.title, "Alpha");
145 assert.equal(added?.workspaceRoot, workspaceRoot);
146
147 yield* runCli(["project", "rename", workspaceRoot, "Beta", "--base-dir", baseDir]);
148 assert.equal((yield* readProjects(baseDir)).projects[0]?.title, "Beta");
149
150 yield* runCli(["project", "remove", added?.id ?? "", "--base-dir", baseDir]);
151 assert.deepEqual((yield* readProjects(baseDir)).projects, []);
152 }).pipe(Effect.provide(NodeServices.layer)),
153);
154
155const makeProjectLookupFixture = Effect.fn("ProjectCliTest.makeProjectLookupFixture")(function* () {
156 const fs = yield* FileSystem.FileSystem;
157 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-v2-project-lookup-" });
158 const baseDir = NodePath.join(root, "state");
159 const workspaceRoot = NodePath.join(root, "workspace");
160 yield* fs.makeDirectory(workspaceRoot);
161 yield* runCli(["project", "add", workspaceRoot, "--base-dir", baseDir]);
162 const project = (yield* readProjects(baseDir)).projects[0];
163 assert.isDefined(project);
164 return { baseDir, workspaceRoot, project: project! };
165});
166
167const makeThreadPersistenceLayer = Effect.fn("ProjectCliTest.makeThreadPersistenceLayer")(
168 function* (baseDir: string) {
169 const config = yield* makeConfig(baseDir);
170 return Layer.mergeAll(
171 RuntimeLayer.layerEventSink,
172 ProjectionStore.layer,
173 EventStore.layer,
174 ).pipe(
175 Layer.provideMerge(SqlitePersistence.layerConfig),
176 Layer.provideMerge(NodeServices.layer),
177 Layer.provide(ServerConfig.layer(config)),
178 Layer.provide(Layer.succeed(References.MinimumLogLevel, config.logLevel)),
179 );
180 },
181);
182
183const seedNativeThreads = Effect.fn("ProjectCliTest.seedNativeThreads")(function* (
184 baseDir: string,
185 threads: ReadonlyArray<{
186 readonly id: ThreadId;
187 readonly projectId: ProjectId;
188 readonly archived: boolean;
189 }>,
190) {
191 const layer = yield* makeThreadPersistenceLayer(baseDir);
192 const createdAt = DateTime.makeUnsafe("2026-09-04T12:00:00.000Z");
193 const providerInstanceId = ProviderInstanceId.make("codex");
194 yield* Effect.gen(function* () {
195 const eventSink = yield* EventSink.EventSinkV2;
196 yield* eventSink.write({
197 commandId: CommandId.make("project-cli-seed-threads"),
198 events: threads.map(({ id, projectId, archived }) => {
199 const payload: OrchestrationV2AppThread = {
200 createdBy: "user",
201 creationSource: "web",
202 id,
203 projectId,
204 title: id,
205 providerInstanceId,
206 modelSelection: { instanceId: providerInstanceId, model: "gpt-5" },
207 runtimeMode: "full-access",
208 interactionMode: "default",
209 branch: null,
210 worktreePath: null,
211 activeProviderThreadId: null,
212 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: id },
213 forkedFrom: null,
214 createdAt,
215 updatedAt: createdAt,
216 archivedAt: archived ? createdAt : null,
217 settledOverride: null,
218 settledAt: null,
219 lastVisitedAt: null,
220 deletedAt: null,
221 };
222 return {
223 id: EventId.make(`project-cli-create-${id}`),
224 type: "thread.created" as const,
225 threadId: id,
226 providerInstanceId,
227 occurredAt: createdAt,
228 payload,
229 };
230 }),
231 });
232 }).pipe(Effect.provide(layer));
233});
234
235const readNativeThreadState = Effect.fn("ProjectCliTest.readNativeThreadState")(function* (
236 baseDir: string,
237 threadId: ThreadId,
238) {
239 const layer = yield* makeThreadPersistenceLayer(baseDir);
240 return yield* Effect.gen(function* () {
241 const projections = yield* ProjectionStore.ProjectionStoreV2;
242 const events = yield* EventStore.EventStoreV2;
243 return {
244 thread: yield* projections.getThread(threadId),
245 events: yield* events.read({ threadId }).pipe(Stream.runCollect),
246 };
247 }).pipe(Effect.provide(layer));
248});
249
250it.layer(NodeServices.layer)("project deletion with native V2 threads", (it) => {
251 it.effect.each([
252 { label: "an active thread", archived: false, missing: false },
253 { label: "an archived thread", archived: true, missing: false },
254 {
255 label: "an active thread after its workspace disappears",
256 archived: false,
257 missing: true,
258 },
259 {
260 label: "an archived thread after its workspace disappears",
261 archived: true,
262 missing: true,
263 },
264 ])("rejects unforced removal of a project with $label", ({ archived, missing }) =>
265 Effect.gen(function* () {
266 const fs = yield* FileSystem.FileSystem;
267 const { baseDir, workspaceRoot, project } = yield* makeProjectLookupFixture();
268 const threadId = ThreadId.make("project-cli-preserved-thread");
269 yield* seedNativeThreads(baseDir, [{ id: threadId, projectId: project.id, archived }]);
270 const before = yield* readNativeThreadState(baseDir, threadId);
271 if (missing) yield* fs.rename(workspaceRoot, `${workspaceRoot}-removed`);
272
273 const error = yield* runCli([
274 "project",
275 "remove",
276 missing ? workspaceRoot : project.id,
277 "--base-dir",
278 baseDir,
279 ]).pipe(
280 Effect.match({
281 onFailure: (error) => error,
282 onSuccess: () => assert.fail("Removing a nonempty project must require --force."),
283 }),
284 );
285
286 assert.include(error.message, "not empty");
287 assert.deepEqual(
288 (yield* readProjects(baseDir)).projects.map((entry) => entry.id),
289 [project.id],
290 );
291 assert.deepEqual(yield* readNativeThreadState(baseDir, threadId), before);
292 assert.equal(yield* fs.exists(workspaceRoot), !missing);
293 }),
294 );
295
296 it.effect.each(["present", "missing"] as const)(
297 "force-removes active and archived V2 threads with the workspace %s, preserving unrelated projects",
298 (workspace) =>
299 Effect.gen(function* () {
300 const fs = yield* FileSystem.FileSystem;
301 const { baseDir, workspaceRoot, project } = yield* makeProjectLookupFixture();
302 const otherWorkspace = `${workspaceRoot}-other`;
303 yield* fs.makeDirectory(otherWorkspace);
304 yield* runCli(["project", "add", otherWorkspace, "--base-dir", baseDir]);
305 const otherProject = (yield* readProjects(baseDir)).projects.find(
306 (entry) => entry.workspaceRoot === otherWorkspace,
307 );
308 assert.isDefined(otherProject);
309 const activeId = ThreadId.make("project-cli-deleted-active");
310 const archivedId = ThreadId.make("project-cli-deleted-archived");
311 const unrelatedId = ThreadId.make("project-cli-unrelated-thread");
312 yield* seedNativeThreads(baseDir, [
313 { id: activeId, projectId: project.id, archived: false },
314 { id: archivedId, projectId: project.id, archived: true },
315 { id: unrelatedId, projectId: otherProject!.id, archived: false },
316 ]);
317 const unrelatedBefore = yield* readNativeThreadState(baseDir, unrelatedId);
318 if (workspace === "missing") {
319 yield* fs.rename(workspaceRoot, `${workspaceRoot}-removed`);
320 }
321
322 yield* runCli([
323 "project",
324 "remove",
325 workspace === "missing" ? workspaceRoot : project.id,
326 "--force",
327 "--base-dir",
328 baseDir,
329 ]);
330
331 assert.deepEqual(
332 (yield* readProjects(baseDir)).projects.map((entry) => entry.id),
333 [otherProject!.id],
334 );
335 for (const threadId of [activeId, archivedId]) {
336 const state = yield* readNativeThreadState(baseDir, threadId);
337 assert.isNotNull(state.thread.deletedAt);
338 assert.lengthOf(
339 state.events.filter((record) => record.event.type === "thread.deleted"),
340 1,
341 );
342 }
343 assert.deepEqual(yield* readNativeThreadState(baseDir, unrelatedId), unrelatedBefore);
344 assert.equal(yield* fs.exists(workspaceRoot), workspace === "present");
345 assert.isTrue(yield* fs.exists(otherWorkspace));
346 }),
347 );
348});
349
350it.layer(NodeServices.layer)("project lookup with unavailable workspaces", (it) => {
351 it.effect.each(["id", "stored path"] as const)(
352 "removes an empty project by %s after its directory is gone",
353 (identifier) =>
354 Effect.gen(function* () {
355 const fs = yield* FileSystem.FileSystem;
356 const { baseDir, workspaceRoot, project } = yield* makeProjectLookupFixture();
357 yield* fs.rename(workspaceRoot, `${workspaceRoot}-removed`);
358 yield* runCli([
359 "project",
360 "remove",
361 identifier === "id" ? project.id : workspaceRoot,
362 "--base-dir",
363 baseDir,
364 ]);
365 assert.deepEqual((yield* readProjects(baseDir)).projects, []);
366 assert.isFalse(yield* fs.exists(workspaceRoot));
367 }),
368 );
369
370 it.effect("renames by ID and stored path after the directory is gone", () =>
371 Effect.gen(function* () {
372 const fs = yield* FileSystem.FileSystem;
373 const { baseDir, workspaceRoot, project } = yield* makeProjectLookupFixture();
374 yield* fs.rename(workspaceRoot, `${workspaceRoot}-removed`);
375 for (const [identifier, title] of [
376 [project.id, "Renamed by ID"],
377 [workspaceRoot, "Renamed by stored path"],
378 ] as const) {
379 yield* runCli(["project", "rename", identifier, title, "--base-dir", baseDir]);
380 assert.equal((yield* readProjects(baseDir)).projects[0]?.title, title);
381 }
382 assert.isFalse(yield* fs.exists(workspaceRoot));
383 }),
384 );
385
386 it.effect("does not resolve another environment's project ID in an empty database", () =>
387 Effect.gen(function* () {
388 const fs = yield* FileSystem.FileSystem;
389 const { baseDir, workspaceRoot, project } = yield* makeProjectLookupFixture();
390 yield* fs.rename(workspaceRoot, `${workspaceRoot}-removed`);
391 const replacementDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-v2-project-empty-" });
392 const error = yield* runCli([
393 "project",
394 "remove",
395 project.id,
396 "--force",
397 "--base-dir",
398 replacementDir,
399 ]).pipe(Effect.flip);
400 assert.include(error.message, "No active project found");
401 assert.deepEqual(
402 (yield* readProjects(baseDir)).projects.map((entry) => entry.id),
403 [project.id],
404 );
405 assert.deepEqual((yield* readProjects(replacementDir)).projects, []);
406 }),
407 );
408
409 it.effect("normalizes existing paths without conflating separately registered symlinks", () =>
410 Effect.gen(function* () {
411 const { baseDir, workspaceRoot, project } = yield* makeProjectLookupFixture();
412 yield* runCli([
413 "project",
414 "rename",
415 `${workspaceRoot}${NodePath.sep}.`,
416 "Normalized",
417 "--base-dir",
418 baseDir,
419 ]);
420 assert.equal((yield* readProjects(baseDir)).projects[0]?.title, "Normalized");
421 const aliasPath = `${workspaceRoot}-alias`;
422 NodeFS.symlinkSync(workspaceRoot, aliasPath, "junction");
423 const unknownAlias = yield* runCli([
424 "project",
425 "remove",
426 aliasPath,
427 "--base-dir",
428 baseDir,
429 ]).pipe(Effect.flip);
430 assert.include(unknownAlias.message, "No active project found");
431 yield* runCli(["project", "add", aliasPath, "--base-dir", baseDir]);
432 const added = (yield* readProjects(baseDir)).projects;
433 assert.equal(added.length, 2);
434 const aliasProject = added.find((entry) => entry.workspaceRoot === aliasPath);
435 assert.isDefined(aliasProject);
436 assert.notEqual(aliasProject?.id, project.id);
437 yield* runCli(["project", "remove", `${aliasPath}${NodePath.sep}.`, "--base-dir", baseDir]);
438 assert.deepEqual(
439 (yield* readProjects(baseDir)).projects.map((entry) => entry.id),
440 [project.id],
441 );
442 assert.isTrue(NodeFS.existsSync(workspaceRoot));
443 }),
444 );
445});