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 return Option.none<{ readonly origin: string }>();
379 },
380);
381
382const runProjectMutation = Effect.fn("runProjectMutation")(function* (
383 flags: CliAuthLocationFlags,
384 run: (input: {
385 readonly snapshot: ProjectSnapshot;
386 readonly dispatch: (
387 command: ProjectCliDispatchCommand,
388 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
389 readonly mode: ProjectCommandExecutionMode;
390 }) => Effect.Effect<
391 string,
392 Error,
393 | Crypto.Crypto
394 | FileSystem.FileSystem
395 | HttpClient.HttpClient
396 | Path.Path
397 | WorkspacePaths.WorkspacePaths
398 >,
399) {
400 const logLevel = yield* GlobalFlag.LogLevel;
401 const config = yield* resolveCliAuthConfig(flags, logLevel);
402 const minimumLogLevel = config.logLevel;
403
404 return yield* Effect.gen(function* () {
405 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
406 const liveMode = yield* tryResolveLiveProjectExecutionMode(environmentAuth, config);
407
408 if (Option.isSome(liveMode)) {
409 return yield* withProjectCliSessionToken(environmentAuth, (token) =>
410 Effect.gen(function* () {
411 const snapshot = yield* fetchLiveOrchestrationSnapshot(liveMode.value.origin, token);
412 const output = yield* run({
413 snapshot,
414 dispatch: (command) =>
415 dispatchLiveOrchestrationCommand(liveMode.value.origin, token, command),
416 mode: "live",
417 });
418 yield* Console.log(output);
419 }),
420 );
421 }
422
423 const layerOfflineRuntime = layerProjectCliRuntime.pipe(
424 Layer.provide(ServerConfig.layer(config)),
425 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
426 );
427
428 // An unreachable server may still be running; never write behind it.
429 yield* ServerOwnership.acquireServerOwnership(config.serverRuntimeStatePath).pipe(
430 Effect.provide(ProcessRunner.layer),
431 );
432 yield* clearPersistedServerRuntimeState(config.serverRuntimeStatePath);
433 return yield* Effect.gen(function* () {
434 const snapshot = yield* getOfflineSnapshot();
435 const projects = yield* ProjectService.ProjectService;
436 const output = yield* run({
437 snapshot,
438 dispatch: (command) => projectMutationOperation(projects, command).pipe(Effect.asVoid),
439 mode: "offline",
440 });
441 yield* Console.log(output);
442 }).pipe(Effect.provide(layerOfflineRuntime));
443 }).pipe(
444 Effect.scoped,
445 Effect.provide(
446 Layer.mergeAll(EnvironmentAuth.layerRuntime, WorkspacePaths.layer).pipe(
447 Layer.provideMerge(FetchHttpClient.layer),
448 Layer.provide(ServerConfig.layer(config)),
449 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
450 ),
451 ),
452 );
453});
454
455const projectAddCommand = Command.make("add", {
456 ...projectLocationFlags,
457 workspaceRoot: Argument.String("path").pipe(
458 Argument.withDescription("Workspace root to add as a project."),
459 ),
460 title: Flag.String("title").pipe(Flag.withDescription("Optional project title."), Flag.optional),
461}).pipe(
462 Command.withDescription("Add a project."),
463 Command.withHandler((flags) =>
464 runProjectMutation(
465 flags,
466 Effect.fn("projectAddMutation")(function* ({
467 snapshot,
468 dispatch,
469 }: {
470 readonly snapshot: ProjectSnapshot;
471 readonly dispatch: (
472 command: ProjectCliDispatchCommand,
473 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
474 }) {
475 const workspaceRoot = yield* normalizeWorkspaceRootForProjectCommand(flags.workspaceRoot);
476 const existingProject = snapshot.projects.find(
477 (project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot,
478 );
479 if (existingProject) {
480 return yield* new ProjectAlreadyExistsError({
481 operation: "addProject",
482 projectId: existingProject.id,
483 workspaceRoot,
484 });
485 }
486
487 const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));
488 const projectId = ProjectId.make(yield* projectCommandUuid);
489 yield* dispatch({
490 type: "project.create",
491 commandId: CommandId.make(yield* projectCommandUuid),
492 projectId,
493 title,
494 workspaceRoot,
495 });
496 return `Added project ${projectId} (${title}) at ${workspaceRoot}.`;
497 }),
498 ),
499 ),
500);
501
502const projectRemoveCommand = Command.make("remove", {
503 ...projectLocationFlags,
504 project: Argument.String("project").pipe(
505 Argument.withDescription("Project id or workspace root to remove."),
506 ),
507 force: Flag.Boolean("force").pipe(
508 Flag.withDescription("Delete the project and all of its threads."),
509 Flag.withDefault(false),
510 ),
511}).pipe(
512 Command.withDescription("Remove a project."),
513 Command.withHandler((flags) =>
514 runProjectMutation(
515 flags,
516 Effect.fn("projectRemoveMutation")(function* ({
517 snapshot,
518 dispatch,
519 }: {
520 readonly snapshot: ProjectSnapshot;
521 readonly dispatch: (
522 command: ProjectCliDispatchCommand,
523 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
524 }) {
525 const project = yield* findActiveProjectTarget({
526 snapshot,
527 identifier: flags.project,
528 });
529 yield* dispatch({
530 type: "project.delete",
531 commandId: CommandId.make(yield* projectCommandUuid),
532 projectId: project.id,
533 force: flags.force,
534 });
535 return `Removed project ${project.id} (${project.title}).`;
536 }),
537 ),
538 ),
539);
540
541const projectRenameCommand = Command.make("rename", {
542 ...projectLocationFlags,
543 project: Argument.String("project").pipe(
544 Argument.withDescription("Project id or workspace root to rename."),
545 ),
546 title: Argument.String("title").pipe(Argument.withDescription("New project title.")),
547}).pipe(
548 Command.withDescription("Rename a project."),
549 Command.withHandler((flags) =>
550 runProjectMutation(
551 flags,
552 Effect.fn("projectRenameMutation")(function* ({
553 snapshot,
554 dispatch,
555 }: {
556 readonly snapshot: ProjectSnapshot;
557 readonly dispatch: (
558 command: ProjectCliDispatchCommand,
559 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
560 }) {
561 const project = yield* findActiveProjectTarget({
562 snapshot,
563 identifier: flags.project,
564 });
565 const nextTitle = yield* resolveProjectTitle(project.workspaceRoot, flags.title);
566 if (nextTitle === project.title) {
567 return `Project ${project.id} is already named ${nextTitle}.`;
568 }
569
570 yield* dispatch({
571 type: "project.update",
572 commandId: CommandId.make(yield* projectCommandUuid),
573 projectId: project.id,
574 title: nextTitle,
575 });
576 return `Renamed project ${project.id} to ${nextTitle}.`;
577 }),
578 ),
579 ),
580);
581
582export const projectCommand = Command.make("project").pipe(
583 Command.withDescription("Manage projects."),
584 Command.withSubcommands([projectAddCommand, projectRemoveCommand, projectRenameCommand]),
585);