pi-odd-worktree 2.1.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/README.md +54 -319
  2. package/extensions/odd-worktree-tools.ts +4145 -2529
  3. package/lib/bash-activity.js +1164 -0
  4. package/lib/bash-design.js +684 -0
  5. package/lib/bash-destructive.js +559 -0
  6. package/lib/bash-frame.js +205 -0
  7. package/lib/card-content.js +23 -0
  8. package/lib/card-style.js +175 -0
  9. package/lib/checkout-facts.js +30 -70
  10. package/lib/codegraph-card-preview.js +628 -0
  11. package/lib/codegraph-card.js +515 -0
  12. package/lib/codegraph-compaction.js +76 -0
  13. package/lib/codegraph-daemon.js +246 -0
  14. package/lib/codegraph-edit-sync.js +182 -0
  15. package/lib/codegraph-guard-target.js +337 -0
  16. package/lib/codegraph-guard.js +211 -0
  17. package/lib/codegraph-index.js +1020 -0
  18. package/lib/codegraph-lock.js +607 -0
  19. package/lib/codegraph-mcp-config.js +134 -0
  20. package/lib/codegraph-mcp.js +123 -0
  21. package/lib/codegraph-paths.js +69 -0
  22. package/lib/codegraph-prompt/explore.md +11 -0
  23. package/lib/codegraph-prompt/fix.md +6 -0
  24. package/lib/codegraph-prompt/generic.md +8 -0
  25. package/lib/codegraph-prompt/judge.md +9 -0
  26. package/lib/codegraph-prompt/orchestrator.md +17 -0
  27. package/lib/codegraph-prompt/verify.md +10 -0
  28. package/lib/codegraph-prompt/worker.md +7 -0
  29. package/lib/codegraph-role.js +55 -0
  30. package/lib/codegraph-rules.js +146 -0
  31. package/lib/codegraph-session.js +303 -383
  32. package/lib/codegraph-warmup.js +139 -0
  33. package/lib/file-card-markdown.js +141 -0
  34. package/lib/file-card-resolver.js +245 -0
  35. package/lib/file-card.js +659 -0
  36. package/lib/files-index.js +387 -0
  37. package/lib/files-insert.js +81 -0
  38. package/lib/files-orders.js +326 -0
  39. package/lib/files-picker-view.js +1416 -0
  40. package/lib/files-preview.js +338 -0
  41. package/lib/files-scope-detail.js +171 -0
  42. package/lib/files-scope-view.js +507 -0
  43. package/lib/gh-issues.js +308 -14
  44. package/lib/issue-preview.js +26 -7
  45. package/lib/issues-bash-mutation.js +206 -0
  46. package/lib/issues-cache-store.js +261 -0
  47. package/lib/issues-section.js +710 -0
  48. package/lib/issues-view.js +649 -52
  49. package/lib/odd-prompt/odd-worktrees.md +21 -0
  50. package/lib/odd-worktrees-prompt.js +10 -28
  51. package/lib/related-issues-cache.js +210 -0
  52. package/lib/shell-card.js +825 -0
  53. package/lib/skill-odd-card.js +183 -0
  54. package/lib/tui-paint.js +4 -5
  55. package/lib/warp-create-panel.js +538 -250
  56. package/lib/warp-create-picker.js +56 -9
  57. package/lib/warp-delete-confirm.js +19 -28
  58. package/lib/warp-selector-view.js +160 -82
  59. package/lib/which-command.js +90 -0
  60. package/lib/worktree-card.js +267 -897
  61. package/lib/worktree-cards.js +383 -0
  62. package/lib/worktree-create.js +287 -0
  63. package/lib/worktree-git.js +3 -3
  64. package/lib/worktree-guard.js +548 -0
  65. package/lib/worktree-hooks.js +421 -712
  66. package/lib/worktree-list.js +120 -0
  67. package/lib/worktree-registry.js +162 -879
  68. package/lib/{worktree-close-herdr.js → worktree-remove.js} +9 -11
  69. package/lib/worktree-setup-runner.js +376 -0
  70. package/lib/worktree-setup.js +140 -0
  71. package/lib/worktree-warp-busy.js +462 -85
  72. package/lib/worktree-warp-sessions.js +1 -2
  73. package/package.json +2 -2
  74. package/tools/bash-activity.test.js +1419 -0
  75. package/tools/bash-design.test.js +1091 -0
  76. package/tools/bash-destructive.test.js +139 -0
  77. package/tools/card-content.test.js +44 -0
  78. package/tools/card-style.test.js +298 -0
  79. package/tools/codegraph-card-preview.test.js +254 -0
  80. package/tools/codegraph-card.test.js +1080 -0
  81. package/tools/codegraph-compaction.test.js +378 -0
  82. package/tools/codegraph-daemon.test.js +248 -0
  83. package/tools/codegraph-edit-sync.test.js +295 -0
  84. package/tools/codegraph-guard-target.test.js +174 -0
  85. package/tools/codegraph-guard.test.js +238 -0
  86. package/tools/codegraph-index.test.js +1948 -0
  87. package/tools/codegraph-lock.test.js +932 -0
  88. package/tools/codegraph-mcp-config.test.js +181 -0
  89. package/tools/codegraph-mcp.test.js +194 -0
  90. package/tools/codegraph-paths.test.js +44 -0
  91. package/tools/codegraph-role.test.js +30 -0
  92. package/tools/codegraph-rules.test.js +250 -0
  93. package/tools/codegraph-session.test.js +660 -391
  94. package/tools/codegraph-warmup.test.js +316 -0
  95. package/tools/commands.test.js +510 -31
  96. package/tools/file-card-markdown.test.js +188 -0
  97. package/tools/file-card.test.js +1289 -0
  98. package/tools/files-bridge.test.js +575 -0
  99. package/tools/files-command.test.js +610 -0
  100. package/tools/files-index.test.js +473 -0
  101. package/tools/files-insert.test.js +139 -0
  102. package/tools/files-orders.test.js +597 -0
  103. package/tools/files-picker-view.test.js +1871 -0
  104. package/tools/files-preview.test.js +452 -0
  105. package/tools/files-scope-detail.test.js +264 -0
  106. package/tools/files-scope-view.test.js +614 -0
  107. package/tools/fixtures/card-codegraph-outputs.js +110 -0
  108. package/tools/fixtures/codegraph-cli-stub.js +16 -0
  109. package/tools/fixtures/codegraph-init-process.js +28 -0
  110. package/tools/fixtures/codegraph-lock-worker.js +117 -0
  111. package/tools/fixtures/daemon-fake.js +98 -0
  112. package/tools/fixtures/daemon-mcp-server.js +39 -0
  113. package/tools/fixtures/daemon-warmup-worker.js +12 -0
  114. package/tools/fixtures/load-extension.js +136 -3
  115. package/tools/gh-issues-feedback.test.js +31 -7
  116. package/tools/gh-issues.test.js +391 -1
  117. package/tools/issue-preview.test.js +44 -7
  118. package/tools/issues-bash-mutation.test.js +101 -0
  119. package/tools/issues-cache-store.test.js +222 -0
  120. package/tools/issues-command.test.js +1512 -66
  121. package/tools/issues-open-guard.test.js +1096 -0
  122. package/tools/issues-section.test.js +4195 -0
  123. package/tools/issues-seed-query-regression.test.js +67 -0
  124. package/tools/issues-view.test.js +1489 -60
  125. package/tools/odd-worktrees-prompt.test.js +98 -65
  126. package/tools/package-surface.test.js +431 -36
  127. package/tools/related-issues-cache.test.js +324 -0
  128. package/tools/shell-card.test.js +834 -0
  129. package/tools/skill-odd-card.test.js +200 -0
  130. package/tools/t5-session-identity.test.js +44 -22
  131. package/tools/warp-busy-guard.test.js +2565 -309
  132. package/tools/warp-create-panel.test.js +499 -74
  133. package/tools/warp-create-picker.test.js +101 -5
  134. package/tools/warp-delete-confirm.test.js +49 -15
  135. package/tools/warp-empty-session.test.js +0 -1
  136. package/tools/warp-fallback-regression.test.js +533 -0
  137. package/tools/warp-selector-view.test.js +460 -196
  138. package/tools/which-command.test.js +126 -0
  139. package/tools/worktree-card.test.js +551 -0
  140. package/tools/worktree-cards.test.js +845 -0
  141. package/tools/worktree-changes.test.js +4 -5
  142. package/tools/worktree-create.test.js +489 -0
  143. package/tools/worktree-guard.test.js +823 -0
  144. package/tools/worktree-hooks.test.js +905 -0
  145. package/tools/worktree-list.test.js +170 -0
  146. package/tools/worktree-registry.test.js +89 -230
  147. package/tools/worktree-remove-async.test.js +318 -0
  148. package/tools/worktree-setup-runner.test.js +276 -0
  149. package/tools/worktree-setup.test.js +140 -0
  150. package/tools/worktree-tools.test.js +419 -199
  151. package/lib/codegraph-commands.js +0 -165
  152. package/lib/odd-prompt/odd-worktrees.with-codegraph.md +0 -19
  153. package/lib/odd-prompt/odd-worktrees.without-codegraph.md +0 -15
  154. package/lib/worktree-model-result.js +0 -291
  155. package/tools/codegraph-commands.test.js +0 -371
  156. package/tools/herdr-free-create.test.js +0 -161
  157. package/tools/worktree-close-herdr-async.test.js +0 -204
  158. package/tools/worktree-odd-migration.test.js +0 -224
  159. package/tools/worktree-registry-cache.test.js +0 -163
  160. package/tools/worktree-registry-odd.test.js +0 -231
@@ -0,0 +1,338 @@
1
+ 'use strict';
2
+ // The file picker's preview pane (S11, S12): the pure half of `/files`' right
3
+ // pane. It reads no file and paints nothing itself — `lib/files-index.js` already
4
+ // bounded the read, and the view paints these cells with the theme — so one
5
+ // `readFilePreview` result becomes an exact row/cell list here and can be
6
+ // asserted without a repository, a theme or a live highlighter.
7
+ //
8
+ // What the pane owns:
9
+ // - its own rounded box inside the given width, with the `line/total` position
10
+ // embedded at the right of the TOP border;
11
+ // - a dim gutter numbering each file line once, its wrapped continuation rows
12
+ // aligned under the same text column;
13
+ // - a left-side wrap instead of an ellipsis: a line wider than the pane
14
+ // continues on the next row, so the numbers show it is the same line;
15
+ // - the optional injected highlighter: it runs ONCE per call on the bounded
16
+ // text, and a highlighted row goes through the injected ANSI-aware wrapper so
17
+ // a colour run survives the wrap;
18
+ // - the honest notices: a binary/error message and the truncation row.
19
+ //
20
+ // Plain text is measured and clipped as PLAIN text; a role is attached afterwards
21
+ // (AGENTS.md invariant 17). The measurement helpers are injected (`metrics`), never
22
+ // statically imported: `visibleWidth`, `truncateToWidth` and `wrapTextWithAnsi`.
23
+ //
24
+ // Cell roles are exactly the three the view paints: `dim` is the gutter, `border`
25
+ // is the box frame, and `text` is every content cell (a source line, a notice, the
26
+ // position label). A highlighted cell keeps the `text` role and already carries
27
+ // the highlighter's own escapes, so the view never re-tones it.
28
+
29
+ const BOX_TOP_LEFT = '╭';
30
+ const BOX_TOP_RIGHT = '╮';
31
+ const BOX_BOTTOM_LEFT = '╰';
32
+ const BOX_BOTTOM_RIGHT = '╯';
33
+ const BOX_HORIZONTAL = '─';
34
+ const BOX_VERTICAL = '│';
35
+ // The box's two vertical border columns and its top and bottom border rows.
36
+ const BOX_COLUMNS = 2;
37
+ const BOX_ROWS = 2;
38
+ // The box paints only when the body can hold its two border rows plus one
39
+ // usable content row, and when one cell is left between its border columns.
40
+ const BOX_MIN_BODY_ROWS = BOX_ROWS + 1;
41
+ const BOX_MIN_WIDTH = BOX_COLUMNS + 1;
42
+ // One space between the line-number gutter and its text.
43
+ const GUTTER_GAP = ' ';
44
+ // The row appended to a preview the reader cut short.
45
+ const TRUNCATED_NOTICE = '… preview truncated.';
46
+ // Stripped from file text before it reaches a cell: a file's own escape
47
+ // sequences are data, never paint, and a control character could break the box.
48
+ const OSC_ESCAPE_PATTERN = /(?:\x1b\]|\x9d)[\s\S]*?(?:\x07|\x1b\\|\x9c|$)/g;
49
+ const NON_OSC_ANSI_ESCAPE_PATTERN = /\x1b\[[0-?]*[ -/]*[@-~]|\x1b[@-Z\\-_]|\x9b[0-?]*[ -/]*[@-~]/g;
50
+ const CONTROL_CHARACTER_PATTERN = /[\u0000-\u0008\u000b-\u000d\u000e-\u001f\u007f-\u009f]/g;
51
+ const graphemes = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
52
+
53
+ /** A whole, non-negative number; anything else is nothing. */
54
+ function whole(value) {
55
+ return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
56
+ }
57
+
58
+ /** File text as terminal-safe plain text: no escape sequence, no control character. */
59
+ function sanitize(value) {
60
+ return String(value == null ? '' : value)
61
+ .replace(OSC_ESCAPE_PATTERN, '')
62
+ .replace(NON_OSC_ANSI_ESCAPE_PATTERN, '')
63
+ .replace(CONTROL_CHARACTER_PATTERN, '');
64
+ }
65
+
66
+ /** One preview line: a tab is two plain cells, so the box stays aligned. */
67
+ function displayPreviewText(value) {
68
+ return sanitize(value).replace(/\t/g, ' ');
69
+ }
70
+
71
+ /**
72
+ * The rows one plain line wraps into at `width` cells, cut on grapheme
73
+ * boundaries only, so a wide grapheme is never split across two rows. A
74
+ * non-positive width never wraps; a grapheme wider than a whole row still gets
75
+ * its own row (the content cell decides whether it fits the pane).
76
+ */
77
+ function wrapByCells(text, width, metrics) {
78
+ if (width <= 0) return [text];
79
+ const rows = [];
80
+ let row = '';
81
+ let used = 0;
82
+ for (const { segment } of graphemes.segment(text)) {
83
+ const cells = metrics.visibleWidth(segment);
84
+ if (used > 0 && used + cells > width) {
85
+ rows.push(row);
86
+ row = '';
87
+ used = 0;
88
+ }
89
+ row += segment;
90
+ used += cells;
91
+ }
92
+ rows.push(row);
93
+ return rows;
94
+ }
95
+
96
+ /** An ANSI-aware wrap that answers nothing usable falls back to the whole line. */
97
+ function wrapHighlighted(text, width, metrics) {
98
+ if (width <= 0) return [text];
99
+ try {
100
+ const rows = metrics.wrapTextWithAnsi(text, width);
101
+ if (Array.isArray(rows) && rows.length > 0 && rows.every((row) => typeof row === 'string')) return rows;
102
+ } catch {
103
+ // Fall through to the unpainted line.
104
+ }
105
+ return [text];
106
+ }
107
+
108
+ /**
109
+ * The highlighter's lines, or `undefined` for the plain preview. Every failure —
110
+ * no highlighter, no path resolver, an unknown language, a throw from either, a
111
+ * list that does not line up with the file — degrades whole, never per line, so
112
+ * the pane is never blank, never an error and never a partial paint. The
113
+ * highlighter runs ONCE per call, on the text the byte budget already bounded.
114
+ */
115
+ function highlightedLines(lines, highlight, languageForPath, path) {
116
+ if (lines.length === 0) return undefined;
117
+ if (typeof highlight !== 'function' || typeof languageForPath !== 'function') return undefined;
118
+ if (typeof path !== 'string' || path.length === 0) return undefined;
119
+ try {
120
+ const language = languageForPath(path);
121
+ if (typeof language !== 'string' || language.length === 0) return undefined;
122
+ const painted = highlight(lines.join('\n'), language);
123
+ if (!Array.isArray(painted) || painted.length !== lines.length) return undefined;
124
+ if (!painted.every((line) => typeof line === 'string')) return undefined;
125
+ return painted;
126
+ } catch {
127
+ return undefined;
128
+ }
129
+ }
130
+
131
+ /**
132
+ * The lines the pane paints, in file order: one per source line with its real
133
+ * number, and — for a truncated read — the unnumbered notice row after them. A
134
+ * binary or error preview is one message line with no number and no position.
135
+ */
136
+ function previewLines(preview, highlight, languageForPath, path) {
137
+ const value = preview && typeof preview === 'object' ? preview : { kind: 'error', message: '' };
138
+ if (value.kind === 'binary' || value.kind === 'error') {
139
+ return {
140
+ kind: value.kind,
141
+ total: 0,
142
+ truncated: false,
143
+ lines: [{ text: displayPreviewText(value.message), number: undefined, highlighted: false }],
144
+ };
145
+ }
146
+ if (value.kind !== 'text' || !Array.isArray(value.lines)) {
147
+ return {
148
+ kind: 'error',
149
+ total: 0,
150
+ truncated: false,
151
+ lines: [{ text: displayPreviewText(value.message), number: undefined, highlighted: false }],
152
+ };
153
+ }
154
+ const plain = value.lines.map(displayPreviewText);
155
+ const painted = highlightedLines(plain, highlight, languageForPath, path);
156
+ const lines = plain.map((text, index) => {
157
+ const paintedText = painted === undefined ? text : painted[index];
158
+ return { text: paintedText, number: index + 1, highlighted: paintedText !== text };
159
+ });
160
+ if (value.truncated === true) lines.push({ text: TRUNCATED_NOTICE, number: undefined, highlighted: false });
161
+ return { kind: 'text', total: plain.length, truncated: value.truncated === true, lines };
162
+ }
163
+
164
+ /** The last line that starts at or before `row`; a continuation belongs to its line. */
165
+ function lineAtRow(rowStarts, row) {
166
+ let low = 0;
167
+ let high = Math.max(0, rowStarts.length - 1);
168
+ while (low < high) {
169
+ const middle = Math.ceil((low + high) / 2);
170
+ if (rowStarts[middle] <= row) low = middle;
171
+ else high = middle - 1;
172
+ }
173
+ return low;
174
+ }
175
+
176
+ /** The file line the top painted row belongs to, walking back over the notice row. */
177
+ function topLineNumber(built, rowStarts, row) {
178
+ if (built.lines.length === 0) return undefined;
179
+ let index = lineAtRow(rowStarts, row);
180
+ while (index > 0 && built.lines[index].number === undefined) index -= 1;
181
+ return built.lines[index].number;
182
+ }
183
+
184
+ /** `top/total`, plus `+` when the reader truncated the file; undefined without line numbers. */
185
+ function positionLabel(built, rowStarts, scroll) {
186
+ if (built.kind !== 'text') return undefined;
187
+ const top = topLineNumber(built, rowStarts, scroll) ?? built.total;
188
+ return `${Math.min(built.total, top)}/${built.total}${built.truncated ? '+' : ''}`;
189
+ }
190
+
191
+ /**
192
+ * One content row's cells at `interiorWidth`: the dim gutter, one gap, the text
193
+ * and the padding that keeps the box square. A grapheme wider than the text
194
+ * column borrows the gap, and one wider than the whole interior paints its
195
+ * gutter alone rather than breaking the frame.
196
+ */
197
+ function contentCells(gutter, text, interiorWidth, metrics) {
198
+ if (interiorWidth <= 0) return [];
199
+ const rawGutterWidth = metrics.visibleWidth(gutter);
200
+ const gutterWidth = Math.min(interiorWidth, rawGutterWidth);
201
+ const shownGutter = gutterWidth === rawGutterWidth ? gutter : metrics.truncateToWidth(gutter, gutterWidth, '');
202
+ const textWidth = metrics.visibleWidth(text);
203
+ const room = Math.max(0, interiorWidth - gutterWidth - GUTTER_GAP.length);
204
+ let gap = GUTTER_GAP;
205
+ let shown = text;
206
+ if (textWidth > room) {
207
+ if (gutterWidth + textWidth <= interiorWidth) gap = '';
208
+ else shown = '';
209
+ }
210
+ const used = gutterWidth + metrics.visibleWidth(gap) + metrics.visibleWidth(shown);
211
+ const padding = ' '.repeat(Math.max(0, interiorWidth - used));
212
+ const cells = [];
213
+ if (shownGutter.length > 0) cells.push({ text: shownGutter, role: 'dim' });
214
+ const content = `${gap}${shown}${padding}`;
215
+ if (content.length > 0) cells.push({ text: content, role: 'text' });
216
+ return cells;
217
+ }
218
+
219
+ /** The box's top border with the position at its right; without a label it is all dashes. */
220
+ function topBorderCells(interiorWidth, label, metrics) {
221
+ const cells = [{ text: BOX_TOP_LEFT, role: 'border' }];
222
+ if (label === undefined) {
223
+ if (interiorWidth > 0) cells.push({ text: BOX_HORIZONTAL.repeat(interiorWidth), role: 'border' });
224
+ cells.push({ text: BOX_TOP_RIGHT, role: 'border' });
225
+ return cells;
226
+ }
227
+ const position = interiorWidth > 0 ? metrics.truncateToWidth(label, interiorWidth, '…') : '';
228
+ const positionWidth = Math.min(interiorWidth, metrics.visibleWidth(position));
229
+ const gap = Math.min(1, Math.max(0, interiorWidth - positionWidth));
230
+ const fill = Math.max(0, interiorWidth - positionWidth - gap);
231
+ if (fill > 0) cells.push({ text: BOX_HORIZONTAL.repeat(fill), role: 'border' });
232
+ const tail = `${' '.repeat(gap)}${position}`;
233
+ if (tail.length > 0) cells.push({ text: tail, role: 'text' });
234
+ cells.push({ text: BOX_TOP_RIGHT, role: 'border' });
235
+ return cells;
236
+ }
237
+
238
+ /** The box's bottom border: one border-tone run between its two corners. */
239
+ function bottomBorderCells(interiorWidth) {
240
+ const cells = [{ text: BOX_BOTTOM_LEFT, role: 'border' }];
241
+ if (interiorWidth > 0) cells.push({ text: BOX_HORIZONTAL.repeat(interiorWidth), role: 'border' });
242
+ cells.push({ text: BOX_BOTTOM_RIGHT, role: 'border' });
243
+ return cells;
244
+ }
245
+
246
+ /** One boxed content row: the interior framed by the box's two border columns. */
247
+ function boxedCells(interior) {
248
+ return [
249
+ { text: BOX_VERTICAL, role: 'border' },
250
+ ...interior,
251
+ { text: BOX_VERTICAL, role: 'border' },
252
+ ];
253
+ }
254
+
255
+ /** The unbordered position row: the label at the pane's right, or a blank row. */
256
+ function positionRowCells(width, label, metrics) {
257
+ if (width <= 0) return [];
258
+ if (label === undefined) return [{ text: ' '.repeat(width), role: 'text' }];
259
+ const shown = metrics.visibleWidth(label) <= width ? label : metrics.truncateToWidth(label, width, '…');
260
+ const padding = Math.max(0, width - metrics.visibleWidth(shown));
261
+ return [{ text: `${' '.repeat(padding)}${shown}`, role: 'text' }];
262
+ }
263
+
264
+ /**
265
+ * The preview pane's rows.
266
+ *
267
+ * @param {{kind: string, lines?: string[], message?: string, truncated?: boolean}} preview
268
+ * the object `lib/files-index.js` `readFilePreview` returns.
269
+ * @param {{width: number, height: number, scroll?: number, highlight?: Function,
270
+ * languageForPath?: Function, path?: string, metrics: object}} options
271
+ * `width`/`height` are the pane's cells and rows including the box (when it
272
+ * paints); `scroll` is the first painted wrapped row.
273
+ * @returns {{rows: Array<{cells: Array<{text: string, role: string}>}>, maxScroll: number, boxed: boolean}}
274
+ */
275
+ function previewRows(preview, options) {
276
+ const settings = options || {};
277
+ const metrics = settings.metrics;
278
+ const width = whole(settings.width);
279
+ const height = whole(settings.height);
280
+ const boxed = height >= BOX_MIN_BODY_ROWS && width >= BOX_MIN_WIDTH;
281
+ const interiorWidth = boxed ? width - BOX_COLUMNS : width;
282
+ const contentRows = boxed ? Math.max(0, height - BOX_ROWS) : Math.max(0, height - 1);
283
+ const built = previewLines(
284
+ preview,
285
+ settings.highlight,
286
+ settings.languageForPath,
287
+ settings.path
288
+ );
289
+ const gutterWidth = Math.max(1, String(built.total).length);
290
+ const textWidth = Math.max(0, interiorWidth - gutterWidth - GUTTER_GAP.length);
291
+
292
+ // Flatten the lines into painted rows once, so the window, the scroll math and
293
+ // the position all count the same rows.
294
+ const rowStarts = [];
295
+ const painted = [];
296
+ for (const line of built.lines) {
297
+ rowStarts.push(painted.length);
298
+ const rows = line.highlighted
299
+ ? wrapHighlighted(line.text, textWidth, metrics)
300
+ : wrapByCells(line.text, textWidth, metrics);
301
+ painted.push(...rows);
302
+ }
303
+ const totalRows = painted.length;
304
+ const maxScroll = Math.max(0, totalRows - contentRows);
305
+ const requested = Number.isFinite(settings.scroll) ? Math.trunc(settings.scroll) : 0;
306
+ const scroll = Math.max(0, Math.min(maxScroll, requested));
307
+ const rows = [];
308
+
309
+ if (width <= 0 || height <= 0) return { rows, maxScroll, boxed };
310
+
311
+ const label = positionLabel(built, rowStarts, scroll);
312
+ const contentCellAt = (row) => {
313
+ if (row >= totalRows) return contentCells(' '.repeat(gutterWidth), '', interiorWidth, metrics);
314
+ const lineIndex = lineAtRow(rowStarts, row);
315
+ const line = built.lines[lineIndex];
316
+ const offset = row - rowStarts[lineIndex];
317
+ const gutter = offset === 0 && line.number !== undefined
318
+ ? String(line.number).padStart(gutterWidth)
319
+ : ' '.repeat(gutterWidth);
320
+ return contentCells(gutter, painted[row] == null ? '' : painted[row], interiorWidth, metrics);
321
+ };
322
+
323
+ if (boxed) {
324
+ rows.push({ cells: topBorderCells(interiorWidth, label, metrics) });
325
+ for (let offset = 0; offset < contentRows; offset += 1) {
326
+ rows.push({ cells: boxedCells(contentCellAt(scroll + offset)) });
327
+ }
328
+ rows.push({ cells: bottomBorderCells(interiorWidth) });
329
+ } else {
330
+ rows.push({ cells: positionRowCells(width, label, metrics) });
331
+ for (let offset = 0; offset < contentRows; offset += 1) {
332
+ rows.push({ cells: contentCellAt(scroll + offset) });
333
+ }
334
+ }
335
+ return { rows, maxScroll, boxed };
336
+ }
337
+
338
+ module.exports = { previewRows };
@@ -0,0 +1,171 @@
1
+ 'use strict';
2
+ // S9: the focused scope's Git facts — the line that sits directly above the
3
+ // scope step's footer. This module is pure data: it orders the scopes the view
4
+ // paints, parses the one `rev-list --left-right --count` answer, formats the
5
+ // `±n files` cell and composes the detail line, and it reads Git only through
6
+ // the injected runner. No child process is spawned here and nothing is written.
7
+ //
8
+ // Ported from the read-only reference (`lib/file-scope-detail.ts`): the
9
+ // `main`-first ordering, the `±`/`↑`/`↓` glyphs, the subject-first field order
10
+ // and the one rule that shapes the line — a field that is zero or absent is not
11
+ // painted at all. Every Git failure degrades to an absent field, so a repository
12
+ // with no remote, no commits or a failing read paints less instead of claiming a
13
+ // zero nobody measured.
14
+
15
+ const { formatAge } = require('./files-index.js');
16
+
17
+ // A worktree is compared with the session repository's local main; the `main`
18
+ // row is compared with the remote main it tracks (S9). T7 feeds these into
19
+ // `loadScopeDetail`, so the two spellings live here instead of in the view.
20
+ const LOCAL_MAIN = 'main';
21
+ const REMOTE_MAIN = 'origin/main';
22
+
23
+ const COUNT = /^\d+$/;
24
+ const SEPARATOR = ' · ';
25
+ const CHANGED_SYMBOL = '±';
26
+ const AHEAD_SYMBOL = '↑';
27
+ const BEHIND_SYMBOL = '↓';
28
+ // S42: the age field carries its own noun. `33s` alone does not say what it
29
+ // measures; the suffix makes the field read without a legend beside it, and it
30
+ // rides the same `s`/`m`/`h`/`d` label T1's `formatAge` already produces.
31
+ const AGE_SUFFIX = 'ago';
32
+
33
+ /**
34
+ * S9: `main` keeps the first row and every other checkout follows it, most
35
+ * recently modified first; recency ties keep their input order, so the ordering
36
+ * is stable and `main` is never displaced by a newer worktree. The input array
37
+ * and its entries are left untouched.
38
+ *
39
+ * @param {Array<{kind?: string, lastModifiedMs?: number}>} scopes
40
+ * @returns {Array<object>} a new array of the same scope objects.
41
+ */
42
+ function orderScopes(scopes) {
43
+ const ranked = (Array.isArray(scopes) ? scopes : []).map((scope, index) => ({ scope, index }));
44
+ const recency = (entry) => {
45
+ const value = Number(entry.scope && entry.scope.lastModifiedMs);
46
+ return Number.isFinite(value) ? value : 0;
47
+ };
48
+ const byRecency = (left, right) => (recency(right) - recency(left)) || (left.index - right.index);
49
+ const main = ranked.filter((entry) => entry.scope && entry.scope.kind === 'main').sort(byRecency);
50
+ const rest = ranked.filter((entry) => !entry.scope || entry.scope.kind !== 'main').sort(byRecency);
51
+ return [...main, ...rest].map((entry) => entry.scope);
52
+ }
53
+
54
+ /**
55
+ * One `rev-list --left-right --count comparison...HEAD` answer. The left count
56
+ * belongs to the comparison alone and the right count to HEAD alone, so the line
57
+ * reads as `<behind> <ahead>`. Anything that is not exactly two whole counts is
58
+ * unparsable, and the caller treats it as absent.
59
+ *
60
+ * @param {string} stdout
61
+ * @returns {{ahead: number, behind: number}|undefined}
62
+ */
63
+ function parseAheadBehind(stdout) {
64
+ if (typeof stdout !== 'string') return undefined;
65
+ const fields = stdout.trim().split(/\s+/).filter((field) => field !== '');
66
+ if (fields.length !== 2) return undefined;
67
+ const [behind, ahead] = fields;
68
+ if (!COUNT.test(behind) || !COUNT.test(ahead)) return undefined;
69
+ return { ahead: Number.parseInt(ahead, 10), behind: Number.parseInt(behind, 10) };
70
+ }
71
+
72
+ /**
73
+ * The uncommitted-file cell (S9): the glyph plus the noun, singular at one. The
74
+ * noun stays because `±3` alone reads as changed lines.
75
+ *
76
+ * @param {number} files
77
+ * @returns {string}
78
+ */
79
+ function countCell(files) {
80
+ const count = Number(files);
81
+ const shown = Number.isFinite(count) ? Math.max(0, Math.trunc(count)) : 0;
82
+ return `${CHANGED_SYMBOL}${shown} ${shown === 1 ? 'file' : 'files'}`;
83
+ }
84
+
85
+ /**
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.
91
+ *
92
+ * @param {{changedFiles?: number, lastModifiedMs?: number, lastCommitSubject?: string, ahead?: number, behind?: number, comparison?: string}} detail
93
+ * @param {number} nowMs the clock read once when the step opened.
94
+ * @returns {string}
95
+ */
96
+ function scopeDetailLine(detail, nowMs) {
97
+ const model = detail !== null && typeof detail === 'object' ? detail : {};
98
+ const fields = [];
99
+ const subject = typeof model.lastCommitSubject === 'string' ? model.lastCommitSubject.trim() : '';
100
+ if (subject !== '') fields.push(subject);
101
+ const files = Number(model.changedFiles);
102
+ if (Number.isFinite(files) && files > 0) fields.push(countCell(files));
103
+ const modified = Number(model.lastModifiedMs);
104
+ // `formatAge` produces the bare label; the suffix is this line's own word, so
105
+ // the picker's file rows keep their bare age column untouched (S42).
106
+ if (Number.isFinite(modified) && modified > 0) fields.push(`${formatAge(modified, nowMs)} ${AGE_SUFFIX}`);
107
+ const comparison = typeof model.comparison === 'string' ? model.comparison.trim() : '';
108
+ const ahead = Number(model.ahead);
109
+ if (comparison !== '' && Number.isFinite(ahead) && ahead > 0) fields.push(`${AHEAD_SYMBOL}${Math.trunc(ahead)} ${comparison}`);
110
+ const behind = Number(model.behind);
111
+ if (comparison !== '' && Number.isFinite(behind) && behind > 0) fields.push(`${BEHIND_SYMBOL}${Math.trunc(behind)} ${comparison}`);
112
+ return fields.join(SEPARATOR);
113
+ }
114
+
115
+ // One bounded read through the injected runner. A non-zero status, a truncated
116
+ // or timed-out answer and a throwing runner are all a failed lookup — never a
117
+ // partial count.
118
+ async function ask(run, args, cwd) {
119
+ if (typeof run !== 'function') return undefined;
120
+ try {
121
+ const result = await run(args, { cwd });
122
+ if (!result || typeof result !== 'object') return undefined;
123
+ if (result.status !== 0) return undefined;
124
+ if (result.truncated === true || result.timedOut === true) return undefined;
125
+ return result;
126
+ } catch {
127
+ return undefined;
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Read the scope's last commit and its distance from `comparison` (S9), with two
133
+ * fixed-argv reads: `rev-list --left-right --count <comparison>...HEAD` and
134
+ * `log -1 --format=%s`. A missing ref (no remote, no local main, an unborn
135
+ * branch), a failed call and a runner that throws all leave the corresponding
136
+ * fields absent. `comparison` is always reported back, so the view knows what the
137
+ * counts would have been measured against.
138
+ *
139
+ * @param {{run?: Function, cwd?: string, comparison?: string}} options
140
+ * @returns {Promise<{comparison?: string, ahead?: number, behind?: number, lastCommitSubject?: string}>}
141
+ */
142
+ async function loadScopeDetail(options = {}) {
143
+ const opts = options !== null && typeof options === 'object' ? options : {};
144
+ const run = typeof opts.run === 'function' ? opts.run : null;
145
+ const cwd = typeof opts.cwd === 'string' ? opts.cwd : undefined;
146
+ const comparison = typeof opts.comparison === 'string' ? opts.comparison.trim() : '';
147
+ const detail = {};
148
+ if (comparison !== '') detail.comparison = comparison;
149
+ const [range, subject] = await Promise.all([
150
+ comparison === '' ? undefined : ask(run, ['rev-list', '--left-right', '--count', `${comparison}...HEAD`], cwd),
151
+ ask(run, ['log', '-1', '--format=%s'], cwd),
152
+ ]);
153
+ const distance = range === undefined ? undefined : parseAheadBehind(range.stdout);
154
+ if (distance !== undefined) {
155
+ detail.ahead = distance.ahead;
156
+ detail.behind = distance.behind;
157
+ }
158
+ const line = subject !== undefined && typeof subject.stdout === 'string' ? subject.stdout.split('\n')[0].trim() : '';
159
+ if (line !== '') detail.lastCommitSubject = line;
160
+ return detail;
161
+ }
162
+
163
+ module.exports = {
164
+ LOCAL_MAIN,
165
+ REMOTE_MAIN,
166
+ countCell,
167
+ loadScopeDetail,
168
+ orderScopes,
169
+ parseAheadBehind,
170
+ scopeDetailLine,
171
+ };