@niwa-labs/git 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts ADDED
@@ -0,0 +1,753 @@
1
+ /**
2
+ * The git module: worktrees an agent works in, beside the owner's checkout.
3
+ *
4
+ * - **git.worktree.create** makes a worktree of a repository on a new branch `wt-<hex>`, the same as
5
+ * its id, in `<home>/worktrees/<id>`. The base is the one asked for, else the repository's current
6
+ * branch (its commit when HEAD is detached). The ignored files `<repo>/.worktreeinclude` lists are
7
+ * copied in, as clones where the file system makes them.
8
+ * - **git.worktree.list** shows the worktrees, and flags a recorded one whose directory is gone and a
9
+ * directory in the store that no record names.
10
+ * - **git.worktree.get** shows one, with how it stands now: dirty, commits ahead of its base, the
11
+ * live niwa sessions in it.
12
+ * - **git.worktree.remove** removes the directory and the branch. It refuses a worktree that is
13
+ * dirty, ahead of its base (on its branch or on the head of its checkout), has a live session in it
14
+ * or cannot be read, unless forced; git's own refusal (a locked worktree) stands without force.
15
+ * - **git.head.observe** records `git.head.moved` for each worktree whose head is on another commit
16
+ * than the last one recorded for it, and `git.remote.updated` for each whose verified remote is
17
+ * another than the last recorded. The module looks by itself when a session's turn ends in a
18
+ * worktree, and names that session in the record; a run that looks is who its record is of.
19
+ *
20
+ * The list and a get show each worktree's head and the remote its base pushes to, verified from the
21
+ * repository's configuration, so what happens on a forge can be tied to the worktrees of its project.
22
+ *
23
+ * The cleanup of old worktrees is a built-in workflow of the module (`workflows/worktree-cleanup.ts`), on a timer
24
+ * the module offers: every day it reads the list and removes what is older than `cleanup.days`, clean, merged and
25
+ * unused. `git({ cleanup: false })` turns it off; the host needs the timers and the workflow module for it.
26
+ *
27
+ * Niwa never merges: the branch is what the work left, and merging it is the agent's or the owner's.
28
+ * The id is issued from the record that reserves the worktree (its repository, base commit, branch and
29
+ * directory, written before the checkout), so a replayed create finds what it made and makes the same.
30
+ */
31
+
32
+ import { existsSync, mkdirSync, readdirSync, realpathSync, rmSync } from "node:fs";
33
+ import { basename, dirname, join, resolve, sep } from "node:path";
34
+ import { fileURLToPath } from "node:url";
35
+
36
+ import { CatchableError, EntityDescription, IdIndex, action, idSchema, recordId, seq, stableJson } from "@niwa-labs/core";
37
+ import type { ActionContext, IssuedId, JournalReader, RecordId, RecordTypeName, SessionRef, StoredRecord } from "@niwa-labs/core";
38
+ import { BUILTIN_WORKFLOW, TIMER_OFFER, plugin } from "@niwa-labs/plugin";
39
+ import type { Plugin, Subscriber } from "@niwa-labs/plugin";
40
+
41
+ import {
42
+ gitCleanupConfig,
43
+ gitHeadObserve,
44
+ gitWorktreeCreate,
45
+ gitWorktreeGet,
46
+ gitWorktreeList,
47
+ gitWorktreeRemove,
48
+ } from "./actions.ts";
49
+ import type { WorktreeEntity, WorktreeState } from "./actions.ts";
50
+ import { aheadOf, branchOf, commitOf, commonDirOf, copyIncluded, currentBase, gitOut, gitRun, headOf, isDirty, repoOf, topOf, verifiedRemote } from "./git.ts";
51
+ import { registeredWorktree, verifyCheckout } from "./registration.ts";
52
+ export { registeredWorktree } from "./registration.ts";
53
+ import { CheckoutVerified, HeadMoved, RemoteUpdated, WorktreeCreated, WorktreeRemote, WorktreeRemovalClaimed, WorktreeRemoved, WorktreeReserved } from "./record-types.ts";
54
+ import type { RemovalMatch, Worktree, WorktreeId } from "./record-types.ts";
55
+
56
+ const DAY_MS = 86_400_000;
57
+
58
+ /** Why a worktree action did not do what it was asked. */
59
+ export type WorktreeRefusalCode =
60
+ | "not-a-repo"
61
+ | "unknown-base"
62
+ | "occupied"
63
+ | "dirty"
64
+ | "ahead"
65
+ | "live-session"
66
+ | "orphan"
67
+ | "unverifiable"
68
+ | "changed";
69
+
70
+ /**
71
+ * A refusal of the git module: the code says which, the message says why. It is the caller's to
72
+ * catch (a cleanup that finds a worktree changed since it looked keeps it and goes on), so it is not
73
+ * a failed step.
74
+ */
75
+ export class WorktreeRefusal extends CatchableError {
76
+ override name = "WorktreeRefusal";
77
+ override readonly code: WorktreeRefusalCode;
78
+
79
+ constructor(code: WorktreeRefusalCode, message: string) {
80
+ super(message);
81
+ this.code = code;
82
+ }
83
+ }
84
+
85
+ /** What the journal says of one worktree. */
86
+ interface Entry {
87
+ readonly worktree: Worktree;
88
+ /** When it was made, from its record. */
89
+ readonly at: number;
90
+ readonly removed: boolean;
91
+ }
92
+
93
+ /** The worktrees the journal holds, by id, in the order they were made. */
94
+ function fold(journal: JournalReader | undefined): Map<string, Entry> {
95
+ const entries = new Map<string, Entry>();
96
+ if (journal === undefined) return entries;
97
+ for (const stored of journal.since(seq(0), [WorktreeCreated.name, WorktreeRemoved.name])) {
98
+ if (stored.type === WorktreeCreated.name) {
99
+ const parsed = WorktreeCreated.schema.safeParse(stored.data);
100
+ if (parsed.success) entries.set(parsed.data.id, { worktree: parsed.data, at: stored.at, removed: false });
101
+ continue;
102
+ }
103
+ const parsed = WorktreeRemoved.schema.safeParse(stored.data);
104
+ const known = parsed.success ? entries.get(parsed.data.id) : undefined;
105
+ if (parsed.success && known !== undefined) entries.set(parsed.data.id, { ...known, removed: true });
106
+ }
107
+ return entries;
108
+ }
109
+
110
+ /** A worktree id comes from its first record, which may be a creation without a reservation. */
111
+ function worktreeIds(journal: () => JournalReader | undefined): IdIndex<"worktree"> {
112
+ return new IdIndex("worktree", () => {
113
+ const issued = new Map<string, IssuedId>();
114
+ for (const stored of journal()?.since(seq(0), [WorktreeReserved.name, WorktreeCreated.name]) ?? []) {
115
+ const parsed = WorktreeCreated.schema.safeParse(stored.data);
116
+ if (parsed.success && !issued.has(parsed.data.id)) issued.set(parsed.data.id, { id: parsed.data.id, seed: stored.id });
117
+ }
118
+ return [...issued.values()];
119
+ });
120
+ }
121
+
122
+ /** The record an action writes first: the seed of what it makes, the same when the step is made again. */
123
+ function birthOf(ctx: ActionContext): RecordId {
124
+ return recordId(`${ctx.operationId}/emit/1`);
125
+ }
126
+
127
+ /** The path with its links resolved, when it exists. */
128
+ function real(path: string): string {
129
+ try {
130
+ return realpathSync(path);
131
+ } catch {
132
+ return resolve(path);
133
+ }
134
+ }
135
+
136
+ /** Whether `path` is `dir` or inside it. */
137
+ function within(path: string, dir: string): boolean {
138
+ return path === dir || path.startsWith(`${dir}${sep}`);
139
+ }
140
+
141
+ /**
142
+ * The niwa sessions alive in a directory, by their niwa ids, read from the sessions module's
143
+ * records by name (the git module does not import it).
144
+ *
145
+ * A session is alive when it started in the directory (or below it), its last word is not that it
146
+ * ended, and it said something since this host started: a session of an earlier host has no
147
+ * process any more, as the processes of a host stop with it.
148
+ */
149
+ function liveSessionsIn(journal: JournalReader | undefined, dir: string, bootedAt: number): string[] {
150
+ if (journal === undefined) return [];
151
+ const started = new Map<string, string>();
152
+ for (const stored of journal.since(seq(0), ["session.started" as RecordTypeName])) {
153
+ const data = stored.data as { session?: unknown; id?: unknown; cwd?: unknown };
154
+ if (typeof data.cwd !== "string" || typeof data.id !== "string") continue;
155
+ if (within(real(data.cwd), dir)) started.set(stableJson(data.session), data.id);
156
+ }
157
+ if (started.size === 0) return [];
158
+ const last = new Map<string, StoredRecord>();
159
+ for (const stored of journal.since(seq(0), SESSION_LIFE_TYPES.map((name) => name as RecordTypeName))) {
160
+ const key = stableJson((stored.data as { session?: unknown }).session);
161
+ if (started.has(key)) last.set(key, stored);
162
+ }
163
+ return [...started].flatMap(([key, id]) => {
164
+ const latest = last.get(key);
165
+ return latest !== undefined && latest.type !== "session.ended" && latest.at >= bootedAt ? [id] : [];
166
+ });
167
+ }
168
+
169
+ /** The records of the sessions module that say a session is alive, or that it ended. */
170
+ const SESSION_LIFE_TYPES = [
171
+ "session.started",
172
+ "session.marked",
173
+ "session.turn-started",
174
+ "session.turn-ended",
175
+ "session.activity",
176
+ "session.ended",
177
+ ] as const;
178
+
179
+ /** What the plugin knows to answer: the journal, the store and the moment the host started. */
180
+ interface Place {
181
+ readonly journal: () => JournalReader | undefined;
182
+ readonly store: () => string;
183
+ readonly bootedAt: number;
184
+ }
185
+
186
+ /** How a worktree stands, as the list and a get show it. */
187
+ type Standing = Pick<WorktreeEntity, "dirty" | "aheadOfBase" | "sessions" | "head" | "remote">;
188
+
189
+ /** How a worktree stands, and what removing it would need to know. */
190
+ interface Inspected {
191
+ readonly standing: Standing;
192
+ readonly repo: string | undefined;
193
+ /** The commit its branch is on, when it has one. */
194
+ readonly tip: string | undefined;
195
+ /** Whether what was read can be trusted: the repository and the checkout answered. What cannot be read is not known to be clean. */
196
+ readonly sound: boolean;
197
+ }
198
+
199
+ /**
200
+ * How a worktree stands now: dirty, ahead of its base, the sessions alive in it, its head and the remote of its base.
201
+ *
202
+ * Ahead counts what is reachable from the branch and from the head of the checkout, so work committed after
203
+ * detaching the head is not lost with the branch.
204
+ */
205
+ async function inspect(place: Place, worktree: Worktree): Promise<Inspected> {
206
+ const present = existsSync(worktree.path);
207
+ // A record can name a linked source checkout that went away. Recover the owner from the
208
+ // surviving checkout so its refs can still be inspected and updated after it is removed.
209
+ const owner = existsSync(worktree.repo) ? worktree.repo : await repoOf(worktree.path);
210
+ const repo = owner === real(worktree.path) ? undefined : owner;
211
+ let sound = repo !== undefined && (await commonDirOf(repo)) !== undefined;
212
+ let dirty = false;
213
+ let head: string | undefined;
214
+ let tip: string | undefined;
215
+ let aheadOfBase = 0;
216
+ let remote: Awaited<ReturnType<typeof verifiedRemote>>;
217
+ try {
218
+ if (present) {
219
+ dirty = await isDirty(worktree.path);
220
+ head = await headOf(worktree.path);
221
+ if (head === undefined) sound = false;
222
+ }
223
+ if (repo !== undefined) {
224
+ tip = await commitOf(repo, `refs/heads/${worktree.branch}`);
225
+ // Ahead of the base as it is now: a base branch that took the commits makes them merged.
226
+ const base = (await commitOf(repo, worktree.base)) === undefined ? worktree.baseSha : worktree.base;
227
+ const tips = [...new Set([tip, head].filter((commit): commit is string => commit !== undefined))];
228
+ aheadOfBase = tips.length === 0 ? 0 : await aheadOf(repo, base, tips);
229
+ remote = await verifiedRemote(repo, worktree.base);
230
+ }
231
+ } catch {
232
+ sound = false;
233
+ }
234
+ const sessions = present ? liveSessionsIn(place.journal(), real(worktree.path), place.bootedAt) : [];
235
+ return {
236
+ standing: { dirty, aheadOfBase, sessions, ...(head === undefined ? {} : { head }), ...(remote === undefined ? {} : { remote }) },
237
+ repo,
238
+ tip,
239
+ sound,
240
+ };
241
+ }
242
+
243
+ const standing = async (place: Place, worktree: Worktree): Promise<Standing> => (await inspect(place, worktree)).standing;
244
+
245
+ /** The last head recorded for each worktree: the one its last `git.head.moved` names, else none. */
246
+ function recordedHeads(journal: JournalReader | undefined): Map<string, string> {
247
+ const heads = new Map<string, string>();
248
+ for (const stored of journal?.since(seq(0), [HeadMoved.name]) ?? []) {
249
+ const parsed = HeadMoved.schema.safeParse(stored.data);
250
+ if (parsed.success) heads.set(parsed.data.worktree, parsed.data.head);
251
+ }
252
+ return heads;
253
+ }
254
+
255
+ /** The last verified remote recorded for each worktree: absent for one whose last record says there is none. */
256
+ function recordedRemotes(journal: JournalReader | undefined): Map<string, WorktreeRemote> {
257
+ const remotes = new Map<string, WorktreeRemote>();
258
+ for (const stored of journal?.since(seq(0), [RemoteUpdated.name]) ?? []) {
259
+ const parsed = RemoteUpdated.schema.safeParse(stored.data);
260
+ if (!parsed.success) continue;
261
+ if (parsed.data.remote === undefined) remotes.delete(parsed.data.worktree);
262
+ else remotes.set(parsed.data.worktree, parsed.data.remote);
263
+ }
264
+ return remotes;
265
+ }
266
+
267
+ /** The directory a session was started in, by its ref, from the sessions module's records read by name. */
268
+ function cwdOfSession(journal: JournalReader | undefined, session: string): string | undefined {
269
+ let cwd: string | undefined;
270
+ for (const stored of journal?.since(seq(0), ["session.started" as RecordTypeName]) ?? []) {
271
+ const data = stored.data as { session?: unknown; cwd?: unknown };
272
+ if (data.session === session && typeof data.cwd === "string") cwd = data.cwd;
273
+ }
274
+ return cwd;
275
+ }
276
+
277
+ /** Why a worktree may not be removed, or undefined when it may. */
278
+ function refusalOf(id: string, inspected: Inspected): WorktreeRefusal | undefined {
279
+ const state = inspected.standing;
280
+ if (state.sessions.length > 0) {
281
+ return new WorktreeRefusal("live-session", `the worktree "${id}" has a live session in it (${state.sessions.join(", ")})`);
282
+ }
283
+ if (!inspected.sound) {
284
+ return new WorktreeRefusal("unverifiable", `the worktree "${id}" and its repository cannot both be read, so nothing says what would be lost`);
285
+ }
286
+ if (state.dirty) return new WorktreeRefusal("dirty", `the worktree "${id}" has uncommitted changes`);
287
+ if (state.aheadOfBase > 0) {
288
+ return new WorktreeRefusal("ahead", `the worktree "${id}" has ${String(state.aheadOfBase)} commit(s) its base does not have`);
289
+ }
290
+ return undefined;
291
+ }
292
+
293
+ /** What is removed with a worktree: where its repository is, if it is anywhere, its directory and its branch. */
294
+ interface Dismantled {
295
+ readonly repo: string | undefined;
296
+ readonly path: string;
297
+ readonly branch: string;
298
+ }
299
+
300
+ /** The worktree paths and refs Git still has registered, including locked or missing checkouts. */
301
+ async function registeredWorktrees(repo: string): Promise<Array<{ path: string; ref: string | undefined }>> {
302
+ const listed = await gitRun(repo, ["worktree", "list", "--porcelain", "-z"]);
303
+ if (listed.code !== 0) {
304
+ throw new WorktreeRefusal("unverifiable", `git could not list the worktrees of ${repo}: ${listed.stderr.trim()}`);
305
+ }
306
+ return listed.stdout.split("\0\0").flatMap((row) => {
307
+ const [worktree, ...details] = row.split("\0");
308
+ if (!worktree?.startsWith("worktree ")) return [];
309
+ return [{ path: worktree.slice("worktree ".length), ref: details.find((field) => field.startsWith("branch "))?.slice("branch ".length) }];
310
+ });
311
+ }
312
+
313
+ /** An update-ref can delete a branch in use, so check the other worktrees first. */
314
+ function keepCheckedOutBranch(worktrees: Awaited<ReturnType<typeof registeredWorktrees>>, branch: string, except?: string): void {
315
+ const other = worktrees.find((worktree) => worktree.ref === `refs/heads/${branch}` &&
316
+ (except === undefined || real(worktree.path) !== real(except)));
317
+ if (other !== undefined) {
318
+ throw new WorktreeRefusal("changed", `the branch "${branch}" is checked out at ${other.path}`);
319
+ }
320
+ }
321
+
322
+ /**
323
+ * Remove the directory and the branch of a worktree; what is gone already stays gone.
324
+ *
325
+ * Without `force`, git decides whether the directory may go (it keeps a dirty or locked one), and the branch goes
326
+ * only if it is still on the commit that was checked. Force may remove an orphaned directory without
327
+ * a readable checkout. Either way, what was asked to go is checked to be gone before this returns.
328
+ */
329
+ async function dismantle(target: Dismantled, force: boolean, seen?: Inspected): Promise<void> {
330
+ const { repo, path, branch } = target;
331
+ const known = repo !== undefined && existsSync(repo);
332
+ const checkouts = known ? await registeredWorktrees(repo) : [];
333
+ const present = existsSync(path);
334
+ const atPath = (worktree: { path: string }): boolean => real(worktree.path) === real(path);
335
+ keepCheckedOutBranch(checkouts, branch, path);
336
+ if (present || checkouts.some(atPath)) {
337
+ const common = present ? await commonDirOf(path) : undefined;
338
+ if (common !== undefined && (!known || common !== (await commonDirOf(repo)))) {
339
+ throw new WorktreeRefusal("changed", `${path} belongs to another repository`);
340
+ }
341
+ if (!force && present && (await headOf(path)) !== seen?.standing.head) {
342
+ throw new WorktreeRefusal("changed", `the HEAD of ${path} moved while the worktree was being removed`);
343
+ }
344
+ const removed = known ? await gitRun(repo, ["worktree", "remove", ...(force ? ["--force", "--force"] : []), path]) : undefined;
345
+ if (removed?.code !== 0) {
346
+ if (!force || common !== undefined || (known && (await registeredWorktrees(repo)).some(atPath)) ||
347
+ (await commonDirOf(path)) !== undefined) {
348
+ throw new WorktreeRefusal("changed", `git keeps ${path}: ${removed?.stderr.trim() ?? "its repository cannot be read"}`);
349
+ }
350
+ rmSync(path, { recursive: true, force: true });
351
+ }
352
+ if (existsSync(path)) throw new Error(`${path} is still there after it was removed`);
353
+ }
354
+ if (!known) return;
355
+ const now = await commitOf(repo, `refs/heads/${branch}`);
356
+ if (now === undefined) return;
357
+ if (!force && now !== seen?.tip) {
358
+ throw new WorktreeRefusal("changed", `the branch "${branch}" moved while the worktree was being removed, and is kept`);
359
+ }
360
+ keepCheckedOutBranch(await registeredWorktrees(repo), branch);
361
+ const deleted = await gitRun(repo, ["update-ref", "-d", `refs/heads/${branch}`, now]);
362
+ if (deleted.code !== 0) throw new WorktreeRefusal("changed", `git keeps the branch "${branch}": ${deleted.stderr.trim()}`);
363
+ if ((await commitOf(repo, `refs/heads/${branch}`)) !== undefined) throw new Error(`the branch "${branch}" is still there after it was removed`);
364
+ }
365
+
366
+ /**
367
+ * Make the checkout of a worktree from its reservation, or take the one a create that was cut off made: the same
368
+ * path, on the same branch and base commit, of the same repository.
369
+ */
370
+ async function checkout(reserved: Worktree, retry: boolean): Promise<void> {
371
+ const { repo, path, branch, baseSha } = reserved;
372
+ if (existsSync(path)) {
373
+ const top = await topOf(path);
374
+ const common = await commonDirOf(repo);
375
+ if (retry && common !== undefined && top !== undefined && real(top) === real(path) &&
376
+ (await commonDirOf(path)) === common && (await branchOf(path)) === branch && (await headOf(path)) === baseSha) return;
377
+ throw new WorktreeRefusal("occupied", `${path} exists and is not the worktree of the branch "${branch}" of ${repo}`);
378
+ }
379
+ mkdirSync(dirname(path), { recursive: true });
380
+ await gitRun(repo, ["worktree", "prune"]);
381
+ if ((await commitOf(repo, `refs/heads/${branch}`)) !== undefined) {
382
+ throw new WorktreeRefusal("occupied", `the branch "${branch}" already exists`);
383
+ }
384
+ await gitOut(repo, ["worktree", "add", "-b", branch, path, baseSha]);
385
+ }
386
+
387
+ /** The timer of the cleanup, the one its script starts on. */
388
+ export const CLEANUP_TIMER = "git-worktree-cleanup";
389
+
390
+ /** The script of the cleanup, as it ships with the module. */
391
+ const CLEANUP_SCRIPT = fileURLToPath(new URL("./workflows/worktree-cleanup.ts", import.meta.url));
392
+
393
+ /** How the cleanup of old worktrees runs. */
394
+ export interface CleanupOptions {
395
+ /** The time of day it runs, "HH:MM" in local time. Default: "04:00". */
396
+ readonly daily?: string;
397
+ /** How many days a worktree is kept before it may be removed. Default: 30. */
398
+ readonly days?: number;
399
+ }
400
+
401
+ /** What the git module is given. */
402
+ export interface GitOptions {
403
+ /** The daily cleanup of old worktrees, a built-in workflow: on unless it is `false`. */
404
+ readonly cleanup?: CleanupOptions | false;
405
+ }
406
+
407
+ /** The git module. */
408
+ export function git(options: GitOptions = {}): Plugin {
409
+ const bootedAt = Date.now();
410
+ const cleanup = options.cleanup === false ? undefined : { daily: options.cleanup?.daily ?? "04:00", days: options.cleanup?.days ?? 30 };
411
+ if (cleanup !== undefined && (!Number.isInteger(cleanup.days) || cleanup.days < 0)) {
412
+ throw new TypeError(`git({ cleanup }): days is a whole number of days, not ${String(cleanup.days)}`);
413
+ }
414
+
415
+ return plugin("git", (api) => {
416
+ // The cleanup is a workflow the module ships, on a timer it offers: the host lists neither.
417
+ if (cleanup !== undefined) {
418
+ api.offer(TIMER_OFFER, { id: CLEANUP_TIMER, daily: cleanup.daily, description: "The daily cleanup of old git worktrees" });
419
+ api.offer(BUILTIN_WORKFLOW, {
420
+ name: "worktree-cleanup",
421
+ file: CLEANUP_SCRIPT,
422
+ description: "Remove old worktrees that are clean, merged and unused",
423
+ triggers: ["timer.fired"],
424
+ });
425
+ api.action(action(gitCleanupConfig, { recovery: "repeat", effect: "read", world: "niwa", run: () => ({ days: cleanup.days }) }));
426
+ }
427
+
428
+ const journal = () => api.journal?.();
429
+ const ids = worktreeIds(journal);
430
+ const place: Place = { journal, store: () => join(api.home(), "worktrees"), bootedAt };
431
+ const entries = () => fold(journal());
432
+
433
+ api.declare(CheckoutVerified, WorktreeReserved, WorktreeCreated, WorktreeRemovalClaimed, WorktreeRemoved, HeadMoved, RemoteUpdated);
434
+
435
+ api.action(
436
+ action(gitWorktreeCreate, {
437
+ // A create made again finds what it made: the id comes from the step, and the checkout of
438
+ // that id is taken as it is.
439
+ recovery: "repeat",
440
+ effect: "write",
441
+ world: "local",
442
+ async run(input, ctx) {
443
+ const birth = birthOf(ctx);
444
+ const id = ids.issue(birth);
445
+ const known = entries().get(id);
446
+ if (known !== undefined) return known.worktree;
447
+ // What an earlier attempt reserved is what this one makes: the base is not read again.
448
+ const earlier = journal()?.get(birth);
449
+ let reserved: ReturnType<typeof WorktreeReserved.schema.parse>;
450
+ if (earlier === undefined) {
451
+ const top = await topOf(resolve(input.repo));
452
+ if (top === undefined) throw new WorktreeRefusal("not-a-repo", `${input.repo} is not inside a git repository`);
453
+ const source = real(top);
454
+ const repo = real((await repoOf(source)) ?? source);
455
+ const base = input.base ?? (await currentBase(source));
456
+ const baseSha = await commitOf(source, base);
457
+ if (baseSha === undefined) throw new WorktreeRefusal("unknown-base", `"${base}" names no commit of ${repo}`);
458
+ const path = join(real(api.home()), "worktrees", id);
459
+ reserved = { id, description: input.description, repo, path, branch: id, base, baseSha, ...(repo === source ? {} : { source }) };
460
+ } else {
461
+ reserved = WorktreeReserved.schema.parse(earlier.data);
462
+ const top = await topOf(resolve(input.repo));
463
+ if (top === undefined || reserved.id !== id || reserved.branch !== id ||
464
+ reserved.path !== join(real(api.home()), "worktrees", id) ||
465
+ reserved.repo !== real((await repoOf(real(top))) ?? top) ||
466
+ (reserved.source ?? reserved.repo) !== real(top)) {
467
+ throw new WorktreeRefusal("changed", "the reserved checkout differs from the requested repository");
468
+ }
469
+ }
470
+ await ctx.emit(WorktreeReserved, reserved);
471
+ const { source, ...worktree } = reserved;
472
+ await checkout(worktree, earlier !== undefined);
473
+ await copyIncluded(source ?? worktree.repo, worktree.path);
474
+ await verifyCheckout(api, worktree, `${ctx.operationId}/emit/2`);
475
+ await ctx.emit(WorktreeCreated, worktree);
476
+ return worktree;
477
+ },
478
+ }),
479
+ );
480
+
481
+ api.action(
482
+ action(gitWorktreeList, {
483
+ recovery: "repeat",
484
+ effect: "read",
485
+ world: "local",
486
+ async run() {
487
+ const live = [...entries().values()].filter((entry) => !entry.removed);
488
+ const named = new Set<string>(live.map((entry) => entry.worktree.id));
489
+ const now = Date.now();
490
+ const recorded = await Promise.all(
491
+ live.map(async ({ worktree, at }) => ({
492
+ id: worktree.id,
493
+ description: worktree.description,
494
+ state: (existsSync(worktree.path) ? "ok" : "missing") satisfies WorktreeState,
495
+ path: worktree.path,
496
+ branch: worktree.branch,
497
+ repo: worktree.repo,
498
+ base: worktree.base,
499
+ ageDays: Math.max(0, (now - at) / DAY_MS),
500
+ ...(await standing(place, worktree)),
501
+ })),
502
+ );
503
+ const orphans = orphanDirs(place.store()).filter((name) => !named.has(name)).map((name) => ({
504
+ id: idSchema("worktree").parse(name),
505
+ description: description("a directory no record names"),
506
+ state: "orphan" satisfies WorktreeState,
507
+ path: join(place.store(), name),
508
+ }));
509
+ return { items: [...recorded, ...orphans] };
510
+ },
511
+ }),
512
+ );
513
+
514
+ api.action(
515
+ action(gitWorktreeGet, {
516
+ recovery: "repeat",
517
+ effect: "read",
518
+ world: "local",
519
+ async run(input) {
520
+ const id = ids.require(input.id);
521
+ const entry = entries().get(id);
522
+ if (entry === undefined || entry.removed) throw new WorktreeRefusal("orphan", `the worktree "${id}" was removed`);
523
+ return { ...entry.worktree, ...(await standing(place, entry.worktree)) };
524
+ },
525
+ }),
526
+ );
527
+
528
+ // Observations and removals of a worktree read its state and record their result one at a time.
529
+ const turns = new Map<string, Promise<unknown>>();
530
+ const worktreeTurn = async <T>(worktree: string, act: () => Promise<T>): Promise<T> => {
531
+ const turn = (turns.get(worktree) ?? Promise.resolve()).then(act);
532
+ const done = turn.catch(() => undefined);
533
+ turns.set(worktree, done);
534
+ try {
535
+ return await turn;
536
+ } finally {
537
+ if (turns.get(worktree) === done) turns.delete(worktree);
538
+ }
539
+ };
540
+
541
+ api.action(
542
+ action(gitHeadObserve, {
543
+ // What is recorded is the last one known: looking again writes nothing new, and a look cut off is made
544
+ // again by writing what it wrote under the same identity, then going on.
545
+ recovery: "repeat",
546
+ effect: "record",
547
+ world: "niwa",
548
+ async run(input, ctx) {
549
+ const only = input.worktree === undefined ? undefined : ids.require(input.worktree);
550
+ const moved: Array<{ worktree: WorktreeId; head: string }> = [];
551
+ // The records are numbered in the order they are written: an attempt that was cut off wrote the first
552
+ // ones, and they are written again as they were, so the new ones follow them and are not taken for them.
553
+ for (let ordinal = 1; ; ordinal += 1) {
554
+ const written = journal()?.get(recordId(`${ctx.operationId}/emit/${String(ordinal)}`));
555
+ if (written === undefined) break;
556
+ if (written.type === RemoteUpdated.name) {
557
+ await ctx.emit(RemoteUpdated, RemoteUpdated.schema.parse(written.data));
558
+ continue;
559
+ }
560
+ const head = HeadMoved.schema.parse(written.data);
561
+ await ctx.emit(HeadMoved, head);
562
+ moved.push({ worktree: head.worktree, head: head.head });
563
+ }
564
+ for (const { worktree, removed } of entries().values()) {
565
+ if (removed || (only !== undefined && worktree.id !== only)) continue;
566
+ await worktreeTurn(worktree.id, async () => {
567
+ if (!existsSync(worktree.path)) return;
568
+ const head = await headOf(worktree.path);
569
+ const previous = recordedHeads(journal()).get(worktree.id) ?? worktree.baseSha;
570
+ if (head !== undefined && head !== previous) {
571
+ const branch = await branchOf(worktree.path);
572
+ await ctx.emit(HeadMoved, {
573
+ worktree: worktree.id,
574
+ repo: worktree.repo,
575
+ path: worktree.path,
576
+ ...(branch === undefined ? {} : { branch }),
577
+ head,
578
+ previous,
579
+ ...(input.session === undefined ? {} : { session: input.session }),
580
+ });
581
+ moved.push({ worktree: worktree.id, head });
582
+ }
583
+ const remote = existsSync(worktree.repo) ? await verifiedRemote(worktree.repo, worktree.base) : undefined;
584
+ const recorded = recordedRemotes(journal()).get(worktree.id);
585
+ if (stableJson(remote ?? null) !== stableJson(recorded ?? null)) {
586
+ await ctx.emit(RemoteUpdated, { worktree: worktree.id, repo: worktree.repo, ...(remote === undefined ? {} : { remote }) });
587
+ }
588
+ });
589
+ }
590
+ return { moved };
591
+ },
592
+ }),
593
+ );
594
+
595
+ // The end of a session's turn is when its commits are seen: the worktrees it was started in are looked at, and a
596
+ // head that moved is recorded for it. The sessions module is read by name, from when the module first serves.
597
+ let firstServed: number | undefined;
598
+ api.subscribers(() => {
599
+ const reader = journal();
600
+ if (reader === undefined) return [];
601
+ firstServed ??= reader.last();
602
+ const turns: Subscriber = {
603
+ id: "head-on-turn-end",
604
+ queries: [{ types: ["session.turn-ended"] }],
605
+ from: firstServed,
606
+ handler: async (data, step) => {
607
+ const session = (data as { session?: unknown }).session;
608
+ if (typeof session !== "string") return;
609
+ const cwd = cwdOfSession(journal(), session);
610
+ if (cwd === undefined) return;
611
+ const at = real(cwd);
612
+ for (const { worktree, removed } of entries().values()) {
613
+ if (removed || !within(at, real(worktree.path))) continue;
614
+ await step(gitHeadObserve, { worktree: worktree.id, session: session as SessionRef }, { key: `observe:${worktree.id}` });
615
+ }
616
+ },
617
+ };
618
+ return [turns];
619
+ });
620
+
621
+ /** Remove a recorded worktree: refused unless it may go or it is forced, then written. */
622
+ const removeEntry = async (
623
+ entry: Entry,
624
+ force: boolean,
625
+ emit: (data: { id: WorktreeId; forced: boolean }) => Promise<unknown>,
626
+ ): Promise<void> => {
627
+ const { worktree } = entry;
628
+ const seen = await inspect(place, worktree);
629
+ const refusal = refusalOf(worktree.id, seen);
630
+ if (refusal !== undefined && !force) throw refusal;
631
+ await dismantle({ ...worktree, repo: seen.repo }, force, seen);
632
+ await emit({ id: idSchema("worktree").parse(worktree.id), forced: refusal !== undefined });
633
+ };
634
+
635
+ /** Remove the expected checkout without deleting the branch or any reachable commits. */
636
+ const removeMatchingCheckout = async (worktree: Worktree, onlyIf: RemovalMatch, ctx: ActionContext): Promise<void> => {
637
+ const { id, repo, branch, path } = worktree;
638
+ if (repo !== onlyIf.repo || branch !== onlyIf.branch || path !== onlyIf.path) {
639
+ throw new WorktreeRefusal("changed", `the worktree "${id}" no longer matches the saved checkout`);
640
+ }
641
+ const prior = journal()?.get(birthOf(ctx));
642
+ const resumed = prior?.type === WorktreeRemovalClaimed.name;
643
+ const checkouts = await registeredWorktrees(repo);
644
+ const registration = checkouts.find((checkout) => checkout.path === path);
645
+ if (!resumed || registration !== undefined || existsSync(path)) {
646
+ if (registration?.ref !== `refs/heads/${branch}` || registeredWorktree(api, path)?.id !== id) {
647
+ throw new WorktreeRefusal("changed", `the registered checkout "${id}" is missing, replaced, or on another branch`);
648
+ }
649
+ }
650
+ await ctx.emit(WorktreeRemovalClaimed, { id, onlyIf });
651
+ if (registration !== undefined || existsSync(path)) {
652
+ const remote = await verifiedRemote(repo, worktree.base);
653
+ if (remote?.host !== onlyIf.project.host || remote.path !== onlyIf.project.path) {
654
+ throw new WorktreeRefusal("changed", `the worktree "${id}" no longer points to the saved forge project`);
655
+ }
656
+ // Git checks its lock and ordinary changes itself. Include ignored files here as Git's removal
657
+ // test does not protect them and this checkout may contain local-only files.
658
+ const status = await gitRun(path, ["status", "--porcelain=v1", "-z", "--untracked-files=all", "--ignored=matching"]);
659
+ if (status.code !== 0) throw new WorktreeRefusal("unverifiable", `cannot read worktree "${id}": ${status.stderr.trim()}`);
660
+ if (status.stdout !== "") throw new WorktreeRefusal("dirty", `the worktree "${id}" has local files or changes`);
661
+ if ((await branchOf(path)) !== branch || (await headOf(path)) !== onlyIf.head || registeredWorktree(api, path)?.id !== id) {
662
+ throw new WorktreeRefusal("changed", `the worktree "${id}" moved after its pull request was registered`);
663
+ }
664
+ const sessions = liveSessionsIn(journal(), path, place.bootedAt);
665
+ if (sessions.length > 0) throw new WorktreeRefusal("live-session", `the worktree "${id}" has a live session in it (${sessions.join(", ")})`);
666
+ const removed = await gitRun(repo, ["worktree", "remove", "--", path]);
667
+ if (removed.code !== 0) throw new WorktreeRefusal("changed", `git keeps ${path}: ${removed.stderr.trim()}`);
668
+ }
669
+ if (existsSync(path)) throw new WorktreeRefusal("changed", `the worktree "${id}" is still present`);
670
+ await ctx.emit(WorktreeRemoved, { id, forced: false, branchKept: true });
671
+ };
672
+
673
+ api.action(
674
+ action(gitWorktreeRemove, {
675
+ // Removing what is removed already is a no-op, so it may be made again.
676
+ recovery: "repeat",
677
+ effect: "write",
678
+ world: "local", destructive: true,
679
+ async run(input, ctx) {
680
+ const force = input.force ?? false;
681
+ const id = ids.resolve(input.id);
682
+ return worktreeTurn(id ?? input.id, async () => {
683
+ const entry = id === undefined ? undefined : entries().get(id);
684
+ if (input.onlyIf !== undefined) {
685
+ if (entry === undefined || input.id !== entry.worktree.id) return { id: input.id, removed: false };
686
+ if (entry.removed) {
687
+ const outcome = journal()?.get(recordId(`${ctx.operationId}/emit/2`));
688
+ return { id: entry.worktree.id, removed: outcome?.type === WorktreeRemoved.name };
689
+ }
690
+ await removeMatchingCheckout(entry.worktree, input.onlyIf, ctx);
691
+ return { id: entry.worktree.id, removed: true };
692
+ }
693
+ if (entry !== undefined && !entry.removed) {
694
+ await removeEntry(entry, force, (data) => ctx.emit(WorktreeRemoved, data));
695
+ return { id: entry.worktree.id, removed: true };
696
+ }
697
+ // A directory of the store that no record names, or that took the place of a worktree that was removed.
698
+ const orphan = entry === undefined ? idSchema("worktree").safeParse(input.id) : idSchema("worktree").safeParse(entry.worktree.id);
699
+ const path = orphan.success ? join(place.store(), orphan.data) : undefined;
700
+ if (!orphan.success || path === undefined || !existsSync(path)) return { id: orphan.success ? orphan.data : input.id, removed: false };
701
+ if (!force) throw new WorktreeRefusal("orphan", `${path} has no record, so nothing says what it holds: remove it with force`);
702
+ const common = await commonDirOf(path);
703
+ const repo = common === undefined ? undefined : basename(common) === ".git" ? dirname(common) : undefined;
704
+ await dismantle({ repo, path, branch: orphan.data }, true);
705
+ return { id: orphan.data, removed: true };
706
+ });
707
+ },
708
+ }),
709
+ );
710
+
711
+ });
712
+ }
713
+
714
+ /** A fixed description of the module's own. */
715
+ function description(text: string): EntityDescription {
716
+ return EntityDescription.parse(text);
717
+ }
718
+
719
+ /** The directories of the store named like a worktree id. */
720
+ function orphanDirs(store: string): string[] {
721
+ if (!existsSync(store)) return [];
722
+ const pattern = idSchema("worktree");
723
+ return readdirSync(store, { withFileTypes: true })
724
+ .filter((entry) => entry.isDirectory() && pattern.safeParse(entry.name).success)
725
+ .map((entry) => entry.name);
726
+ }
727
+
728
+ export {
729
+ SessionWorktree,
730
+ gitCleanupConfig,
731
+ gitHeadObserve,
732
+ WorktreeEntity,
733
+ WorktreeOption,
734
+ WorktreeState,
735
+ gitWorktreeCreate,
736
+ gitWorktreeGet,
737
+ gitWorktreeList,
738
+ gitWorktreeRemove,
739
+ } from "./actions.ts";
740
+ export type { WorktreeOptionGiven } from "./actions.ts";
741
+ export {
742
+ CommitId,
743
+ GIT_TYPES,
744
+ HeadMoved,
745
+ RemoteUpdated,
746
+ Worktree,
747
+ WorktreeCreated,
748
+ WorktreeId,
749
+ WorktreeRemote,
750
+ WorktreeRemovalClaimed,
751
+ WorktreeRemoved,
752
+ WorktreeReserved,
753
+ } from "./record-types.ts";