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