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