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,387 @@
1
+ 'use strict';
2
+ // The file picker's data source (files-picker S6, S13, S16): the repository
3
+ // listing Git answers, each file's working-tree state with its age, and one
4
+ // bounded preview read.
5
+ //
6
+ // Read-only by construction (S16): every Git read is ONE fixed argv array —
7
+ // never a shell string — handed to the injected async runner
8
+ // `run(args, opts) -> { status, stdout, stderr }`, the exact shape
9
+ // lib/worktree-git.js `runArgvAsync` resolves, with a bounded timeout on every
10
+ // call. Nothing here stages, writes, opens a socket or prunes a worktree, and
11
+ // `git status` runs with `--no-optional-locks` so even the stat-cache refresh
12
+ // it would normally write back is skipped. The preview half spawns nothing at
13
+ // all: it is one `open`/`read` of at most FILE_PREVIEW_LIMITS.maxBytes.
14
+ //
15
+ // The list is Git's, not a directory walk (S13): `git ls-files --cached
16
+ // --others --exclude-standard` is exactly the tracked files plus the untracked
17
+ // files Git does not ignore, so `.gitignore` is respected without this module
18
+ // ever parsing it. Outside a repository the listing fails and the failure is a
19
+ // sentence a panel can paint, never an empty success.
20
+ //
21
+ // Change state (S6) comes from one `git status --porcelain=v1 -z
22
+ // --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
25
+ // repository root Git reports — `git rev-parse --show-toplevel`, never
26
+ // `process.cwd()`, because the picker browses another checkout than the one the
27
+ // process happens to sit in. An unreadable root or file leaves the timestamp
28
+ // out rather than failing the whole listing.
29
+ //
30
+ // The order is the panel's contract: changed files first, newest change first,
31
+ // then the untouched ones by path. Every comparison is by code unit, never
32
+ // `localeCompare`, so the list is identical on every host and every run.
33
+
34
+ const fs = require('node:fs');
35
+ const path = require('node:path');
36
+
37
+ // One bounded Git process per read; a picker that waits longer than this has
38
+ // nothing to paint anyway.
39
+ const GIT_TIMEOUT_MS = 15_000;
40
+
41
+ // `-z` avoids Git's quoting of paths holding whitespace or newlines; the cached
42
+ // and others sources together are the tracked files plus the untracked ones Git
43
+ // does not ignore — the picker's whole list, `.gitignore` respected by Git.
44
+ const LIST_ARGS = Object.freeze(['ls-files', '-z', '--cached', '--others', '--exclude-standard']);
45
+
46
+ // One call decides every state: `-z` for the same reason as above,
47
+ // `--untracked-files=all` so an untracked file is listed instead of its
48
+ // directory, and `--no-optional-locks` so the refresh Git would write back into
49
+ // `.git/index` is skipped (S16).
50
+ const STATUS_ARGS = Object.freeze([
51
+ '--no-optional-locks',
52
+ 'status',
53
+ '--porcelain=v1',
54
+ '-z',
55
+ '--untracked-files=all',
56
+ ]);
57
+
58
+ // The root the mtimes are read under. Resolved from Git rather than the process
59
+ // cwd because the picker can browse another checkout.
60
+ const ROOT_ARGS = Object.freeze(['rev-parse', '--show-toplevel']);
61
+
62
+ const FILES_ERROR = 'Cannot list repository files';
63
+ const CHANGES_ERROR = 'Cannot read repository changes';
64
+
65
+ const MINUTE = 60_000;
66
+ const HOUR = 3_600_000;
67
+ const DAY = 86_400_000;
68
+
69
+ const ELLIPSIS = '\u2026';
70
+
71
+ function errorMessage(error) {
72
+ return error instanceof Error ? error.message : String(error);
73
+ }
74
+
75
+ // Byte order, not locale order: the list is rebuilt on every open and must come
76
+ // out the same everywhere.
77
+ function byCodePoint(left, right) {
78
+ return left < right ? -1 : left > right ? 1 : 0;
79
+ }
80
+
81
+ // One sentence a panel can paint, with exactly one full stop.
82
+ function sentence(text) {
83
+ const trimmed = String(text === undefined || text === null ? '' : text).trim();
84
+ if (trimmed.length === 0) return '';
85
+ return /[.!?]$/.test(trimmed) ? trimmed : `${trimmed}.`;
86
+ }
87
+
88
+ function notRepositoryMessage(cwd) {
89
+ const where = typeof cwd === 'string' && cwd.trim().length > 0 ? cwd.trim() : 'this directory';
90
+ return sentence(`Not a Git repository: ${where}`);
91
+ }
92
+
93
+ // The first line Git said, then a spawn error, then the exit status: the same
94
+ // priority as lib/worktree-git.js `gitFailureReason`, so the sentence names the
95
+ // real cause instead of "exit 128".
96
+ function failureReason(result) {
97
+ const stderr = result && typeof result.stderr === 'string' ? result.stderr.trim() : '';
98
+ if (stderr.length > 0) return stderr.split('\n')[0];
99
+ if (result && result.error !== undefined && result.error !== null && String(result.error).length > 0) {
100
+ return String(result.error);
101
+ }
102
+ return `Git exited with status ${result && result.status !== undefined ? result.status : 'unknown'}`;
103
+ }
104
+
105
+ function isNotRepository(detail) {
106
+ return /not a git repository/i.test(String(detail));
107
+ }
108
+
109
+ // One fixed argv through the injected runner. Never throws, and never resolves
110
+ // a failure as a success: a runner that rejects, one that resolves a non-zero
111
+ // status, and one that answers nothing all come back as `{ ok: false }`, so the
112
+ // caller decides which sentence to paint.
113
+ async function runGit(run, args, cwd) {
114
+ let result;
115
+ try {
116
+ result = await run([...args], { cwd, timeoutMs: GIT_TIMEOUT_MS });
117
+ } catch (error) {
118
+ return { ok: false, detail: errorMessage(error), notRepository: false };
119
+ }
120
+ if (result === null || typeof result !== 'object') {
121
+ return { ok: false, detail: 'the Git runner returned nothing usable', notRepository: false };
122
+ }
123
+ if (result.truncated === true) {
124
+ return { ok: false, detail: 'the output was truncated', notRepository: false };
125
+ }
126
+ if (result.status !== 0) {
127
+ const detail = failureReason(result);
128
+ return { ok: false, detail, notRepository: isNotRepository(detail) };
129
+ }
130
+ return { ok: true, stdout: typeof result.stdout === 'string' ? result.stdout : '' };
131
+ }
132
+
133
+ function listingFailure(failure, cwd) {
134
+ return {
135
+ ok: false,
136
+ message: failure.notRepository ? notRepositoryMessage(cwd) : sentence(`${FILES_ERROR}: ${failure.detail}`),
137
+ };
138
+ }
139
+
140
+ function changesFailure(failure, cwd) {
141
+ return {
142
+ ok: false,
143
+ message: failure.notRepository ? notRepositoryMessage(cwd) : sentence(`${CHANGES_ERROR}: ${failure.detail}`),
144
+ };
145
+ }
146
+
147
+ /** Repository-relative POSIX paths; a failed listing is a failure, never an empty success. */
148
+ async function listRepositoryFiles(input = {}) {
149
+ const run = input && input.run;
150
+ const cwd = input && input.cwd;
151
+ if (typeof run !== 'function') {
152
+ return { ok: false, message: sentence(`${FILES_ERROR}: no Git runner was supplied`) };
153
+ }
154
+ const listed = await runGit(run, LIST_ARGS, cwd);
155
+ if (listed.ok !== true) {
156
+ return listingFailure(listed, cwd);
157
+ }
158
+ const paths = new Set();
159
+ for (const entry of listed.stdout.split('\0')) if (entry.length > 0) paths.add(entry);
160
+ return { ok: true, files: [...paths].sort(byCodePoint) };
161
+ }
162
+
163
+ // `XY <path>` records; a rename or copy puts its original path in the next
164
+ // field, which is not a record of its own.
165
+ function parseStatus(stdout) {
166
+ const states = new Map();
167
+ const fields = stdout.split('\0');
168
+ for (let index = 0; index < fields.length; index += 1) {
169
+ const record = fields[index];
170
+ if (typeof record !== 'string' || record.length < 4) continue;
171
+ const code = record.slice(0, 2);
172
+ const filePath = record.slice(3);
173
+ if (filePath.length > 0) states.set(filePath, code === '??' ? 'new' : 'updated');
174
+ if (code[0] === 'R' || code[0] === 'C') index += 1;
175
+ }
176
+ return states;
177
+ }
178
+
179
+ async function repositoryRoot(run, cwd) {
180
+ const resolved = await runGit(run, ROOT_ARGS, cwd);
181
+ if (resolved.ok !== true) return undefined;
182
+ const root = resolved.stdout.trim();
183
+ return root.length > 0 ? root : undefined;
184
+ }
185
+
186
+ // An mtime feeds the age label, not the list: an unreadable file or root leaves
187
+ // mtimeMs undefined rather than failing the whole listing.
188
+ function modificationTime(root, filePath) {
189
+ if (root === undefined) return undefined;
190
+ try {
191
+ const stats = fs.statSync(path.join(root, filePath));
192
+ return typeof stats.mtimeMs === 'number' && Number.isFinite(stats.mtimeMs) ? stats.mtimeMs : undefined;
193
+ } catch {
194
+ return undefined;
195
+ }
196
+ }
197
+
198
+ // Newest change first; entries without a timestamp (a file that is not on disk,
199
+ // an unreadable root) follow the timed ones, and path breaks every tie so the
200
+ // order is stable.
201
+ function byRecency(left, right) {
202
+ if (left.mtimeMs !== undefined && right.mtimeMs !== undefined && left.mtimeMs !== right.mtimeMs) {
203
+ return right.mtimeMs - left.mtimeMs;
204
+ }
205
+ if (left.mtimeMs !== undefined && right.mtimeMs === undefined) return -1;
206
+ if (left.mtimeMs === undefined && right.mtimeMs !== undefined) return 1;
207
+ return byCodePoint(left.path, right.path);
208
+ }
209
+
210
+ // The age is fixed when the panel opens (S6): the caller passes `now`, and this
211
+ // module never reads the clock on its own once it has one.
212
+ function clockMs(now) {
213
+ if (typeof now === 'number' && Number.isFinite(now)) return now;
214
+ if (now instanceof Date && Number.isFinite(now.getTime())) return now.getTime();
215
+ return Date.now();
216
+ }
217
+
218
+ /**
219
+ * The picker's rows: the same file set as `listRepositoryFiles`, changed files
220
+ * first and newest first, then untouched files by path. Each changed row carries
221
+ * its state, its mtime and the age label computed from the injected `now`.
222
+ */
223
+ async function listRepositoryEntries(input = {}) {
224
+ const run = input && input.run;
225
+ const cwd = input && input.cwd;
226
+ const listing = await listRepositoryFiles({ run, cwd });
227
+ if (listing.ok !== true) return { ok: false, message: listing.message };
228
+ const status = await runGit(run, STATUS_ARGS, cwd);
229
+ if (status.ok !== true) {
230
+ return changesFailure(status, cwd);
231
+ }
232
+ const states = parseStatus(status.stdout);
233
+ const changedPaths = listing.files.filter((filePath) => states.has(filePath));
234
+ const root = changedPaths.length > 0 ? await repositoryRoot(run, cwd) : undefined;
235
+ const nowMs = clockMs(input && input.now);
236
+ const changed = changedPaths.map((filePath) => {
237
+ const entry = { path: filePath, state: states.get(filePath) };
238
+ const mtimeMs = modificationTime(root, filePath);
239
+ if (mtimeMs !== undefined) {
240
+ entry.mtimeMs = mtimeMs;
241
+ entry.age = formatAge(mtimeMs, nowMs);
242
+ }
243
+ return entry;
244
+ });
245
+ changed.sort(byRecency);
246
+ const clean = listing.files
247
+ .filter((filePath) => !states.has(filePath))
248
+ .sort(byCodePoint)
249
+ .map((filePath) => ({ path: filePath, state: 'clean' }));
250
+ return { ok: true, entries: [...changed, ...clean] };
251
+ }
252
+
253
+ /** A coarse label for one elapsed age; the caller computes it once at open (S6). */
254
+ function formatAge(mtimeMs, nowMs) {
255
+ const elapsed = Number(nowMs) - Number(mtimeMs);
256
+ if (!Number.isFinite(elapsed)) return '0s';
257
+ if (elapsed < MINUTE) return `${Math.max(0, Math.floor(elapsed / 1000))}s`;
258
+ if (elapsed < HOUR) return `${Math.floor(elapsed / MINUTE)}m`;
259
+ if (elapsed < DAY) return `${Math.floor(elapsed / HOUR)}h`;
260
+ return `${Math.floor(elapsed / DAY)}d`;
261
+ }
262
+
263
+ // A preview is the first bytes of a file, never the whole file: the caps keep
264
+ // one minified line, one huge binary, or one enormous source file from reaching
265
+ // the renderer. maxLineWidth counts characters, not terminal cells — the pane
266
+ // wraps, it never measures here.
267
+ const FILE_PREVIEW_LIMITS = Object.freeze({ maxBytes: 64 * 1024, maxLines: 200, maxLineWidth: 400 });
268
+
269
+ const FILE_PREVIEW_BINARY_NOTICE = 'Binary file \u2014 preview not available.';
270
+
271
+ // An override can only LOWER a bound: the limits are the guarantee that no file
272
+ // stalls the paint, so a caller that asks for more gets the default.
273
+ function bound(requested, fallback) {
274
+ const value = Number(requested);
275
+ if (!Number.isFinite(value) || value < 1) return fallback;
276
+ return Math.min(Math.floor(value), fallback);
277
+ }
278
+
279
+ function previewLimits(opts) {
280
+ const source = opts !== null && typeof opts === 'object' ? opts : {};
281
+ return {
282
+ maxBytes: bound(source.maxBytes, FILE_PREVIEW_LIMITS.maxBytes),
283
+ maxLines: bound(source.maxLines, FILE_PREVIEW_LIMITS.maxLines),
284
+ maxLineWidth: bound(source.maxLineWidth, FILE_PREVIEW_LIMITS.maxLineWidth),
285
+ };
286
+ }
287
+
288
+ // One whole read of at most `buffer.length` bytes, so a short read or a slow
289
+ // pipe cannot cut the preview early.
290
+ function readInto(fd, buffer) {
291
+ let length = 0;
292
+ while (length < buffer.length) {
293
+ const read = fs.readSync(fd, buffer, length, buffer.length - length, length);
294
+ if (read === 0) break;
295
+ length += read;
296
+ }
297
+ return length;
298
+ }
299
+
300
+ function unreadable(relativePath, error) {
301
+ const code = error && typeof error === 'object' ? error.code : undefined;
302
+ const named = typeof relativePath === 'string' && relativePath.length > 0 ? relativePath : 'the file';
303
+ const reason = typeof code === 'string' ? ` (${code})` : error && typeof error.message === 'string' ? `: ${error.message}` : '';
304
+ return { kind: 'error', message: sentence(`Cannot read ${named}${reason}`) };
305
+ }
306
+
307
+ // A preview path is repository-relative by contract; one that climbs out of the
308
+ // root is refused instead of read, so a listing can never point the preview at
309
+ // an unrelated file.
310
+ function outsideRoot(relativePath) {
311
+ if (path.isAbsolute(relativePath)) return true;
312
+ const normalized = path.normalize(relativePath);
313
+ return normalized === '..' || normalized.startsWith(`..${path.sep}`) || normalized.split(/[\\/]/).includes('..');
314
+ }
315
+
316
+ function readPreview(root, relativePath, opts) {
317
+ if (typeof root !== 'string' || root.trim().length === 0) {
318
+ return { kind: 'error', message: sentence('Cannot read the file: no checkout path was given') };
319
+ }
320
+ if (typeof relativePath !== 'string' || relativePath.length === 0) {
321
+ return { kind: 'error', message: sentence('Cannot read the file: no path was given') };
322
+ }
323
+ if (outsideRoot(relativePath)) {
324
+ return { kind: 'error', message: sentence(`Cannot read ${relativePath}: outside the checkout`) };
325
+ }
326
+ const limits = previewLimits(opts);
327
+ const full = path.join(root, relativePath);
328
+ let fd;
329
+ try {
330
+ fd = fs.openSync(full, 'r');
331
+ } catch (error) {
332
+ return unreadable(relativePath, error);
333
+ }
334
+ let head;
335
+ let overBudget;
336
+ try {
337
+ const buffer = Buffer.allocUnsafe(limits.maxBytes);
338
+ const length = readInto(fd, buffer);
339
+ // A full budget is a truncation only when a further byte exists: a file of
340
+ // exactly maxBytes previews whole.
341
+ overBudget = length === buffer.length && fs.readSync(fd, Buffer.allocUnsafe(1), 0, 1, length) > 0;
342
+ head = buffer.subarray(0, length);
343
+ } catch (error) {
344
+ return unreadable(relativePath, error);
345
+ } finally {
346
+ try {
347
+ fs.closeSync(fd);
348
+ } catch {
349
+ // A preview that already read its bytes is not failed by a close error.
350
+ }
351
+ }
352
+ if (head.includes(0)) return { kind: 'binary', message: FILE_PREVIEW_BINARY_NOTICE };
353
+ // A lone CR counts as a line break too, so an old Mac file reads as lines.
354
+ const split = head.toString('utf8').replace(/\r\n?/g, '\n').split('\n');
355
+ if (split[split.length - 1] === '') split.pop();
356
+ const lineCapped = split.length > limits.maxLines;
357
+ const candidates = lineCapped ? split.slice(0, limits.maxLines) : split;
358
+ let widthCapped = false;
359
+ const lines = candidates.map((line) => {
360
+ if (line.length <= limits.maxLineWidth) return line;
361
+ widthCapped = true;
362
+ return `${line.slice(0, limits.maxLineWidth - 1)}${ELLIPSIS}`;
363
+ });
364
+ return { kind: 'text', lines, truncated: overBudget || lineCapped || widthCapped };
365
+ }
366
+
367
+ /**
368
+ * One bounded preview of `root/relativePath`: text lines with an explicit
369
+ * truncation flag, a notice for a binary file, or a sentence naming why the file
370
+ * could not be read. Filesystem only, and it never throws.
371
+ */
372
+ function readFilePreview(root, relativePath, opts) {
373
+ try {
374
+ return readPreview(root, relativePath, opts);
375
+ } catch (error) {
376
+ return unreadable(relativePath, error);
377
+ }
378
+ }
379
+
380
+ module.exports = {
381
+ listRepositoryEntries,
382
+ listRepositoryFiles,
383
+ readFilePreview,
384
+ formatAge,
385
+ FILE_PREVIEW_LIMITS,
386
+ FILE_PREVIEW_BINARY_NOTICE,
387
+ };
@@ -0,0 +1,81 @@
1
+ 'use strict';
2
+ // The file picker's insertion form (S8): the picker emits paths relative to the
3
+ // scope root it browsed, and this turns that payload into the exact text pasted
4
+ // into the prompt. Pure, so both forms are testable without a Pi session or a
5
+ // repository: a file of the session's own checkout travels as `@` plus its path
6
+ // from the session cwd, and any other file — another worktree, a path outside
7
+ // the cwd — travels as its real absolute path, because Pi resolves `@` against
8
+ // the session cwd and does not expand `~`.
9
+
10
+ const { posix } = require('node:path');
11
+
12
+ // The repository's own path style is forward slashes, and Pi resolves the same
13
+ // form on every platform; a Windows path accepts them too.
14
+ function forwardSlashes(path) {
15
+ return String(path).replace(/\\/g, '/');
16
+ }
17
+
18
+ function normalizedPath(path) {
19
+ const slashed = forwardSlashes(path).trim();
20
+ if (slashed.length === 0) return '';
21
+ const normalized = posix.normalize(slashed);
22
+ return normalized === '.' ? '' : normalized;
23
+ }
24
+
25
+ function relativeToScope(relative) {
26
+ return normalizedPath(relative).replace(/^(\.\/)+/, '');
27
+ }
28
+
29
+ function scopeRoot(root) {
30
+ const normalized = normalizedPath(root);
31
+ return normalized.endsWith('/') ? normalized.slice(0, -1) : normalized;
32
+ }
33
+
34
+ // The file's real absolute path: the scope root joined with its path in it.
35
+ function absolutePath(root, relative) {
36
+ const base = scopeRoot(root);
37
+ return posix.normalize(base.length === 0 ? `/${relative}` : `${base}/${relative}`);
38
+ }
39
+
40
+ // The path of `absolute` below `cwd`, or undefined when the file is not under it.
41
+ function pathBelow(cwd, absolute) {
42
+ const base = scopeRoot(cwd);
43
+ if (base.length === 0) return undefined;
44
+ const prefix = base.endsWith('/') ? base : `${base}/`;
45
+ return absolute.startsWith(prefix) ? absolute.slice(prefix.length) : undefined;
46
+ }
47
+
48
+ // True for a path already absolute, so it is never prefixed a second time.
49
+ function isAbsolutePath(path) {
50
+ return path.startsWith('/') || /^[A-Za-z]:\//.test(path);
51
+ }
52
+
53
+ // One file's reference. A file below the session cwd is `@` plus its path from
54
+ // that cwd, which is what Pi resolves (`@AGENTS.md`), never the path from the
55
+ // repository root: a session started in a subdirectory would name another file.
56
+ // Any other file -- outside the cwd, from another checkout, or a name that would
57
+ // read as a home reference -- is its real absolute path.
58
+ function fileReference(scope, relative) {
59
+ const path = relativeToScope(relative);
60
+ if (path.length === 0) return '';
61
+ if (isAbsolutePath(path)) return path;
62
+ const scopeInfo = scope || {};
63
+ const absolute = absolutePath(scopeInfo.root || '', path);
64
+ if (scopeInfo.kind !== 'main') return absolute;
65
+ const fromCwd = pathBelow(scopeInfo.cwd || '', absolute);
66
+ return fromCwd === undefined || fromCwd.startsWith('~') ? absolute : `@${fromCwd}`;
67
+ }
68
+
69
+ // The exact text Enter pastes for the chosen files: one reference per file,
70
+ // space-separated, in the order given, with no leading, trailing or doubled
71
+ // separator. A repeated file is named once.
72
+ function formatFileInsertion(relativePaths, scope) {
73
+ const references = [];
74
+ for (const relative of Array.isArray(relativePaths) ? relativePaths : []) {
75
+ const reference = fileReference(scope, relative);
76
+ if (reference.length > 0 && !references.includes(reference)) references.push(reference);
77
+ }
78
+ return references.join(' ');
79
+ }
80
+
81
+ module.exports = { fileReference, formatFileInsertion };