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