Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - CLI integration exercises Node HTTP and filesystem boundaries.
2import * as NodeHttp from "node:http";
3import * as NodeFS from "node:fs";
4import * as NodeOS from "node:os";
5import * as NodePath from "node:path";
6
7import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
8import * as NodeServices from "@effect/platform-node/NodeServices";
9import { EnvironmentOrchestrationHttpApi } from "@v12/contracts";
10import * as NetService from "@v12/shared/Net";
11import { assert, it } from "@effect/vitest";
12import * as Effect from "effect/Effect";
13import * as Layer from "effect/Layer";
14import * as HttpRouter from "effect/unstable/http/HttpRouter";
15import * as HttpServer from "effect/unstable/http/HttpServer";
16import * as HttpApi from "effect/unstable/httpapi/HttpApi";
17import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
18import * as CliError from "effect/unstable/cli/CliError";
19import * as TestConsole from "effect/testing/TestConsole";
20import { Command } from "effect/unstable/cli";
21
22import { cli, makeCli } from "./bin.ts";
23import * as ServerConfig from "./config.ts";
24import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
25import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
26import { orchestrationHttpApiLayer } from "./orchestration/http.ts";
27import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
28import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts";
29import {
30 makePersistedServerRuntimeState,
31 persistServerRuntimeState,
32} from "./serverRuntimeState.ts";
33import * as WorkspacePaths from "./workspace/WorkspacePaths.ts";
34import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
35import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
36import { environmentAuthenticatedAuthLayer } from "./auth/http.ts";
37
38const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
39class ProjectCliHttpApi extends HttpApi.make("environment").add(EnvironmentOrchestrationHttpApi) {}
40
41const connectCli = makeCli({ cloudEnabled: true });
42const noConnectCli = makeCli({ cloudEnabled: false });
43const runCli = (args: ReadonlyArray<string>, command = cli) =>
44 Command.runWith(command, { version: "0.0.0" })(args);
45const runConnectCli = (args: ReadonlyArray<string>) => runCli(args, connectCli);
46const runCliWithRuntime = (args: ReadonlyArray<string>) =>
47 runCli(args).pipe(Effect.provide(CliRuntimeLayer));
48
49const captureStdout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
50 Effect.gen(function* () {
51 const result = yield* effect;
52 const output =
53 (yield* TestConsole.logLines).findLast((line): line is string => typeof line === "string") ??
54 "";
55 return { result, output };
56 }).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer)));
57
58const makeCliTestServerConfig = (baseDir: string) =>
59 Effect.gen(function* () {
60 const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, undefined);
61 return {
62 logLevel: "Info",
63 traceMinLevel: "Info",
64 traceTimingEnabled: true,
65 traceBatchWindowMs: 200,
66 traceMaxBytes: 10 * 1024 * 1024,
67 traceMaxFiles: 10,
68 otlpTracesUrl: undefined,
69 otlpMetricsUrl: undefined,
70 otlpExportIntervalMs: 10_000,
71 otlpServiceName: "v12-server",
72 mode: "web",
73 port: 0,
74 host: "127.0.0.1",
75 cwd: process.cwd(),
76 baseDir,
77 ...derivedPaths,
78 staticDir: undefined,
79 devUrl: undefined,
80 noBrowser: true,
81 startupPresentation: "browser",
82 desktopBootstrapToken: undefined,
83 autoBootstrapProjectFromCwd: false,
84 logWebSocketEvents: false,
85 tailscaleServeEnabled: false,
86 tailscaleServePort: 443,
87 } satisfies ServerConfig.ServerConfig["Service"];
88 });
89
90const makeProjectPersistenceLayer = (config: ServerConfig.ServerConfig["Service"]) =>
91 Layer.mergeAll(
92 OrchestrationLayerLive.pipe(
93 Layer.provideMerge(RepositoryIdentityResolver.layer),
94 Layer.provideMerge(SqlitePersistenceLayerLive),
95 ),
96 WorkspacePaths.layer,
97 ).pipe(Layer.provideMerge(NodeServices.layer), Layer.provide(ServerConfig.layer(config)));
98
99const readPersistedSnapshot = (baseDir: string) =>
100 Effect.gen(function* () {
101 const config = yield* makeCliTestServerConfig(baseDir);
102 return yield* Effect.gen(function* () {
103 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
104 return yield* projectionSnapshotQuery.getSnapshot();
105 }).pipe(Effect.provide(makeProjectPersistenceLayer(config)));
106 });
107
108const withLiveProjectCliServer = <A, E, R>(baseDir: string, run: () => Effect.Effect<A, E, R>) =>
109 Effect.gen(function* () {
110 const config = yield* makeCliTestServerConfig(baseDir);
111 const routesLayer = HttpApiBuilder.layer(ProjectCliHttpApi).pipe(
112 Layer.provide(orchestrationHttpApiLayer),
113 Layer.provide(environmentAuthenticatedAuthLayer),
114 );
115 const appLayer = HttpRouter.serve(routesLayer, {
116 disableListenLog: true,
117 disableLogger: true,
118 }).pipe(
119 Layer.provideMerge(
120 EnvironmentAuth.layer.pipe(
121 Layer.provideMerge(SqlitePersistenceLayerLive),
122 Layer.provide(ServerSecretStore.layer),
123 ),
124 ),
125 Layer.provideMerge(makeProjectPersistenceLayer(config)),
126 Layer.provideMerge(
127 NodeHttpServer.layer(NodeHttp.createServer, {
128 host: "127.0.0.1",
129 port: 0,
130 }),
131 ),
132 Layer.provideMerge(NodeServices.layer),
133 Layer.provide(ServerConfig.layer(config)),
134 );
135
136 return yield* Effect.scoped(
137 Effect.gen(function* () {
138 const server = yield* HttpServer.HttpServer;
139 const address = server.address;
140 if (typeof address === "string" || !("port" in address)) {
141 assert.fail(`Expected TCP address, got ${address}`);
142 }
143 yield* persistServerRuntimeState({
144 path: config.serverRuntimeStatePath,
145 state: yield* makePersistedServerRuntimeState({
146 config,
147 port: address.port,
148 }),
149 });
150 return yield* run();
151 }).pipe(Effect.provide(Layer.mergeAll(appLayer, NodeServices.layer))),
152 );
153 });
154
155it.layer(NodeServices.layer)("bin cli parsing", (it) => {
156 it.effect("accepts the built-in lowercase log-level flag values", () =>
157 runCliWithRuntime(["--log-level", "debug", "--version"]),
158 );
159
160 it.effect("accepts canonical --no-<flag> boolean negation", () =>
161 runCliWithRuntime(["--no-log-websocket-events", "--version"]),
162 );
163
164 it.effect("rejects invalid log-level casing before launching the server", () =>
165 Effect.gen(function* () {
166 const error = yield* runCliWithRuntime(["--log-level", "Debug"]).pipe(Effect.flip);
167
168 if (!CliError.isCliError(error)) {
169 assert.fail(`Expected CliError, got ${String(error)}`);
170 }
171 if (error._tag !== "InvalidValue") {
172 assert.fail(`Expected InvalidValue, got ${error._tag}`);
173 }
174 assert.equal(error.option, "log-level");
175 assert.equal(error.value, "Debug");
176 }),
177 );
178
179 it.effect("rejects connect commands when public configuration is missing", () =>
180 Effect.gen(function* () {
181 const error = yield* runCli(["connect", "status"], noConnectCli).pipe(Effect.flip);
182
183 if (!CliError.isCliError(error)) {
184 assert.fail(`Expected CliError, got ${String(error)}`);
185 }
186 if (error._tag !== "ShowHelp") {
187 assert.fail(`Expected ShowHelp, got ${error._tag}`);
188 }
189 assert.deepEqual(error.commandPath, ["v12", "connect"]);
190 assert.include(error.errors[0]?.message ?? "", "missing V12 Connect public configuration");
191
192 const output = (yield* TestConsole.errorLines).join("\n");
193 assert.include(output, "ERROR");
194 assert.include(output, "missing V12 Connect public configuration");
195 }).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer))),
196 );
197
198 it.effect("reports fresh headless connect state without requiring local configuration", () =>
199 Effect.gen(function* () {
200 const baseDir = NodeFS.mkdtempSync(
201 NodePath.join(NodeOS.tmpdir(), "v12-cli-cloud-status-test-"),
202 );
203 const { output } = yield* captureStdout(
204 runConnectCli(["connect", "status", "--base-dir", baseDir, "--json"]),
205 );
206 // @effect-diagnostics-next-line preferSchemaOverJson:off - CLI JSON output is decoded as a presentation DTO.
207 const status = JSON.parse(output) as {
208 readonly desired: boolean;
209 readonly authenticated: boolean;
210 readonly linked: boolean;
211 readonly cloudUserId: string | null;
212 readonly relayUrl: string | null;
213 };
214
215 assert.equal(status.desired, false);
216 assert.equal(status.authenticated, false);
217 assert.equal(status.linked, false);
218 assert.equal(status.cloudUserId, null);
219 assert.equal(status.relayUrl, null);
220 }),
221 );
222
223 it.effect("reports actionable human-readable headless connect state", () =>
224 Effect.gen(function* () {
225 const baseDir = NodeFS.mkdtempSync(
226 NodePath.join(NodeOS.tmpdir(), "v12-cli-cloud-status-human-test-"),
227 );
228 const { output } = yield* captureStdout(
229 runConnectCli(["connect", "status", "--base-dir", baseDir]),
230 );
231
232 assert.include(output, "V12 Connect\n Exposure: disabled");
233 assert.include(output, " Authorization: missing");
234 assert.include(output, " Environment link: not provisioned");
235 assert.include(output, "Next: Run `v12 connect link` to authorize and enable V12 Connect.");
236 }),
237 );
238
239 it.effect("logs in to headless connect without enabling access", () =>
240 Effect.gen(function* () {
241 const baseDir = NodeFS.mkdtempSync(
242 NodePath.join(NodeOS.tmpdir(), "v12-cli-cloud-login-test-"),
243 );
244 const { secretsDir } = yield* ServerConfig.deriveServerPaths(baseDir, undefined);
245 NodeFS.mkdirSync(secretsDir, { recursive: true });
246 NodeFS.writeFileSync(
247 NodePath.join(secretsDir, "cloud-cli-oauth-token.bin"),
248 // @effect-diagnostics-next-line preferSchemaOverJson:off - Test fixture matches the persisted CLI token representation.
249 JSON.stringify({
250 accessToken: "access-token",
251 refreshToken: "refresh-token",
252 expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
253 }),
254 );
255
256 const login = yield* captureStdout(
257 runConnectCli(["connect", "login", "--base-dir", baseDir]),
258 );
259 const status = yield* captureStdout(
260 runConnectCli(["connect", "status", "--base-dir", baseDir, "--json"]),
261 );
262 // @effect-diagnostics-next-line preferSchemaOverJson:off - CLI JSON output is decoded as a presentation DTO.
263 const decoded = JSON.parse(status.output) as {
264 readonly desired: boolean;
265 readonly authenticated: boolean;
266 };
267
268 assert.equal(login.output, "Signed in to V12 Connect.");
269 assert.isFalse(decoded.desired);
270 assert.isTrue(decoded.authenticated);
271 }),
272 );
273
274 it.effect("disables headless connect without a running server", () =>
275 Effect.gen(function* () {
276 const baseDir = NodeFS.mkdtempSync(
277 NodePath.join(NodeOS.tmpdir(), "v12-cli-cloud-unlink-test-"),
278 );
279 const { output } = yield* captureStdout(
280 runConnectCli(["connect", "unlink", "--base-dir", baseDir]),
281 );
282
283 assert.equal(output, "V12 Connect is disabled locally.");
284 }),
285 );
286
287 it.effect("logs out of headless connect and removes the stored CLI authorization", () =>
288 Effect.gen(function* () {
289 const baseDir = NodeFS.mkdtempSync(
290 NodePath.join(NodeOS.tmpdir(), "v12-cli-cloud-logout-test-"),
291 );
292 const { secretsDir } = yield* ServerConfig.deriveServerPaths(baseDir, undefined);
293 const tokenPath = NodePath.join(secretsDir, "cloud-cli-oauth-token.bin");
294 NodeFS.mkdirSync(secretsDir, { recursive: true });
295 NodeFS.writeFileSync(tokenPath, "invalid persisted token");
296
297 const { output } = yield* captureStdout(
298 runConnectCli(["connect", "logout", "--base-dir", baseDir]),
299 );
300
301 assert.equal(output, "Signed out of V12 Connect locally.");
302 assert.isFalse(NodeFS.existsSync(tokenPath));
303 }),
304 );
305
306 it.effect("executes auth pairing subcommands and redacts secrets from list output", () =>
307 Effect.gen(function* () {
308 const baseDir = NodeFS.mkdtempSync(
309 NodePath.join(NodeOS.tmpdir(), "v12-cli-auth-pairing-test-"),
310 );
311
312 const createdOutput = yield* captureStdout(
313 runCli(["auth", "pairing", "create", "--base-dir", baseDir, "--json"]),
314 );
315 // @effect-diagnostics-next-line preferSchemaOverJson:off
316 const created = JSON.parse(createdOutput.output) as {
317 readonly id: string;
318 readonly credential: string;
319 };
320 const listedOutput = yield* captureStdout(
321 runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]),
322 );
323 // @effect-diagnostics-next-line preferSchemaOverJson:off
324 const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{
325 readonly id: string;
326 readonly credential?: string;
327 }>;
328
329 assert.equal(typeof created.id, "string");
330 assert.equal(typeof created.credential, "string");
331 assert.equal(created.credential.length > 0, true);
332 assert.equal(listed.length, 1);
333 assert.equal(listed[0]?.id, created.id);
334 assert.equal("credential" in (listed[0] ?? {}), false);
335 }),
336 );
337
338 it.effect("executes auth session subcommands and redacts secrets from list output", () =>
339 Effect.gen(function* () {
340 const baseDir = NodeFS.mkdtempSync(
341 NodePath.join(NodeOS.tmpdir(), "v12-cli-auth-session-test-"),
342 );
343
344 const issuedOutput = yield* captureStdout(
345 runCli(["auth", "session", "issue", "--base-dir", baseDir, "--json"]),
346 );
347 // @effect-diagnostics-next-line preferSchemaOverJson:off
348 const issued = JSON.parse(issuedOutput.output) as {
349 readonly sessionId: string;
350 readonly token: string;
351 readonly scopes: ReadonlyArray<string>;
352 };
353 const listedOutput = yield* captureStdout(
354 runCli(["auth", "session", "list", "--base-dir", baseDir, "--json"]),
355 );
356 // @effect-diagnostics-next-line preferSchemaOverJson:off
357 const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{
358 readonly sessionId: string;
359 readonly token?: string;
360 readonly scopes: ReadonlyArray<string>;
361 }>;
362
363 assert.equal(typeof issued.sessionId, "string");
364 assert.equal(typeof issued.token, "string");
365 assert.deepEqual(issued.scopes, [
366 "orchestration:read",
367 "orchestration:operate",
368 "terminal:operate",
369 "review:write",
370 "relay:read",
371 "access:read",
372 "access:write",
373 "relay:write",
374 ]);
375 assert.equal(listed.length, 1);
376 assert.equal(listed[0]?.sessionId, issued.sessionId);
377 assert.deepEqual(listed[0]?.scopes, [
378 "orchestration:read",
379 "orchestration:operate",
380 "terminal:operate",
381 "review:write",
382 "relay:read",
383 "access:read",
384 "access:write",
385 "relay:write",
386 ]);
387 assert.equal("token" in (listed[0] ?? {}), false);
388 }),
389 );
390
391 it.effect("rejects invalid ttl values before running auth commands", () =>
392 Effect.gen(function* () {
393 const error = yield* runCliWithRuntime(["auth", "pairing", "create", "--ttl", "soon"]).pipe(
394 Effect.flip,
395 );
396
397 if (!CliError.isCliError(error)) {
398 assert.fail(`Expected CliError, got ${String(error)}`);
399 }
400 if (error._tag !== "ShowHelp") {
401 assert.fail(`Expected ShowHelp, got ${error._tag}`);
402 }
403 assert.deepEqual(error.commandPath, ["v12", "auth", "pairing", "create"]);
404 const ttlError = error.errors[0] as CliError.CliError | undefined;
405 if (!ttlError || ttlError._tag !== "InvalidValue") {
406 assert.fail(`Expected InvalidValue, got ${String(ttlError?._tag)}`);
407 }
408 assert.equal(ttlError.option, "ttl");
409 assert.equal(ttlError.value, "soon");
410 assert.isTrue(ttlError.message.includes("Invalid duration"));
411 assert.isTrue(ttlError.message.includes("5m, 1h, 30d, or 15 minutes"));
412 }),
413 );
414
415 it.effect("adds, renames, and removes projects offline through the orchestration engine", () =>
416 Effect.gen(function* () {
417 const baseDir = NodeFS.mkdtempSync(
418 NodePath.join(NodeOS.tmpdir(), "v12-cli-projects-offline-test-"),
419 );
420 const workspaceRoot = NodeFS.mkdtempSync(
421 NodePath.join(NodeOS.tmpdir(), "v12-cli-projects-workspace-"),
422 );
423
424 yield* runCliWithRuntime([
425 "project",
426 "add",
427 workspaceRoot,
428 "--title",
429 "Alpha",
430 "--base-dir",
431 baseDir,
432 ]);
433 const afterAdd = yield* readPersistedSnapshot(baseDir);
434 const addedProject = afterAdd.projects.find(
435 (project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null,
436 );
437 assert.isTrue(addedProject !== undefined);
438 assert.equal(addedProject?.title, "Alpha");
439
440 yield* runCliWithRuntime(["project", "rename", workspaceRoot, "Beta", "--base-dir", baseDir]);
441 const afterRename = yield* readPersistedSnapshot(baseDir);
442 const renamedProject = afterRename.projects.find(
443 (project) => project.id === addedProject?.id,
444 );
445 assert.equal(renamedProject?.title, "Beta");
446 assert.equal(renamedProject?.deletedAt, null);
447
448 yield* runCliWithRuntime([
449 "project",
450 "remove",
451 addedProject?.id ?? "",
452 "--base-dir",
453 baseDir,
454 ]);
455 const afterRemove = yield* readPersistedSnapshot(baseDir);
456 const removedProject = afterRemove.projects.find(
457 (project) => project.id === addedProject?.id,
458 );
459 assert.isTrue((removedProject?.deletedAt ?? null) !== null);
460 }),
461 );
462
463 it.effect("routes project commands through a running server when runtime state is present", () =>
464 Effect.gen(function* () {
465 const baseDir = NodeFS.mkdtempSync(
466 NodePath.join(NodeOS.tmpdir(), "v12-cli-projects-live-test-"),
467 );
468 const workspaceRoot = NodeFS.mkdtempSync(
469 NodePath.join(NodeOS.tmpdir(), "v12-cli-projects-live-workspace-"),
470 );
471
472 yield* withLiveProjectCliServer(baseDir, () =>
473 Effect.gen(function* () {
474 yield* runCliWithRuntime([
475 "project",
476 "add",
477 workspaceRoot,
478 "--title",
479 "Live Project",
480 "--base-dir",
481 baseDir,
482 ]);
483 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
484 const readModel = yield* projectionSnapshotQuery.getSnapshot();
485 const addedProject = readModel.projects.find(
486 (project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null,
487 );
488 assert.isTrue(addedProject !== undefined);
489 assert.equal(addedProject?.title, "Live Project");
490 }),
491 );
492 }),
493 );
494
495 it.effect("rejects dev-url on project commands", () =>
496 Effect.gen(function* () {
497 const workspaceRoot = NodeFS.mkdtempSync(
498 NodePath.join(NodeOS.tmpdir(), "v12-cli-projects-unknown-option-workspace-"),
499 );
500 const error = yield* runCliWithRuntime([
501 "project",
502 "add",
503 workspaceRoot,
504 "--dev-url",
505 "http://127.0.0.1:5173",
506 ]).pipe(Effect.flip);
507
508 if (!CliError.isCliError(error)) {
509 assert.fail(`Expected CliError, got ${String(error)}`);
510 }
511 if (error._tag !== "ShowHelp") {
512 assert.fail(`Expected ShowHelp, got ${error._tag}`);
513 }
514 assert.deepEqual(error.commandPath, ["v12", "project", "add"]);
515 const optionError = error.errors[0] as CliError.CliError | undefined;
516 if (!optionError || optionError._tag !== "UnrecognizedOption") {
517 assert.fail(`Expected UnrecognizedOption, got ${String(optionError?._tag)}`);
518 }
519 assert.equal(optionError.option, "--dev-url");
520 }),
521 );
522});