Open History to see the last commit
1import {
2 AuthStandardClientScopes,
3 CommandId,
4 EnvironmentHttpCommonError,
5 PROJECT_TRACKED_FOLDERS_MAX,
6 type ProjectMutation,
7 type ProjectSnapshot,
8 ProjectId,
9} from "@t3tools/contracts";
10import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
11import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations";
12import * as HostProcess from "@t3tools/shared/HostProcess";
13import * as Console from "effect/Console";
14import * as SecureRandom from "effect/crypto/SecureRandom";
15import * as Effect from "effect/Effect";
16import * as FileSystem from "effect/FileSystem";
17import * as Layer from "effect/Layer";
18import * as Option from "effect/Option";
19import * as Path from "effect/Path";
20import * as References from "effect/References";
21import * as Schema from "effect/Schema";
22import { Argument, Command, Flag, GlobalFlag } from "effect/cli";
23import { FetchHttpClient, HttpClient, HttpClientError } from "effect/http";
24
25import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
26import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
27
28import * as ServerConfig from "../config.ts";
29import * as SqlitePersistence from "../persistence/Sqlite.ts";
30import type * as RuntimeLayer from "../orchestration-v2/runtimeLayer.ts";
31import * as ProjectEnrichmentService from "../project/ProjectEnrichmentService.ts";
32import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
33import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
34import * as ProjectService from "../project/ProjectService.ts";
35import { projectMutationOperation } from "../project/ProjectMutation.ts";
36import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
37import * as ServerSettings from "../serverSettings.ts";
38import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
39import { discoverFolders, mergeProjectFolders } from "../workspace/WorkspaceFolders.ts";
40import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
41import { type CliAuthLocationFlags, projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
42import * as RunningServer from "./runningServer.ts";
43
44type ProjectMutationTarget = {
45 readonly id: ProjectId;
46 readonly title: string;
47 readonly workspaceRoot: string;
48};
49
50type ProjectCliDispatchCommand = ProjectMutation;
51
52const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
53
54export class ProjectCommandIdGenerationError extends Schema.TaggedError<ProjectCommandIdGenerationError>()(
55 "ProjectCommandIdGenerationError",
56 {
57 operation: Schema.Literal("generateProjectCommandId"),
58 cause: Schema.Defect(),
59 },
60) {
61 override get message(): string {
62 return "Failed to generate a project command identifier.";
63 }
64}
65
66export class ProjectLiveServerDeclaredResponseError extends Schema.TaggedError<ProjectLiveServerDeclaredResponseError>()(
67 "ProjectLiveServerDeclaredResponseError",
68 {
69 operation: Schema.Literal("callLiveServer"),
70 code: Schema.String,
71 traceId: Schema.String,
72 cause: Schema.Defect(),
73 },
74) {
75 override get message(): string {
76 return `Server request failed (${this.code}, trace ${this.traceId}).`;
77 }
78}
79
80export class ProjectLiveServerUndeclaredStatusError extends Schema.TaggedError<ProjectLiveServerUndeclaredStatusError>()(
81 "ProjectLiveServerUndeclaredStatusError",
82 {
83 operation: Schema.Literal("callLiveServer"),
84 status: Schema.Int,
85 cause: Schema.Defect(),
86 },
87) {
88 override get message(): string {
89 return `Server request failed with undeclared status ${this.status}.`;
90 }
91}
92
93export class ProjectTitleEmptyError extends Schema.TaggedError<ProjectTitleEmptyError>()(
94 "ProjectTitleEmptyError",
95 {
96 operation: Schema.Literal("validateProjectTitle"),
97 title: Schema.String,
98 },
99) {
100 override get message(): string {
101 return "Project title cannot be empty.";
102 }
103}
104
105export class ProjectIdentifierEmptyError extends Schema.TaggedError<ProjectIdentifierEmptyError>()(
106 "ProjectIdentifierEmptyError",
107 {
108 operation: Schema.Literal("resolveProjectTarget"),
109 identifier: Schema.String,
110 },
111) {
112 override get message(): string {
113 return "Project identifier cannot be empty.";
114 }
115}
116
117export class ProjectNotFoundError extends Schema.TaggedError<ProjectNotFoundError>()(
118 "ProjectNotFoundError",
119 {
120 operation: Schema.Literal("resolveProjectTarget"),
121 identifier: Schema.String,
122 normalizedWorkspaceRoot: Schema.optional(Schema.String),
123 activeProjectCount: Schema.Number,
124 cause: Schema.optional(Schema.Defect()),
125 },
126) {
127 override get message(): string {
128 return `No active project found for '${this.identifier}'.`;
129 }
130}
131
132export class ProjectAlreadyExistsError extends Schema.TaggedError<ProjectAlreadyExistsError>()(
133 "ProjectAlreadyExistsError",
134 {
135 operation: Schema.Literal("addProject"),
136 projectId: ProjectId,
137 workspaceRoot: Schema.String,
138 },
139) {
140 override get message(): string {
141 return `An active project already exists for '${this.workspaceRoot}'.`;
142 }
143}
144
145export class ProjectTooManyTrackedFoldersError extends Schema.TaggedError<ProjectTooManyTrackedFoldersError>()(
146 "ProjectTooManyTrackedFoldersError",
147 {
148 operation: Schema.Literal("addProject"),
149 count: Schema.Number,
150 max: Schema.Number,
151 },
152) {
153 override get message(): string {
154 return `--track names ${this.count} folders, but a project tracks at most ${this.max}.`;
155 }
156}
157
158export class ProjectTrackedFolderEmptyError extends Schema.TaggedError<ProjectTrackedFolderEmptyError>()(
159 "ProjectTrackedFolderEmptyError",
160 { operation: Schema.Literal("addProject") },
161) {
162 override get message(): string {
163 return "--track folder path cannot be empty.";
164 }
165}
166
167export class ProjectPathEmptyError extends Schema.TaggedError<ProjectPathEmptyError>()(
168 "ProjectPathEmptyError",
169 { operation: Schema.Literal("addProject") },
170) {
171 override get message(): string {
172 return "Project path cannot be empty.";
173 }
174}
175
176export const ProjectCommandError = Schema.Union([
177 ProjectCommandIdGenerationError,
178 ProjectLiveServerDeclaredResponseError,
179 ProjectLiveServerUndeclaredStatusError,
180 ProjectTitleEmptyError,
181 ProjectIdentifierEmptyError,
182 ProjectNotFoundError,
183 ProjectAlreadyExistsError,
184 ProjectTooManyTrackedFoldersError,
185 ProjectTrackedFolderEmptyError,
186 ProjectPathEmptyError,
187]);
188export type ProjectCommandError = typeof ProjectCommandError.Type;
189
190/** Names a server's error answer; unanswered requests pass through for `changeState`. */
191function projectCommandErrorFromServerAnswer<E>(cause: E) {
192 if (isEnvironmentHttpCommonError(cause)) {
193 return new ProjectLiveServerDeclaredResponseError({
194 operation: "callLiveServer",
195 code: cause.code,
196 traceId: cause.traceId,
197 cause,
198 });
199 }
200 if (HttpClientError.isHttpClientError(cause) && cause.response !== undefined) {
201 return new ProjectLiveServerUndeclaredStatusError({
202 operation: "callLiveServer",
203 status: cause.response.status,
204 cause,
205 });
206 }
207 return cause;
208}
209
210const projectCommandUuid = SecureRandom.SecureRandom.pipe(
211 Effect.flatMap((random) => random.uuidV4()),
212 Effect.mapError(
213 (cause) =>
214 new ProjectCommandIdGenerationError({
215 operation: "generateProjectCommandId",
216 cause,
217 }),
218 ),
219);
220
221const makeProjectCliRuntimeLayer = (layerProjectService: typeof RuntimeLayer.layerProjectService) =>
222 layerProjectService.pipe(
223 Layer.provideMerge(ProjectEnrichmentService.layer),
224 Layer.provideMerge(RepositoryIdentityResolver.layer),
225 Layer.provideMerge(
226 ProjectFaviconResolver.layer.pipe(
227 Layer.provide(WorkspacePaths.layer),
228 Layer.provide(T3ProjectFileLoader.layer),
229 ),
230 ),
231 Layer.provideMerge(WorkspacePaths.layer),
232 Layer.provideMerge(
233 ServerSettings.layer.pipe(
234 Layer.provide(Layer.merge(ServerSecretStore.layer, ManagedPolicy.layer)),
235 ),
236 ),
237 // Built after acquireServerOwnership; layerCliConfig would contend with this process's own lock.
238 Layer.provideMerge(SqlitePersistence.layerConfig),
239 );
240
241const normalizeWorkspaceRootForProjectCommand = Effect.fn(
242 "normalizeWorkspaceRootForProjectCommand",
243)(function* (workspaceRoot: string) {
244 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
245 if (workspaceRoot !== workspaceRoot.trimStart()) {
246 const path = yield* Path.Path;
247 const home = yield* HostProcess.HomeDirectory;
248 if (path.parse(expandHomePath(workspaceRoot.trim(), home)).root === "") {
249 // Resolving the relative argument first keeps its leading space inside the absolute path.
250 return yield* workspacePaths.normalizeWorkspaceRoot(path.resolve(workspaceRoot.trimEnd()));
251 }
252 }
253 return yield* workspacePaths.normalizeWorkspaceRoot(workspaceRoot);
254});
255
256const resolveProjectTitle = Effect.fn("resolveProjectTitle")(function* (
257 workspaceRoot: string,
258 explicitTitle?: string,
259) {
260 if (explicitTitle !== undefined) {
261 const trimmed = explicitTitle.trim();
262 if (trimmed.length > 0) {
263 return trimmed;
264 }
265 return yield* new ProjectTitleEmptyError({
266 operation: "validateProjectTitle",
267 title: explicitTitle,
268 });
269 }
270
271 const path = yield* Path.Path;
272 const basename = path.basename(workspaceRoot).trim();
273 return basename.length > 0 ? basename : "project";
274});
275
276const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (input: {
277 readonly snapshot: ProjectSnapshot;
278 readonly identifier: string;
279}) {
280 const trimmedIdentifier = input.identifier.trim();
281 if (trimmedIdentifier.length === 0) {
282 return yield* new ProjectIdentifierEmptyError({
283 operation: "resolveProjectTarget",
284 identifier: input.identifier,
285 });
286 }
287
288 const activeProjects = input.snapshot.projects.filter((project) => project.deletedAt === null);
289 const exactIdMatch = activeProjects.find((project) => project.id === trimmedIdentifier);
290 if (exactIdMatch) {
291 return {
292 id: exactIdMatch.id,
293 title: exactIdMatch.title,
294 workspaceRoot: exactIdMatch.workspaceRoot,
295 } satisfies ProjectMutationTarget;
296 }
297
298 const normalizedWorkspaceRootResult = yield* Effect.result(
299 normalizeWorkspaceRootForProjectCommand(input.identifier),
300 );
301 // A stored workspace path still identifies its project after the directory is gone, so a
302 // relative or trailing-slash path resolves the same way it would while the directory exists.
303 const normalizedWorkspaceRoot =
304 normalizedWorkspaceRootResult._tag === "Success"
305 ? normalizedWorkspaceRootResult.success
306 : normalizedWorkspaceRootResult.failure.normalizedWorkspaceRoot;
307
308 const exactWorkspaceMatch = activeProjects.find(
309 (project) => project.workspaceRoot === normalizedWorkspaceRoot,
310 );
311
312 const resolved = exactWorkspaceMatch;
313 if (!resolved) {
314 return yield* new ProjectNotFoundError({
315 operation: "resolveProjectTarget",
316 identifier: trimmedIdentifier,
317 activeProjectCount: activeProjects.length,
318 normalizedWorkspaceRoot,
319 ...(normalizedWorkspaceRootResult._tag === "Failure"
320 ? { cause: normalizedWorkspaceRootResult.failure }
321 : {}),
322 });
323 }
324
325 return {
326 id: resolved.id,
327 title: resolved.title,
328 workspaceRoot: resolved.workspaceRoot,
329 } satisfies ProjectMutationTarget;
330});
331
332const runProjectMutation = Effect.fn("runProjectMutation")(function* (
333 flags: CliAuthLocationFlags,
334 run: (input: {
335 readonly snapshot: ProjectSnapshot;
336 readonly dispatch: (
337 command: ProjectCliDispatchCommand,
338 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
339 }) => Effect.Effect<
340 string,
341 Error,
342 | SecureRandom.SecureRandom
343 | FileSystem.FileSystem
344 | HttpClient.HttpClient
345 | Path.Path
346 | WorkspacePaths.WorkspacePaths
347 >,
348) {
349 const logLevel = yield* GlobalFlag.LogLevel;
350 const config = yield* resolveCliAuthConfig(flags, logLevel);
351 const minimumLogLevel = config.logLevel;
352
353 return yield* Effect.gen(function* () {
354 const output = yield* RunningServer.changeState({
355 scopes: AuthStandardClientScopes,
356 viaServer: Effect.fn("project.viaServer")(function* (client) {
357 return yield* run({
358 snapshot: yield* client.projects.snapshot({ headers: {} }),
359 dispatch: (command) =>
360 client.projects.mutate({ headers: {}, payload: command } as Parameters<
361 typeof client.projects.mutate
362 >[0]),
363 });
364 }, Effect.mapError(projectCommandErrorFromServerAnswer)),
365 locally: Effect.promise(() => import("../orchestration-v2/runtimeLayer.ts")).pipe(
366 Effect.flatMap(({ layerProjectService }) =>
367 Effect.gen(function* () {
368 const projects = yield* ProjectService.ProjectService;
369 return yield* run({
370 snapshot: yield* projects.snapshot,
371 dispatch: (command) =>
372 projectMutationOperation(projects, command).pipe(Effect.asVoid),
373 });
374 }).pipe(
375 Effect.provide(
376 makeProjectCliRuntimeLayer(layerProjectService).pipe(
377 Layer.provide(ServerConfig.layer(config)),
378 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
379 ),
380 ),
381 ),
382 ),
383 ),
384 });
385 yield* Console.log(output);
386 }).pipe(
387 Effect.scoped,
388 Effect.provide(
389 Layer.mergeAll(EnvironmentAuth.layerRuntime, WorkspacePaths.layer).pipe(
390 Layer.provideMerge(FetchHttpClient.layer),
391 Layer.provideMerge(ServerConfig.layer(config)),
392 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
393 ),
394 ),
395 );
396});
397
398const projectAddCommand = Command.make("add", {
399 ...projectLocationFlags,
400 workspaceRoot: Argument.String("path").pipe(
401 Argument.withDescription("Workspace root to add as a project."),
402 ),
403 title: Flag.String("title").pipe(Flag.withDescription("Optional project title."), Flag.optional),
404 track: Flag.String("track").pipe(
405 Flag.withDescription(
406 "A folder outside the path that the project also works in. Repositories inside the path are found on their own. Repeat for more.",
407 ),
408 Flag.atLeast(0),
409 ),
410}).pipe(
411 Command.withDescription("Add a project."),
412 Command.withHandler((flags) => {
413 // path.resolve("") is the current folder, which the user did not name.
414 if (flags.workspaceRoot.trim().length === 0) {
415 return Effect.fail(new ProjectPathEmptyError({ operation: "addProject" }));
416 }
417 if (flags.track.some((folder) => folder.trim().length === 0)) {
418 return Effect.fail(new ProjectTrackedFolderEmptyError({ operation: "addProject" }));
419 }
420 return runProjectMutation(
421 flags,
422 Effect.fn("projectAddMutation")(function* ({
423 snapshot,
424 dispatch,
425 }: {
426 readonly snapshot: ProjectSnapshot;
427 readonly dispatch: (
428 command: ProjectCliDispatchCommand,
429 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
430 }) {
431 const workspaceRoot = yield* normalizeWorkspaceRootForProjectCommand(flags.workspaceRoot);
432 const existingProject = snapshot.projects.find(
433 (project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot,
434 );
435 const path = yield* Path.Path;
436 const home = yield* HostProcess.HomeDirectory;
437 const named = flags.track
438 .map((folder) => {
439 const resolved = path.resolve(expandHomePath(folder, home));
440 const name = (path.basename(resolved) || resolved).trim() || "folder";
441 return {
442 path: resolved,
443 name: name.slice(0, splitsSurrogatePair(name, 128) ? 127 : 128).trim(),
444 };
445 })
446 .filter(
447 (folder, index, all) => all.findIndex((other) => other.path === folder.path) === index,
448 );
449 // Re-adding an archived project's folder restores it, matching the clients.
450 if (existingProject?.archivedAt != null) {
451 const title = Option.isSome(flags.title)
452 ? yield* resolveProjectTitle(workspaceRoot, flags.title.value)
453 : undefined;
454 // An update replaces the whole list of added folders.
455 const kept = (existingProject.trackedFolders ?? [])
456 .filter((folder) => folder.discovered !== true)
457 .map((folder) => ({ path: folder.path, name: folder.name }));
458 const added = named.filter(
459 (folder) => !kept.some((existing) => existing.path === folder.path),
460 );
461 if (kept.length + added.length > PROJECT_TRACKED_FOLDERS_MAX) {
462 return yield* new ProjectTooManyTrackedFoldersError({
463 operation: "addProject",
464 count: kept.length + added.length,
465 max: PROJECT_TRACKED_FOLDERS_MAX,
466 });
467 }
468 yield* dispatch({
469 type: "project.update",
470 commandId: CommandId.make(yield* projectCommandUuid),
471 projectId: existingProject.id,
472 archived: false,
473 ...(title === undefined ? {} : { title }),
474 ...(added.length === 0 ? {} : { trackedFolders: [...kept, ...added] }),
475 });
476 const unarchived = `Unarchived project ${existingProject.id} (${title ?? existingProject.title}) at ${workspaceRoot}.`;
477 return added.length === 0
478 ? unarchived
479 : `${unarchived} It now also covers ${added.length} more ${added.length === 1 ? "folder" : "folders"}.`;
480 }
481 if (existingProject) {
482 return yield* new ProjectAlreadyExistsError({
483 operation: "addProject",
484 projectId: existingProject.id,
485 workspaceRoot,
486 });
487 }
488
489 const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));
490 // Found here, not by a running server: this command runs on the server's machine.
491 const found = yield* discoverFolders(workspaceRoot);
492 if (named.length > PROJECT_TRACKED_FOLDERS_MAX) {
493 return yield* new ProjectTooManyTrackedFoldersError({
494 operation: "addProject",
495 count: named.length,
496 max: PROJECT_TRACKED_FOLDERS_MAX,
497 });
498 }
499 const trackedFolders = mergeProjectFolders(found, named);
500 const projectId = ProjectId.make(yield* projectCommandUuid);
501 yield* dispatch({
502 type: "project.create",
503 commandId: CommandId.make(yield* projectCommandUuid),
504 projectId,
505 title,
506 workspaceRoot,
507 ...(trackedFolders.length === 0 ? {} : { trackedFolders }),
508 });
509 const added = `Added project ${projectId} (${title}) at ${workspaceRoot}.`;
510 if (trackedFolders.length > 0) {
511 return `${added} It also covers ${trackedFolders.length} other ${trackedFolders.length === 1 ? "folder" : "folders"}.`;
512 }
513 return added;
514 }),
515 );
516 }),
517);
518
519const projectRemoveCommand = Command.make("remove", {
520 ...projectLocationFlags,
521 project: Argument.String("project").pipe(
522 Argument.withDescription("Project id or workspace root to remove."),
523 ),
524 force: Flag.Boolean("force").pipe(
525 Flag.withDescription("Delete the project and all of its threads."),
526 Flag.withDefault(false),
527 ),
528}).pipe(
529 Command.withDescription("Remove a project."),
530 Command.withHandler((flags) =>
531 runProjectMutation(
532 flags,
533 Effect.fn("projectRemoveMutation")(function* ({
534 snapshot,
535 dispatch,
536 }: {
537 readonly snapshot: ProjectSnapshot;
538 readonly dispatch: (
539 command: ProjectCliDispatchCommand,
540 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
541 }) {
542 const project = yield* findActiveProjectTarget({
543 snapshot,
544 identifier: flags.project,
545 });
546 yield* dispatch({
547 type: "project.delete",
548 commandId: CommandId.make(yield* projectCommandUuid),
549 projectId: project.id,
550 force: flags.force,
551 });
552 return `Removed project ${project.id} (${project.title}).`;
553 }),
554 ),
555 ),
556);
557
558const projectRenameCommand = Command.make("rename", {
559 ...projectLocationFlags,
560 project: Argument.String("project").pipe(
561 Argument.withDescription("Project id or workspace root to rename."),
562 ),
563 title: Argument.String("title").pipe(Argument.withDescription("New project title.")),
564}).pipe(
565 Command.withDescription("Rename a project."),
566 Command.withHandler((flags) =>
567 runProjectMutation(
568 flags,
569 Effect.fn("projectRenameMutation")(function* ({
570 snapshot,
571 dispatch,
572 }: {
573 readonly snapshot: ProjectSnapshot;
574 readonly dispatch: (
575 command: ProjectCliDispatchCommand,
576 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
577 }) {
578 const project = yield* findActiveProjectTarget({
579 snapshot,
580 identifier: flags.project,
581 });
582 const nextTitle = yield* resolveProjectTitle(project.workspaceRoot, flags.title);
583 if (nextTitle === project.title) {
584 return `Project ${project.id} is already named ${nextTitle}.`;
585 }
586
587 yield* dispatch({
588 type: "project.update",
589 commandId: CommandId.make(yield* projectCommandUuid),
590 projectId: project.id,
591 title: nextTitle,
592 });
593 return `Renamed project ${project.id} to ${nextTitle}.`;
594 }),
595 ),
596 ),
597);
598
599export const projectCommand = Command.make("project").pipe(
600 Command.withDescription("Manage projects."),
601 Command.withSubcommands([projectAddCommand, projectRemoveCommand, projectRenameCommand]),
602);