gcf-aif-ext 0.22.1 → 0.24.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/lib/shelf.js ADDED
@@ -0,0 +1,1003 @@
1
+ // A card's unfinished work in main mode (docs/Shelve-Plan.md): the main folder holds the work of
2
+ // one card at most. A claim pins a baseline, the disk's tree at `refs/gcf/main-work`; the card's
3
+ // paths are what differs from it since. When another card claims the folder, that work goes to
4
+ // branch `work/<id>` as a commit carrying `GCF-Shelved: <id>`, which the integrator ignores, and
5
+ // comes back when the card is claimed again. Plumbing only: no hook judges half-done work.
6
+ //
7
+ // shortcut: a project inside a bigger repository gets none of this and stops as before, because
8
+ // `git status` there speaks from the repository's root; lift when such a project runs on main.
9
+ import { spawnSync } from 'node:child_process';
10
+ import { closeSync, copyFileSync, existsSync, lstatSync, openSync, rmSync } from 'node:fs';
11
+ import os from 'node:os';
12
+ import path from 'node:path';
13
+ import { operationInProgress } from './git.js';
14
+ import { refusal } from './refusal.js';
15
+
16
+ const WORK = 'refs/gcf/main-work';
17
+ const SWITCH = 'refs/gcf/main-switch';
18
+ const branchRef = (id) => `refs/heads/work/${id}`;
19
+ const returnedRef = (id) => `refs/gcf/returned/${id}`;
20
+ // Only for a branch deleted by hand: without it a card's lost work would read as no work at all.
21
+ const shelvedRef = (id) => `refs/gcf/shelved/${id}`;
22
+ // Staged text the disk did not hold when a switch began: a chain that lives to the card's end.
23
+ const stagedRef = (id) => `refs/gcf/staged/${id}`;
24
+ // What a return finished in recovery has to tell its card, until that card's own claim.
25
+ const owedRef = (id) => `refs/gcf/owed/${id}`;
26
+
27
+ const GITLINK = '160000';
28
+ const NO_FILE = '000000';
29
+ const SHELVED = 'GCF-Shelved';
30
+ const WHOLE = 'GCF-Whole';
31
+ const NOT_CODE = ['gcf', '.ai-factory', '.gcf-session'];
32
+ // `merge-tree --merge-base` came in 2.40.
33
+ const GIT_MIN = [2, 40];
34
+
35
+ const IDENT = { name: 'gcf', email: 'gcf@localhost' };
36
+
37
+ /**
38
+ * @param {string} dir
39
+ * @param {string[]} args
40
+ * @param {{env?: Record<string, string>, input?: string}} [opts]
41
+ */
42
+ function git(dir, args, { env = {}, input } = {}) {
43
+ const r = spawnSync('git', args, {
44
+ cwd: dir,
45
+ encoding: 'utf8',
46
+ input,
47
+ maxBuffer: 1 << 28,
48
+ env: { ...process.env, GIT_LITERAL_PATHSPECS: '1', ...env },
49
+ });
50
+
51
+ return {
52
+ ok: r.status === 0,
53
+ status: r.status,
54
+ out: r.stdout ?? '',
55
+ err: (r.stderr ?? '').trim() || (r.error?.message ?? ''),
56
+ };
57
+ }
58
+
59
+ /** @param {string} dir @param {string[]} args @param {Parameters<typeof git>[2]} [opts] */
60
+ function must(dir, args, opts) {
61
+ const r = git(dir, args, opts);
62
+ if (!r.ok) throw new Error(`git ${args[0]}: ${r.err}`);
63
+
64
+ return r.out.trim();
65
+ }
66
+
67
+ const resolve = (dir, ref) => {
68
+ const r = git(dir, ['rev-parse', '-q', '--verify', `${ref}^{commit}`]);
69
+
70
+ return r.ok ? r.out.trim() : null;
71
+ };
72
+
73
+ const trailer = (dir, rev, key) =>
74
+ must(dir, ['log', '-1', `--format=%(trailers:key=${key},valueonly)`, rev]);
75
+
76
+ /** The folder if a shelf can work there, else null: nothing is recorded, today's stop holds. */
77
+ function folderOf(projectDir, gitVersion) {
78
+ const dir = path.resolve(projectDir);
79
+ const version = gitVersion ?? git(dir, ['version']).out;
80
+ const m = version.match(/(\d+)\.(\d+)/);
81
+ if (!m || +m[1] < GIT_MIN[0] || (+m[1] === GIT_MIN[0] && +m[2] < GIT_MIN[1])) return null;
82
+ const r = git(dir, ['rev-parse', '--show-prefix', '--git-dir', '--git-common-dir']);
83
+ if (!r.ok) return null;
84
+ const [prefix, gitDir, common] = r.out.split(/\r?\n/);
85
+ // A linked worktree shares these refs with the main folder and must not read them as its own.
86
+ if (prefix || path.resolve(dir, gitDir) !== path.resolve(dir, common)) return null;
87
+ if (!resolve(dir, 'HEAD')) return null;
88
+ const branch = git(dir, ['symbolic-ref', '-q', 'HEAD']).out.trim();
89
+
90
+ return branch.startsWith('refs/heads/work/') ? null : dir;
91
+ }
92
+
93
+ let indexes = 0;
94
+ const tmpIndex = () =>
95
+ path.join(os.tmpdir(), `gcf-shelf-${process.pid}-${Date.now()}-${indexes++}`);
96
+
97
+ function dropIndex(index) {
98
+ rmSync(index, { force: true });
99
+ rmSync(`${index}.lock`, { force: true });
100
+ }
101
+
102
+ const realIndex = (dir) => path.resolve(dir, must(dir, ['rev-parse', '--git-path', 'index']));
103
+
104
+ /** The disk's tree and an index up to date with it: `read-tree -u` needs its stat data. */
105
+ function snapshot(dir) {
106
+ const index = tmpIndex();
107
+ const real = realIndex(dir);
108
+ try {
109
+ if (existsSync(real)) copyFileSync(real, index);
110
+ const env = { GIT_INDEX_FILE: index };
111
+ must(dir, ['add', '-A', '--', '.'], { env });
112
+
113
+ return { tree: must(dir, ['write-tree'], { env }), index };
114
+ } catch (e) {
115
+ dropIndex(index);
116
+ throw e;
117
+ }
118
+ }
119
+
120
+ /** The paths that differ between two trees, each with its mode and blob in the second. */
121
+ function diff(dir, from, to) {
122
+ const out = must(dir, ['diff-tree', '-r', '-z', '--no-renames', from, to]);
123
+ const parts = out.split('\0');
124
+ const entries = [];
125
+ for (let i = 0; i + 1 < parts.length; i += 2) {
126
+ const [oldMode, mode, oldOid, oid] = parts[i].slice(1).split(' ');
127
+ entries.push({ path: parts[i + 1], oldMode, mode, oldOid, oid });
128
+ }
129
+
130
+ return entries;
131
+ }
132
+
133
+ /** `base` with `paths` taken from `source`. */
134
+ function overlay(dir, base, source, paths) {
135
+ const want = new Set(paths);
136
+ const lines = diff(dir, base, source)
137
+ .filter((e) => want.has(e.path))
138
+ .map((e) => `${e.mode} ${e.oid}\t${e.path}\0`)
139
+ .join('');
140
+ const index = tmpIndex();
141
+ const env = { GIT_INDEX_FILE: index };
142
+ try {
143
+ must(dir, ['read-tree', base], { env });
144
+ must(dir, ['update-index', '-z', '--index-info'], { env, input: lines });
145
+
146
+ return must(dir, ['write-tree'], { env });
147
+ } finally {
148
+ dropIndex(index);
149
+ }
150
+ }
151
+
152
+ function ident(dir) {
153
+ const of = (key, fallback) => git(dir, ['config', key]).out.trim() || fallback;
154
+ const name = of('user.name', IDENT.name);
155
+ const email = of('user.email', IDENT.email);
156
+
157
+ return {
158
+ GIT_AUTHOR_NAME: name,
159
+ GIT_AUTHOR_EMAIL: email,
160
+ GIT_COMMITTER_NAME: name,
161
+ GIT_COMMITTER_EMAIL: email,
162
+ };
163
+ }
164
+
165
+ function commit(dir, tree, parents, message) {
166
+ const args = ['commit-tree', tree, ...parents.flatMap((p) => ['-p', p]), '-F', '-'];
167
+
168
+ return must(dir, args, { env: ident(dir), input: `${message}\n` });
169
+ }
170
+
171
+ /** One transaction: a crash leaves all of these moved, or none. */
172
+ const refs = (dir, lines) =>
173
+ must(dir, ['update-ref', '--stdin'], { input: `${lines.filter(Boolean).join('\n')}\n` });
174
+
175
+ const baselineMessage = (id) => `gcf(main-work): ${id}`;
176
+
177
+ function baselineOf(dir) {
178
+ const rev = resolve(dir, WORK);
179
+ if (!rev) return null;
180
+ const [subject, parent] = must(dir, ['log', '-1', '--format=%s%x00%P', rev]).split('\0');
181
+ const id = subject.match(/^gcf\(main-work\): (\S+)$/)?.[1];
182
+
183
+ return id ? { id, rev, parent, tree: must(dir, ['rev-parse', `${rev}^{tree}`]) } : null;
184
+ }
185
+
186
+ function pin(dir, id, tree, head) {
187
+ must(dir, ['update-ref', WORK, commit(dir, tree, [head], baselineMessage(id))]);
188
+ }
189
+
190
+ /**
191
+ * The card's paths: what differs between the baseline and the disk, minus what the disk shares
192
+ * with HEAD (committed meanwhile). Under `gcf/` only its own card: any other edit there stays,
193
+ * and refuses moves as it always did.
194
+ */
195
+ function cardPaths(dir, base, tree, head) {
196
+ const fromHead = new Set(diff(dir, head, tree).map((e) => e.path));
197
+ const card = `gcf/work/${base.id}.md`;
198
+ // A nested repository moves no files by its gitlink: it stays, and counts as a human's.
199
+ const link = (e) => e.mode === GITLINK || e.oldMode === GITLINK;
200
+
201
+ return diff(dir, base.tree, tree)
202
+ .filter((e) => !link(e))
203
+ .map((e) => e.path)
204
+ .filter(
205
+ (p) =>
206
+ fromHead.has(p) && (!p.startsWith('gcf/') || p === card) && !p.startsWith('.gcf-session/'),
207
+ );
208
+ }
209
+
210
+ const isCode = (p) => !NOT_CODE.some((n) => p === n || p.startsWith(`${n}/`));
211
+
212
+ const codeSince = (dir, from, to) => diff(dir, from, to).some((e) => isCode(e.path));
213
+
214
+ /**
215
+ * Whether none of the card's code reached main since its first baseline: anyone's commit during
216
+ * the card counts against it, and so does what its earlier shelf says.
217
+ */
218
+ function whole(dir, base, head) {
219
+ if (codeSince(dir, base.parent, head)) return false;
220
+ const back = resolve(dir, returnedRef(base.id));
221
+
222
+ return !back || trailer(dir, back, WHOLE) === 'yes';
223
+ }
224
+
225
+ /**
226
+ * A card's code may be on main where no later baseline can see it (a card that left with nothing
227
+ * to shelve, a claim that pinned none): its returned ref says so, or a later shelve would call the
228
+ * card whole. Its tree stays: it may hold a copy a return named.
229
+ */
230
+ function markNotWhole(dir, id, head) {
231
+ const back = resolve(dir, returnedRef(id));
232
+ if (back && trailer(dir, back, WHOLE) !== 'yes') return;
233
+ const tree = must(dir, ['rev-parse', `${back ?? head}^{tree}`]);
234
+ const note = commit(dir, tree, [back ?? head], `gcf(main-work): ${id} may have code on main`);
235
+ must(dir, ['update-ref', returnedRef(id), note]);
236
+ }
237
+
238
+ function noteCodeOnMain(dir, base, head) {
239
+ if (codeSince(dir, base.parent, head)) markNotWhole(dir, base.id, head);
240
+ }
241
+
242
+ /** What stands at a path, none when nothing does: under a file too, which POSIX calls ENOTDIR. */
243
+ function statAt(full) {
244
+ try {
245
+ return lstatSync(full, { throwIfNoEntry: false });
246
+ } catch (e) {
247
+ if (/** @type {NodeJS.ErrnoException} */ (e).code === 'ENOTDIR') return undefined;
248
+ throw e;
249
+ }
250
+ }
251
+
252
+ /**
253
+ * `read-tree -u` overwrites what git ignores without a word: nothing the switch writes may land
254
+ * on an ignored file, or take a folder holding one. A human's file or a card's untracked edit
255
+ * would be gone, so the claim refuses and names it.
256
+ */
257
+ function refuseIgnoredInTheWay(dir, disk, target) {
258
+ const changes = diff(dir, disk.tree, target);
259
+ // Any case: on a folder that ignores it, a case-only rename finds its own old name.
260
+ const gone = new Set(changes.filter((e) => e.mode === NO_FILE).map((e) => e.path.toLowerCase()));
261
+ const statOf = (p) => statAt(path.join(dir, p));
262
+ const inTheWay = (p) => {
263
+ if (gone.has(p.toLowerCase())) return false;
264
+ const st = statOf(p);
265
+ if (st?.isDirectory()) {
266
+ const args = ['ls-files', '-o', '-i', '--exclude-standard', '-z', '--', p];
267
+
268
+ return git(dir, args, { env: { GIT_INDEX_FILE: disk.index } }).out !== '';
269
+ }
270
+
271
+ if (st) return true;
272
+ const parts = p.split('/');
273
+
274
+ return parts.slice(1).some((_, n) => {
275
+ const up = parts.slice(0, n + 1).join('/');
276
+
277
+ return !gone.has(up.toLowerCase()) && statOf(up)?.isFile();
278
+ });
279
+ };
280
+
281
+ const held = changes
282
+ .filter((e) => e.oldMode === NO_FILE)
283
+ .map((e) => e.path)
284
+ .filter(inTheWay);
285
+ if (held.length)
286
+ throw new Error(`an ignored file stands where the work goes: ${held.slice(0, 5).join(', ')}`);
287
+ }
288
+
289
+ /**
290
+ * Move the disk from one tree to the other. Git's own word on the result is the only word: what
291
+ * it writes cannot be read back reliably (a blob stored with CRLF under autocrlf hashes to
292
+ * another, a `.gitignore` hides a path from `git add`), and a check that misreads would hold the
293
+ * switch, and every claim of the project behind it, forever. `held`: it could not do it all,
294
+ * also when it only warned of a file it could not unlink and exited 0.
295
+ */
296
+ function moveFiles(dir, index, from, to) {
297
+ const env = { GIT_INDEX_FILE: index, LC_ALL: 'C', LANGUAGE: 'C' };
298
+ const r = git(dir, ['read-tree', '-m', '-u', from, to], { env });
299
+
300
+ return {
301
+ ...r,
302
+ // Checked before a single file moves (unpack-trees), so nothing has happened yet.
303
+ refused: !r.ok && /not uptodate/.test(r.err),
304
+ held: !r.ok || /unable to unlink/.test(r.err),
305
+ };
306
+ }
307
+
308
+ /** Only a sharing violation: a broken link or a file with no read right is no hold to wait out. */
309
+ function refuseIfLocked(file) {
310
+ try {
311
+ closeSync(openSync(file, 'r'));
312
+ } catch (e) {
313
+ if (/** @type {NodeJS.ErrnoException} */ (e).code === 'EBUSY') throw e;
314
+ }
315
+ }
316
+
317
+ /** Whether a file and a folder would want the same place: `a` and `a/b`, in any case. */
318
+ const clashes = (p, others) => {
319
+ const low = p.toLowerCase();
320
+
321
+ return others
322
+ .map((o) => o.toLowerCase())
323
+ .some((o) => o.startsWith(`${low}/`) || low.startsWith(`${o}/`));
324
+ };
325
+
326
+ /**
327
+ * The switch's paths the disk still holds as the switch found them: a crash came before them. A
328
+ * path saved by hand since reads as moved, and stays. Through an index of those entries, as
329
+ * `git add` compares: it keeps a blob stored with CRLF as stored. A case-only rename has two
330
+ * names for one file on a folder that ignores case, so the pair goes as one: with the same blob
331
+ * neither is due, or the file itself would go; edited too, both, while the disk holds the old.
332
+ */
333
+ function stillDue(dir, source, target) {
334
+ const entries = diff(dir, source, target);
335
+ const was = entries.filter((e) => e.oldMode !== NO_FILE);
336
+ const index = tmpIndex();
337
+ const env = { GIT_INDEX_FILE: index, GIT_OPTIONAL_LOCKS: '1' };
338
+ let differs;
339
+ try {
340
+ const input = was.map((e) => `${e.oldMode} ${e.oldOid}\t${e.path}\0`).join('');
341
+ must(dir, ['update-index', '-z', '--index-info'], { env, input });
342
+ // Its exit says some differ: the list below says which.
343
+ git(dir, ['update-index', '-q', '--refresh'], { env });
344
+ differs = new Set(must(dir, ['diff-files', '--name-only', '-z'], { env }).split('\0'));
345
+ } finally {
346
+ dropIndex(index);
347
+ }
348
+
349
+ const fileAt = (p) => {
350
+ const st = statAt(path.join(dir, p));
351
+
352
+ return st && !st.isDirectory();
353
+ };
354
+
355
+ const names = new Map();
356
+ for (const e of entries) {
357
+ const name = e.path.toLowerCase();
358
+ names.set(name, [...(names.get(name) ?? []), e]);
359
+ }
360
+
361
+ return entries
362
+ .filter((e) => e.oid !== e.oldOid)
363
+ .filter((e) => {
364
+ const pair = names.get(e.path.toLowerCase());
365
+ const left = pair.find((x) => x.mode === NO_FILE);
366
+ const came = pair.find((x) => x.oldMode === NO_FILE);
367
+ if (pair.length === 2 && left && came) {
368
+ if (left.oldOid === came.oid) return false;
369
+ if (fileAt(left.path) && differs.has(left.path)) refuseIfLocked(path.join(dir, left.path));
370
+
371
+ return !differs.has(left.path);
372
+ }
373
+
374
+ const here = fileAt(e.path);
375
+ // A file locked outright reads as differing, as a human's save would: it is neither.
376
+ if (here && differs.has(e.path)) refuseIfLocked(path.join(dir, e.path));
377
+ // A file the target has and the disk lost: a move that died between its unlink and its write.
378
+ if (e.mode !== NO_FILE && !here) return true;
379
+
380
+ return e.oldMode === NO_FILE ? !here : !differs.has(e.path);
381
+ })
382
+ .map((e) => e.path);
383
+ }
384
+
385
+ function readJournal(dir, rev) {
386
+ const parents = must(dir, ['log', '-1', '--format=%P', rev]).split(' ');
387
+ const body = must(dir, ['log', '-1', '--format=%b', rev]);
388
+
389
+ return { rev, parents, ...JSON.parse(body) };
390
+ }
391
+
392
+ /** The disk's tree for a baseline. A disk git cannot read holds the switch: a file is locked. */
393
+ function treeNow(dir, j) {
394
+ let disk;
395
+ try {
396
+ disk = snapshot(dir);
397
+
398
+ return disk.tree;
399
+ } catch (e) {
400
+ throw heldError(j, e.message);
401
+ } finally {
402
+ if (disk) dropIndex(disk.index);
403
+ }
404
+ }
405
+
406
+ /**
407
+ * The index's tree, read on a copy: a lock on the real one does not stop it. A path in conflict
408
+ * has no one entry and stays out: its stages come from commits, the rest still count.
409
+ */
410
+ function indexTree(dir) {
411
+ const index = tmpIndex();
412
+ const real = realIndex(dir);
413
+ try {
414
+ if (existsSync(real)) copyFileSync(real, index);
415
+ const env = { GIT_INDEX_FILE: index };
416
+ const records = must(dir, ['ls-files', '-u', '-z'], { env }).split('\0').filter(Boolean);
417
+ const input = [...new Set(records.map((r) => r.slice(r.indexOf('\t') + 1)))].join('\0');
418
+ if (input) must(dir, ['update-index', '--force-remove', '-z', '--stdin'], { env, input });
419
+
420
+ return must(dir, ['write-tree'], { env });
421
+ } finally {
422
+ dropIndex(index);
423
+ }
424
+ }
425
+
426
+ /**
427
+ * Staged text no tree of the switch holds, as each is read from the disk: the reset that follows
428
+ * would drop its only copy, and a path resets what lies under it too. A commit of the index keeps
429
+ * it; returns the tip of the card's chain.
430
+ */
431
+ function keepStaged(dir, j, source, paths) {
432
+ const kept = resolve(dir, stagedRef(j.from));
433
+ const index = indexTree(dir);
434
+ const head = must(dir, ['rev-parse', 'HEAD']);
435
+ const inSwitch = (p) => paths.some((x) => p === x || p.startsWith(`${x}/`));
436
+ const staged = new Set(
437
+ diff(dir, head, index)
438
+ .filter((e) => e.mode !== NO_FILE)
439
+ .map((e) => e.path),
440
+ );
441
+ const lost = diff(dir, source, index).some((e) => staged.has(e.path) && inSwitch(e.path));
442
+ if (!lost || (kept && must(dir, ['rev-parse', `${kept}^{tree}`]) === index)) return kept;
443
+ const next = commit(dir, index, kept ? [kept, head] : [head], `gcf(staged): ${j.from}`);
444
+ must(dir, ['update-ref', stagedRef(j.from), next]);
445
+
446
+ return next;
447
+ }
448
+
449
+ /**
450
+ * Index and refs of a switch whose files have moved. Each step repeated gives the same result. A
451
+ * shelve's baseline is the disk now, not the target: what the switch made visible (a card's
452
+ * ignored output, once its `.gitignore` left) is no work of the card coming in.
453
+ */
454
+ function settle(dir, j, step) {
455
+ const source = j.parents[1];
456
+ const paths = diff(dir, source, j.rev).map((e) => e.path);
457
+ const staged = keepStaged(dir, j, source, paths);
458
+ if (paths.length) {
459
+ const input = paths.join('\0');
460
+ // A file written anew may differ in size from the old entry with the same blob (autocrlf):
461
+ // git calls that modified, unread. An entry made anew carries no stat to believe.
462
+ must(dir, ['update-index', '--force-remove', '-z', '--stdin'], { input });
463
+ must(dir, ['reset', '-q', '--pathspec-from-file=-', '--pathspec-file-nul'], { input });
464
+ }
465
+
466
+ step?.('index');
467
+ if (j.kind === 'return') return finishReturn(dir, j, staged, step);
468
+ const head = must(dir, ['rev-parse', 'HEAD']);
469
+ const next = commit(dir, treeNow(dir, j), [head], baselineMessage(j.incoming));
470
+ refs(dir, [`update ${WORK} ${next}`, `delete ${SWITCH}`]);
471
+ // Against the journal, not the ref now: a pass that died after keeping it still tells it.
472
+ const told = staged && staged !== (j.kept ?? null) ? { staged } : {};
473
+
474
+ return { shelved: { id: j.from, files: j.files, branch: `work/${j.from}`, ...told } };
475
+ }
476
+
477
+ /** A return's report as a blob for its owed ref, over what its card has not heard yet. */
478
+ function owedBlob(dir, j, returned) {
479
+ const report = { returned, moved: j.moved, conflicts: j.conflicts };
480
+ const owed = readOwed(dir, owedRef(j.from));
481
+ const input = JSON.stringify(owed ? withReturn(owed, report) : report);
482
+
483
+ return must(dir, ['hash-object', '-w', '--stdin'], { input });
484
+ }
485
+
486
+ /**
487
+ * The refs of a return. A branch that moved on since it began holds someone's commits: it stays,
488
+ * and the card's work still comes back. Staged text is told once: the note reaches what it told.
489
+ */
490
+ function finishReturn(dir, j, staged, step) {
491
+ const [shelf, source, baseline = source] = j.parents;
492
+ const back = resolve(dir, returnedRef(j.from));
493
+ const tip = resolve(dir, branchRef(j.from));
494
+ const told = staged && back && git(dir, ['merge-base', '--is-ancestor', staged, back]).ok;
495
+ const yes = trailer(dir, shelf, WHOLE) === 'yes' ? `\n\n${WHOLE}: yes` : '';
496
+ const shelfTree = must(dir, ['rev-parse', `${shelf}^{tree}`]);
497
+ // Parents, not a new tip alone: the copy an earlier return named stays reachable.
498
+ const parents = [back, shelf, staged].filter(Boolean);
499
+ const note = commit(dir, shelfTree, parents, `gcf(returned): ${j.from}${yes}`);
500
+ const blob = owedBlob(dir, j, {
501
+ id: j.from,
502
+ files: j.files,
503
+ copy: shelf,
504
+ ...(staged && !told ? { staged } : {}),
505
+ ...(tip && tip !== shelf ? { branch_moved: true } : {}),
506
+ });
507
+ step?.('refs');
508
+ // Its report goes with the journal, whoever's claim this is: it waits for its card's next word,
509
+ // and a death after this loses neither.
510
+ refs(dir, [
511
+ `update ${owedRef(j.from)} ${blob}`,
512
+ `update ${returnedRef(j.from)} ${note}`,
513
+ // Its old value too: a commit landing this moment fails this, and the next claim keeps it.
514
+ tip === shelf && `delete ${branchRef(j.from)} ${shelf}`,
515
+ resolve(dir, shelvedRef(j.from)) && `delete ${shelvedRef(j.from)}`,
516
+ `update ${WORK} ${baseline}`,
517
+ `delete ${SWITCH}`,
518
+ ]);
519
+
520
+ return {};
521
+ }
522
+
523
+ /**
524
+ * The way out of a switch that cannot finish. A shelve's journal may go: every path stays the
525
+ * card's. A return's may not: it merges again over what came back, and its markers nest.
526
+ */
527
+ const giveUp = (j, words) =>
528
+ j.kind === 'return'
529
+ ? `Keep ${SWITCH}: deleting it merges the work again over what came back`
530
+ : `${words}, git update-ref -d ${SWITCH}, then gcf claim ${j.from}`;
531
+
532
+ /** A switch that cannot finish: what holds it, and the way out when nothing lets go of it. */
533
+ function heldError(j, detail) {
534
+ return new Error(
535
+ `a file is held: ${detail}. Close what holds it: the next claim finishes the move. ` +
536
+ `${giveUp(j, 'If nothing does')}. If git names a broken index, delete it ` +
537
+ '(git rev-parse --git-path index), then git reset',
538
+ );
539
+ }
540
+
541
+ /** A switch a file on the disk stands against: nothing holds it, so the operator moves it. */
542
+ function blockedError(j, detail) {
543
+ return new Error(
544
+ `a file is in the way: ${detail}. Move it aside: the next claim finishes the move. ` +
545
+ `${giveUp(j, 'To keep it there')}`,
546
+ );
547
+ }
548
+
549
+ /** A return ends by deleting its branch: a worktree on it, with no commit yet, would lose HEAD. */
550
+ function refuseBranchTaken(dir, j) {
551
+ if (j.kind !== 'return' || resolve(dir, branchRef(j.from)) !== j.parents[0]) return;
552
+ try {
553
+ refuseWorktreeBranch(dir, j.from);
554
+ } catch {
555
+ throw new Error(
556
+ `work/${j.from} is checked out in a worktree: commit there or remove it, ` +
557
+ 'and the next claim then finishes the return',
558
+ );
559
+ }
560
+ }
561
+
562
+ /** Finish the switch a journal names: what it still owes, then index and refs. No journal: none. */
563
+ function finishSwitch(dir, step) {
564
+ const rev = resolve(dir, SWITCH);
565
+ if (!rev) return {};
566
+ const j = readJournal(dir, rev);
567
+ refuseBranchTaken(dir, j);
568
+ let disk;
569
+ try {
570
+ const due = stillDue(dir, j.parents[1], rev);
571
+ if (due.length) {
572
+ disk = snapshot(dir);
573
+ // A file and a folder for one place, and a human's save is in one of them: nothing moves.
574
+ const off = new Set(diff(dir, rev, disk.tree).map((e) => e.path));
575
+ const saved = diff(dir, j.parents[1], disk.tree)
576
+ .map((e) => e.path)
577
+ .filter((f) => off.has(f));
578
+ const hit = due.find((d) => clashes(d, saved));
579
+ if (hit) throw blockedError(j, `a file saved since stands in the way of ${hit}`);
580
+ const target = overlay(dir, disk.tree, rev, due);
581
+ try {
582
+ refuseIgnoredInTheWay(dir, disk, target);
583
+ } catch (e) {
584
+ throw blockedError(j, e.message);
585
+ }
586
+
587
+ const moved = moveFiles(dir, disk.index, disk.tree, target);
588
+ if (moved.held) throw heldError(j, moved.err);
589
+ }
590
+ } catch (e) {
591
+ throw /^a file (is held|is in the way)/.test(e.message) ? e : heldError(j, e.message);
592
+ } finally {
593
+ if (disk) dropIndex(disk.index);
594
+ }
595
+
596
+ step?.('files');
597
+
598
+ return settled(dir, j, step);
599
+ }
600
+
601
+ /**
602
+ * The switch's last steps, its files moved: a journal deleted now moves them again, so no way out
603
+ * deletes it, on the first refusal too. What git names is its own to clear.
604
+ */
605
+ function settled(dir, j, step) {
606
+ try {
607
+ return settle(dir, j, step);
608
+ } catch (e) {
609
+ if (/^a file (is held|is in the way)/.test(e.message)) throw e;
610
+ throw new Error(
611
+ `the files have moved, the last step failed: ${e.message}. Keep ${SWITCH}: deleting it ` +
612
+ 'moves them again. Clear what git names (a .lock a dead git left; a broken index: ' +
613
+ 'delete it, git rev-parse --git-path index, then git reset): the next claim finishes the ' +
614
+ 'move',
615
+ { cause: e },
616
+ );
617
+ }
618
+ }
619
+
620
+ /**
621
+ * Move the folder as the journal says. A refusal before anything moved (a file saved in the
622
+ * window) means a retry from a new snapshot, so nothing of it is lost: `undo` takes the journal
623
+ * back. Anything else may have moved some: the journal stands, and goes on as a crash's recovery.
624
+ */
625
+ function applySwitch(dir, { disk, target, journal, undo }, step) {
626
+ const j = readJournal(dir, journal);
627
+ step?.('journal');
628
+ const moved = moveFiles(dir, disk.index, disk.tree, target);
629
+ if (moved.refused) {
630
+ undo();
631
+
632
+ return null;
633
+ }
634
+
635
+ if (moved.held) return finishSwitch(dir, step);
636
+ step?.('files');
637
+
638
+ return settled(dir, j, step);
639
+ }
640
+
641
+ function shelve(dir, base, incoming, step) {
642
+ const branch = branchRef(base.id);
643
+ for (let attempt = 0; attempt < 2; attempt++) {
644
+ const disk = snapshot(dir);
645
+ try {
646
+ const head = resolve(dir, 'HEAD');
647
+ const paths = cardPaths(dir, base, disk.tree, head);
648
+ if (!paths.length) {
649
+ noteCodeOnMain(dir, base, head);
650
+ pin(dir, incoming, disk.tree, head);
651
+
652
+ return {};
653
+ }
654
+
655
+ if (shelvedIn(dir, base.id))
656
+ throw new Error(`work/${base.id} holds earlier work: gcf claim ${base.id} brings it back`);
657
+ if (resolve(dir, branch))
658
+ throw new Error(
659
+ `branch work/${base.id} exists and is not ours to overwrite: rename or delete it`,
660
+ );
661
+ const headTree = must(dir, ['rev-parse', `${head}^{tree}`]);
662
+ const tail = whole(dir, base, head) ? `\n${WHOLE}: yes` : '';
663
+ const shelf = commit(
664
+ dir,
665
+ overlay(dir, headTree, disk.tree, paths),
666
+ [head],
667
+ `gcf(shelve): ${base.id}: ${incoming} claimed the folder\n\n${SHELVED}: ${base.id}${tail}`,
668
+ );
669
+ const target = overlay(dir, disk.tree, headTree, paths);
670
+ refuseIgnoredInTheWay(dir, disk, target);
671
+ const source = commit(dir, disk.tree, [head], `gcf(main-switch): ${base.id} as it stood`);
672
+ const kept = resolve(dir, stagedRef(base.id));
673
+ const body = { kind: 'shelve', from: base.id, incoming, files: paths.length, kept };
674
+ const journal = commit(
675
+ dir,
676
+ target,
677
+ [shelf, source],
678
+ `gcf(main-switch): ${incoming}\n\n${JSON.stringify(body)}`,
679
+ );
680
+ refs(dir, [
681
+ `create ${branch} ${shelf}`,
682
+ `update ${shelvedRef(base.id)} ${shelf}`,
683
+ `update ${SWITCH} ${journal}`,
684
+ ]);
685
+ const undo = () =>
686
+ refs(dir, [
687
+ `delete ${branch} ${shelf}`,
688
+ `delete ${shelvedRef(base.id)}`,
689
+ `delete ${SWITCH}`,
690
+ ]);
691
+ const done = applySwitch(dir, { disk, target, journal, undo }, step);
692
+ if (done) return done;
693
+ } finally {
694
+ dropIndex(disk.index);
695
+ }
696
+ }
697
+
698
+ throw new Error(`a file of ${base.id} was saved while the folder moved, twice: try again`);
699
+ }
700
+
701
+ /** `merge-tree --write-tree -z`: the tree, then each conflicted path's stages. */
702
+ function parseMerge(out) {
703
+ const [tree, ...rest] = out.split('\0');
704
+ const end = rest.indexOf('');
705
+ const stages = new Map();
706
+ for (const rec of rest.slice(0, end < 0 ? rest.length : end)) {
707
+ const m = rec.match(/^\d+ ([0-9a-f]+) (\d)\t(.+)$/s);
708
+ if (!m) continue;
709
+ if (!stages.has(m[3])) stages.set(m[3], {});
710
+ stages.get(m[3])[m[2]] = m[1];
711
+ }
712
+
713
+ return { tree, stages };
714
+ }
715
+
716
+ function returnWork(dir, id, step) {
717
+ const shelf = must(dir, ['rev-parse', branchRef(id)]);
718
+ const base = must(dir, ['rev-parse', `${shelf}^`]);
719
+ const card = `gcf/work/${id}.md`;
720
+ for (let attempt = 0; attempt < 2; attempt++) {
721
+ const disk = snapshot(dir);
722
+ try {
723
+ const head = must(dir, ['rev-parse', 'HEAD']);
724
+ const start = commit(dir, disk.tree, [head], `gcf(main-switch): ${id} as it stood`);
725
+ // What stands on disk as the shelf has it (a move given up halfway) is still the card's.
726
+ const same = new Set(diff(dir, disk.tree, shelf).map((e) => e.path));
727
+ const beside = diff(dir, base, disk.tree).map((e) => e.path);
728
+ const stayed = diff(dir, base, shelf)
729
+ .map((e) => e.path)
730
+ .filter((p) => !same.has(p) && !clashes(p, beside));
731
+ const baseline = commit(
732
+ dir,
733
+ overlay(dir, disk.tree, base, stayed),
734
+ [head],
735
+ baselineMessage(id),
736
+ );
737
+ const merged = git(dir, [
738
+ 'merge-tree',
739
+ '--write-tree',
740
+ '-z',
741
+ `--merge-base=${base}`,
742
+ start,
743
+ shelf,
744
+ ]);
745
+ if (merged.status !== 0 && merged.status !== 1)
746
+ throw new Error(`git merge-tree: ${merged.err}`);
747
+ const { tree, stages } = parseMerge(merged.out);
748
+ // A conflict on the card's own file takes main's, the rule of a resumed worktree.
749
+ const target = stages.has(card) ? overlay(dir, tree, disk.tree, [card]) : tree;
750
+ refuseIgnoredInTheWay(dir, disk, target);
751
+ const changed = new Map(diff(dir, disk.tree, target).map((e) => [e.path, e.oid]));
752
+ const conflicts = [...stages].map(([p, s]) => ({
753
+ path: p,
754
+ // Git keeps main's file for a binary: no markers to resolve, the card's copy stays on
755
+ // the returned ref. A marker file differs from both sides.
756
+ kept_main: p === card || Boolean(s[2] && s[3] && !changed.has(p)),
757
+ }));
758
+ const files = must(dir, ['diff-tree', '-r', '--name-only', '--no-renames', base, shelf])
759
+ .split('\n')
760
+ .filter(Boolean).length;
761
+ const moved = Number(must(dir, ['rev-list', '--count', `${base}..${head}`]));
762
+ const body = { kind: 'return', from: id, incoming: id, files, moved, conflicts };
763
+ const journal = commit(
764
+ dir,
765
+ target,
766
+ [shelf, start, baseline],
767
+ `gcf(main-switch): ${id}\n\n${JSON.stringify(body)}`,
768
+ );
769
+ must(dir, ['update-ref', SWITCH, journal]);
770
+ const undo = () => must(dir, ['update-ref', '-d', SWITCH]);
771
+ const done = applySwitch(dir, { disk, target, journal, undo }, step);
772
+ if (done) return done;
773
+ } finally {
774
+ dropIndex(disk.index);
775
+ }
776
+ }
777
+
778
+ throw new Error(`a file was saved while ${id}'s work came back, twice: try again`);
779
+ }
780
+
781
+ /** The shelf's tip says it: a worktree run that verified the branch has moved past it. */
782
+ function shelvedIn(dir, id) {
783
+ return resolve(dir, branchRef(id)) !== null && trailer(dir, branchRef(id), SHELVED).includes(id);
784
+ }
785
+
786
+ const EMPTY = { shelved: null, returned: null, moved: 0, conflicts: [] };
787
+
788
+ /** `later` over `earlier`: its words win, and a conflict named by either stays named. */
789
+ function withReturn(earlier, later) {
790
+ const paths = new Set(later.conflicts.map((c) => c.path));
791
+
792
+ return {
793
+ returned: { ...earlier.returned, ...later.returned },
794
+ // The most it missed: the commit behind an earlier conflict still counts.
795
+ moved: Math.max(earlier.moved, later.moved),
796
+ conflicts: [...earlier.conflicts.filter((c) => !paths.has(c.path)), ...later.conflicts],
797
+ };
798
+ }
799
+
800
+ /**
801
+ * What a return has to tell its card (finishReturn). It may be another card's claim that finished
802
+ * it, or this claim may yet refuse: a session must not miss its markers and its staged text.
803
+ */
804
+ function readOwed(dir, ref) {
805
+ const blob = git(dir, ['cat-file', 'blob', ref]);
806
+
807
+ return blob.ok ? JSON.parse(blob.out) : null;
808
+ }
809
+
810
+ /** The report of this claim, with what a return left for this card; paid last, if it can be. */
811
+ function paid(dir, id, report) {
812
+ const ref = owedRef(id);
813
+ const owed = readOwed(dir, ref);
814
+ if (!owed) return report;
815
+ const told = { ...report, ...withReturn(owed, report) };
816
+ must(dir, ['update-ref', '-d', ref]);
817
+
818
+ return told;
819
+ }
820
+
821
+ function refuseLostBranch(dir, id) {
822
+ const shelf = resolve(dir, shelvedRef(id));
823
+ if (!shelf || resolve(dir, branchRef(id))) return;
824
+ // A worktree run took the branch and it was merged: the work is on main, nothing is lost.
825
+ if (git(dir, ['merge-base', '--is-ancestor', shelf, 'HEAD']).ok) {
826
+ must(dir, ['update-ref', '-d', shelvedRef(id)]);
827
+
828
+ return;
829
+ }
830
+
831
+ throw new Error(
832
+ `branch work/${id} that held its work is gone. The work is at ${shelvedRef(id)}: ` +
833
+ `git branch work/${id} ${shelvedRef(id)} brings it back, ` +
834
+ `git update-ref -d ${shelvedRef(id)} gives it up`,
835
+ );
836
+ }
837
+
838
+ /** A worktree run owns the branch it has checked out: its folder holds more than the shelf. */
839
+ function refuseWorktreeBranch(dir, id) {
840
+ const list = must(dir, ['worktree', 'list', '--porcelain']);
841
+ if (list.split(/\r?\n/).includes(`branch ${branchRef(id)}`))
842
+ throw new Error(`work/${id} is checked out in a worktree: run the card there, or remove it`);
843
+ }
844
+
845
+ /** Another session lives here: nothing moves, and the folder has no baseline until it is clean. */
846
+ function shareFolder(dir, id, waiting) {
847
+ if (waiting) throw new Error('another session works in the folder: its work waits for it');
848
+ const head = must(dir, ['rev-parse', 'HEAD']);
849
+ markNotWhole(dir, id, head);
850
+ const base = baselineOf(dir);
851
+ if (!base) return;
852
+ noteCodeOnMain(dir, base, head);
853
+ must(dir, ['update-ref', '-d', WORK]);
854
+ }
855
+
856
+ /** No baseline when the disk cannot be read (a file locked, a nested empty repository). */
857
+ function pinDisk(dir, id) {
858
+ let disk;
859
+ try {
860
+ disk = snapshot(dir);
861
+ pin(dir, id, disk.tree, must(dir, ['rev-parse', 'HEAD']));
862
+ } catch {
863
+ markNotWhole(dir, id, must(dir, ['rev-parse', 'HEAD']));
864
+ } finally {
865
+ if (disk) dropIndex(disk.index);
866
+ }
867
+ }
868
+
869
+ /** The card that holds the folder goes to its branch, and this card's work comes back. */
870
+ function takeFolder(dir, id, waiting, step) {
871
+ const busy = operationInProgress(dir);
872
+ const base = baselineOf(dir);
873
+ const due = (base && base.id !== id) || waiting;
874
+ if (due && busy) throw new Error(`a ${busy} is in progress in the folder`);
875
+ const shelved = base && base.id !== id ? shelve(dir, base, id, step) : {};
876
+ if (waiting) return { ...shelved, ...returnWork(dir, id, step) };
877
+ if (busy) markNotWhole(dir, id, must(dir, ['rev-parse', 'HEAD']));
878
+ else if (!baselineOf(dir)) pinDisk(dir, id);
879
+
880
+ return shelved;
881
+ }
882
+
883
+ /**
884
+ * Card `id` takes the folder, under the main lock (`gcf claim`). `shared`: another session lives
885
+ * here. `step`, for a test: called after each step of a switch, and it may throw to stop there.
886
+ * @param {string} projectDir
887
+ * @param {string} id
888
+ * @param {{shared?: boolean, step?: (name: string) => void, gitVersion?: string}} [opts]
889
+ * @returns {{
890
+ * shelved: {id: string, files: number, branch: string} | null,
891
+ * returned: {id: string, files: number, branch: string} | null,
892
+ * moved: number,
893
+ * conflicts: {path: string, kept_main: boolean}[],
894
+ * }}
895
+ */
896
+ export function enterFolder(projectDir, id, { shared = false, step, gitVersion } = {}) {
897
+ const dir = folderOf(projectDir, gitVersion);
898
+ if (!dir) return EMPTY;
899
+ try {
900
+ const recovered = finishSwitch(dir, step);
901
+ const waiting = shelvedIn(dir, id);
902
+ if (waiting) refuseWorktreeBranch(dir, id);
903
+ else refuseLostBranch(dir, id);
904
+ if (shared) {
905
+ shareFolder(dir, id, waiting);
906
+
907
+ return paid(dir, id, { ...EMPTY, ...recovered });
908
+ }
909
+
910
+ return paid(dir, id, { ...EMPTY, ...recovered, ...takeFolder(dir, id, waiting, step) });
911
+ } catch (e) {
912
+ const message = `${id}: the folder cannot change hands: ${e.message}`;
913
+ throw refusal('shelve', { reason: e.message }, message);
914
+ }
915
+ }
916
+
917
+ /** The card the folder's baseline names, or null. */
918
+ export function folderCard(projectDir) {
919
+ const dir = path.resolve(projectDir);
920
+ if (!resolve(dir, WORK) || !folderOf(dir)) return null;
921
+
922
+ return baselineOf(dir)?.id ?? null;
923
+ }
924
+
925
+ /** The card in the folder and its paths, or null: no read of the disk without a baseline. */
926
+ export function mainWork(projectDir) {
927
+ const dir = path.resolve(projectDir);
928
+ if (!resolve(dir, WORK) || !folderOf(dir)) return null;
929
+ const base = baselineOf(dir);
930
+ if (!base) return null;
931
+ let disk;
932
+ try {
933
+ disk = snapshot(dir);
934
+
935
+ return {
936
+ id: base.id,
937
+ paths: cardPaths(dir, base, disk.tree, must(dir, ['rev-parse', 'HEAD'])),
938
+ };
939
+ } catch {
940
+ // A disk it cannot read: an audit still answers, and the loose work reads as a human's.
941
+ return null;
942
+ } finally {
943
+ if (disk) dropIndex(disk.index);
944
+ }
945
+ }
946
+
947
+ /** Whether the card's work waits on its branch. */
948
+ export const isShelved = (projectDir, id) => {
949
+ const dir = path.resolve(projectDir);
950
+
951
+ return folderOf(dir) !== null && shelvedIn(dir, id);
952
+ };
953
+
954
+ /** Whether a switch not finished (a file held) moves this card's work or brings it in. */
955
+ export function inSwitch(projectDir, id) {
956
+ const dir = path.resolve(projectDir);
957
+ const rev = folderOf(dir) ? resolve(dir, SWITCH) : null;
958
+ if (!rev) return false;
959
+ const j = readJournal(dir, rev);
960
+
961
+ return j.from === id || j.incoming === id;
962
+ }
963
+
964
+ /** Whether the shelf holds all of the card's code: none of it ever reached main. */
965
+ export const wholeOnShelf = (projectDir, id) =>
966
+ isShelved(projectDir, id) && trailer(path.resolve(projectDir), branchRef(id), WHOLE) === 'yes';
967
+
968
+ /** Every shelved card, one read of the branches: id → the files it holds, the commits it missed. */
969
+ export function shelvedCards(projectDir) {
970
+ const dir = path.resolve(projectDir);
971
+ const format = `--format=%(objectname) %(refname:strip=3) %(trailers:key=${SHELVED},valueonly)`;
972
+ const r = git(dir, ['for-each-ref', format, 'refs/heads/work/']);
973
+ const cards = new Map();
974
+ if (!r.ok) return cards;
975
+ for (const line of r.out.split(/\r?\n/)) {
976
+ const m = line.match(/^(\S+) (\S+) (\S+)$/);
977
+ if (!m || m[2] !== m[3]) continue;
978
+ const files = must(dir, ['diff-tree', '-r', '--name-only', '--no-renames', `${m[1]}^`, m[1]])
979
+ .split('\n')
980
+ .filter(Boolean).length;
981
+ const commits = Number(must(dir, ['rev-list', '--count', `${m[1]}^..HEAD`]));
982
+ cards.set(m[2], { files, commits });
983
+ }
984
+
985
+ return cards;
986
+ }
987
+
988
+ /** The card's run ended with its work committed: what still lies loose is no longer its own. */
989
+ export function leaveFolder(projectDir, id) {
990
+ const dir = path.resolve(projectDir);
991
+ if (resolve(dir, WORK) && folderOf(dir) && baselineOf(dir)?.id === id)
992
+ must(dir, ['update-ref', '-d', WORK]);
993
+ }
994
+
995
+ /** The card ended: its shelf, its returned ref and its baseline go. */
996
+ export function clearCard(projectDir, id) {
997
+ const dir = path.resolve(projectDir);
998
+ if (!folderOf(dir)) return;
999
+ if (shelvedIn(dir, id)) git(dir, ['branch', '-D', `work/${id}`]);
1000
+ for (const ref of [shelvedRef(id), returnedRef(id), stagedRef(id), owedRef(id)])
1001
+ git(dir, ['update-ref', '-d', ref]);
1002
+ leaveFolder(dir, id);
1003
+ }