Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

project.ts

614 lines21.8 KB

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