pi-odd-worktree 3.5.0 → 3.6.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.
@@ -6989,7 +6989,11 @@ async function filesCheckouts(cwd) {
6989
6989
  } catch {
6990
6990
  // Git's own spelling is all it answered.
6991
6991
  }
6992
- return { repo, mainRoot, entries };
6992
+ // S2: the branch a worktree's badges are measured against is the branch the
6993
+ // PRINCIPAL checkout has, whatever it is called — a repository on `master`
6994
+ // must not end up comparing against a `main` that does not exist.
6995
+ const mainBranch = main && typeof main.branch === 'string' && main.branch.length > 0 ? main.branch : null;
6996
+ return { repo, mainRoot, mainBranch, entries };
6993
6997
  }
6994
6998
 
6995
6999
  // S9: the ODD directory IS a checkout's identity in this package (invariant 12),
@@ -7031,6 +7035,7 @@ function filesAllWorktrees(checkouts) {
7031
7035
  root: entry.path,
7032
7036
  kind: 'worktree',
7033
7037
  label: filesWorktreeLabel(entry.path, entry.branch),
7038
+ base: checkouts.mainBranch,
7034
7039
  });
7035
7040
  }
7036
7041
  return others;
@@ -7044,10 +7049,29 @@ function filesAllWorktrees(checkouts) {
7044
7049
  * local `main` for every worktree. A read that failed leaves its fields absent, so
7045
7050
  * the step paints less instead of claiming a zero nobody measured.
7046
7051
  */
7052
+ /**
7053
+ * S1/S2: how a scope's change badges are read. The principal checkout answers
7054
+ * from its own `git status`, so a commit there clears the badge; a worktree
7055
+ * answers from the commits it has ahead of the principal branch, so a commit is
7056
+ * what MARKS the file. The comparison is the same one the `±`/`↑`/`↓` line uses
7057
+ * (`lib/files-scope-detail.js`), so the scope row and the picker's rows can never
7058
+ * disagree about what the branch changed.
7059
+ */
7060
+ function filesComparison(detailLib, scope) {
7061
+ if (!scope || scope.kind !== 'worktree') return undefined;
7062
+ // The principal checkout's own branch when Git reported one, and the package's
7063
+ // conventional `main` when the principal checkout is detached.
7064
+ return typeof scope.base === 'string' && scope.base.length > 0 ? scope.base : detailLib.LOCAL_MAIN;
7065
+ }
7066
+
7047
7067
  async function filesScopeFacts(index, detailLib, run, scope) {
7048
7068
  const facts = {};
7049
7069
  try {
7050
- const listing = await index.listRepositoryEntries({ run, cwd: scope.root });
7070
+ const listing = await index.listRepositoryEntries({
7071
+ run,
7072
+ cwd: scope.root,
7073
+ comparison: filesComparison(detailLib, scope),
7074
+ });
7051
7075
  if (listing && listing.ok === true && Array.isArray(listing.entries)) {
7052
7076
  let changed = 0;
7053
7077
  let newest;
@@ -7145,6 +7169,7 @@ function filesSessionScopes(checkouts, cwd, registeredRoots) {
7145
7169
  root: entry.path,
7146
7170
  kind: 'worktree',
7147
7171
  label: filesWorktreeLabel(entry.path, entry.branch),
7172
+ base: checkouts.mainBranch,
7148
7173
  });
7149
7174
  }
7150
7175
  return scopes;
@@ -7263,6 +7288,9 @@ async function mountFilesPicker(ctx, input) {
7263
7288
  const index = libRequire('files-index.js');
7264
7289
  const insertLib = libRequire('files-insert.js');
7265
7290
  const pickerView = libRequire('files-picker-view.js');
7291
+ // The same module the scope step reads its comparison from, so the badges and
7292
+ // the `↑n main` line are measured against one branch (S1, S2).
7293
+ const scopeLib = libRequire('files-scope-detail.js');
7266
7294
  const run = filesRunner(libRequire('worktree-git.js'));
7267
7295
  const agent = await filesAgentSeam();
7268
7296
  const scope = input.scope;
@@ -7297,7 +7325,11 @@ async function mountFilesPicker(ctx, input) {
7297
7325
  cwd: input.cwd,
7298
7326
  // The listing and the preview are the T1 reader's own, read from the scope
7299
7327
  // root rather than the session cwd: the picker browses another checkout.
7300
- loadEntries: () => index.listRepositoryEntries({ run, cwd: scope.root }),
7328
+ loadEntries: () => index.listRepositoryEntries({
7329
+ run,
7330
+ cwd: scope.root,
7331
+ comparison: filesComparison(scopeLib, scope),
7332
+ }),
7301
7333
  loadPreview: (relative) => index.readFilePreview(scope.root, relative),
7302
7334
  ...(agent.highlight === undefined ? {} : { highlight: agent.highlight }),
7303
7335
  ...(agent.languageForPath === undefined ? {} : { languageForPath: agent.languageForPath }),
@@ -18,10 +18,20 @@
18
18
  // ever parsing it. Outside a repository the listing fails and the failure is a
19
19
  // sentence a panel can paint, never an empty success.
20
20
  //
21
- // Change state (S6) comes from one `git status --porcelain=v1 -z
21
+ // Change state (S6) comes from two reads, one per scope kind. The principal
22
+ // checkout is marked from a single `git status --porcelain=v1 -z
22
23
  // --untracked-files=all`: `??` is `new` (untracked), any other record is
23
- // `updated` (tracked and dirty), and a file the status does not name is
24
- // `clean`. Change state carries no time, so the ages come from a stat under the
24
+ // `modified` (tracked and dirty), and a file the status does not name is
25
+ // `clean`. A worktree is marked from its own work instead (S2): one
26
+ // `git diff --name-status -z -M <principal>...HEAD` names every path the branch
27
+ // changed ahead of the principal branch, with its net state — `A` when the
28
+ // merge-base does not have the path, `M` when it does — so committing a
29
+ // worktree no longer erases the badges. The two sets are unioned (S4): a path
30
+ // the commits already named keeps that state, and the worktree's uncommitted
31
+ // work still marks the rest. A path the commits deleted is dropped, because a
32
+ // file that is gone has no row to paint (S5).
33
+ //
34
+ // Change state carries no time, so the ages come from a stat under the
25
35
  // repository root Git reports — `git rev-parse --show-toplevel`, never
26
36
  // `process.cwd()`, because the picker browses another checkout than the one the
27
37
  // process happens to sit in. An unreadable root or file leaves the timestamp
@@ -59,8 +69,32 @@ const STATUS_ARGS = Object.freeze([
59
69
  // cwd because the picker can browse another checkout.
60
70
  const ROOT_ARGS = Object.freeze(['rev-parse', '--show-toplevel']);
61
71
 
72
+ // S2: a worktree's own work is the record of what its branch changed ahead of
73
+ // the principal branch. Three dots compare against the merge-base, so a `main`
74
+ // that moved on since the fork is never read as this branch's work, and a path
75
+ // named by several commits arrives once, already deduplicated, with its net
76
+ // state (S3). `-z` for the same reason as every other read.
77
+ //
78
+ // The ref is spelled out as `refs/heads/<branch>` on purpose: a bare `main` is
79
+ // ambiguous the moment a tag or a remote of that name exists, and a checkout
80
+ // holding an ordinary file called `main...HEAD` makes the whole read fail. The
81
+ // trailing `--` says the argument list ends before any path could start.
82
+ // `--no-renames` keeps the read READ-ONLY: similarity detection is what makes
83
+ // Git fetch a missing blob in a partial clone and write a pack, and the net
84
+ // state does not need it — an undetected rename is delete plus add, and the
85
+ // delete is a path that gets no row anyway.
86
+ const commitArgs = (comparison) => [
87
+ 'diff',
88
+ '--name-status',
89
+ '-z',
90
+ '--no-renames',
91
+ `refs/heads/${comparison}...HEAD`,
92
+ '--',
93
+ ];
94
+
62
95
  const FILES_ERROR = 'Cannot list repository files';
63
96
  const CHANGES_ERROR = 'Cannot read repository changes';
97
+ const COMMITS_ERROR = "Cannot read the branch's commits";
64
98
 
65
99
  const MINUTE = 60_000;
66
100
  const HOUR = 3_600_000;
@@ -144,6 +178,13 @@ function changesFailure(failure, cwd) {
144
178
  };
145
179
  }
146
180
 
181
+ function commitsFailure(failure, cwd) {
182
+ return {
183
+ ok: false,
184
+ message: failure.notRepository ? notRepositoryMessage(cwd) : sentence(`${COMMITS_ERROR}: ${failure.detail}`),
185
+ };
186
+ }
187
+
147
188
  /** Repository-relative POSIX paths; a failed listing is a failure, never an empty success. */
148
189
  async function listRepositoryFiles(input = {}) {
149
190
  const run = input && input.run;
@@ -170,12 +211,49 @@ function parseStatus(stdout) {
170
211
  if (typeof record !== 'string' || record.length < 4) continue;
171
212
  const code = record.slice(0, 2);
172
213
  const filePath = record.slice(3);
173
- if (filePath.length > 0) states.set(filePath, code === '??' ? 'new' : 'updated');
214
+ if (filePath.length > 0) states.set(filePath, code === '??' ? 'new' : 'modified');
174
215
  if (code[0] === 'R' || code[0] === 'C') index += 1;
175
216
  }
176
217
  return states;
177
218
  }
178
219
 
220
+ // S3: `<letter>\0<path>\0` records, NUL terminated. `--no-renames` means the
221
+ // read produces `A`/`M`/`D`/`T` only, so a rename arrives as its two halves; a
222
+ // rename or copy record is still parsed (`<status>\0<original>\0<path>\0`, the
223
+ // original first) in case a caller ever turns detection back on, and the path the
224
+ // record is ABOUT is always the last field it carries. `A` is a path the
225
+ // merge-base does not have; anything else that is not a delete is `modified`. A
226
+ // delete maps to `deleted` so the caller drops it deliberately instead of relying
227
+ // on the path being absent.
228
+ function parseNameStatus(stdout) {
229
+ const states = new Map();
230
+ const fields = stdout.split('\0');
231
+ for (let index = 0; index < fields.length; index += 1) {
232
+ const record = fields[index];
233
+ if (typeof record !== 'string' || record.length === 0) continue;
234
+ const letter = record[0];
235
+ const carried = letter === 'R' || letter === 'C';
236
+ const filePath = fields[index + (carried ? 2 : 1)];
237
+ index += carried ? 2 : 1;
238
+ if (typeof filePath !== 'string' || filePath.length === 0) continue;
239
+ if (letter === 'D') states.set(filePath, 'deleted');
240
+ else if (letter === 'A' || carried) states.set(filePath, 'added');
241
+ else states.set(filePath, 'modified');
242
+ }
243
+ return states;
244
+ }
245
+
246
+ // The worktree half of the change read (S2, S5): the one name-status diff, with
247
+ // every deleted path dropped. Never throws; a failure comes back as
248
+ // `{ok:false}` so the caller paints one sentence instead of half a listing.
249
+ async function listCommitChanges(run, cwd, comparison) {
250
+ const named = await runGit(run, commitArgs(comparison), cwd);
251
+ if (named.ok !== true) return { ok: false, failure: named };
252
+ const states = parseNameStatus(named.stdout);
253
+ for (const [filePath, state] of states) if (state === 'deleted') states.delete(filePath);
254
+ return { ok: true, states };
255
+ }
256
+
179
257
  async function repositoryRoot(run, cwd) {
180
258
  const resolved = await runGit(run, ROOT_ARGS, cwd);
181
259
  if (resolved.ok !== true) return undefined;
@@ -219,17 +297,33 @@ function clockMs(now) {
219
297
  * The picker's rows: the same file set as `listRepositoryFiles`, changed files
220
298
  * first and newest first, then untouched files by path. Each changed row carries
221
299
  * its state, its mtime and the age label computed from the injected `now`.
300
+ *
301
+ * `comparison` selects how the states are read (S2, S4): omitted or empty, the
302
+ * principal checkout's own `git status`; the name of the principal BRANCH, the
303
+ * branch's net diff against the merge-base with it (`refs/heads/<branch>`),
304
+ * unioned with the status so uncommitted work is still marked. The commit state
305
+ * wins where both name a path.
222
306
  */
223
307
  async function listRepositoryEntries(input = {}) {
224
308
  const run = input && input.run;
225
309
  const cwd = input && input.cwd;
226
310
  const listing = await listRepositoryFiles({ run, cwd });
227
311
  if (listing.ok !== true) return { ok: false, message: listing.message };
312
+ const comparison = input && typeof input.comparison === 'string' ? input.comparison.trim() : '';
313
+ let committed = new Map();
314
+ if (comparison.length > 0) {
315
+ const read = await listCommitChanges(run, cwd, comparison);
316
+ if (read.ok !== true) return commitsFailure(read.failure, cwd);
317
+ committed = read.states;
318
+ }
228
319
  const status = await runGit(run, STATUS_ARGS, cwd);
229
320
  if (status.ok !== true) {
230
321
  return changesFailure(status, cwd);
231
322
  }
232
- const states = parseStatus(status.stdout);
323
+ const states = new Map(committed);
324
+ for (const [filePath, state] of parseStatus(status.stdout)) {
325
+ if (!states.has(filePath)) states.set(filePath, state);
326
+ }
233
327
  const changedPaths = listing.files.filter((filePath) => states.has(filePath));
234
328
  const root = changedPaths.length > 0 ? await repositoryRoot(run, cwd) : undefined;
235
329
  const nowMs = clockMs(input && input.now);
@@ -22,7 +22,7 @@
22
22
  // direction S40's legend paints.
23
23
  //
24
24
  // Entry shape is the listing seam's (lib/files-index.js): `{ path, state:
25
- // "new" | "updated" | "clean", mtimeMs? }`, already changed-first by recency
25
+ // "added" | "modified" | "new" | "clean", mtimeMs? }`, already changed-first by recency
26
26
  // then clean. `files` re-applies that rule here so the order is the module's own,
27
27
  // not a property of the caller's array.
28
28
 
@@ -104,8 +104,7 @@ const CLOSE_HINT = 'esc';
104
104
  const HINT_COLUMNS = CLOSE_HINT.length + 2;
105
105
  const TITLE_SEPARATOR_COLUMNS = 3;
106
106
  // The fewest columns a left-elided path is worth painting beside the title.
107
- const MIN_DETAIL_COLUMNS = 4;
108
- const BODY_RULE_ROWS = 1;
107
+ const MIN_DETAIL_COLUMNS = 4;const BODY_RULE_ROWS = 1;
109
108
  const MIN_CARD_HEIGHT = CHROME_ROWS + 1;
110
109
  const MIN_WIDTH = 20;
111
110
  // 0-based row of the first body row: the top rule, the search row and the info row.
@@ -139,6 +138,14 @@ const LOADING_PREVIEW = 'Loading preview \u2026';
139
138
  const NO_FILES = 'No files in this repository.';
140
139
  const UNTRACKED_BADGE = 'U';
141
140
  const MODIFIED_BADGE = 'M';
141
+ const ADDED_BADGE = 'A';
142
+ // S44: the title's ahead field — the scope step's own glyph, and the separator the
143
+ // card's heading uses between its name and its detail.
144
+ const AHEAD_MARK = '\u2191';
145
+ const DETAIL_SEPARATOR = ' \u00b7 ';
146
+ // S5: the whole vocabulary — the listing's states map to exactly these letters,
147
+ // and an unknown state still reads as a change instead of vanishing silently.
148
+ const BADGES = Object.freeze({ added: ADDED_BADGE, modified: MODIFIED_BADGE, new: UNTRACKED_BADGE });
142
149
  // S38: a group row is a row the cursor rests on and it holds no file, so the preview
143
150
  // keeps its box and says so — in the one notice shape T5 gives a preview with no
144
151
  // numbered lines — instead of claiming a `line/total` position or blanking the pane.
@@ -771,19 +778,49 @@ function createFilesPickerView(options = {}) {
771
778
 
772
779
  // ---- painting -------------------------------------------------------------
773
780
 
781
+ /**
782
+ * S44: the commits this checkout has that its comparison does not — ` · ↑3 main`
783
+ * — read from the scope's own detail, so the title names what the badges are
784
+ * measured against with no extra Git read. Only AHEAD is painted: a worktree is
785
+ * almost always behind its principal branch, and `↑1 · ↓310` reads as a
786
+ * contradiction even though both counts are true. Empty when the checkout is
787
+ * level, when the detail is absent, or when the count was never measured.
788
+ */
789
+ function aheadField() {
790
+ const detail = scope.detail !== null && typeof scope.detail === 'object' ? scope.detail : undefined;
791
+ if (detail === undefined) return '';
792
+ const ahead = Number(detail.ahead);
793
+ if (!Number.isFinite(ahead) || Math.trunc(ahead) <= 0) return '';
794
+ const count = `${AHEAD_MARK}${Math.trunc(ahead)}`;
795
+ const comparison = typeof detail.comparison === 'string' ? sanitize(detail.comparison.trim()) : '';
796
+ return comparison === '' ? `${DETAIL_SEPARATOR}${count}` : `${DETAIL_SEPARATOR}${count} ${comparison}`;
797
+ }
798
+
774
799
  /**
775
800
  * S37: the checkout's path rides the panel's OWN title — `Files · <path>` — so it
776
801
  * reads beside the panel's name and elides from its own left, which is what keeps
777
802
  * the tail that identifies the checkout. `cardTop` clips a heading's detail from
778
803
  * its RIGHT, so the path is elided here first, at exactly the columns the heading
779
804
  * leaves it, and the substrate is handed one that already fits.
805
+ *
806
+ * S44 adds the ahead field at the tail of that detail, and the field never gives
807
+ * way: the path elides first, and when not even `MIN_DETAIL_COLUMNS` is left for a
808
+ * path worth painting, the field keeps the row alone.
780
809
  */
781
810
  function titleDetail(width) {
782
811
  const room = width - TOP_CHROME_COLUMNS - HINT_COLUMNS - titleHeadWidth - TITLE_SEPARATOR_COLUMNS;
783
812
  if (room < MIN_DETAIL_COLUMNS) return undefined;
813
+ const field = aheadField();
814
+ const fieldWidth = field === '' ? 0 : measure(helpers, field);
784
815
  const root = sanitize(scope.root === undefined ? '' : scope.root);
785
- if (root === '') return undefined;
786
- return elideLeft(root, room);
816
+ if (root !== '' && room - fieldWidth >= MIN_DETAIL_COLUMNS) {
817
+ return `${elideLeft(root, room - fieldWidth)}${field}`;
818
+ }
819
+ // The path is gone or was never there: the field answers for the detail, and
820
+ // only when it fits in the room the heading left it.
821
+ const alone = field.replace(/^ /, '');
822
+ if (alone !== '') return measure(helpers, alone) <= room ? alone : undefined;
823
+ return root === '' ? undefined : elideLeft(root, room);
787
824
  }
788
825
 
789
826
  // The card the top rule draws: the panel's name, and the path as its detail when
@@ -886,11 +923,12 @@ function createFilesPickerView(options = {}) {
886
923
  return '';
887
924
  }
888
925
 
889
- // The trailing badge and age, plain: `/changes` own letters, `U` for a file Git
890
- // does not track yet and `M` for a tracked one with an uncommitted change (S6).
926
+ // The trailing badge and age, plain: `/changes` own letters — `A` for a file
927
+ // the branch added, `M` for one it modified or that is dirty, `U` for one Git
928
+ // does not track yet (S5). A clean row paints neither.
891
929
  function suffixOf(entry) {
892
930
  if (entry.state === 'clean') return '';
893
- const badge = entry.state === 'new' ? UNTRACKED_BADGE : MODIFIED_BADGE;
931
+ const badge = BADGES[entry.state] ?? MODIFIED_BADGE;
894
932
  const age = ageOf(entry);
895
933
  return age === '' ? badge : `${badge} ${age}`;
896
934
  }
@@ -84,10 +84,12 @@ function countCell(files) {
84
84
 
85
85
  /**
86
86
  * The focused scope's line (S9): the last commit subject first, then `±n files`,
87
- * the age of the last modification, suffixed `ago` (S42), and the distance from
88
- * the comparison ref (`↑n main` / `↓n origin/main` for the `main` row). A field
89
- * that is zero or absent is not painted, and an unknown comparison never claims
90
- * a distance.
87
+ * the age of the last modification, suffixed `ago` (S42), and ONE distance from
88
+ * the comparison ref — `↑n main` when the checkout has commits the comparison
89
+ * does not, and `↓n main` only when it has none, because a checkout measured
90
+ * against a moving principal branch is almost always behind it and `↑1 · ↓310`
91
+ * reads as a contradiction though both are true (S44). A field that is zero or
92
+ * absent is not painted, and an unknown comparison never claims a distance.
91
93
  *
92
94
  * @param {{changedFiles?: number, lastModifiedMs?: number, lastCommitSubject?: string, ahead?: number, behind?: number, comparison?: string}} detail
93
95
  * @param {number} nowMs the clock read once when the step opened.
@@ -106,9 +108,14 @@ function scopeDetailLine(detail, nowMs) {
106
108
  if (Number.isFinite(modified) && modified > 0) fields.push(`${formatAge(modified, nowMs)} ${AGE_SUFFIX}`);
107
109
  const comparison = typeof model.comparison === 'string' ? model.comparison.trim() : '';
108
110
  const ahead = Number(model.ahead);
109
- if (comparison !== '' && Number.isFinite(ahead) && ahead > 0) fields.push(`${AHEAD_SYMBOL}${Math.trunc(ahead)} ${comparison}`);
110
111
  const behind = Number(model.behind);
111
- if (comparison !== '' && Number.isFinite(behind) && behind > 0) fields.push(`${BEHIND_SYMBOL}${Math.trunc(behind)} ${comparison}`);
112
+ // S44: one relation, never two. Ahead is the actionable half; behind is only
113
+ // worth a glyph when there is nothing ahead to report.
114
+ if (comparison !== '' && Number.isFinite(ahead) && Math.trunc(ahead) > 0) {
115
+ fields.push(`${AHEAD_SYMBOL}${Math.trunc(ahead)} ${comparison}`);
116
+ } else if (comparison !== '' && Number.isFinite(behind) && Math.trunc(behind) > 0) {
117
+ fields.push(`${BEHIND_SYMBOL}${Math.trunc(behind)} ${comparison}`);
118
+ }
112
119
  return fields.join(SEPARATOR);
113
120
  }
114
121
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-odd-worktree",
3
- "version": "3.5.0",
3
+ "version": "3.6.0",
4
4
  "description": "Pi package for odd-worktree: the Git worktree tools a Pi session uses (create and list the checkouts the agent works in), the /warp worktree panel, the /odd ODD viewer, and the /issues GitHub issue reader. Needs only Pi and git: no companion app, no extra service.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -42,9 +42,9 @@ function git(cwd, args) {
42
42
  }
43
43
 
44
44
  /** A real repository: `main`, one commit and one tracked file. */
45
- function makeRepo() {
45
+ function makeRepo({ branch = 'main' } = {}) {
46
46
  const dir = track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-files-repo-')));
47
- git(dir, ['init', '-b', 'main']);
47
+ git(dir, ['init', '-b', branch]);
48
48
  git(dir, ['config', 'user.email', 'test@example.test']);
49
49
  git(dir, ['config', 'user.name', 'Test']);
50
50
  fs.writeFileSync(path.join(dir, 'a.js'), 'const x = 1;\n');
@@ -55,10 +55,10 @@ function makeRepo() {
55
55
  }
56
56
 
57
57
  /** One checkout this package owns, at the canonical directory, one file short of committed. */
58
- function addOwnedWorktree(repo, odd, branch) {
58
+ function addOwnedWorktree(repo, odd, branch, base = 'main') {
59
59
  const parent = path.dirname(repo);
60
60
  const target = path.join(parent, `${path.basename(repo)}-worktrees`, odd);
61
- git(repo, ['worktree', 'add', '-b', branch, target, 'main']);
61
+ git(repo, ['worktree', 'add', '-b', branch, target, base]);
62
62
  fs.writeFileSync(path.join(target, 'x.js'), 'const y = 2;\n');
63
63
  return fs.realpathSync(target);
64
64
  }
@@ -537,6 +537,118 @@ describe('several checkouts: the scope step (S9)', () => {
537
537
  });
538
538
  });
539
539
 
540
+ describe('the badges of a scope (S1-S4)', () => {
541
+ // The row a `/files` list paints for one file: `<name> … <badge> <age> │`, the
542
+ // badge right-aligned against the pane's rule. Ages are `s`/`h`/`d`, so a badge
543
+ // is only ever a letter followed by one.
544
+ const badgeOf = (text, name) => {
545
+ const found = text.match(new RegExp(`${name.replace('.', '\\.')} +([AMU])(?: +\\d+[smhd])?(?= *│)`));
546
+ return found === null ? null : found[1];
547
+ };
548
+
549
+ test('a worktree reads its own commits, so committing keeps the badges', async () => {
550
+ const repo = makeRepo();
551
+ // One file added and one tracked file modified, both COMMITTED: the working
552
+ // tree no longer knows about them, which is exactly what used to erase the
553
+ // badges. `x.js` stays uncommitted, so the union with the status read is
554
+ // proved by the same browse.
555
+ const worktree = addOwnedWorktree(repo, 'with-commits', 'feat/commits');
556
+ fs.writeFileSync(path.join(worktree, 'committed.js'), 'const c = 1;\n');
557
+ git(worktree, ['add', 'committed.js']);
558
+ git(worktree, ['commit', '-m', 'add committed.js']);
559
+ fs.writeFileSync(path.join(worktree, 'a.js'), 'const x = 2;\n');
560
+ git(worktree, ['commit', '-am', 'touch a.js']);
561
+
562
+ const { mod, commands } = await loadFilesExtension();
563
+ mod.setFilesTuiLoader(async () => helpers);
564
+ const host = mountHost();
565
+ const running = commands.get('files').handler('', ctxFor(repo, host.ui, { registeredRoots: [worktree] }));
566
+
567
+ await waitFor(() => host.mounts.length >= 1, 'the scope mount');
568
+ const step = host.mounts[0].component;
569
+ await waitFor(() => textOf(step).includes('with-commits · feat/commits'), 'the worktree row');
570
+ step.handleInput('\u001b[B');
571
+ step.handleInput('\r');
572
+
573
+ await waitFor(() => host.mounts.length >= 2, 'the picker over the worktree');
574
+ const picker = host.mounts[1].component;
575
+ await waitFor(() => textOf(picker).includes('committed.js'), 'the worktree listing');
576
+ const text = textOf(picker);
577
+ // S44: the title names the distance ahead, and only ahead — the two commits are
578
+ // what the badges are measured against.
579
+ assert.match(text, /^╭─ ✿ Files · .*with-commits · ↑2 main /m,
580
+ 'the title carries the commits ahead of the principal branch');
581
+ assert.ok(!/↓\d+ /.test(text), 'behind is never painted beside ahead');
582
+ assert.equal(badgeOf(text, 'committed.js'), 'A', 'a file the branch added reads A');
583
+ assert.equal(badgeOf(text, 'a.js'), 'M', 'a file the branch modified reads M');
584
+ assert.equal(badgeOf(text, 'x.js'), 'U', 'uncommitted work is still marked');
585
+ assert.equal(badgeOf(text, 'README.md'), null, 'a file the branch never touched reads nothing');
586
+
587
+ // The scope row above the picker counts the same set, so the number and the
588
+ // badges can never disagree.
589
+ assert.match(textOf(step), /with-commits · feat\/commits +±3 files/, 'the row counts the same set the badges mark');
590
+
591
+ picker.handleInput('\u001b');
592
+ await running;
593
+ });
594
+
595
+ test('a repository whose principal branch is not `main` still marks its worktrees', async () => {
596
+ // S2: the comparison is the branch the PRINCIPAL checkout has, not a constant,
597
+ // so a `master` repository does not end up diffing against a `main` that does
598
+ // not exist — which would fail the read and leave the picker with no listing.
599
+ const repo = makeRepo({ branch: 'master' });
600
+ const worktree = addOwnedWorktree(repo, 'on-master', 'feat/on-master', 'master');
601
+ git(worktree, ['add', 'x.js']);
602
+ git(worktree, ['commit', '-m', 'commit x.js']);
603
+
604
+ const { mod, commands } = await loadFilesExtension();
605
+ mod.setFilesTuiLoader(async () => helpers);
606
+ const host = mountHost();
607
+ const running = commands.get('files').handler('', ctxFor(repo, host.ui, { registeredRoots: [worktree] }));
608
+
609
+ await waitFor(() => host.mounts.length >= 1, 'the scope mount');
610
+ const step = host.mounts[0].component;
611
+ await waitFor(() => textOf(step).includes('on-master · feat/on-master'), 'the worktree row');
612
+ step.handleInput('\u001b[B');
613
+ step.handleInput('\r');
614
+
615
+ await waitFor(() => host.mounts.length >= 2, 'the picker over the worktree');
616
+ const picker = host.mounts[1].component;
617
+ await waitFor(() => textOf(picker).includes('x.js'), 'the worktree listing');
618
+ const text = textOf(picker);
619
+ assert.equal(badgeOf(text, 'x.js'), 'A', 'the committed file is marked against `master`');
620
+ assert.equal(badgeOf(text, 'a.js'), null);
621
+
622
+ picker.handleInput('\u001b');
623
+ await running;
624
+ });
625
+
626
+ test('the main scope still reads its own status: a commit there clears the badge', async () => {
627
+ const repo = makeRepo();
628
+ fs.writeFileSync(path.join(repo, 'a.js'), 'const x = 9;\n');
629
+ git(repo, ['commit', '-am', 'touch a.js']);
630
+ fs.appendFileSync(path.join(repo, 'README.md'), 'dirty\n');
631
+
632
+ const { mod, commands } = await loadFilesExtension();
633
+ mod.setFilesTuiLoader(async () => helpers);
634
+ const host = mountHost();
635
+ const running = commands.get('files').handler('', ctxFor(repo, host.ui));
636
+
637
+ await waitFor(() => host.mounts.length >= 1, 'the scope mount');
638
+ host.mounts[0].component.handleInput('\r');
639
+
640
+ await waitFor(() => host.mounts.length >= 2, 'the picker over main');
641
+ const picker = host.mounts[1].component;
642
+ await waitFor(() => textOf(picker).includes('a.js'), 'the main listing');
643
+ const text = textOf(picker);
644
+ assert.equal(badgeOf(text, 'a.js'), null, 'a committed change in the principal checkout paints nothing');
645
+ assert.equal(badgeOf(text, 'README.md'), 'M', 'its uncommitted change still reads M');
646
+
647
+ picker.handleInput('\u001b');
648
+ await running;
649
+ });
650
+ });
651
+
540
652
  describe('the preview and the editor (S12, S14)', () => {
541
653
  test('the injected highlighter reaches the pane through the command’s own seams (S12)', async () => {
542
654
  const repo = makeRepo();
@@ -3,18 +3,22 @@
3
3
  // each file's change state with its age, and the bounded preview reader.
4
4
  //
5
5
  // The public surface only: the exact argv the injected runner receives, the
6
- // classification of untracked / dirty / clean (a .gitignore'd file never
7
- // appears because Git is asked for the standard exclude set), the recency order
8
- // and the age labels, and the preview's text / truncation / binary / error paths
9
- // against real temporary files. No child process is spawned and no network is
10
- // touched: every Git read goes through the fake runner below, and the temporary
11
- // directories live under os.tmpdir() and are removed in after().
6
+ // classification of a changed file (a .gitignore'd file never appears because Git
7
+ // is asked for the standard exclude set), the recency order and the age labels,
8
+ // and the preview's text / truncation / binary / error paths against real
9
+ // temporary files. Every Git read goes through the fake runner below, EXCEPT the
10
+ // two tests under "against real Git": those spawn Git in a scratch repository,
11
+ // because an ambiguous ref and a partial clone's lazy fetch are properties no
12
+ // fake answer can express. No network is touched, and every temporary directory
13
+ // lives under os.tmpdir() and is removed in after().
12
14
 
13
15
  const { test, after } = require('node:test');
14
16
  const assert = require('node:assert/strict');
17
+ const { spawnSync } = require('node:child_process');
15
18
  const fs = require('node:fs');
16
19
  const os = require('node:os');
17
20
  const path = require('node:path');
21
+ const { pathToFileURL } = require('node:url');
18
22
 
19
23
  const {
20
24
  listRepositoryEntries,
@@ -163,7 +167,7 @@ test('no runner at all is a sentence, not a throw', async () => {
163
167
 
164
168
  // --- entries: state, recency and age --------------------------------------
165
169
 
166
- test('changed files come first — untracked as new, dirty as updated, newest first — then the clean ones by path', async () => {
170
+ test('changed files come first — untracked as new, dirty as modified, newest first — then the clean ones by path', async () => {
167
171
  const root = tempDir();
168
172
  const now = Date.parse('2024-05-01T12:00:00Z');
169
173
  const dirty = writeFile(root, 'src/a.ts', 'export const a = 1;\n');
@@ -183,7 +187,7 @@ test('changed files come first — untracked as new, dirty as updated, newest fi
183
187
 
184
188
  assert.deepEqual(pairs(result.entries), [
185
189
  ['notes.md', 'new'],
186
- ['src/a.ts', 'updated'],
190
+ ['src/a.ts', 'modified'],
187
191
  ['src/b.js', 'clean'],
188
192
  ['src/clean.ts', 'clean'],
189
193
  ]);
@@ -243,15 +247,15 @@ test('an unreadable root or a file that is not on disk removes the age instead o
243
247
 
244
248
  const result = await listRepositoryEntries({ run, cwd: '/repo', now: Date.now() });
245
249
 
246
- assert.deepEqual(pairs(result.entries), [['present.ts', 'updated'], ['gone.ts', 'updated']],
250
+ assert.deepEqual(pairs(result.entries), [['present.ts', 'modified'], ['gone.ts', 'modified']],
247
251
  'the timed change comes first, the untimed one after');
248
252
  assert.equal(typeof result.entries[0].mtimeMs, 'number');
249
- assert.deepEqual(result.entries[1], { path: 'gone.ts', state: 'updated' }, 'no timestamp, no age');
253
+ assert.deepEqual(result.entries[1], { path: 'gone.ts', state: 'modified' }, 'no timestamp, no age');
250
254
 
251
255
  const noRoot = fakeRunner(gitAnswer({ listing: 'present.ts\0', status: ' M present.ts\0', root: undefined }));
252
256
  const withoutRoot = await listRepositoryEntries({ run: noRoot.run, cwd: '/repo', now: Date.now() });
253
- assert.deepEqual(pairs(withoutRoot.entries), [['present.ts', 'updated']], 'a failed rev-parse is not a failed listing');
254
- assert.deepEqual(withoutRoot.entries[0], { path: 'present.ts', state: 'updated' });
257
+ assert.deepEqual(pairs(withoutRoot.entries), [['present.ts', 'modified']], 'a failed rev-parse is not a failed listing');
258
+ assert.deepEqual(withoutRoot.entries[0], { path: 'present.ts', state: 'modified' });
255
259
  });
256
260
 
257
261
  test('a rename record skips its original path field', async () => {
@@ -262,7 +266,7 @@ test('a rename record skips its original path field', async () => {
262
266
  }));
263
267
 
264
268
  const result = await listRepositoryEntries({ run, cwd: '/repo', now: Date.now() });
265
- assert.deepEqual(pairs(result.entries), [['src/new.ts', 'updated'], ['src/old.ts', 'clean']],
269
+ assert.deepEqual(pairs(result.entries), [['src/new.ts', 'modified'], ['src/old.ts', 'clean']],
266
270
  'the original path is not a record of its own, so it is not marked changed');
267
271
  });
268
272
 
@@ -315,6 +319,243 @@ test('every Git read is a fixed read-only argv: nothing stages, commits or check
315
319
  assert.ok(calls[1].args.includes('--no-optional-locks'), 'status may not write the index back');
316
320
  });
317
321
 
322
+ // --- a worktree scope: the branch's own commits (S2-S5) --------------------
323
+
324
+ // The one read a worktree scope adds: the NET name-status record of what the
325
+ // branch changed against the merge-base with the principal branch. Three dots,
326
+ // so a `main` that moved on since the fork is not read as the branch's work.
327
+ // A bare ref would be ambiguous the moment a tag shares its name, and a file
328
+ // named `<ref>...HEAD` would break the read, so the branch is qualified and the
329
+ // argument list is closed with `--`. `--no-renames` is what keeps the read
330
+ // read-only in a partial clone.
331
+ const COMMIT_ARGV = (comparison) => [
332
+ 'diff',
333
+ '--name-status',
334
+ '-z',
335
+ '--no-renames',
336
+ `refs/heads/${comparison}...HEAD`,
337
+ '--',
338
+ ];
339
+
340
+ function worktreeAnswer({ listing = '', commits = '', status = '', root } = {}) {
341
+ return (args) => {
342
+ if (args[0] === 'ls-files') return { status: 0, stdout: listing, stderr: '' };
343
+ if (args[0] === 'diff') return { status: 0, stdout: commits, stderr: '' };
344
+ if (args[0] === '--no-optional-locks') return { status: 0, stdout: status, stderr: '' };
345
+ if (args[0] === 'rev-parse') {
346
+ return { status: root === undefined ? 128 : 0, stdout: root === undefined ? '' : `${root}\n`, stderr: '' };
347
+ }
348
+ return { status: 1, stdout: '', stderr: 'unexpected argv' };
349
+ };
350
+ }
351
+
352
+ test('a worktree scope marks the branch\'s commits, one row per path, and keeps its uncommitted work', async () => {
353
+ const root = tempDir();
354
+ const now = Date.parse('2024-05-01T12:00:00Z');
355
+ setMtime(writeFile(root, 'a.txt', 'three\n'), now - 4 * HOUR);
356
+ setMtime(writeFile(root, 'added.txt', 'new\n'), now - 3 * HOUR);
357
+ setMtime(writeFile(root, 'src/moved.txt', 'deep\n'), now - 2 * HOUR);
358
+ setMtime(writeFile(root, 'u.txt', 'untracked\n'), now - HOUR);
359
+ writeFile(root, 'clean.ts', 'clean\n');
360
+
361
+ const { run, calls } = fakeRunner(worktreeAnswer({
362
+ listing: 'a.txt\0added.txt\0src/moved.txt\0clean.ts\0u.txt\0',
363
+ // The branch modified one file, added one, deleted one, renamed one.
364
+ commits: 'M\0a.txt\0A\0added.txt\0D\0b.txt\0R100\0src/deep.txt\0src/moved.txt\0',
365
+ // `a.txt` is dirty on top of its commit, and `u.txt` was never committed.
366
+ status: ' M a.txt\0?? u.txt\0',
367
+ root,
368
+ }));
369
+
370
+ const result = await listRepositoryEntries({ run, cwd: '/repo', now, comparison: 'main' });
371
+
372
+ assert.deepEqual(pairs(result.entries), [
373
+ ['u.txt', 'new'],
374
+ ['src/moved.txt', 'added'],
375
+ ['added.txt', 'added'],
376
+ ['a.txt', 'modified'],
377
+ ['clean.ts', 'clean'],
378
+ ]);
379
+ assert.deepEqual(calls.map((call) => call.args), [LIST_ARGV, COMMIT_ARGV('main'), STATUS_ARGV, ROOT_ARGV],
380
+ 'the commit read sits between the listing and the status, one fixed argv each');
381
+ assert.ok(calls.every((call) => call.opts.cwd === '/repo'), 'every read runs in the browsed checkout');
382
+
383
+ assert.equal(result.entries.filter((entry) => entry.path === 'a.txt').length, 1,
384
+ 'a path named by a commit and again by status is one row');
385
+ assert.equal(result.entries.find((entry) => entry.path === 'a.txt').state, 'modified',
386
+ 'the commit state wins over the dirty one, and both read M');
387
+ assert.equal(result.entries.some((entry) => entry.path === 'b.txt'), false, 'a deleted file is never listed');
388
+ assert.equal(result.entries.some((entry) => entry.path === 'src/deep.txt'), false,
389
+ 'a rename\'s original path is not a row of its own');
390
+ assert.equal(result.entries[1].age, formatAge(fs.statSync(path.join(root, 'src/moved.txt')).mtimeMs, now),
391
+ 'a committed row keeps the same age label as any other');
392
+ });
393
+
394
+ test('the comparison is the caller\'s, carried verbatim into the one diff read', async () => {
395
+ const { run, calls } = fakeRunner(worktreeAnswer({ listing: 'a.ts\0', commits: 'A\0a.ts\0' }));
396
+
397
+ await listRepositoryEntries({ run, cwd: '/repo', now: 0, comparison: 'trunk' });
398
+
399
+ assert.deepEqual(calls[1].args, COMMIT_ARGV('trunk'),
400
+ 'the principal branch is the caller\'s, whatever the repository calls it');
401
+ });
402
+
403
+ test('an empty comparison is the status read alone, exactly as the main scope reads', async () => {
404
+ const { run, calls } = fakeRunner(gitAnswer({
405
+ listing: 'a.ts\0b.ts\0',
406
+ status: '?? b.ts\0',
407
+ root: undefined,
408
+ }));
409
+
410
+ const result = await listRepositoryEntries({ run, cwd: '/repo', now: 0, comparison: '' });
411
+
412
+ assert.deepEqual(pairs(result.entries), [['b.ts', 'new'], ['a.ts', 'clean']]);
413
+ assert.deepEqual(calls.map((call) => call.args), [LIST_ARGV, STATUS_ARGV, ROOT_ARGV],
414
+ 'no comparison asks Git nothing about commits');
415
+ });
416
+
417
+ test('a path the branch deleted and the working tree recreated is untracked, never a deleted row', async () => {
418
+ const { run } = fakeRunner(worktreeAnswer({
419
+ listing: 'gone.ts\0',
420
+ commits: 'D\0gone.ts\0',
421
+ status: '?? gone.ts\0',
422
+ }));
423
+
424
+ const result = await listRepositoryEntries({ run, cwd: '/repo', now: 0, comparison: 'main' });
425
+
426
+ assert.deepEqual(pairs(result.entries), [['gone.ts', 'new']],
427
+ 'the file exists and Git does not track it, so the row is the honest one');
428
+ });
429
+
430
+ test('a copy record names its new path only', async () => {
431
+ const { run } = fakeRunner(worktreeAnswer({
432
+ listing: 'src/copy.ts\0src/orig.ts\0',
433
+ // Git writes the ORIGINAL path first and the path the record is about second
434
+ // (verified against `git diff --name-status -z -M -C --find-copies-harder`).
435
+ commits: 'C100\0src/orig.ts\0src/copy.ts\0M\0src/orig.ts\0',
436
+ }));
437
+
438
+ const result = await listRepositoryEntries({ run, cwd: '/repo', now: 0, comparison: 'main' });
439
+
440
+ assert.deepEqual(pairs(result.entries), [['src/copy.ts', 'added'], ['src/orig.ts', 'modified']],
441
+ 'the copy is new at its own path; the original keeps the state its own record gives it');
442
+ });
443
+
444
+ test('a failed commit read is a sentence, never a half listing', async () => {
445
+ const { run, calls } = fakeRunner((args) => {
446
+ if (args[0] === 'ls-files') return { status: 0, stdout: 'a.ts\0', stderr: '' };
447
+ if (args[0] === 'diff') return { status: 128, stdout: '', stderr: "fatal: ambiguous argument 'main...HEAD'" };
448
+ return { status: 0, stdout: '', stderr: '' };
449
+ });
450
+
451
+ assert.deepEqual(await listRepositoryEntries({ run, cwd: '/repo', now: 0, comparison: 'main' }), {
452
+ ok: false,
453
+ message: "Cannot read the branch's commits: fatal: ambiguous argument 'main...HEAD'.",
454
+ });
455
+ assert.deepEqual(calls.map((call) => call.args[0]), ['ls-files', 'diff'],
456
+ 'the status read never runs once the commit read failed');
457
+ });
458
+
459
+ // --- against real Git ------------------------------------------------------
460
+ //
461
+ // The only two properties a fake answer cannot express: an ambiguous ref, and a
462
+ // read that must write nothing to the repository (a partial clone is where `-M`
463
+ // used to fetch the missing merge-base blob and leave a pack behind).
464
+
465
+ // A real Git runner with the injected runner's signature, over a scratch
466
+ // repository whose configuration is this test's alone: no system config, no
467
+ // global config, and a temporary HOME.
468
+ function realGit(root) {
469
+ const home = tempDir();
470
+ const env = {
471
+ PATH: process.env.PATH,
472
+ HOME: home,
473
+ TMPDIR: home,
474
+ GIT_CONFIG_NOSYSTEM: '1',
475
+ GIT_CONFIG_GLOBAL: os.devNull,
476
+ GIT_ALLOW_PROTOCOL: 'file',
477
+ };
478
+ const run = (args, opts = {}, extra = {}) => spawnSync('git', args, {
479
+ cwd: opts.cwd === undefined ? root : opts.cwd,
480
+ timeout: opts.timeoutMs === undefined ? 15_000 : opts.timeoutMs,
481
+ encoding: 'utf8',
482
+ env: { ...env, ...extra },
483
+ });
484
+ const git = (...args) => {
485
+ const result = run(args);
486
+ assert.equal(result.status, 0, `git ${args.join(' ')}: ${String(result.stderr)}`);
487
+ return String(result.stdout).trim();
488
+ };
489
+ git('init', '-q', '-b', 'main');
490
+ git('config', 'user.name', 'Files Test');
491
+ git('config', 'user.email', 'files@example.invalid');
492
+ return { git, run };
493
+ }
494
+
495
+ test('S2: a tag or a file spelled like the revision cannot shadow the principal branch', async () => {
496
+ const root = tempDir();
497
+ const { git, run } = realGit(root);
498
+ git('commit', '-q', '--allow-empty', '-m', 'base');
499
+ git('checkout', '-qb', 'feature');
500
+ writeFile(root, 'added.txt', 'branch addition\n');
501
+ git('add', '.');
502
+ git('commit', '-qm', 'feature');
503
+
504
+ // A tag on the tip: a bare `main` would resolve to it and answer "no changes".
505
+ git('tag', 'main');
506
+ const tagged = await listRepositoryEntries({ run, cwd: root, now: 0, comparison: 'main' });
507
+ assert.equal(tagged.ok, true, tagged.message);
508
+ assert.equal(tagged.entries.find((entry) => entry.path === 'added.txt').state, 'added',
509
+ 'the local branch is read, never the tag that shares its name');
510
+
511
+ // An ordinary file whose name spells the whole revision: Git would read it as a
512
+ // path and fail the entire read.
513
+ git('tag', '-d', 'main');
514
+ writeFile(root, 'main...HEAD', 'ordinary file\n');
515
+ const shadowed = await listRepositoryEntries({ run, cwd: root, now: 0, comparison: 'main' });
516
+ assert.equal(shadowed.ok, true, shadowed.message);
517
+ assert.equal(shadowed.entries.find((entry) => entry.path === 'added.txt').state, 'added');
518
+ assert.equal(shadowed.entries.find((entry) => entry.path === 'main...HEAD').state, 'new',
519
+ 'the file is the untracked row it is, not a broken read');
520
+ });
521
+
522
+ test('S6: marking a partial clone fetches nothing and writes no pack', async () => {
523
+ const origin = tempDir();
524
+ const { git, run } = realGit(origin);
525
+ git('config', 'uploadpack.allowFilter', 'true');
526
+ git('config', 'uploadpack.allowAnySHA1InWant', 'true');
527
+ const body = Array.from({ length: 200 }, (_, index) => `source line ${index}\n`).join('');
528
+ writeFile(origin, 'source.txt', body);
529
+ git('add', '.');
530
+ git('commit', '-qm', 'base');
531
+ const blob = git('rev-parse', 'main:source.txt');
532
+ git('checkout', '-qb', 'feature');
533
+ git('mv', 'source.txt', 'dest.txt');
534
+ writeFile(origin, 'dest.txt', body.replace('line 199', 'line changed'));
535
+ git('commit', '-qam', 'rename with edit');
536
+
537
+ const clone = path.join(tempDir(), 'clone');
538
+ const linked = path.join(tempDir(), 'linked');
539
+ git('clone', '-q', '--filter=blob:none', '--no-checkout', pathToFileURL(origin).href, clone);
540
+ const inClone = (...args) => git('-C', clone, ...args);
541
+ inClone('branch', 'main', 'origin/main');
542
+ inClone('worktree', 'add', '-q', '--detach', linked, 'origin/feature');
543
+
544
+ const missing = () => run(['cat-file', '-e', blob],
545
+ { cwd: clone, timeoutMs: 15_000 }, { GIT_NO_LAZY_FETCH: '1' }).status;
546
+ const packs = () => fs.readdirSync(path.join(clone, '.git', 'objects', 'pack')).sort();
547
+ assert.equal(missing(), 1, 'the merge-base blob starts absent, which is what a partial clone is');
548
+ const before = packs();
549
+
550
+ const result = await listRepositoryEntries({ run, cwd: linked, now: 0, comparison: 'main' });
551
+
552
+ assert.equal(result.ok, true, result.message);
553
+ assert.equal(result.entries.find((entry) => entry.path === 'dest.txt').state, 'added',
554
+ 'an undetected rename still reads as the new path being added');
555
+ assert.equal(missing(), 1, 'the read fetched nothing');
556
+ assert.deepEqual(packs(), before, 'and wrote no pack into the clone');
557
+ });
558
+
318
559
  // --- formatAge -------------------------------------------------------------
319
560
 
320
561
  test('formatAge labels one elapsed age in s, m, h and d', () => {
@@ -39,12 +39,12 @@ function entry(path, state, mtimeMs) {
39
39
  // Deliberately NOT in the listing's own order: the builder owns the `files`
40
40
  // order, so it is asserted against an unsorted input.
41
41
  const ENTRIES = [
42
- entry('lib/view-layout.js', 'updated', 3000),
42
+ entry('lib/view-layout.js', 'modified', 3000),
43
43
  entry('README.md', 'clean', 1500),
44
44
  entry('lib/files-orders.js', 'new', 5000),
45
45
  entry('AGENTS.md', 'clean', 1000),
46
46
  entry('lib/odd-prompt/odd-worktrees.md', 'clean', 2000),
47
- entry('docs/reference.md', 'updated', 4000),
47
+ entry('docs/reference.md', 'modified', 4000),
48
48
  entry('tools/files-orders.test.js', 'new', 3500),
49
49
  entry('LICENSE', 'clean', 800),
50
50
  ];
@@ -124,9 +124,9 @@ describe('files: one flat file list (S10, S33)', () => {
124
124
  test('a changed file without an mtime sorts after the timed changes and before clean files', () => {
125
125
  const rows = buildRows([
126
126
  entry('b.md', 'clean'),
127
- entry('x.js', 'updated'),
127
+ entry('x.js', 'modified'),
128
128
  entry('a.js', 'new', 100),
129
- entry('y.js', 'updated', 200),
129
+ entry('y.js', 'modified', 200),
130
130
  ], { order: 'files' });
131
131
  assert.deepEqual(paths(rows), ['y.js', 'a.js', 'x.js', 'b.md']);
132
132
  });
@@ -120,7 +120,7 @@ const SCOPE = { root: '/home/dev/repo-worktrees/files-picker', kind: 'worktree',
120
120
  // The listing T1 answers: changed first and newest first, then clean by path.
121
121
  const FILES = [
122
122
  { path: 'brand-new.ts', state: 'new', mtimeMs: NOW - 5_000, age: '5s' },
123
- { path: 'src/cursor.ts', state: 'updated', mtimeMs: NOW - 2 * HOUR, age: '2h' },
123
+ { path: 'src/cursor.ts', state: 'modified', mtimeMs: NOW - 2 * HOUR, age: '2h' },
124
124
  { path: 'README.md', state: 'clean' },
125
125
  { path: 'src/lib/util.ts', state: 'clean' },
126
126
  ];
@@ -335,6 +335,44 @@ describe('the card chrome (S1, S15)', () => {
335
335
  assert.match(afterPath, /^ ─+ esc ╮$/, `only the rule and esc follow the path: ${JSON.stringify(afterPath)}`);
336
336
  });
337
337
 
338
+ test('the commits ahead of the base ride the title, and only ahead is named (S44)', async () => {
339
+ const ahead = {
340
+ ...SCOPE,
341
+ detail: { comparison: 'main', ahead: 3, behind: 310, lastCommitSubject: 'fix(warp): the dash' },
342
+ };
343
+ const { view } = await open({ scope: ahead });
344
+ const title = rowsOf(view)[0];
345
+ assert.ok(title.startsWith(`╭─ ✿ Files · ${SCOPE.root} · ↑3 main `),
346
+ `the ahead field is the title's tail, never beside a behind count: ${title}`);
347
+ assert.ok(!title.includes('↓'), 'behind is not painted next to ahead');
348
+ assert.equal(helpers.visibleWidth(title), WIDTH);
349
+
350
+ // Already on top of the base, or never measured: no field at all.
351
+ const level = await open({ scope: { ...SCOPE, detail: { comparison: 'main', ahead: 0, behind: 4 } } });
352
+ assert.ok(rowsOf(level.view)[0].startsWith(`╭─ ✿ Files · ${SCOPE.root} `), 'no ahead, no field');
353
+ const unmeasured = await open({ scope: { ...SCOPE, detail: {} } });
354
+ assert.ok(rowsOf(unmeasured.view)[0].startsWith(`╭─ ✿ Files · ${SCOPE.root} `), 'no detail, no field');
355
+ });
356
+
357
+ test('a narrow title keeps the ahead field and gives way with the path (S44)', async () => {
358
+ const { view } = await open({
359
+ scope: { ...SCOPE, detail: { comparison: 'main', ahead: 12, behind: 310 } },
360
+ });
361
+ // 52 columns: 30 for the detail, of which the field takes 9, so the path keeps
362
+ // 21 and still shows the identifying tail.
363
+ const narrow = view.render(52).map(strip)[0];
364
+ assert.equal(narrow, '╭─ ✿ Files · …rktrees/files-picker · ↑12 main esc ╮',
365
+ 'the field is never elided; the path gives way to it');
366
+ // Too narrow for a path worth painting: the field keeps the row alone.
367
+ const tiniest = view.render(34).map(strip)[0];
368
+ assert.ok(tiniest.includes('↑12 main'), tiniest);
369
+ assert.ok(!tiniest.includes('…'), `no elided path beside the field at the smallest width: ${tiniest}`);
370
+ assert.ok(!tiniest.includes('files-picker'), 'the path is gone, not truncated into the field');
371
+ for (const width of [52, 34]) {
372
+ assert.equal(helpers.visibleWidth(view.render(width).map(strip)[0]), width, `the row fills ${width}`);
373
+ }
374
+ });
375
+
338
376
  test('a narrow card elides the path from its left, so the tail that identifies the checkout survives (S37)', async () => {
339
377
  const { view } = await open();
340
378
  // 50 columns: the title keeps 30 for the path (50 - 7 for `✿ Files` - 3 for
@@ -541,10 +579,25 @@ describe('the list rows (S6, S15)', () => {
541
579
  assert.ok(!bodyText(rows).includes('new '), 'the word badge is never painted');
542
580
  });
543
581
 
582
+ test('a file the branch added paints A, and the three letters are the whole vocabulary', async () => {
583
+ const entries = [
584
+ { path: 'arrived.ts', state: 'added' },
585
+ { path: 'edited.ts', state: 'modified' },
586
+ { path: 'brand-new.ts', state: 'new' },
587
+ { path: 'plain.ts', state: 'clean' },
588
+ ];
589
+ const { view } = await open({ entries, now: NOW });
590
+ const rows = rowsOf(view);
591
+ assert.match(listCell(rows, 'arrived.ts'), /A$/, 'a committed addition reads A, never M');
592
+ assert.match(listCell(rows, 'edited.ts'), /M$/);
593
+ assert.match(listCell(rows, 'brand-new.ts'), /U$/);
594
+ assert.match(listCell(rows, 'plain.ts'), /^\s+plain\.ts *$/, 'a clean row still paints no badge');
595
+ });
596
+
544
597
  test('a changed row without an age keeps its letter and falls back to its mtime once', async () => {
545
598
  const entries = [
546
599
  { path: 'brand-new.ts', state: 'new' },
547
- { path: 'edited.ts', state: 'updated', mtimeMs: NOW - 3 * HOUR },
600
+ { path: 'edited.ts', state: 'modified', mtimeMs: NOW - 3 * HOUR },
548
601
  { path: 'plain.ts', state: 'clean' },
549
602
  ];
550
603
  const { view } = await open({ entries, now: NOW });
@@ -96,16 +96,19 @@ describe('countCell (S9)', () => {
96
96
  });
97
97
 
98
98
  describe('scopeDetailLine (S9)', () => {
99
- test('the last commit subject leads, then the count, the age and the distances', () => {
99
+ test('the last commit subject leads, then the count, the age and ONE distance', () => {
100
100
  const line = scopeDetailLine({
101
101
  lastCommitSubject: 'add the scope step',
102
102
  changedFiles: 3,
103
103
  lastModifiedMs: NOW - 5 * MINUTE,
104
104
  ahead: 2,
105
- behind: 1,
105
+ behind: 310,
106
106
  comparison: 'main',
107
107
  }, NOW);
108
- assert.equal(line, 'add the scope step · ±3 files · 5m ago · ↑2 main · ↓1 main');
108
+ // A worktree is almost always behind its principal branch, so `↓` beside `↑`
109
+ // is noise that reads as a contradiction (S44): ahead wins when there is any,
110
+ // and behind is painted only when the checkout is merely stale.
111
+ assert.equal(line, 'add the scope step · ±3 files · 5m ago · ↑2 main');
109
112
  });
110
113
 
111
114
  test('the main row names the remote ref it is measured against', () => {
@@ -269,7 +269,9 @@ describe('the focused detail line (S9)', () => {
269
269
  assert.ok(rowsOf(view)[HEIGHT - 3].includes('main subject'));
270
270
  view.handleInput('down');
271
271
  const moved = rowsOf(view);
272
- assert.ok(moved[HEIGHT - 3].includes('add the scope step · ±3 files · 2m ago · ↑2 main · ↓1 main'), moved[HEIGHT - 3]);
272
+ // S44: one distance, never two — ahead wins when the checkout has any.
273
+ assert.ok(moved[HEIGHT - 3].includes('add the scope step · ±3 files · 2m ago · ↑2 main'), moved[HEIGHT - 3]);
274
+ assert.ok(!/↓\d+/.test(moved[HEIGHT - 3]), 'behind is not painted beside ahead');
273
275
  });
274
276
 
275
277
  test('an absent or empty detail keeps a blank row of the same geometry', () => {