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

ScratchThreadPromotion.ts

159 lines6.1 KB

1import {
2 CommandId,
3 type OrchestrationV2ThreadShell,
4 ProjectId,
5 type ThreadId,
6} from "@t3tools/contracts";
7import * as Context from "effect/Context";
8import * as SecureRandom from "effect/crypto/SecureRandom";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import * as Option from "effect/Option";
12import * as Path from "effect/Path";
13import * as Schema from "effect/Schema";
14​
15import { threadHasUnfinishedWork } from "../orchestration-v2/Orchestrator.ts";
16import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
17import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
18import * as ManagedProjectFolders from "./ManagedProjectFolders.ts";
19import * as ProjectService from "./ProjectService.ts";
20​
21export class ScratchThreadPromotionError extends Schema.TaggedError<ScratchThreadPromotionError>()(
22 "ScratchThreadPromotionError",
23 {
24 reason: Schema.String,
25 cause: Schema.optional(Schema.Defect()),
26 },
27) {
28 override get message(): string {
29 return this.reason;
30 }
32​
33export class ScratchThreadPromotion extends Context.Service<
34 ScratchThreadPromotion,
35 {
36 /**
37 * Turns a No project thread's folder into a project, in place, and moves every
38 * thread working in that folder into it. Running it again finishes a partial move.
39 */
40 readonly promote: (input: {
41 readonly threadId: ThreadId;
42 }) => Effect.Effect<{ readonly projectId: ProjectId }, ScratchThreadPromotionError>;
43 }
44>()("t3/project/ScratchThreadPromotion") {}
45​
46const make = Effect.gen(function* () {
47 const managedFolders = yield* ManagedProjectFolders.ManagedProjectFolders;
48 const projects = yield* ProjectService.ProjectService;
49 const threads = yield* ThreadManagementService.ThreadManagementService;
50 const scheduledTasks = yield* ScheduledTaskService.ScheduledTaskService;
51 const random = yield* SecureRandom.SecureRandom;
52 const path = yield* Path.Path;
53​
54 const fail = (reason: string) => (cause: unknown) =>
55 new ScratchThreadPromotionError({ reason, cause });
56​
57 const promote: ScratchThreadPromotion["Service"]["promote"] = Effect.fn(
58 "ScratchThreadPromotion.promote",
59 )(function* (input) {
60 const thread = yield* threads.getThreadShell(input.threadId).pipe(
61 Effect.mapError(fail("Could not read the thread.")),
62 Effect.filterOrFail(
63 (shell) => shell !== null,
64 () => new ScratchThreadPromotionError({ reason: "Thread not found." }),
65 ),
66 );
67 const project = yield* projects
68 .getById(thread.projectId)
69 .pipe(Effect.mapError(fail("Could not read the thread's project.")));
70 const folder = thread.worktreePath ?? Option.getOrUndefined(project)?.workspaceRoot;
71 const scratchRoot = Option.getOrUndefined(yield* managedFolders.scratchRoot);
72 const isScratch = yield* managedFolders.isScratchProject(thread.projectId);
73 // A thread already rooted at its folder is a partial earlier promotion; finish it.
74 const alreadyPromoted =
75 Option.isSome(project) && project.value.workspaceRoot === folder && !isScratch;
76 if (
77 folder === undefined ||
78 scratchRoot === undefined ||
79 path.dirname(folder) !== scratchRoot ||
80 !(isScratch || alreadyPromoted)
81 ) {
82 return yield* new ScratchThreadPromotionError({
83 reason: "Only a No project thread with its own folder can become a project.",
84 });
85 }
86​
87 const snapshot = yield* Effect.flatten(
88 threads.readShellSnapshot({ worktreePath: folder }),
89 ).pipe(Effect.mapError(fail("Could not read the threads in this folder.")));
90 const moveSet = new Map<ThreadId, OrchestrationV2ThreadShell>();
91 if (isScratch) moveSet.set(thread.id, thread);
92 for (const candidate of [...snapshot.threads, ...snapshot.archivedThreads]) {
93 if (yield* managedFolders.isScratchProject(candidate.projectId)) {
94 moveSet.set(candidate.id, candidate);
95 }
96 }
97​
98 for (const candidate of moveSet.values()) {
99 const records = yield* threads
100 .getThreadRecords(candidate.id, ["runs", "runtimeRequests"], { turnItemTypes: [] })
101 .pipe(Effect.mapError(fail(`Could not read "${candidate.title}".`)));
102 if (threadHasUnfinishedWork(records)) {
103 return yield* new ScratchThreadPromotionError({
104 reason: `"${candidate.title}" is still working. Finish or stop it first.`,
105 });
106 }
107 }
108​
109 return yield* Effect.uninterruptible(
110 Effect.gen(function* () {
111 const projectId = yield* createProject(thread.title, folder);
112 yield* scheduledTasks
113 .moveThreadTasks({ threadIds: [...moveSet.keys()], projectId })
114 .pipe(Effect.mapError(fail("Could not move the thread's scheduled tasks.")));
115 for (const candidate of moveSet.values()) {
116 const commandId = CommandId.make(`scratch-promotion:${yield* randomId}`);
117 yield* threads
118 .dispatch({
119 type: "thread.project.adopt-folder",
120 commandId,
121 threadId: candidate.id,
122 projectId,
123 })
124 .pipe(Effect.mapError(fail(`Could not move "${candidate.title}". Try again.`)));
125 }
126 return { projectId };
127 }),
128 );
129 });
130​
131 const randomId = random.uuidV4();
132​
133 // bootstrap returns the project that already owns the folder, so retries reuse it.
134 const createProject = Effect.fn("ScratchThreadPromotion.createProject")(function* (
135 title: string,
136 workspaceRoot: string,
137 ) {
138 const id = yield* randomId;
139 return yield* projects
140 .bootstrap({
141 commandId: CommandId.make(`scratch-promotion-project:${id}`),
142 projectId: ProjectId.make(id),
143 title,
144 workspaceRoot,
145 })
146 .pipe(
147 Effect.map(({ project }) => project.id),
148 // bootstrap reads before locking; racing creates return the winner in a conflict.
149 Effect.catchTags({
150 ProjectConflictError: (conflict) => Effect.succeed(conflict.conflictingProjectId),
151 }),
152 Effect.mapError(fail("Could not create the project.")),
153 );
154 });
155​
156 return ScratchThreadPromotion.of({ promote });
157});
158​
159export const layer = Layer.effect(ScratchThreadPromotion, make);