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