Open History to see the last commit
1import {
2 AuthAdministrativeScopes,
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: AuthAdministrativeScopes,
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 = (origin: string, bearerToken: string) =>
320 Effect.gen(function* () {
321 const client = yield* makeLiveServerClient(origin);
322 return yield* client.projects.snapshot({
323 headers: { authorization: `Bearer ${bearerToken}` },
324 });
325 }).pipe(
326 withProjectCliLiveServerTimeout,
327 Effect.mapError(projectCommandErrorFromLiveServerRequest),
328 );
329
330const dispatchLiveOrchestrationCommand = (
331 origin: string,
332 bearerToken: string,
333 command: ProjectCliDispatchCommand,
334) =>
335 Effect.gen(function* () {
336 const client = yield* makeLiveServerClient(origin);
337 yield* client.projects.mutate({
338 headers: { authorization: `Bearer ${bearerToken}` },
339 payload: command,
340 } as Parameters<typeof client.projects.mutate>[0]);
341 }).pipe(
342 withProjectCliLiveServerTimeout,
343 Effect.mapError(projectCommandErrorFromLiveServerRequest),
344 );
345
346const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
347 const projects = yield* ProjectService.ProjectService;
348 return yield* projects.snapshot;
349});
350
351const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecutionMode")(
352 function* (
353 environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"],
354 config: ServerConfig.ServerConfig["Service"],
355 ) {
356 const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
357 if (Option.isNone(runtimeState)) {
358 return Option.none<{ readonly origin: string }>();
359 }
360
361 const attempt = withProjectCliSessionToken(environmentAuth, (token) =>
362 fetchLiveOrchestrationSnapshot(runtimeState.value.origin, token).pipe(
363 Effect.as({
364 origin: runtimeState.value.origin,
365 }),
366 ),
367 );
368
369 const attempted = yield* Effect.result(attempt);
370 if (attempted._tag === "Success") {
371 return Option.some(attempted.success);
372 }
373
374 yield* Effect.logDebug("Failed to connect to the persisted project CLI server.", {
375 origin: runtimeState.value.origin,
376 cause: attempted.failure,
377 });
378 // The offline path decides whether that server still owns the home.
379 return Option.none<{ readonly origin: string }>();
380 },
381);
382
383const runProjectMutation = Effect.fn("runProjectMutation")(function* (
384 flags: CliAuthLocationFlags,
385 run: (input: {
386 readonly snapshot: ProjectSnapshot;
387 readonly dispatch: (
388 command: ProjectCliDispatchCommand,
389 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
390 readonly mode: ProjectCommandExecutionMode;
391 }) => Effect.Effect<
392 string,
393 Error,
394 | Crypto.Crypto
395 | FileSystem.FileSystem
396 | HttpClient.HttpClient
397 | Path.Path
398 | WorkspacePaths.WorkspacePaths
399 >,
400) {
401 const logLevel = yield* GlobalFlag.LogLevel;
402 const config = yield* resolveCliAuthConfig(flags, logLevel);
403 const minimumLogLevel = config.logLevel;
404
405 return yield* Effect.gen(function* () {
406 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
407 const liveMode = yield* tryResolveLiveProjectExecutionMode(environmentAuth, config);
408
409 if (Option.isSome(liveMode)) {
410 return yield* withProjectCliSessionToken(environmentAuth, (token) =>
411 Effect.gen(function* () {
412 const snapshot = yield* fetchLiveOrchestrationSnapshot(liveMode.value.origin, token);
413 const output = yield* run({
414 snapshot,
415 dispatch: (command) =>
416 dispatchLiveOrchestrationCommand(liveMode.value.origin, token, command),
417 mode: "live",
418 });
419 yield* Console.log(output);
420 }),
421 );
422 }
423
424 const layerOfflineRuntime = layerProjectCliRuntime.pipe(
425 Layer.provide(ServerConfig.layer(config)),
426 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
427 );
428
429 // An unreachable server may still be running; never write behind it.
430 yield* ServerOwnership.acquireServerOwnership(config.serverRuntimeStatePath).pipe(
431 Effect.provide(ProcessRunner.layer),
432 );
433 yield* clearPersistedServerRuntimeState(config.serverRuntimeStatePath);
434 return yield* Effect.gen(function* () {
435 const snapshot = yield* getOfflineSnapshot();
436 const projects = yield* ProjectService.ProjectService;
437 const output = yield* run({
438 snapshot,
439 dispatch: (command) => projectMutationOperation(projects, command).pipe(Effect.asVoid),
440 mode: "offline",
441 });
442 yield* Console.log(output);
443 }).pipe(Effect.provide(layerOfflineRuntime));
444 }).pipe(
445 Effect.scoped,
446 Effect.provide(
447 Layer.mergeAll(EnvironmentAuth.layerRuntime, WorkspacePaths.layer).pipe(
448 Layer.provideMerge(FetchHttpClient.layer),
449 Layer.provide(ServerConfig.layer(config)),
450 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
451 ),
452 ),
453 );
454});
455
456const projectAddCommand = Command.make("add", {
457 ...projectLocationFlags,
458 workspaceRoot: Argument.String("path").pipe(
459 Argument.withDescription("Workspace root to add as a project."),
460 ),
461 title: Flag.String("title").pipe(Flag.withDescription("Optional project title."), Flag.optional),
462}).pipe(
463 Command.withDescription("Add a project."),
464 Command.withHandler((flags) =>
465 runProjectMutation(
466 flags,
467 Effect.fn("projectAddMutation")(function* ({
468 snapshot,
469 dispatch,
470 }: {
471 readonly snapshot: ProjectSnapshot;
472 readonly dispatch: (
473 command: ProjectCliDispatchCommand,
474 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
475 }) {
476 const workspaceRoot = yield* normalizeWorkspaceRootForProjectCommand(flags.workspaceRoot);
477 const existingProject = snapshot.projects.find(
478 (project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot,
479 );
480 if (existingProject) {
481 return yield* new ProjectAlreadyExistsError({
482 operation: "addProject",
483 projectId: existingProject.id,
484 workspaceRoot,
485 });
486 }
487
488 const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));
489 const projectId = ProjectId.make(yield* projectCommandUuid);
490 yield* dispatch({
491 type: "project.create",
492 commandId: CommandId.make(yield* projectCommandUuid),
493 projectId,
494 title,
495 workspaceRoot,
496 });
497 return `Added project ${projectId} (${title}) at ${workspaceRoot}.`;
498 }),
499 ),
500 ),
501);
502
503const projectRemoveCommand = Command.make("remove", {
504 ...projectLocationFlags,
505 project: Argument.String("project").pipe(
506 Argument.withDescription("Project id or workspace root to remove."),
507 ),
508 force: Flag.Boolean("force").pipe(
509 Flag.withDescription("Delete the project and all of its threads."),
510 Flag.withDefault(false),
511 ),
512}).pipe(
513 Command.withDescription("Remove a project."),
514 Command.withHandler((flags) =>
515 runProjectMutation(
516 flags,
517 Effect.fn("projectRemoveMutation")(function* ({
518 snapshot,
519 dispatch,
520 }: {
521 readonly snapshot: ProjectSnapshot;
522 readonly dispatch: (
523 command: ProjectCliDispatchCommand,
524 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
525 }) {
526 const project = yield* findActiveProjectTarget({
527 snapshot,
528 identifier: flags.project,
529 });
530 yield* dispatch({
531 type: "project.delete",
532 commandId: CommandId.make(yield* projectCommandUuid),
533 projectId: project.id,
534 force: flags.force,
535 });
536 return `Removed project ${project.id} (${project.title}).`;
537 }),
538 ),
539 ),
540);
541
542const projectRenameCommand = Command.make("rename", {
543 ...projectLocationFlags,
544 project: Argument.String("project").pipe(
545 Argument.withDescription("Project id or workspace root to rename."),
546 ),
547 title: Argument.String("title").pipe(Argument.withDescription("New project title.")),
548}).pipe(
549 Command.withDescription("Rename a project."),
550 Command.withHandler((flags) =>
551 runProjectMutation(
552 flags,
553 Effect.fn("projectRenameMutation")(function* ({
554 snapshot,
555 dispatch,
556 }: {
557 readonly snapshot: ProjectSnapshot;
558 readonly dispatch: (
559 command: ProjectCliDispatchCommand,
560 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
561 }) {
562 const project = yield* findActiveProjectTarget({
563 snapshot,
564 identifier: flags.project,
565 });
566 const nextTitle = yield* resolveProjectTitle(project.workspaceRoot, flags.title);
567 if (nextTitle === project.title) {
568 return `Project ${project.id} is already named ${nextTitle}.`;
569 }
570
571 yield* dispatch({
572 type: "project.update",
573 commandId: CommandId.make(yield* projectCommandUuid),
574 projectId: project.id,
575 title: nextTitle,
576 });
577 return `Renamed project ${project.id} to ${nextTitle}.`;
578 }),
579 ),
580 ),
581);
582
583export const projectCommand = Command.make("project").pipe(
584 Command.withDescription("Manage projects."),
585 Command.withSubcommands([projectAddCommand, projectRemoveCommand, projectRenameCommand]),
586);