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