pi-odd-worktree 3.11.2 → 3.12.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.
@@ -0,0 +1,655 @@
1
+ 'use strict';
2
+ // What each checkout has in `odd/tasks`, and what a worktree has that main does
3
+ // not (odd-rail-section S10).
4
+ //
5
+ // The ODD panel draws one collapsible group per checkout registered in the
6
+ // session, so the grouping question is answered here, once, as ONE pure async
7
+ // function of the machine as it is right now: the main checkout's whole list
8
+ // first, then one group per OWNED worktree carrying only its delta against main.
9
+ // It caches nothing, writes nothing and keeps no state between calls.
10
+ //
11
+ // Checkouts (reuse, not duplication): this module owns the ONE enumeration now
12
+ // that lib/odd-scan.js is gone — one `git worktree list --porcelain -z` read over
13
+ // the package's `runAsync(bin, argv, cwd)` seam, parsed by lib/worktree-registry.js's own
14
+ // porcelain parser, the main row first and then the checkouts this package owns,
15
+ // i.e. the ones under `<repo-parent>/<repo-name>-worktrees` in worktree-name
16
+ // order. Invariant 10: a worktree is a path, not a document, so there is nothing
17
+ // to read and nothing is read. A worktree Git knows outside that directory is not
18
+ // ours and is not grouped — unless the caller asks for EVERY worktree (S11,
19
+ // `all: true` below), which is the `a` mode of the panel and nothing else.
20
+ //
21
+ // S13: the scope is an INPUT, because this machine holds ~20 worktrees and a diff
22
+ // per worktree on every refresh is real cost. `roots` is the set of worktrees the
23
+ // SESSION registered. Absent (undefined/null), the enumeration above is unchanged:
24
+ // every owned worktree. Present as an array, only what Git lists AND that array
25
+ // names is grouped, and the owned-checkout rule no longer applies — registration is
26
+ // the authority, so a worktree registered outside
27
+ // `<repo-parent>/<repo-name>-worktrees` is included. The main checkout is always
28
+ // first and always whole, whether or not `roots` names it, so a root equal to main
29
+ // is never a second group and an empty array is `main` alone. A root Git does not
30
+ // list (stale, deleted, another clone) contributes nothing and never throws. An
31
+ // excluded worktree is never ASKED anything: the git reads below happen only for
32
+ // the included ones.
33
+ //
34
+ // S11: `all: true` is the ADDITIVE third scope, and the only one without a filter:
35
+ // every worktree Git lists except main, registered or not and wherever it lives —
36
+ // the panel's `a` key, whose meaning is "todos los worktrees, da igual si esta
37
+ // registrado o no". It wins over `roots` when a caller passes both, because a
38
+ // caller asking for everything cannot also be asking for a subset. Absent or
39
+ // false it changes nothing: the two scopes above answer exactly as before, which
40
+ // is what every existing caller relies on. Failure is unchanged — an unreadable
41
+ // checkout (a stale registration Git still lists) contributes no document and
42
+ // never throws.
43
+ //
44
+ // The MAIN group (S10) carries EVERY document of `<main>/odd/tasks`, scanned by
45
+ // lib/odd-docs.js's `listOddDocsLocal` — the `<root>/odd/tasks/*.md` rule
46
+ // (non-recursive, regular files only, dotfiles skipped, absent directory = empty)
47
+ // stays stated in exactly one place — and no document carries a `status`, because
48
+ // against itself nothing is new or modified.
49
+ //
50
+ // A WORKTREE group carries ONLY the documents that are new or modified relative
51
+ // to main, and answering that takes two comparisons, both required:
52
+ //
53
+ // (a) THE BRANCH'S OWN WORK, against the MERGE BASE. A plain working-tree diff
54
+ // is not enough: once the worktree commits, its tree matches its own HEAD
55
+ // and the ordinary diff finds nothing. The shape borrowed from
56
+ // lib/worktree-changes.js (`resolveMergeBase`, `git merge-base HEAD <sha>`)
57
+ // and lib/files-index.js (the three-dot comparison against the merge base)
58
+ // is: resolve main's HEAD once, then ask the WORKTREE for
59
+ // `git merge-base HEAD <mainHead>`, and name the documents of that branch
60
+ // with one `git diff --name-status -z --no-renames <base>` — a diff against
61
+ // the merge-base COMMIT with no second revision, so committed and
62
+ // not-yet-committed work both count. `--no-renames` keeps the read
63
+ // read-only (rename detection is what makes Git fetch a missing blob in a
64
+ // partial clone and write a pack) and spells a rename as delete plus add.
65
+ // The working tree's own status is unioned in, exactly as the files panel
66
+ // unions it: a brand-new document that is still untracked has no commit to
67
+ // name it, and "new relative to main" is the case the group exists for.
68
+ //
69
+ // (b) THE BYTES. A document the first comparison names is still not a
70
+ // difference when its CONTENT equals main's current copy — the case the
71
+ // user named, where main advanced and the worktree's copy happens to be
72
+ // byte-identical. Both sides are read and compared as buffers; an equal
73
+ // pair is dropped. This is also why `status` is decided by main's own
74
+ // listing rather than by Git's letter: `added` is a path main does not
75
+ // have, `modified` a path it does.
76
+ //
77
+ // Order (two rules that never fight): the groups come back main first, then the
78
+ // owned worktrees by name; within a group the most recently modified document
79
+ // comes first, then the ODD name, then the document path — code-unit comparisons
80
+ // only, never `localeCompare`, so the sequence is identical on every host and
81
+ // every run.
82
+ //
83
+ // Cost: one `git worktree list`, then per worktree WITH documents to compare one
84
+ // `merge-base`, one `diff` and one `status` — and one `rev-parse HEAD` in the main
85
+ // checkout for the whole call, resolved lazily so a machine whose worktrees hold
86
+ // no documents runs no git beyond the listing. No `git log`, no history walk, no
87
+ // per-document process.
88
+ //
89
+ // Failure is silence, never a throw: an unreadable checkout, an absent
90
+ // `odd/tasks`, a `merge-base`, `diff` or `status` that fails or throws, a main
91
+ // HEAD that cannot be read — each contributes no document. An empty delta is a
92
+ // group with `docs: []`, NOT a missing group: whether an empty group is drawn is
93
+ // the CALLER's decision (S10/S13: a worktree with no difference keeps the panel in
94
+ // its ordinary main-only listing), so this module never makes that call.
95
+
96
+ const fs = require('node:fs');
97
+ const path = require('node:path');
98
+
99
+ const { ownedCheckouts, parseWorktreePorcelain } = require('./worktree-registry.js');
100
+ const { listOddDocsLocal, TASKS_DIR } = require('./odd-docs.js');
101
+
102
+ const MAIN = 'main';
103
+ // Git wants forward slashes even on Windows, and so does every path this module
104
+ // compares against Git's own output.
105
+ const TASKS_POSIX = TASKS_DIR.split(path.sep).join('/');
106
+
107
+ // S13 (T13): the one listing read whose failure is not a machine with no
108
+ // worktrees. With `failClosed` a caller that may not degrade to "the session's
109
+ // own checkout, called main" gets `null` instead of a model.
110
+ const WORKTREE_LIST_ARGS = ['worktree', 'list', '--porcelain', '-z'];
111
+ const HEAD_ARGS = ['rev-parse', 'HEAD'];
112
+ // The working tree's own work, limited to the one directory the group is about.
113
+ // `--no-optional-locks` keeps the read read-only: the stat-cache refresh Git would
114
+ // otherwise write back into `.git/index` is skipped.
115
+ const STATUS_ARGS = [
116
+ '--no-optional-locks',
117
+ 'status',
118
+ '--porcelain=v1',
119
+ '-z',
120
+ '--untracked-files=all',
121
+ '--',
122
+ TASKS_POSIX,
123
+ ];
124
+ // (a) above: the branch's net change against the merge-base COMMIT, one fixed
125
+ // argv array per call. `--` says the argument list ends before any path could
126
+ // start, so a checkout holding a file named like a revision cannot break the read.
127
+ const diffArgs = (base) => ['diff', '--name-status', '-z', '--no-renames', base, '--', TASKS_POSIX];
128
+
129
+ // The one configuration that would corrupt a read: `core.quotePath=false` keeps a
130
+ // non-ASCII path readable instead of octal-escaped.
131
+ const GIT_CONFIG_ARGS = ['-c', 'core.quotePath=false'];
132
+ const GIT_TIMEOUT_MS = 5000;
133
+
134
+ const compareText = (a, b) => (a === b ? 0 : a < b ? -1 : 1);
135
+
136
+ /** Worktrees order by name, so the sequence never depends on Git's own. */
137
+ function compareCheckout(a, b) {
138
+ const named = compareText(path.basename(a.path), path.basename(b.path));
139
+ return named === 0 ? compareText(a.path, b.path) : named;
140
+ }
141
+
142
+ /** One group's documents: most recently modified first, then name, then path. */
143
+ function compareDocs(a, b) {
144
+ if (a.mtimeMs !== b.mtimeMs) return b.mtimeMs - a.mtimeMs;
145
+ return compareText(a.name, b.name) || compareText(a.docPath, b.docPath);
146
+ }
147
+
148
+ const samePath = (a, b) => a.length > 1 && b.length > 1 && a.replace(/[\\/]+$/, '') === b.replace(/[\\/]+$/, '');
149
+
150
+ /**
151
+ * The checkouts to group: the main checkout first, then the worktrees in scope.
152
+ * `entries` is `git worktree list`'s answer, or null when git could not give one —
153
+ * and then the caller's own root is the only checkout there is, reported as the
154
+ * main one because with no listing nothing can tell the two apart. `scope` is the
155
+ * normalized set of registered roots, or null when the caller scoped nothing and
156
+ * every owned worktree is in play (S13). `all` is the unfiltered scope of S11: every
157
+ * listed worktree except main, registration and location ignored.
158
+ */
159
+ function checkoutsOf(entries, repoRoot, scope, all) {
160
+ if (entries === null) return [{ root: repoRoot, name: MAIN }];
161
+ const main = mainOf(entries, repoRoot);
162
+ const mainRoot = main.root;
163
+ const rest = entries.filter((entry) => entry !== main.entry
164
+ && !(entry && typeof entry.path === 'string' && samePath(entry.path, mainRoot)));
165
+ // S11: `all` is the ONE unfiltered scope — every listed worktree except main.
166
+ // Otherwise registration (or its absence) decides, exactly as before.
167
+ let worktrees = [];
168
+ if (all === true) {
169
+ worktrees = rest.filter((entry) => entry && typeof entry.path === 'string' && entry.path.length > 0);
170
+ } else {
171
+ worktrees = scope === null ? ownedCheckouts(rest, mainRoot) : registeredCheckouts(rest, scope);
172
+ }
173
+ const checkouts = [{ root: mainRoot, name: MAIN }];
174
+ for (const entry of worktrees.sort(compareCheckout)) {
175
+ checkouts.push({ root: entry.path, name: path.basename(entry.path) });
176
+ }
177
+ return checkouts;
178
+ }
179
+
180
+ // T17/F1/T18: WHICH listed entry is main. Git's first record is the main worktree for
181
+ // an ordinary repository, but not for every shape: a repository created with
182
+ // `git init --separate-git-dir` is listed with its METADATA directory in that place
183
+ // (Git derives the main record from the COMMON dir), and a bare repository is listed
184
+ // as itself. Electing the first record blindly made main a directory with no
185
+ // `odd/tasks`, and bare `/odd` then reported that the checkout had no documents at all.
186
+ //
187
+ // So main is the record that OWNS the repository: a checkout owns it when its own
188
+ // `.git` marker — the directory of an ordinary repository, or the link file a separate
189
+ // git dir writes — resolves to the common dir ITSELF. A linked worktree's marker points
190
+ // inside `<common>/worktrees`, so it never does, which is exactly what tells main apart
191
+ // from every other checkout of the clone. A record equal to or inside the common dir is
192
+ // a METADATA tree, never a checkout, so nothing under its `odd/tasks` is main's — the
193
+ // metadata record is how the directory used to be elected.
194
+ //
195
+ // A listed record that owns the repository is main, first one wins (the ordinary
196
+ // repository, every worktree of one, and `/`-separated spellings alike). When NONE does,
197
+ // Git never named the checkout — for a separate git dir it cannot, it prints the common
198
+ // dir — so the working tree is read from disk instead: the caller's own root when IT owns
199
+ // the repository, otherwise one directory beside the common dir whose marker does. That
200
+ // second one is the shape `git init --separate-git-dir git-meta checkout` leaves: the
201
+ // metadata dir is a sibling of the checkout that owns it. A main tree that cannot be
202
+ // found that way stays UNKNOWN (no root), never the first record's.
203
+ //
204
+ // An entry Git flags `bare` is never main, and when EVERY record is bare, or no marker
205
+ // is readable anywhere at all (the shape a fake git seam builds), the previous election
206
+ // answers byte for byte.
207
+ // `entry` is the elected RECORD (null when main was read from disk), so the worktree
208
+ // list below can never draw the record main was elected from as a group of its own.
209
+ function mainOf(entries, repoRoot) {
210
+ const listed = Array.isArray(entries) ? entries : [];
211
+ const usable = listed.filter((entry) => entryPathOf(entry) !== null);
212
+ const common = commonDirOf(repoRoot);
213
+ if (common !== null) {
214
+ for (const entry of usable) {
215
+ if (entry.bare === true) continue;
216
+ const target = entryPathOf(entry);
217
+ // T18: the metadata tree is not a checkout, whatever it holds under `odd/tasks`.
218
+ if (insideCommonDir(target, common)) continue;
219
+ if (ownsCommonDir(target, common)) return { root: target, entry };
220
+ }
221
+ // T18: no record owns the repository, so the working tree is the one on disk.
222
+ return { root: ownerRootOf(repoRoot, common) ?? '', entry: null };
223
+ }
224
+ for (const entry of usable) {
225
+ if (entry.bare === true) continue;
226
+ const target = entryPathOf(entry);
227
+ if (isWorkingTree(target)) return { root: target, entry };
228
+ // Git's main record is not a checkout: this listing never names the working
229
+ // tree, so the caller's own root answers — unless the listing already holds it.
230
+ const root = normalizedPath(repoRoot);
231
+ const named = root !== null && usable.some((other) => samePath(entryPathOf(other), root));
232
+ if (named) return { root: entryPathOf(usable[0]), entry: usable[0] };
233
+ return { root: repoRoot, entry: null };
234
+ }
235
+ // Every record is bare (or there is none): the first one, exactly as before.
236
+ if (usable.length > 0) return { root: entryPathOf(usable[0]), entry: usable[0] };
237
+ return { root: repoRoot, entry: null };
238
+ }
239
+
240
+ /** An entry's usable path, or null when it names none. */
241
+ function entryPathOf(entry) {
242
+ return entry && typeof entry.path === 'string' && entry.path.length > 0 ? entry.path : null;
243
+ }
244
+
245
+ /**
246
+ * True when `target` is a checkout ROOT: it carries a `.git` marker, the
247
+ * directory of an ordinary repository or the link file a separate git dir writes.
248
+ * One stat, never a process, and never anything inside the checkout's own files.
249
+ */
250
+ function isWorkingTree(target) {
251
+ if (typeof target !== 'string' || target.length === 0) return false;
252
+ try {
253
+ return fs.existsSync(path.join(target, '.git'));
254
+ } catch {
255
+ return false;
256
+ }
257
+ }
258
+
259
+ // T18: the `.git` marker a checkout root carries, resolved: `{ target, link }`, where
260
+ // `link` says it is the FILE a separate git dir writes (whose whole content is the
261
+ // `gitdir:` line) rather than the directory of an ordinary repository. `null` when the
262
+ // directory carries no readable marker, which is also how a metadata tree answers: its
263
+ // `.git` (if any) is not a marker OF IT.
264
+ function gitMarkerOf(root) {
265
+ if (typeof root !== 'string' || root.length === 0) return null;
266
+ const marker = path.join(root, '.git');
267
+ let stats = null;
268
+ try {
269
+ stats = fs.statSync(marker);
270
+ } catch {
271
+ return null;
272
+ }
273
+ if (stats.isDirectory()) return { target: realPathOf(marker), link: false };
274
+ if (!stats.isFile()) return null;
275
+ let text = '';
276
+ try {
277
+ text = fs.readFileSync(marker, 'utf8');
278
+ } catch {
279
+ return null;
280
+ }
281
+ const line = text.split('\n').map((value) => value.trim()).find((value) => value.length > 0) ?? '';
282
+ const GITDIR = 'gitdir:';
283
+ if (!line.toLowerCase().startsWith(GITDIR)) return null;
284
+ const name = line.slice(GITDIR.length).trim();
285
+ if (name.length === 0) return null;
286
+ // A link file may spell the git dir relative to the checkout that holds it.
287
+ return { target: realPathOf(path.resolve(root, name)), link: true };
288
+ }
289
+
290
+ /**
291
+ * T18: the common dir of the repository `root` belongs to, read from disk — the git
292
+ * dir its own marker names, or that dir's `commondir` when it is a LINKED worktree's.
293
+ * `null` when `root` carries no readable marker at all, which is the only shape the
294
+ * previous election still answers.
295
+ */
296
+ function commonDirOf(root) {
297
+ const marker = gitMarkerOf(root);
298
+ if (marker === null) return null;
299
+ let shared = '';
300
+ try {
301
+ shared = fs.readFileSync(path.join(marker.target, 'commondir'), 'utf8').trim();
302
+ } catch {
303
+ return marker.target;
304
+ }
305
+ return shared.length > 0 ? realPathOf(path.resolve(marker.target, shared)) : marker.target;
306
+ }
307
+
308
+ /**
309
+ * T18: true when `root` is the working tree that OWNS `common` — the checkout whose own
310
+ * marker resolves to the common dir itself. A linked worktree's marker lands inside
311
+ * `<common>/worktrees`, so it never owns the repository, and a metadata tree carries no
312
+ * marker of its own.
313
+ */
314
+ function ownsCommonDir(root, common) {
315
+ const marker = gitMarkerOf(root);
316
+ return marker !== null && typeof common === 'string' && samePath(marker.target, common);
317
+ }
318
+
319
+ /** T18: `target` is `common` itself or sits inside it: a metadata tree, not a checkout. */
320
+ function insideCommonDir(target, common) {
321
+ const child = normalizedPath(target);
322
+ const parent = normalizedPath(common);
323
+ if (child === null || parent === null) return false;
324
+ return child === parent || child.startsWith(`${parent}${path.sep}`);
325
+ }
326
+
327
+ /**
328
+ * T18: the main working tree read from disk, or null when it cannot be found. The
329
+ * caller's own root answers first (a session standing in the main checkout), then the
330
+ * common dir's own sibling — the checkout that owns it — and only when exactly one
331
+ * directory there does, so an ambiguous machine answers nothing rather than a guess.
332
+ */
333
+ function ownerRootOf(repoRoot, common) {
334
+ if (ownsCommonDir(repoRoot, common)) return normalizedPath(repoRoot);
335
+ const beside = path.dirname(common);
336
+ if (ownsCommonDir(beside, common)) return normalizedPath(beside);
337
+ let names = [];
338
+ try {
339
+ names = fs.readdirSync(beside).sort(compareText);
340
+ } catch {
341
+ return null;
342
+ }
343
+ const owners = [];
344
+ for (const name of names) {
345
+ const candidate = path.join(beside, name);
346
+ if (insideCommonDir(candidate, common)) continue;
347
+ if (ownsCommonDir(candidate, common)) owners.push(candidate);
348
+ }
349
+ return owners.length === 1 ? normalizedPath(owners[0]) : null;
350
+ }
351
+
352
+ /** The real path of `target` when the system can answer, its resolved spelling otherwise. */
353
+ function realPathOf(target) {
354
+ try {
355
+ return fs.realpathSync(target);
356
+ } catch {
357
+ return path.resolve(target);
358
+ }
359
+ }
360
+
361
+ /** A path normalized for comparison: absolute, no trailing separator. */
362
+ function normalizedPath(value) {
363
+ if (typeof value !== 'string' || value.length === 0) return null;
364
+ const resolved = path.resolve(value);
365
+ return resolved.length > 1 ? resolved.replace(/[\\/]+$/, '') : resolved;
366
+ }
367
+
368
+ /**
369
+ * S13: the roots a caller scoped the scan to, as normalized paths — or null when
370
+ * it scoped nothing at all. Only an array scopes: `roots` absent, null or any other
371
+ * shape keeps the "every owned worktree" behaviour an existing caller relies on.
372
+ */
373
+ function scopeOf(roots) {
374
+ // Absent means "no scope" (every owned worktree, the unchanged default). A scope that is
375
+ // PRESENT but not a list is a caller mistake and fails closed to main only, never to the
376
+ // most expensive path.
377
+ if (roots === undefined || roots === null) return null;
378
+ if (!Array.isArray(roots)) return new Set();
379
+ const scope = new Set();
380
+ for (const root of roots) {
381
+ const normalized = normalizedPath(root);
382
+ if (normalized !== null) scope.add(normalized);
383
+ }
384
+ return scope;
385
+ }
386
+
387
+ /**
388
+ * S13: the listed checkouts a session registered. Git still decides existence — a
389
+ * registered root it does not list is simply not a checkout — while registration
390
+ * decides scope, so the owned-checkout rule deliberately does not apply here.
391
+ */
392
+ function registeredCheckouts(entries, scope) {
393
+ return entries.filter((entry) => {
394
+ if (!entry || typeof entry.path !== 'string') return false;
395
+ const normalized = normalizedPath(entry.path);
396
+ return normalized !== null && scope.has(normalized);
397
+ });
398
+ }
399
+
400
+ /**
401
+ * One checkout's documents in group order, each dated by its own mtime. An
402
+ * unreadable checkout, an absent `odd/tasks` and a document whose timestamp cannot
403
+ * be read all contribute nothing: every row this module returns carries a real
404
+ * modification time.
405
+ */
406
+ function scanDocs(root) {
407
+ const listing = listOddDocsLocal(root);
408
+ if (listing.ok !== true) return [];
409
+ const docs = [];
410
+ for (const doc of listing.docs) {
411
+ const mtimeMs = readMtimeMs(doc.path);
412
+ if (mtimeMs === null) continue;
413
+ docs.push({ name: doc.name, docPath: doc.path, mtimeMs });
414
+ }
415
+ return docs.sort(compareDocs);
416
+ }
417
+
418
+ /** Modification time in ms, or null when it cannot be read. */
419
+ function readMtimeMs(target) {
420
+ try {
421
+ const stats = fs.statSync(target);
422
+ return Number.isFinite(stats.mtimeMs) ? stats.mtimeMs : null;
423
+ } catch {
424
+ return null;
425
+ }
426
+ }
427
+
428
+ /**
429
+ * The main group: EVERY document of the main checkout, and deliberately no
430
+ * `status` — against itself nothing is new or modified, so the field is absent
431
+ * rather than invented.
432
+ */
433
+ function mainGroup(checkout) {
434
+ return {
435
+ checkoutName: MAIN,
436
+ checkoutRoot: checkout.root,
437
+ isMain: true,
438
+ docs: scanDocs(checkout.root),
439
+ };
440
+ }
441
+
442
+ /**
443
+ * A worktree's delta (comparisons (a) and (b) above), in group order. Nothing it
444
+ * cannot establish ever becomes a row: a worktree with no document of its own to
445
+ * compare costs no git read at all, and a base or a path set it could not read
446
+ * leaves the group empty instead of guessing.
447
+ */
448
+ async function deltaOf({ checkout, mainRoot, mainByRel, head, opts }) {
449
+ const docs = scanDocs(checkout.root);
450
+ if (docs.length === 0) return [];
451
+ const base = await mergeBaseOf(checkout.root, mainRoot, head, opts);
452
+ if (base === null) return [];
453
+ const named = await namedPathsOf(checkout.root, base, opts);
454
+ if (named === null) return [];
455
+ const delta = [];
456
+ for (const doc of docs) {
457
+ const rel = relativePosix(checkout.root, doc.docPath);
458
+ if (!named.has(rel)) continue;
459
+ const mainDoc = mainByRel.get(rel);
460
+ if (mainDoc === undefined) {
461
+ // `added`: main has no document of this path, so there is nothing to match.
462
+ delta.push({ ...doc, status: 'added' });
463
+ continue;
464
+ }
465
+ // (b): equal bytes are not a difference, whichever side moved.
466
+ const mine = readBytes(doc.docPath);
467
+ const theirs = readBytes(mainDoc.docPath);
468
+ if (mine === null || theirs === null || mine.equals(theirs)) continue;
469
+ delta.push({ ...doc, status: 'modified' });
470
+ }
471
+ return delta;
472
+ }
473
+
474
+ // (a), base half: the merge base of the worktree's branch with main, resolved the
475
+ // way lib/worktree-changes.js resolves it — main's HEAD first, then
476
+ // `git merge-base HEAD <sha>` INSIDE the worktree — and memoized for the whole
477
+ // call, so one `rev-parse` answers every worktree. Null when either read cannot
478
+ // answer, which leaves the group empty rather than comparing against something
479
+ // that is not the base.
480
+ async function mergeBaseOf(worktreeRoot, mainRoot, head, opts) {
481
+ const mainHead = await mainHeadOf(mainRoot, head, opts);
482
+ if (mainHead === null) return null;
483
+ const base = await runGitAsync(worktreeRoot, ['merge-base', 'HEAD', mainHead], opts);
484
+ if (base === null) return null;
485
+ const tree = base.trim();
486
+ return tree.length > 0 ? tree : null;
487
+ }
488
+
489
+ async function mainHeadOf(mainRoot, head, opts) {
490
+ if (head.resolved !== true) {
491
+ head.resolved = true;
492
+ const answer = await runGitAsync(mainRoot, HEAD_ARGS, opts);
493
+ const sha = answer === null ? '' : answer.trim();
494
+ head.sha = sha.length > 0 ? sha : null;
495
+ }
496
+ return head.sha;
497
+ }
498
+
499
+ // (a), path half: the branch's own work, unioned from the commit diff against the
500
+ // merge base and the working tree's status. `null` when either read fails — the
501
+ // same closed answer for both, because half a comparison is not a comparison.
502
+ async function namedPathsOf(root, base, opts) {
503
+ const diff = await runGitAsync(root, diffArgs(base), opts);
504
+ if (diff === null) return null;
505
+ const status = await runGitAsync(root, STATUS_ARGS, opts);
506
+ if (status === null) return null;
507
+ const named = new Set(parseNameStatusPaths(diff));
508
+ for (const entry of parseStatusPaths(status)) named.add(entry);
509
+ return named;
510
+ }
511
+
512
+ // `--name-status -z` records: `<letter>\0<path>\0`. `--no-renames` means the read
513
+ // produces `A`/`M`/`D`/`T` only; a rename or copy record (`<letter>\0<original>\0
514
+ // <path>\0`, original first) is still parsed in case a caller ever turns detection
515
+ // back on. A deleted path is left out: a document that is gone in the worktree has
516
+ // no row to draw.
517
+ function parseNameStatusPaths(stdout) {
518
+ const paths = new Set();
519
+ const fields = stdout.split('\0');
520
+ for (let index = 0; index < fields.length; index += 1) {
521
+ const record = fields[index];
522
+ if (record.length === 0) continue;
523
+ const letter = record[0];
524
+ const carried = letter === 'R' || letter === 'C';
525
+ const target = fields[index + (carried ? 2 : 1)];
526
+ index += carried ? 2 : 1;
527
+ if (typeof target !== 'string' || target.length === 0) continue;
528
+ if (letter === 'D') continue;
529
+ paths.add(target);
530
+ }
531
+ return paths;
532
+ }
533
+
534
+ // `status --porcelain=v1 -z` records: `<XY> <path>\0`, the original path of a
535
+ // rename or copy in the next field, which is consumed so it can never be read as a
536
+ // record of its own. A path the working tree deleted is left out for the same
537
+ // reason as above.
538
+ function parseStatusPaths(stdout) {
539
+ const paths = new Set();
540
+ const fields = stdout.split('\0');
541
+ for (let index = 0; index < fields.length; index += 1) {
542
+ const entry = fields[index];
543
+ if (entry.length < 4) continue;
544
+ const code = entry.slice(0, 2);
545
+ const target = entry.slice(3);
546
+ if (code[0] === 'R' || code[0] === 'C') index += 1;
547
+ if (code.includes('D')) continue;
548
+ if (target.length > 0) paths.add(target);
549
+ }
550
+ return paths;
551
+ }
552
+
553
+ /** One file's bytes, or null when it cannot be read (fail closed: no row). */
554
+ function readBytes(target) {
555
+ try {
556
+ return fs.readFileSync(target);
557
+ } catch {
558
+ return null;
559
+ }
560
+ }
561
+
562
+ /** A document's path relative to its checkout, POSIX-spelled to match Git's own. */
563
+ function relativePosix(root, target) {
564
+ return path.relative(root, target).split(path.sep).join('/');
565
+ }
566
+
567
+ /**
568
+ * The grouped model: the main checkout's whole list, then one group per worktree in
569
+ * scope carrying only what that worktree has that main does not. `repoRoot` is the
570
+ * repository the git reads run in; `runAsync` is the package's git seam
571
+ * (`(bin, argv, cwd) => Promise<{status, stdout, stderr, error}>`), defaulting to
572
+ * the shared bounded async spawn wrapper. `roots` — optional — is the registered
573
+ * worktrees to group (S13): absent means every owned worktree, and an array means
574
+ * only the listed ones, main always first and always whole. `all` — optional — is
575
+ * S11's unfiltered scope: `true` groups EVERY worktree Git lists except main,
576
+ * registered or not, and wins over `roots`. `failClosed` — optional — is S13's
577
+ * strict reading of the ONE read that can answer neither: when the listing fails,
578
+ * the default answers a synthetic main made of the caller's own root (what every
579
+ * existing caller relies on), while `failClosed: true` answers `null` — no model
580
+ * at all — because that synthetic main would show a linked checkout's private
581
+ * documents under main's name. A root that is not usable is still `[]` (a caller
582
+ * mistake, not a Git read), and the default is byte-identical.
583
+ */
584
+ async function groupOddDocs(input) {
585
+ const opts = input && typeof input === 'object' ? input : {};
586
+ const repoRoot = absoluteRoot(opts.repoRoot);
587
+ if (repoRoot === null) return [];
588
+ const scope = scopeOf(opts.roots);
589
+ const entries = await listCheckoutEntries(repoRoot, opts);
590
+ // S13 (T13): a caller that cannot degrade to a synthetic main asks for
591
+ // `failClosed`; the listing it could not read is no model, never a wrong one.
592
+ if (entries === null && opts.failClosed === true) return null;
593
+ const checkouts = checkoutsOf(entries, repoRoot, scope, opts.all === true);
594
+ const main = checkouts[0];
595
+ const groups = [mainGroup(main)];
596
+ if (checkouts.length === 1) return groups;
597
+ // Main's own listing answers both questions a worktree needs from it: which
598
+ // relative paths it has (`added` vs `modified`) and which bytes to compare.
599
+ const mainByRel = new Map(groups[0].docs.map((doc) => [relativePosix(main.root, doc.docPath), doc]));
600
+ const head = { resolved: false, sha: null };
601
+ for (const checkout of checkouts.slice(1)) {
602
+ groups.push({
603
+ checkoutName: checkout.name,
604
+ checkoutRoot: checkout.root,
605
+ isMain: false,
606
+ docs: await deltaOf({ checkout, mainRoot: main.root, mainByRel, head, opts }),
607
+ });
608
+ }
609
+ return groups;
610
+ }
611
+
612
+ /** The root as an absolute path, or null when the caller gave nothing usable. */
613
+ function absoluteRoot(value) {
614
+ if (typeof value !== 'string' || value.length === 0) return null;
615
+ return path.resolve(value);
616
+ }
617
+
618
+ // The one listing read: fixed argv through the seam, parsed by the shared parser.
619
+ // `null` means "git could not answer" — not an exception and not an empty machine.
620
+ async function listCheckoutEntries(repoRoot, opts) {
621
+ const listed = await runGitAsync(repoRoot, WORKTREE_LIST_ARGS, opts);
622
+ return listed === null ? null : parseWorktreePorcelain(listed);
623
+ }
624
+
625
+ // One read, awaited instead of spawned inline, with the identical
626
+ // stdout-or-null contract every git read in this package keeps: a missing
627
+ // binary, a non-zero exit, a timeout or a throw is `null`.
628
+ function runGitAsync(root, args, opts) {
629
+ let pending = null;
630
+ try {
631
+ pending = asyncRunnerOf(opts)('git', [...GIT_CONFIG_ARGS, ...args], root);
632
+ } catch {
633
+ return Promise.resolve(null);
634
+ }
635
+ return Promise.resolve(pending)
636
+ .then((result) => {
637
+ if (!result || result.error || result.status !== 0) return null;
638
+ return typeof result.stdout === 'string' ? result.stdout : '';
639
+ })
640
+ .catch(() => null);
641
+ }
642
+
643
+ // The injected runner when a caller supplies it, otherwise the shared bounded
644
+ // async spawn wrapper — loaded lazily, so a caller that only ever uses its own
645
+ // seam never pays for it.
646
+ function asyncRunnerOf(opts) {
647
+ const options = opts && typeof opts === 'object' ? opts : {};
648
+ if (typeof options.runAsync === 'function') return options.runAsync;
649
+ const worktreeGit = require('./worktree-git.js');
650
+ return (bin, args, cwd) => worktreeGit.runArgvAsync(bin, args, { cwd, timeoutMs: GIT_TIMEOUT_MS });
651
+ }
652
+
653
+ module.exports = {
654
+ groupOddDocs,
655
+ };