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 SecureRandom from "effect/crypto/SecureRandom";
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 type * 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 readLiveServerRuntimeState,
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 = SecureRandom.SecureRandom.pipe(
194 Effect.flatMap((random) => random.uuidV4()),
195 Effect.mapError(
196 (cause) =>
197 new ProjectCommandIdGenerationError({
198 operation: "generateProjectCommandId",
199 cause,
200 }),
201 ),
202);
203
204const makeProjectCliRuntimeLayer = (layerProjectService: typeof RuntimeLayer.layerProjectService) =>
205 layerProjectService.pipe(
206 Layer.provideMerge(ProjectEnrichmentService.layer),
207 Layer.provideMerge(RepositoryIdentityResolver.layer),
208 Layer.provideMerge(
209 ProjectFaviconResolver.layer.pipe(
210 Layer.provide(WorkspacePaths.layer),
211 Layer.provide(T3ProjectFileLoader.layer),
212 ),
213 ),
214 Layer.provideMerge(WorkspacePaths.layer),
215 Layer.provideMerge(
216 ServerSettings.layer.pipe(
217 Layer.provide(Layer.merge(ServerSecretStore.layer, ManagedPolicy.layer)),
218 ),
219 ),
220 // Built after acquireServerOwnership; layerCliConfig would contend with this process's own lock.
221 Layer.provideMerge(SqlitePersistence.layerConfig),
222 );
223
224const PROJECT_CLI_LIVE_SERVER_PROBE_TIMEOUT = Duration.seconds(1);
225const PROJECT_CLI_LIVE_SERVER_REQUEST_TIMEOUT = Duration.seconds(10);
226const withProjectCliSessionToken = <A, E, R>(
227 environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"],
228 run: (token: string) => Effect.Effect<A, E, R>,
229) =>
230 Effect.acquireUseRelease(
231 environmentAuth.issueSession({
232 scopes: AuthStandardClientScopes,
233 label: "t3 project cli",
234 }),
235 (issued) => run(issued.token),
236 (issued) => environmentAuth.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),
237 );
238
239const makeLiveServerClient = (origin: string) =>
240 HttpApiClient.make(EnvironmentHttpApi, {
241 baseUrl: origin,
242 });
243
244const normalizeWorkspaceRootForProjectCommand = Effect.fn(
245 "normalizeWorkspaceRootForProjectCommand",
246)(function* (workspaceRoot: string) {
247 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
248 return yield* workspacePaths.normalizeWorkspaceRoot(workspaceRoot);
249});
250
251const resolveProjectTitle = Effect.fn("resolveProjectTitle")(function* (
252 workspaceRoot: string,
253 explicitTitle?: string,
254) {
255 if (explicitTitle !== undefined) {
256 const trimmed = explicitTitle.trim();
257 if (trimmed.length > 0) {
258 return trimmed;
259 }
260 return yield* new ProjectTitleEmptyError({
261 operation: "validateProjectTitle",
262 title: explicitTitle,
263 });
264 }
265
266 const path = yield* Path.Path;
267 const basename = path.basename(workspaceRoot).trim();
268 return basename.length > 0 ? basename : "project";
269});
270
271const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (input: {
272 readonly snapshot: ProjectSnapshot;
273 readonly identifier: string;
274}) {
275 const trimmedIdentifier = input.identifier.trim();
276 if (trimmedIdentifier.length === 0) {
277 return yield* new ProjectIdentifierEmptyError({
278 operation: "resolveProjectTarget",
279 identifier: input.identifier,
280 });
281 }
282
283 const activeProjects = input.snapshot.projects.filter((project) => project.deletedAt === null);
284 const exactIdMatch = activeProjects.find((project) => project.id === trimmedIdentifier);
285 if (exactIdMatch) {
286 return {
287 id: exactIdMatch.id,
288 title: exactIdMatch.title,
289 workspaceRoot: exactIdMatch.workspaceRoot,
290 } satisfies ProjectMutationTarget;
291 }
292
293 const normalizedWorkspaceRootResult = yield* Effect.result(
294 normalizeWorkspaceRootForProjectCommand(trimmedIdentifier),
295 );
296 // A stored workspace path still identifies its project after the directory is gone, so a
297 // relative or trailing-slash path resolves the same way it would while the directory exists.
298 const normalizedWorkspaceRoot =
299 normalizedWorkspaceRootResult._tag === "Success"
300 ? normalizedWorkspaceRootResult.success
301 : normalizedWorkspaceRootResult.failure.normalizedWorkspaceRoot;
302
303 const exactWorkspaceMatch = activeProjects.find(
304 (project) => project.workspaceRoot === normalizedWorkspaceRoot,
305 );
306
307 const resolved = exactWorkspaceMatch;
308 if (!resolved) {
309 return yield* new ProjectNotFoundError({
310 operation: "resolveProjectTarget",
311 identifier: trimmedIdentifier,
312 activeProjectCount: activeProjects.length,
313 normalizedWorkspaceRoot,
314 ...(normalizedWorkspaceRootResult._tag === "Failure"
315 ? { cause: normalizedWorkspaceRootResult.failure }
316 : {}),
317 });
318 }
319
320 return {
321 id: resolved.id,
322 title: resolved.title,
323 workspaceRoot: resolved.workspaceRoot,
324 } satisfies ProjectMutationTarget;
325});
326
327const fetchLiveOrchestrationSnapshot = Effect.fn("project.fetchLiveOrchestrationSnapshot")(
328 function* (origin: string, bearerToken: string, _timeout?: Duration.Duration) {
329 const client = yield* makeLiveServerClient(origin);
330 return yield* client.projects.snapshot({
331 headers: { authorization: `Bearer ${bearerToken}` },
332 });
333 },
334 (effect, _origin, _bearerToken, timeout = PROJECT_CLI_LIVE_SERVER_REQUEST_TIMEOUT) =>
335 effect.pipe(Effect.timeout(timeout), Effect.mapError(projectCommandErrorFromLiveServerRequest)),
336);
337
338const dispatchLiveOrchestrationCommand = Effect.fn("project.dispatchLiveOrchestrationCommand")(
339 function* (origin: string, bearerToken: string, command: ProjectCliDispatchCommand) {
340 const client = yield* makeLiveServerClient(origin);
341 yield* client.projects.mutate({
342 headers: { authorization: `Bearer ${bearerToken}` },
343 payload: command,
344 } as Parameters<typeof client.projects.mutate>[0]);
345 },
346 (effect, _origin, _bearerToken, _command) =>
347 effect.pipe(
348 Effect.timeout(PROJECT_CLI_LIVE_SERVER_REQUEST_TIMEOUT),
349 Effect.mapError(projectCommandErrorFromLiveServerRequest),
350 ),
351);
352
353const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
354 const projects = yield* ProjectService.ProjectService;
355 return yield* projects.snapshot;
356});
357
358const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecutionMode")(
359 function* (
360 environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"],
361 config: ServerConfig.ServerConfig["Service"],
362 ) {
363 const runtimeState = yield* readLiveServerRuntimeState(config.serverRuntimeStatePath);
364 if (Option.isNone(runtimeState)) {
365 return Option.none<{ readonly origin: string }>();
366 }
367
368 const attempt = withProjectCliSessionToken(environmentAuth, (token) =>
369 fetchLiveOrchestrationSnapshot(
370 runtimeState.value.origin,
371 token,
372 PROJECT_CLI_LIVE_SERVER_PROBE_TIMEOUT,
373 ).pipe(
374 Effect.as({
375 origin: runtimeState.value.origin,
376 }),
377 ),
378 );
379
380 const attempted = yield* Effect.result(attempt);
381 if (attempted._tag === "Success") {
382 return Option.some(attempted.success);
383 }
384
385 yield* Effect.logDebug("Failed to connect to the persisted project CLI server.", {
386 origin: runtimeState.value.origin,
387 cause: attempted.failure,
388 });
389 return Option.none<{ readonly origin: string }>();
390 },
391);
392
393const runProjectMutation = Effect.fn("runProjectMutation")(function* (
394 flags: CliAuthLocationFlags,
395 run: (input: {
396 readonly snapshot: ProjectSnapshot;
397 readonly dispatch: (
398 command: ProjectCliDispatchCommand,
399 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
400 readonly mode: ProjectCommandExecutionMode;
401 }) => Effect.Effect<
402 string,
403 Error,
404 | SecureRandom.SecureRandom
405 | FileSystem.FileSystem
406 | HttpClient.HttpClient
407 | Path.Path
408 | WorkspacePaths.WorkspacePaths
409 >,
410) {
411 const logLevel = yield* GlobalFlag.LogLevel;
412 const config = yield* resolveCliAuthConfig(flags, logLevel);
413 const minimumLogLevel = config.logLevel;
414
415 return yield* Effect.gen(function* () {
416 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
417 const liveMode = yield* tryResolveLiveProjectExecutionMode(environmentAuth, config);
418
419 if (Option.isSome(liveMode)) {
420 return yield* withProjectCliSessionToken(environmentAuth, (token) =>
421 Effect.gen(function* () {
422 const snapshot = yield* fetchLiveOrchestrationSnapshot(liveMode.value.origin, token);
423 const output = yield* run({
424 snapshot,
425 dispatch: (command) =>
426 dispatchLiveOrchestrationCommand(liveMode.value.origin, token, command),
427 mode: "live",
428 });
429 yield* Console.log(output);
430 }),
431 );
432 }
433
434 // Before ownership and clearing, so a failed import leaves server state alone.
435 const { layerProjectService } = yield* Effect.promise(
436 () => import("../orchestration-v2/runtimeLayer.ts"),
437 );
438 const layerOfflineRuntime = makeProjectCliRuntimeLayer(layerProjectService).pipe(
439 Layer.provide(ServerConfig.layer(config)),
440 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
441 );
442
443 // An unreachable server may still be running; never write behind it.
444 yield* ServerOwnership.acquireServerOwnership(config.serverRuntimeStatePath).pipe(
445 Effect.provide(ProcessRunner.layer),
446 );
447 yield* clearPersistedServerRuntimeState(config.serverRuntimeStatePath);
448 return yield* Effect.gen(function* () {
449 const snapshot = yield* getOfflineSnapshot();
450 const projects = yield* ProjectService.ProjectService;
451 const output = yield* run({
452 snapshot,
453 dispatch: (command) => projectMutationOperation(projects, command).pipe(Effect.asVoid),
454 mode: "offline",
455 });
456 yield* Console.log(output);
457 }).pipe(Effect.provide(layerOfflineRuntime));
458 }).pipe(
459 Effect.scoped,
460 Effect.provide(
461 Layer.mergeAll(EnvironmentAuth.layerRuntime, WorkspacePaths.layer).pipe(
462 Layer.provideMerge(FetchHttpClient.layer),
463 Layer.provide(ServerConfig.layer(config)),
464 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
465 ),
466 ),
467 );
468});
469
470const projectAddCommand = Command.make("add", {
471 ...projectLocationFlags,
472 workspaceRoot: Argument.String("path").pipe(
473 Argument.withDescription("Workspace root to add as a project."),
474 ),
475 title: Flag.String("title").pipe(Flag.withDescription("Optional project title."), Flag.optional),
476}).pipe(
477 Command.withDescription("Add a project."),
478 Command.withHandler((flags) =>
479 runProjectMutation(
480 flags,
481 Effect.fn("projectAddMutation")(function* ({
482 snapshot,
483 dispatch,
484 }: {
485 readonly snapshot: ProjectSnapshot;
486 readonly dispatch: (
487 command: ProjectCliDispatchCommand,
488 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
489 }) {
490 const workspaceRoot = yield* normalizeWorkspaceRootForProjectCommand(flags.workspaceRoot);
491 const existingProject = snapshot.projects.find(
492 (project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot,
493 );
494 if (existingProject) {
495 return yield* new ProjectAlreadyExistsError({
496 operation: "addProject",
497 projectId: existingProject.id,
498 workspaceRoot,
499 });
500 }
501
502 const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));
503 const projectId = ProjectId.make(yield* projectCommandUuid);
504 yield* dispatch({
505 type: "project.create",
506 commandId: CommandId.make(yield* projectCommandUuid),
507 projectId,
508 title,
509 workspaceRoot,
510 });
511 return `Added project ${projectId} (${title}) at ${workspaceRoot}.`;
512 }),
513 ),
514 ),
515);
516
517const projectRemoveCommand = Command.make("remove", {
518 ...projectLocationFlags,
519 project: Argument.String("project").pipe(
520 Argument.withDescription("Project id or workspace root to remove."),
521 ),
522 force: Flag.Boolean("force").pipe(
523 Flag.withDescription("Delete the project and all of its threads."),
524 Flag.withDefault(false),
525 ),
526}).pipe(
527 Command.withDescription("Remove a project."),
528 Command.withHandler((flags) =>
529 runProjectMutation(
530 flags,
531 Effect.fn("projectRemoveMutation")(function* ({
532 snapshot,
533 dispatch,
534 }: {
535 readonly snapshot: ProjectSnapshot;
536 readonly dispatch: (
537 command: ProjectCliDispatchCommand,
538 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
539 }) {
540 const project = yield* findActiveProjectTarget({
541 snapshot,
542 identifier: flags.project,
543 });
544 yield* dispatch({
545 type: "project.delete",
546 commandId: CommandId.make(yield* projectCommandUuid),
547 projectId: project.id,
548 force: flags.force,
549 });
550 return `Removed project ${project.id} (${project.title}).`;
551 }),
552 ),
553 ),
554);
555
556const projectRenameCommand = Command.make("rename", {
557 ...projectLocationFlags,
558 project: Argument.String("project").pipe(
559 Argument.withDescription("Project id or workspace root to rename."),
560 ),
561 title: Argument.String("title").pipe(Argument.withDescription("New project title.")),
562}).pipe(
563 Command.withDescription("Rename a project."),
564 Command.withHandler((flags) =>
565 runProjectMutation(
566 flags,
567 Effect.fn("projectRenameMutation")(function* ({
568 snapshot,
569 dispatch,
570 }: {
571 readonly snapshot: ProjectSnapshot;
572 readonly dispatch: (
573 command: ProjectCliDispatchCommand,
574 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
575 }) {
576 const project = yield* findActiveProjectTarget({
577 snapshot,
578 identifier: flags.project,
579 });
580 const nextTitle = yield* resolveProjectTitle(project.workspaceRoot, flags.title);
581 if (nextTitle === project.title) {
582 return `Project ${project.id} is already named ${nextTitle}.`;
583 }
584
585 yield* dispatch({
586 type: "project.update",
587 commandId: CommandId.make(yield* projectCommandUuid),
588 projectId: project.id,
589 title: nextTitle,
590 });
591 return `Renamed project ${project.id} to ${nextTitle}.`;
592 }),
593 ),
594 ),
595);
596
597export const projectCommand = Command.make("project").pipe(
598 Command.withDescription("Manage projects."),
599 Command.withSubcommands([projectAddCommand, projectRemoveCommand, projectRenameCommand]),
600);