Open History to see the last commit
1import {
2 AuthStandardClientScopes,
3 CommandId,
4 EnvironmentHttpApi,
5 EnvironmentHttpCommonError,
6 PROJECT_TRACKED_FOLDERS_MAX,
7 type ProjectMutation,
8 type ProjectSnapshot,
9 ProjectId,
10} from "@t3tools/contracts";
11import * as Console from "effect/Console";
12import * as SecureRandom from "effect/crypto/SecureRandom";
13import * as Duration from "effect/Duration";
14import * as Effect from "effect/Effect";
15import * as FileSystem from "effect/FileSystem";
16import * as Layer from "effect/Layer";
17import * as Option from "effect/Option";
18import * as Path from "effect/Path";
19import * as References from "effect/References";
20import * as Schema from "effect/Schema";
21import { Argument, Command, Flag, GlobalFlag } from "effect/cli";
22import { FetchHttpClient, HttpClient, HttpClientError } from "effect/http";
23import * as HttpApiClient from "effect/http-api/HttpApiClient";
24
25import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
26import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
27
28import * as ServerConfig from "../config.ts";
29import * as SqlitePersistence from "../persistence/Sqlite.ts";
30import * as ProcessRunner from "../processRunner.ts";
31import * as ServerOwnership from "../serverOwnership.ts";
32import type * as RuntimeLayer from "../orchestration-v2/runtimeLayer.ts";
33import * as ProjectEnrichmentService from "../project/ProjectEnrichmentService.ts";
34import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
35import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
36import * as ProjectService from "../project/ProjectService.ts";
37import { projectMutationOperation } from "../project/ProjectMutation.ts";
38import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
39import * as ServerSettings from "../serverSettings.ts";
40import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
41import {
42 clearPersistedServerRuntimeState,
43 readLiveServerRuntimeState,
44} from "../serverRuntimeState.ts";
45import { scanFolders } from "../workspace/WorkspaceFolders.ts";
46import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
47import { type CliAuthLocationFlags, projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
48
49type ProjectMutationTarget = {
50 readonly id: ProjectId;
51 readonly title: string;
52 readonly workspaceRoot: string;
53};
54
55type ProjectCommandExecutionMode = "live" | "offline";
56type ProjectCliDispatchCommand = ProjectMutation;
57
58const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
59
60export class ProjectCommandIdGenerationError extends Schema.TaggedError<ProjectCommandIdGenerationError>()(
61 "ProjectCommandIdGenerationError",
62 {
63 operation: Schema.Literal("generateProjectCommandId"),
64 cause: Schema.Defect(),
65 },
66) {
67 override get message(): string {
68 return "Failed to generate a project command identifier.";
69 }
70}
71
72export class ProjectLiveServerDeclaredResponseError extends Schema.TaggedError<ProjectLiveServerDeclaredResponseError>()(
73 "ProjectLiveServerDeclaredResponseError",
74 {
75 operation: Schema.Literal("callLiveServer"),
76 code: Schema.String,
77 traceId: Schema.String,
78 cause: Schema.Defect(),
79 },
80) {
81 override get message(): string {
82 return `Server request failed (${this.code}, trace ${this.traceId}).`;
83 }
84}
85
86export class ProjectLiveServerUndeclaredStatusError extends Schema.TaggedError<ProjectLiveServerUndeclaredStatusError>()(
87 "ProjectLiveServerUndeclaredStatusError",
88 {
89 operation: Schema.Literal("callLiveServer"),
90 status: Schema.Int,
91 cause: Schema.Defect(),
92 },
93) {
94 override get message(): string {
95 return `Server request failed with undeclared status ${this.status}.`;
96 }
97}
98
99export class ProjectLiveServerRequestError extends Schema.TaggedError<ProjectLiveServerRequestError>()(
100 "ProjectLiveServerRequestError",
101 {
102 operation: Schema.Literal("callLiveServer"),
103 cause: Schema.Defect(),
104 },
105) {
106 override get message(): string {
107 return "Failed to call the running server.";
108 }
109}
110
111export class ProjectTitleEmptyError extends Schema.TaggedError<ProjectTitleEmptyError>()(
112 "ProjectTitleEmptyError",
113 {
114 operation: Schema.Literal("validateProjectTitle"),
115 title: Schema.String,
116 },
117) {
118 override get message(): string {
119 return "Project title cannot be empty.";
120 }
121}
122
123export class ProjectIdentifierEmptyError extends Schema.TaggedError<ProjectIdentifierEmptyError>()(
124 "ProjectIdentifierEmptyError",
125 {
126 operation: Schema.Literal("resolveProjectTarget"),
127 identifier: Schema.String,
128 },
129) {
130 override get message(): string {
131 return "Project identifier cannot be empty.";
132 }
133}
134
135export class ProjectNotFoundError extends Schema.TaggedError<ProjectNotFoundError>()(
136 "ProjectNotFoundError",
137 {
138 operation: Schema.Literal("resolveProjectTarget"),
139 identifier: Schema.String,
140 normalizedWorkspaceRoot: Schema.optional(Schema.String),
141 activeProjectCount: Schema.Number,
142 cause: Schema.optional(Schema.Defect()),
143 },
144) {
145 override get message(): string {
146 return `No active project found for '${this.identifier}'.`;
147 }
148}
149
150export class ProjectAlreadyExistsError extends Schema.TaggedError<ProjectAlreadyExistsError>()(
151 "ProjectAlreadyExistsError",
152 {
153 operation: Schema.Literal("addProject"),
154 projectId: ProjectId,
155 workspaceRoot: Schema.String,
156 },
157) {
158 override get message(): string {
159 return `An active project already exists for '${this.workspaceRoot}'.`;
160 }
161}
162
163export const ProjectCommandError = Schema.Union([
164 ProjectCommandIdGenerationError,
165 ProjectLiveServerDeclaredResponseError,
166 ProjectLiveServerUndeclaredStatusError,
167 ProjectLiveServerRequestError,
168 ProjectTitleEmptyError,
169 ProjectIdentifierEmptyError,
170 ProjectNotFoundError,
171 ProjectAlreadyExistsError,
172]);
173export type ProjectCommandError = typeof ProjectCommandError.Type;
174
175function projectCommandErrorFromLiveServerRequest(cause: unknown): ProjectCommandError {
176 if (isEnvironmentHttpCommonError(cause)) {
177 return new ProjectLiveServerDeclaredResponseError({
178 operation: "callLiveServer",
179 code: cause.code,
180 traceId: cause.traceId,
181 cause,
182 });
183 }
184 if (HttpClientError.isHttpClientError(cause) && cause.response !== undefined) {
185 return new ProjectLiveServerUndeclaredStatusError({
186 operation: "callLiveServer",
187 status: cause.response.status,
188 cause,
189 });
190 }
191
192 return new ProjectLiveServerRequestError({ operation: "callLiveServer", cause });
193}
194
195const projectCommandUuid = SecureRandom.SecureRandom.pipe(
196 Effect.flatMap((random) => random.uuidV4()),
197 Effect.mapError(
198 (cause) =>
199 new ProjectCommandIdGenerationError({
200 operation: "generateProjectCommandId",
201 cause,
202 }),
203 ),
204);
205
206const makeProjectCliRuntimeLayer = (layerProjectService: typeof RuntimeLayer.layerProjectService) =>
207 layerProjectService.pipe(
208 Layer.provideMerge(ProjectEnrichmentService.layer),
209 Layer.provideMerge(RepositoryIdentityResolver.layer),
210 Layer.provideMerge(
211 ProjectFaviconResolver.layer.pipe(
212 Layer.provide(WorkspacePaths.layer),
213 Layer.provide(T3ProjectFileLoader.layer),
214 ),
215 ),
216 Layer.provideMerge(WorkspacePaths.layer),
217 Layer.provideMerge(
218 ServerSettings.layer.pipe(
219 Layer.provide(Layer.merge(ServerSecretStore.layer, ManagedPolicy.layer)),
220 ),
221 ),
222 // Built after acquireServerOwnership; layerCliConfig would contend with this process's own lock.
223 Layer.provideMerge(SqlitePersistence.layerConfig),
224 );
225
226const PROJECT_CLI_LIVE_SERVER_PROBE_TIMEOUT = Duration.seconds(1);
227const PROJECT_CLI_LIVE_SERVER_REQUEST_TIMEOUT = Duration.seconds(10);
228const withProjectCliSessionToken = <A, E, R>(
229 environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"],
230 run: (token: string) => Effect.Effect<A, E, R>,
231) =>
232 Effect.acquireUseRelease(
233 environmentAuth.issueSession({
234 scopes: AuthStandardClientScopes,
235 label: "t3 project cli",
236 }),
237 (issued) => run(issued.token),
238 (issued) => environmentAuth.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),
239 );
240
241const makeLiveServerClient = (origin: string) =>
242 HttpApiClient.make(EnvironmentHttpApi, {
243 baseUrl: origin,
244 });
245
246const normalizeWorkspaceRootForProjectCommand = Effect.fn(
247 "normalizeWorkspaceRootForProjectCommand",
248)(function* (workspaceRoot: string) {
249 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
250 return yield* workspacePaths.normalizeWorkspaceRoot(workspaceRoot);
251});
252
253const resolveProjectTitle = Effect.fn("resolveProjectTitle")(function* (
254 workspaceRoot: string,
255 explicitTitle?: string,
256) {
257 if (explicitTitle !== undefined) {
258 const trimmed = explicitTitle.trim();
259 if (trimmed.length > 0) {
260 return trimmed;
261 }
262 return yield* new ProjectTitleEmptyError({
263 operation: "validateProjectTitle",
264 title: explicitTitle,
265 });
266 }
267
268 const path = yield* Path.Path;
269 const basename = path.basename(workspaceRoot).trim();
270 return basename.length > 0 ? basename : "project";
271});
272
273const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (input: {
274 readonly snapshot: ProjectSnapshot;
275 readonly identifier: string;
276}) {
277 const trimmedIdentifier = input.identifier.trim();
278 if (trimmedIdentifier.length === 0) {
279 return yield* new ProjectIdentifierEmptyError({
280 operation: "resolveProjectTarget",
281 identifier: input.identifier,
282 });
283 }
284
285 const activeProjects = input.snapshot.projects.filter((project) => project.deletedAt === null);
286 const exactIdMatch = activeProjects.find((project) => project.id === trimmedIdentifier);
287 if (exactIdMatch) {
288 return {
289 id: exactIdMatch.id,
290 title: exactIdMatch.title,
291 workspaceRoot: exactIdMatch.workspaceRoot,
292 } satisfies ProjectMutationTarget;
293 }
294
295 const normalizedWorkspaceRootResult = yield* Effect.result(
296 normalizeWorkspaceRootForProjectCommand(trimmedIdentifier),
297 );
298 // A stored workspace path still identifies its project after the directory is gone, so a
299 // relative or trailing-slash path resolves the same way it would while the directory exists.
300 const normalizedWorkspaceRoot =
301 normalizedWorkspaceRootResult._tag === "Success"
302 ? normalizedWorkspaceRootResult.success
303 : normalizedWorkspaceRootResult.failure.normalizedWorkspaceRoot;
304
305 const exactWorkspaceMatch = activeProjects.find(
306 (project) => project.workspaceRoot === normalizedWorkspaceRoot,
307 );
308
309 const resolved = exactWorkspaceMatch;
310 if (!resolved) {
311 return yield* new ProjectNotFoundError({
312 operation: "resolveProjectTarget",
313 identifier: trimmedIdentifier,
314 activeProjectCount: activeProjects.length,
315 normalizedWorkspaceRoot,
316 ...(normalizedWorkspaceRootResult._tag === "Failure"
317 ? { cause: normalizedWorkspaceRootResult.failure }
318 : {}),
319 });
320 }
321
322 return {
323 id: resolved.id,
324 title: resolved.title,
325 workspaceRoot: resolved.workspaceRoot,
326 } satisfies ProjectMutationTarget;
327});
328
329const fetchLiveOrchestrationSnapshot = Effect.fn("project.fetchLiveOrchestrationSnapshot")(
330 function* (origin: string, bearerToken: string, _timeout?: Duration.Duration) {
331 const client = yield* makeLiveServerClient(origin);
332 return yield* client.projects.snapshot({
333 headers: { authorization: `Bearer ${bearerToken}` },
334 });
335 },
336 (effect, _origin, _bearerToken, timeout = PROJECT_CLI_LIVE_SERVER_REQUEST_TIMEOUT) =>
337 effect.pipe(Effect.timeout(timeout), Effect.mapError(projectCommandErrorFromLiveServerRequest)),
338);
339
340const dispatchLiveOrchestrationCommand = Effect.fn("project.dispatchLiveOrchestrationCommand")(
341 function* (origin: string, bearerToken: string, command: ProjectCliDispatchCommand) {
342 const client = yield* makeLiveServerClient(origin);
343 yield* client.projects.mutate({
344 headers: { authorization: `Bearer ${bearerToken}` },
345 payload: command,
346 } as Parameters<typeof client.projects.mutate>[0]);
347 },
348 (effect, _origin, _bearerToken, _command) =>
349 effect.pipe(
350 Effect.timeout(PROJECT_CLI_LIVE_SERVER_REQUEST_TIMEOUT),
351 Effect.mapError(projectCommandErrorFromLiveServerRequest),
352 ),
353);
354
355const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
356 const projects = yield* ProjectService.ProjectService;
357 return yield* projects.snapshot;
358});
359
360const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecutionMode")(
361 function* (
362 environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"],
363 config: ServerConfig.ServerConfig["Service"],
364 ) {
365 const runtimeState = yield* readLiveServerRuntimeState(config.serverRuntimeStatePath);
366 if (Option.isNone(runtimeState)) {
367 return Option.none<{ readonly origin: string }>();
368 }
369
370 const attempt = withProjectCliSessionToken(environmentAuth, (token) =>
371 fetchLiveOrchestrationSnapshot(
372 runtimeState.value.origin,
373 token,
374 PROJECT_CLI_LIVE_SERVER_PROBE_TIMEOUT,
375 ).pipe(
376 Effect.as({
377 origin: runtimeState.value.origin,
378 }),
379 ),
380 );
381
382 const attempted = yield* Effect.result(attempt);
383 if (attempted._tag === "Success") {
384 return Option.some(attempted.success);
385 }
386
387 yield* Effect.logDebug("Failed to connect to the persisted project CLI server.", {
388 origin: runtimeState.value.origin,
389 cause: attempted.failure,
390 });
391 return Option.none<{ readonly origin: string }>();
392 },
393);
394
395const runProjectMutation = Effect.fn("runProjectMutation")(function* (
396 flags: CliAuthLocationFlags,
397 run: (input: {
398 readonly snapshot: ProjectSnapshot;
399 readonly dispatch: (
400 command: ProjectCliDispatchCommand,
401 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
402 readonly mode: ProjectCommandExecutionMode;
403 }) => Effect.Effect<
404 string,
405 Error,
406 | SecureRandom.SecureRandom
407 | FileSystem.FileSystem
408 | HttpClient.HttpClient
409 | Path.Path
410 | WorkspacePaths.WorkspacePaths
411 >,
412) {
413 const logLevel = yield* GlobalFlag.LogLevel;
414 const config = yield* resolveCliAuthConfig(flags, logLevel);
415 const minimumLogLevel = config.logLevel;
416
417 return yield* Effect.gen(function* () {
418 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
419 const liveMode = yield* tryResolveLiveProjectExecutionMode(environmentAuth, config);
420
421 if (Option.isSome(liveMode)) {
422 return yield* withProjectCliSessionToken(environmentAuth, (token) =>
423 Effect.gen(function* () {
424 const snapshot = yield* fetchLiveOrchestrationSnapshot(liveMode.value.origin, token);
425 const output = yield* run({
426 snapshot,
427 dispatch: (command) =>
428 dispatchLiveOrchestrationCommand(liveMode.value.origin, token, command),
429 mode: "live",
430 });
431 yield* Console.log(output);
432 }),
433 );
434 }
435
436 // Before ownership and clearing, so a failed import leaves server state alone.
437 const { layerProjectService } = yield* Effect.promise(
438 () => import("../orchestration-v2/runtimeLayer.ts"),
439 );
440 const layerOfflineRuntime = makeProjectCliRuntimeLayer(layerProjectService).pipe(
441 Layer.provide(ServerConfig.layer(config)),
442 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
443 );
444
445 // An unreachable server may still be running; never write behind it.
446 yield* ServerOwnership.acquireServerOwnership(config.serverRuntimeStatePath).pipe(
447 Effect.provide(ProcessRunner.layer),
448 );
449 yield* clearPersistedServerRuntimeState(config.serverRuntimeStatePath);
450 return yield* Effect.gen(function* () {
451 const snapshot = yield* getOfflineSnapshot();
452 const projects = yield* ProjectService.ProjectService;
453 const output = yield* run({
454 snapshot,
455 dispatch: (command) => projectMutationOperation(projects, command).pipe(Effect.asVoid),
456 mode: "offline",
457 });
458 yield* Console.log(output);
459 }).pipe(Effect.provide(layerOfflineRuntime));
460 }).pipe(
461 Effect.scoped,
462 Effect.provide(
463 Layer.mergeAll(EnvironmentAuth.layerRuntime, WorkspacePaths.layer).pipe(
464 Layer.provideMerge(FetchHttpClient.layer),
465 Layer.provide(ServerConfig.layer(config)),
466 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
467 ),
468 ),
469 );
470});
471
472const projectAddCommand = Command.make("add", {
473 ...projectLocationFlags,
474 workspaceRoot: Argument.String("path").pipe(
475 Argument.withDescription("Workspace root to add as a project."),
476 ),
477 title: Flag.String("title").pipe(Flag.withDescription("Optional project title."), Flag.optional),
478 trackRepos: Flag.Boolean("track-repos").pipe(
479 Flag.withDescription(
480 "Also track the repositories directly inside the path and the folders its .code-workspace file lists.",
481 ),
482 Flag.withDefault(false),
483 ),
484 track: Flag.String("track").pipe(
485 Flag.withDescription("Another folder the project works in. Repeat for more."),
486 Flag.atLeast(0),
487 ),
488}).pipe(
489 Command.withDescription("Add a project."),
490 Command.withHandler((flags) =>
491 runProjectMutation(
492 flags,
493 Effect.fn("projectAddMutation")(function* ({
494 snapshot,
495 dispatch,
496 }: {
497 readonly snapshot: ProjectSnapshot;
498 readonly dispatch: (
499 command: ProjectCliDispatchCommand,
500 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
501 }) {
502 const workspaceRoot = yield* normalizeWorkspaceRootForProjectCommand(flags.workspaceRoot);
503 const existingProject = snapshot.projects.find(
504 (project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot,
505 );
506 if (existingProject) {
507 return yield* new ProjectAlreadyExistsError({
508 operation: "addProject",
509 projectId: existingProject.id,
510 workspaceRoot,
511 });
512 }
513
514 const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));
515 const path = yield* Path.Path;
516 // Scanned here, not by a running server: this command runs on the server's machine.
517 const scanned = flags.trackRepos ? (yield* scanFolders({ workspaceRoot })).folders : [];
518 const named = flags.track.map((folder) => {
519 const resolved = path.resolve(folder);
520 return { path: resolved, name: path.basename(resolved) || resolved };
521 });
522 const trackedFolders = [...named, ...scanned]
523 .filter(
524 (folder, index, all) => all.findIndex((other) => other.path === folder.path) === index,
525 )
526 .slice(0, PROJECT_TRACKED_FOLDERS_MAX)
527 .map((folder) => ({ path: folder.path, name: folder.name }));
528 const projectId = ProjectId.make(yield* projectCommandUuid);
529 yield* dispatch({
530 type: "project.create",
531 commandId: CommandId.make(yield* projectCommandUuid),
532 projectId,
533 title,
534 workspaceRoot,
535 ...(trackedFolders.length === 0 ? {} : { trackedFolders }),
536 });
537 const added = `Added project ${projectId} (${title}) at ${workspaceRoot}.`;
538 if (trackedFolders.length > 0) {
539 return `${added} Tracking ${trackedFolders.length} other ${trackedFolders.length === 1 ? "folder" : "folders"}.`;
540 }
541 return flags.trackRepos ? `${added} Found no other folders to track.` : added;
542 }),
543 ),
544 ),
545);
546
547const projectRemoveCommand = Command.make("remove", {
548 ...projectLocationFlags,
549 project: Argument.String("project").pipe(
550 Argument.withDescription("Project id or workspace root to remove."),
551 ),
552 force: Flag.Boolean("force").pipe(
553 Flag.withDescription("Delete the project and all of its threads."),
554 Flag.withDefault(false),
555 ),
556}).pipe(
557 Command.withDescription("Remove a project."),
558 Command.withHandler((flags) =>
559 runProjectMutation(
560 flags,
561 Effect.fn("projectRemoveMutation")(function* ({
562 snapshot,
563 dispatch,
564 }: {
565 readonly snapshot: ProjectSnapshot;
566 readonly dispatch: (
567 command: ProjectCliDispatchCommand,
568 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
569 }) {
570 const project = yield* findActiveProjectTarget({
571 snapshot,
572 identifier: flags.project,
573 });
574 yield* dispatch({
575 type: "project.delete",
576 commandId: CommandId.make(yield* projectCommandUuid),
577 projectId: project.id,
578 force: flags.force,
579 });
580 return `Removed project ${project.id} (${project.title}).`;
581 }),
582 ),
583 ),
584);
585
586const projectRenameCommand = Command.make("rename", {
587 ...projectLocationFlags,
588 project: Argument.String("project").pipe(
589 Argument.withDescription("Project id or workspace root to rename."),
590 ),
591 title: Argument.String("title").pipe(Argument.withDescription("New project title.")),
592}).pipe(
593 Command.withDescription("Rename a project."),
594 Command.withHandler((flags) =>
595 runProjectMutation(
596 flags,
597 Effect.fn("projectRenameMutation")(function* ({
598 snapshot,
599 dispatch,
600 }: {
601 readonly snapshot: ProjectSnapshot;
602 readonly dispatch: (
603 command: ProjectCliDispatchCommand,
604 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
605 }) {
606 const project = yield* findActiveProjectTarget({
607 snapshot,
608 identifier: flags.project,
609 });
610 const nextTitle = yield* resolveProjectTitle(project.workspaceRoot, flags.title);
611 if (nextTitle === project.title) {
612 return `Project ${project.id} is already named ${nextTitle}.`;
613 }
614
615 yield* dispatch({
616 type: "project.update",
617 commandId: CommandId.make(yield* projectCommandUuid),
618 projectId: project.id,
619 title: nextTitle,
620 });
621 return `Renamed project ${project.id} to ${nextTitle}.`;
622 }),
623 ),
624 ),
625);
626
627export const projectCommand = Command.make("project").pipe(
628 Command.withDescription("Manage projects."),
629 Command.withSubcommands([projectAddCommand, projectRemoveCommand, projectRenameCommand]),
630);