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