pi-odd-worktree 2.0.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 -311
  2. package/extensions/odd-worktree-tools.ts +4149 -2447
  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 -711
  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 +2569 -308
  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 +477 -93
  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,628 @@
1
+ 'use strict';
2
+ // S10: what a CodeGraph card says, decided from the call and the output alone.
3
+ //
4
+ // Ported from the user's own `lib/codegraph-card-preview.ts` of PR #74
5
+ // (`jonasotoaguilar/gentle-shell`, branch `cards-bash-v2`, copied read-only under
6
+ // `odd/reference/pr74-card/`): the identity (the tool name, its mark and the theme
7
+ // role its title wears), the heading detail, the count `query` and `explore`
8
+ // state in their own output, the init sentence, the bounded preview and the
9
+ // `bash` command recognition.
10
+ //
11
+ // One shape is this package's addition (S10): `codegraph sync` is a different
12
+ // program run from the same binary, and its own output says what it did
13
+ // (`Synced N changed files`, `No files changed`, `Already up to date`). Its card
14
+ // states that sentence, so an init is never read as a sync or the other way
15
+ // round, and neither is invented when the output does not carry it.
16
+ //
17
+ // The rules the whole module obeys:
18
+ // * the card states only what CodeGraph printed. No row adds a status, a count
19
+ // or an outcome the output lacks; an unreadable shape keeps its own rows.
20
+ // * no specialized fallback: when nothing specific is readable the last rows it
21
+ // printed are the preview, whatever the operation was.
22
+ // * a failure always keeps the reason it printed, at any level.
23
+ // * pure: no Pi, no theme, no colour, no filesystem, no process and no clock.
24
+ // The rows are PLAIN strings here; lib/codegraph-card.js paints them.
25
+ //
26
+ // The command recognition is the reference classifier's own plumbing — its
27
+ // quote-aware segmenter, its segment stripping and no-op table, its shell word
28
+ // reader and its package-runner words — and it is self-contained: gentle-shell's
29
+ // `lib/odd-phase-inference.ts` is not a dependency of this package. What it decides
30
+ // changed for this card: the deciding fact is that `codegraph` is the command word
31
+ // of some segment of the command, so any subcommand counts (`codegraph --help`,
32
+ // `status`, `callers X`, `node Y`, several of them in one pipeline or chain) and a
33
+ // command that merely MENTIONS the program is none of this card's. The command
34
+ // itself is the card's detail, so no operation has to be readable for it to draw.
35
+
36
+ /** The program both surfaces draw, and the mark and theme role its card wears. */
37
+ const CODEGRAPH_TOOL = 'codegraph';
38
+ const CODEGRAPH_MCP_TOOL = 'codegraph_explore';
39
+ // The database glyph, and the theme's own `mdCode` slot: both are the shell's
40
+ // semantic vocabulary, never a fixed palette, so a light theme, a neon theme or a
41
+ // design pack repaints them along with everything else.
42
+ const CODEGRAPH_MARK = '\u{F01BC}';
43
+ const CODEGRAPH_TITLE_ROLE = 'mdCode';
44
+
45
+ // The collapsed preview budget, in rows the program printed.
46
+ const PREVIEW_ROWS = 3;
47
+ // The init CLI paints a progress box; its separator rows carry no facts.
48
+ const CHROME = /^[\s│┌└─]*$/;
49
+ // A status row's mark is decoration; the row's own words are the fact.
50
+ const STATUS_MARK = /^[◆◇●▲✗✓ℹ]\s+/;
51
+ // The init log trails into telemetry and upgrade notices after its summary, so the
52
+ // collapsed rows name the index it built rather than the last lines it wrote.
53
+ const INIT_FACT = /\b(Indexed \d+ files?|\d+ nodes?, \d+ edges?|Initialized in)\b/;
54
+ // This build's init ends with one sentence about the workspace index: it built a new
55
+ // one, or found the one already there. Only those sentences state that fact.
56
+ const INIT_OUTCOMES = [
57
+ [/^Initialized in .+$/, 'initialized'],
58
+ [/^Already initialized in .+$/, 'already initialized'],
59
+ ];
60
+ // This build's sync ends with one of these sentences, and each states its own
61
+ // outcome. A row is read only when it matches one of them, so an init log or an
62
+ // unreadable sync log keeps the rows it printed instead of borrowing one.
63
+ const SYNC_OUTCOMES = [/^Synced [\d,]+ changed files?$/, /^No files changed$/, /^Already up to date$/];
64
+ // The last lines of an output, and the blank line the terminal sequence leaves.
65
+ const TRAILING_BLANK = /(?:\n[ \t]*)+$/;
66
+
67
+ /** The CodeGraph call a card heads: the operation it ran, and the query it named. */
68
+ // {
69
+ // operation: string,
70
+ // query?: string,
71
+ // }
72
+
73
+ function outputLines(text) {
74
+ const normalized = text.replace(/\r\n/g, '\n').replace(/\n$/, '');
75
+ return normalized.length > 0 ? normalized.split('\n') : [];
76
+ }
77
+
78
+ /** A row's fact: the row's own words, without the status mark the CLI decorates it with. */
79
+ function factRow(line) {
80
+ return line.trim().replace(STATUS_MARK, '');
81
+ }
82
+
83
+ /** The lower-case first letter of a sentence the program printed, so the card's row reads as a statement. */
84
+ function sentence(row) {
85
+ return row.length === 0 ? row : `${row[0].toLowerCase()}${row.slice(1)}`;
86
+ }
87
+
88
+ // ---- what a call is ----
89
+
90
+ /**
91
+ * The last segment of a path, without its separators or a trailing slash. Used for the
92
+ * MCP card's explored checkout, never as a way to resolve a path: this module reads
93
+ * no filesystem and no cwd.
94
+ */
95
+ function lastPathSegment(value) {
96
+ if (typeof value !== 'string') return undefined;
97
+ const trimmed = value.trim().replace(/[\\/]+$/, '');
98
+ if (trimmed.length === 0) return undefined;
99
+ const segments = trimmed.split(/[\\/]+/);
100
+ const segment = segments[segments.length - 1];
101
+ return segment !== undefined && segment.length > 0 ? segment : undefined;
102
+ }
103
+
104
+ /**
105
+ * The path with one separator shape, no trailing slash, and every `.`/`..`
106
+ * segment resolved LEXICALLY (S6). Pure string work: nothing here asks the
107
+ * filesystem what a path means, and a path that does not exist resolves exactly
108
+ * like one that does.
109
+ */
110
+ function normalizePath(value) {
111
+ const text = value.trim().replace(/[\\/]+/g, '/');
112
+ const absolute = text.startsWith('/');
113
+ const parts = [];
114
+ for (const part of text.split('/')) {
115
+ if (part === '' || part === '.') continue;
116
+ if (part === '..') {
117
+ // A `..` above a relative path's start is kept: the lexical answer of
118
+ // `../repo` depends on where it is read from, and the caller joins it to
119
+ // the cwd first. An absolute path's root has nothing above it.
120
+ if (parts.length > 0 && parts[parts.length - 1] !== '..') parts.pop();
121
+ else if (!absolute) parts.push('..');
122
+ continue;
123
+ }
124
+ parts.push(part);
125
+ }
126
+ const joined = parts.join('/');
127
+ if (absolute) return joined.length > 0 ? `/${joined}` : '/';
128
+ return joined;
129
+ }
130
+
131
+ /** Whether a path is absolute in either separator shape. */
132
+ function isAbsolutePath(value) {
133
+ return /^[\\/]/.test(value) || /^[A-Za-z]:[\\/]/.test(value);
134
+ }
135
+
136
+ /**
137
+ * The checkout an MCP `projectPath` names, as the one segment its heading shows, or
138
+ * undefined when there is nothing to name: an absent or empty argument, or the
139
+ * session's own checkout. A relative argument is read against the session's own
140
+ * checkout — exactly like the shell would — and `.`/`..` are resolved lexically
141
+ * before the comparison (S6), so `/work/repo/..`, `/work/repo/.` and `../repo`
142
+ * from `/work/repo` are all that same checkout and add no segment. A bare name
143
+ * (`gentle-shell`) compares equal to the same name as the cwd. `cwd` undefined
144
+ * means the seam could not answer, and then the caller's explicit argument is
145
+ * shown rather than silently dropped.
146
+ */
147
+ function projectPathSegment(projectPath, cwd) {
148
+ const last = lastPathSegment(projectPath);
149
+ if (last === undefined) return undefined;
150
+ if (typeof cwd !== 'string' || cwd.trim().length === 0) return last;
151
+ const raw = projectPath.trim().replace(/[\\/]+/g, '/').replace(/\/+$/, '');
152
+ const base = normalizePath(cwd);
153
+ // A bare (relative) name is the checkout whose own segment carries it.
154
+ const own = base.split('/').pop();
155
+ if (!raw.includes('/') && raw === own) return undefined;
156
+ const joined = base.length > 0 ? `${base}/${raw}` : raw;
157
+ const target = isAbsolutePath(raw) ? normalizePath(raw) : normalizePath(joined);
158
+ if (target.length === 0) return undefined;
159
+ if (target === base) return undefined;
160
+ // The segment is the RESOLVED checkout's own last segment: `/work/repo/..`
161
+ // names `/work`, so it reads ` · work`, never the literal `..`.
162
+ return target.split('/').pop() || last;
163
+ }
164
+
165
+ // Stream merges and discarded output; neither writes a file.
166
+ const HARMLESS_REDIRECTS = /\s*(\d?>&\d|&?\d?>\s*\/dev\/null)/g;
167
+ // Shell keywords that prefix the command they introduce (`do grep x`).
168
+ const LEADING_KEYWORDS = /^(do|then|else|elif|if|while|until|time|!|\{|\()\s+/;
169
+
170
+ // Segments that neither inspect nor change anything worth naming: shell control
171
+ // words, no-op builtins, and bare variable assignments (their command
172
+ // substitutions are classified as commands of their own).
173
+ const NEUTRAL_COMMANDS = [
174
+ /^(cd|pushd|popd|echo|printf|sleep|true|false|export|set)\b/,
175
+ /^(done|fi|esac|\}|\))$/,
176
+ /^for\s+\w+(\s+in\b.*)?$/,
177
+ // Each assignment must end at whitespace or the end: an optional separator would
178
+ // let `a=a=a=…` split anywhere and backtrack exponentially.
179
+ /^([A-Za-z_][A-Za-z0-9_]*=("[^"]*"|'[^']*'|[^\s"'])*(\s+|$))+$/,
180
+ ];
181
+
182
+ // Package runners that run the program they name, and the words their own syntax
183
+ // puts between them and it: `npx codegraph status` runs it directly, while pnpm,
184
+ // npm, yarn and bun need their execution subcommand (`pnpm exec codegraph status`).
185
+ // `npm run codegraph` runs a script of that name, so `run` is deliberately absent:
186
+ // only an explicit execution of the program counts. Values are the number of
187
+ // launcher words (including the subcommand) to skip before the program.
188
+ const PROGRAM_RUNNERS = {
189
+ npx: 1,
190
+ bunx: 1,
191
+ pnpx: 1,
192
+ pnpm: 2,
193
+ npm: 2,
194
+ yarn: 2,
195
+ bun: 2,
196
+ };
197
+ const RUN_SUBCOMMANDS = new Set(['exec', 'dlx']);
198
+ // A launcher that also runs the program it names directly: `yarn codegraph status`
199
+ // runs the binary, while `yarn exec codegraph status` spells the execution out. Both
200
+ // are the program; `yarn run codegraph` stays a script of that name.
201
+ const DIRECT_RUNNERS = new Set(['yarn']);
202
+
203
+ /**
204
+ * Splits a segment into the words the program receives, dropping the quoting
205
+ * characters the shell would drop. A quoted `--help` is text handed to the
206
+ * program, and a quoted `-m` is still an option, so both the text and whether the
207
+ * word was quoted are kept.
208
+ */
209
+ function shellWordTokens(segment) {
210
+ const words = [];
211
+ let text = '';
212
+ let quoted = false;
213
+ let started = false;
214
+ const push = () => {
215
+ if (started) words.push({ text, quoted });
216
+ text = '';
217
+ quoted = false;
218
+ started = false;
219
+ };
220
+ for (let i = 0; i < segment.length; i += 1) {
221
+ const char = segment[i];
222
+ if (char === '\\') {
223
+ // `\X` is the literal X and `\<newline>` is a line continuation, so an
224
+ // escaped space never ends a word: `foo\ --help` is one argument.
225
+ const next = segment[i + 1];
226
+ if (next === undefined) {
227
+ text += char;
228
+ started = true;
229
+ continue;
230
+ }
231
+ i += 1;
232
+ if (next !== '\n') text += next;
233
+ started = true;
234
+ continue;
235
+ }
236
+ if (char === "'") {
237
+ // Nothing is escaped inside single quotes.
238
+ const end = segment.indexOf("'", i + 1);
239
+ text += segment.slice(i + 1, end < 0 ? segment.length : end);
240
+ quoted = true;
241
+ started = true;
242
+ i = end < 0 ? segment.length : end;
243
+ continue;
244
+ }
245
+ if (char === '"') {
246
+ // A double-quoted span is one word whatever spaces it holds, and only `\X`
247
+ // and a continuation escape; the quotes the shell would drop are dropped, so
248
+ // a `--help` inside it stays text.
249
+ let inner = '';
250
+ let end = i + 1;
251
+ while (end < segment.length && segment[end] !== '"') {
252
+ const innerChar = segment[end];
253
+ if (innerChar !== '\\') {
254
+ inner += innerChar;
255
+ end += 1;
256
+ continue;
257
+ }
258
+ const next = segment[end + 1];
259
+ if (next === undefined) {
260
+ inner += innerChar;
261
+ end += 1;
262
+ continue;
263
+ }
264
+ end += 2;
265
+ if (next !== '\n') inner += next;
266
+ }
267
+ text += inner;
268
+ quoted = true;
269
+ started = true;
270
+ i = end;
271
+ continue;
272
+ }
273
+ if (/\s/.test(char)) {
274
+ push();
275
+ continue;
276
+ }
277
+ text += char;
278
+ started = true;
279
+ }
280
+ push();
281
+ return words;
282
+ }
283
+
284
+ /** The words a simple command passes, with each quoted span folded into the word that carries it. */
285
+ function shellWords(segment) {
286
+ return shellWordTokens(segment).map((word) => word.text);
287
+ }
288
+
289
+ /**
290
+ * The segment's text with every quoted span blanked, except a span that is a
291
+ * flag-shaped word of its own: `black "--check" .` passes that flag, while
292
+ * `prettier 'a --write b.ts'` names one file whose text only looks like one.
293
+ */
294
+ function unquotedSegment(segment) {
295
+ return segment.replace(/"[^"]*"|'[^']*'/g, (quoted) => (/^-\S+$/.test(quoted.slice(1, -1)) ? quoted.slice(1, -1) : ' '));
296
+ }
297
+
298
+ // Output redirection to a file is a write. A `>` inside a quoted span is the
299
+ // program's own argument, never a redirect, so only the text the shell would act
300
+ // on counts.
301
+ function writesFile(segment) {
302
+ return unquotedSegment(segment).replace(HARMLESS_REDIRECTS, '').includes('>');
303
+ }
304
+
305
+ function matchesAny(patterns, segment) {
306
+ return patterns.some((pattern) => pattern.test(segment));
307
+ }
308
+
309
+ /**
310
+ * The index of a command-position `codegraph` program in the words of a segment, or
311
+ * -1 when the segment runs something else. Only the command position names a
312
+ * program, so `echo codegraph init` and `cat codegraph.json` never match; a package
313
+ * runner that executes what it names (`npx codegraph status`, `pnpm exec codegraph
314
+ * status`) is the program too.
315
+ */
316
+ function codeGraphProgramIndex(words, start) {
317
+ const program = (value) => /^(?:\S*\/)?codegraph$/.test(value);
318
+ const word = words[start] === undefined ? '' : words[start];
319
+ if (program(word)) return start;
320
+ if (!Object.prototype.hasOwnProperty.call(PROGRAM_RUNNERS, word)) return -1;
321
+ let index = start + 1;
322
+ const skipped = PROGRAM_RUNNERS[word];
323
+ if (skipped > 1) {
324
+ // The launcher's own options come before its execution subcommand.
325
+ while (index < words.length && words[index].startsWith('-')) index += 1;
326
+ const subcommand = words[index] === undefined ? '' : words[index];
327
+ if (RUN_SUBCOMMANDS.has(subcommand)) index += 1;
328
+ else if (!DIRECT_RUNNERS.has(word)) return -1;
329
+ }
330
+ while (index < words.length && (words[index].startsWith('-') || words[index] === '--')) index += 1;
331
+ return program(words[index] === undefined ? '' : words[index]) ? index : -1;
332
+ }
333
+
334
+ /**
335
+ * The words after a command-position `codegraph` program, or undefined when the
336
+ * segment runs something else. Every subcommand is CodeGraph's — the card names the
337
+ * command it ran, so an invocation it cannot interpret, or one that passes only
338
+ * flags, is still that card.
339
+ */
340
+ function codeGraphCommandWords(segment) {
341
+ const words = shellWords(segment);
342
+ let index = 0;
343
+ while (index < words.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[index])) index += 1;
344
+ const at = codeGraphProgramIndex(words, index);
345
+ return at < 0 ? undefined : words.slice(at + 1);
346
+ }
347
+
348
+ // `&` inside a redirection (`2>&1`, `&>/dev/null`) is not a separator.
349
+ function isSeparator(command, i) {
350
+ const char = command[i];
351
+ if (char === '&') return command[i - 1] !== '>' && command[i + 1] !== '>';
352
+ return char === ';' || char === '|' || char === '\n';
353
+ }
354
+
355
+ // Index of the `)` closing a `$(` whose body starts at `start`, or -1.
356
+ function findSubstitutionEnd(command, start) {
357
+ let depth = 1;
358
+ let quote;
359
+ for (let i = start; i < command.length; i += 1) {
360
+ const char = command[i];
361
+ if (quote) {
362
+ if (char === quote) quote = undefined;
363
+ else if (char === '\\' && quote === '"') i += 1;
364
+ } else if (char === '\\') i += 1;
365
+ else if (char === "'" || char === '"') quote = char;
366
+ else if (char === '(') depth += 1;
367
+ else if (char === ')' && (depth -= 1) === 0) return i;
368
+ }
369
+ return -1;
370
+ }
371
+
372
+ /**
373
+ * Splits a shell command into its simple commands. Top-level `&&`, `||`, `;`, `|`,
374
+ * `&` and newlines separate them, quoted text never does, and every `$(...)`
375
+ * substitution contributes its own commands. Not a full shell parser: whatever it
376
+ * cannot follow lands in a segment that matches no pattern, so the card leaves the
377
+ * call alone.
378
+ */
379
+ function shellCommandSegments(command) {
380
+ const commands = [];
381
+ let current = '';
382
+ let quote;
383
+ for (let i = 0; i < command.length; i += 1) {
384
+ const char = command[i];
385
+ if (quote === "'") {
386
+ current += char;
387
+ if (char === "'") quote = undefined;
388
+ } else if (char === '\\') {
389
+ current += char + (command[i + 1] === undefined ? '' : command[i + 1]);
390
+ i += 1;
391
+ } else if (char === '$' && command[i + 1] === '(') {
392
+ const end = findSubstitutionEnd(command, i + 2);
393
+ if (end < 0) return [...commands, current + command.slice(i)];
394
+ commands.push(...shellCommandSegments(command.slice(i + 2, end)));
395
+ current += '$_';
396
+ i = end;
397
+ } else if (quote === '"') {
398
+ current += char;
399
+ if (char === '"') quote = undefined;
400
+ } else if (char === "'" || char === '"') {
401
+ quote = char;
402
+ current += char;
403
+ } else if (isSeparator(command, i)) {
404
+ commands.push(current);
405
+ current = '';
406
+ if ((char === '|' || char === '&') && command[i + 1] === char) i += 1;
407
+ } else {
408
+ current += char;
409
+ }
410
+ }
411
+ commands.push(current);
412
+ return commands;
413
+ }
414
+
415
+ // Drops harmless redirections (`2>&1`, `2>/dev/null`), leading shell keywords
416
+ // (`do grep x`), environment assignments (`CI=1 pnpm test`), git global options
417
+ // (`git -C dir status`), and whitespace.
418
+ function stripSegment(segment) {
419
+ let stripped = segment.replace(HARMLESS_REDIRECTS, '').trim();
420
+ while (LEADING_KEYWORDS.test(stripped)) stripped = stripped.replace(LEADING_KEYWORDS, '');
421
+ return stripped
422
+ .replace(/^([A-Za-z_][A-Za-z0-9_]*=("[^"]*"|'[^']*'|[^\s"'])*\s+)+(?=\S)/, '')
423
+ .replace(/^git\s+((-C|-c)\s+\S+\s+|--no-pager\s+)+/, 'git ');
424
+ }
425
+
426
+ // A segment that writes a file (`echo x > out`) is never a no-op.
427
+ function isNeutral(segment) {
428
+ return !writesFile(segment) && matchesAny(NEUTRAL_COMMANDS, segment);
429
+ }
430
+
431
+ /** The command split into the simple commands this reader inspects, with the no-ops dropped. */
432
+ function shellSegments(command) {
433
+ return shellCommandSegments(command)
434
+ .map(stripSegment)
435
+ .filter((segment) => segment.length > 0 && !isNeutral(segment));
436
+ }
437
+
438
+ /** The payload after the command's own `--`; a bare word is read only when alone, since an option may take the next one. */
439
+ function queryPayload(operation, words) {
440
+ if (operation !== 'query' && operation !== 'explore') return undefined;
441
+ const separator = words.indexOf('--');
442
+ const payload = separator >= 0 ? words.slice(separator + 1) : words.slice(words.indexOf(operation) + 1);
443
+ if (separator < 0 && payload.length !== 1) return undefined;
444
+ const query = payload.join(' ').replace(/\s+/g, ' ').trim();
445
+ return query.length > 0 ? query : undefined;
446
+ }
447
+
448
+ /**
449
+ * The CodeGraph call a shell command runs: its own operation and the query it
450
+ * named, read from the words the command passes. Undefined when no segment of the
451
+ * command runs CodeGraph, so the caller can leave that command's card exactly as it
452
+ * found it.
453
+ *
454
+ * The deciding fact is the command word alone: a segment that runs `codegraph` is a
455
+ * CodeGraph call whatever its subcommand, however many of them the command chains,
456
+ * and whatever else it runs beside them. An invocation with no readable operation
457
+ * (`codegraph --help`) is the empty call `{}` and not a refusal, because the card
458
+ * names the command itself.
459
+ */
460
+ function codegraphCallFromCommand(command) {
461
+ if (typeof command !== 'string') return undefined;
462
+ const segments = shellSegments(command);
463
+ if (segments.length === 0) return undefined;
464
+ let found = false;
465
+ let call;
466
+ for (const segment of segments) {
467
+ const words = codeGraphCommandWords(segment);
468
+ if (words === undefined) continue;
469
+ found = true;
470
+ const operation = words.find((word) => !word.startsWith('-'));
471
+ if (operation === undefined) continue;
472
+ const query = queryPayload(operation, words);
473
+ call = { operation, ...(query === undefined ? {} : { query }) };
474
+ }
475
+ return found ? call ?? {} : undefined;
476
+ }
477
+
478
+ /** The heading detail: the operation, and the query when the call named one. */
479
+ function codegraphCallDetail(call) {
480
+ return call.query === undefined ? call.operation : `${call.operation} ${call.query}`;
481
+ }
482
+
483
+ // ---- what the output says ----
484
+
485
+ /**
486
+ * The index facts an init printed: the rows that state what it built, without the
487
+ * progress chrome and without the sentence an outcome row already states.
488
+ */
489
+ function codeGraphInitFacts(text) {
490
+ const facts = [];
491
+ for (const line of outputLines(text)) {
492
+ const row = factRow(line);
493
+ if (!INIT_FACT.test(row)) continue;
494
+ if (INIT_OUTCOMES.some(([pattern]) => pattern.test(row))) continue;
495
+ if (!facts.includes(row)) facts.push(row);
496
+ }
497
+ return facts;
498
+ }
499
+
500
+ /**
501
+ * The rows an expanded init draws (S4): the outcome row the collapsed card states,
502
+ * plus at most the index facts it printed. The CLI's advisory line is never one of
503
+ * them. An output with neither an outcome nor a fact keeps its own rows, so the card
504
+ * never goes blank over an init it could not read.
505
+ */
506
+ function codeGraphInitRows(text) {
507
+ const outcome = codeGraphInitOutcome(text);
508
+ const rows = [...(outcome === undefined ? [] : [`→ ${outcome}`]), ...codeGraphInitFacts(text)];
509
+ if (rows.length > 0) return rows;
510
+ return outputLines(text)
511
+ .filter((line) => !CHROME.test(line))
512
+ .map((line) => line.trim())
513
+ .filter((line) => line.length > 0);
514
+ }
515
+
516
+ /** What an init stated it did to the index, or undefined when it printed no such sentence. */
517
+ function codeGraphInitOutcome(text) {
518
+ for (const line of outputLines(text)) {
519
+ const row = factRow(line);
520
+ for (const [pattern, action] of INIT_OUTCOMES) if (pattern.test(row)) return action;
521
+ }
522
+ return undefined;
523
+ }
524
+
525
+ /** What a sync stated it did, in its own words, or undefined when it printed no such sentence. */
526
+ function codeGraphSyncOutcome(text) {
527
+ for (const line of outputLines(text)) {
528
+ const row = factRow(line);
529
+ if (SYNC_OUTCOMES.some((pattern) => pattern.test(row))) return sentence(row);
530
+ }
531
+ return undefined;
532
+ }
533
+
534
+ /** The count CodeGraph's own output states, or undefined for a shape the card cannot read. */
535
+ function codeGraphResultSummary(operation, text) {
536
+ if (operation === 'query') {
537
+ if (/^.*No results found for /m.test(text)) return '0 results';
538
+ if (!/^Search Results for .*:$/m.test(text)) return undefined;
539
+ // One entry per blank-line-separated block: a symbol line at column zero
540
+ // followed by its indented path:line location.
541
+ const entries = text.split(/\n\s*\n/).filter((block) => {
542
+ const [head = '', ...rest] = outputLines(block);
543
+ return /^\S+\s{2,}\S/.test(head) && rest.some((line) => /^ {2}.+:\d+(?::\d+)?\s*$/.test(line));
544
+ });
545
+ return entries.length === 0 ? undefined : `${entries.length} ${entries.length === 1 ? 'result' : 'results'}`;
546
+ }
547
+ if (operation !== 'explore') return undefined;
548
+ // The MCP explore tool states the same count in one header sentence. Its sentence
549
+ // may carry a further clause on the same line (`2 files pinned from the query.`),
550
+ // which states more, not something else, so the count is read from the sentence's
551
+ // own beginning.
552
+ const found = /^Found (\d+) symbols? across (\d+) files?\./m.exec(text);
553
+ if (!found) return undefined;
554
+ const symbols = Number(found[1]);
555
+ const files = Number(found[2]);
556
+ return `${symbols} ${symbols === 1 ? 'symbol' : 'symbols'} in ${files} ${files === 1 ? 'file' : 'files'}`;
557
+ }
558
+
559
+ /** The output without the progress box's empty rows, keeping the rows it ends with. */
560
+ function codeGraphPreview(text, limit = PREVIEW_ROWS) {
561
+ return outputLines(text).filter((line) => !CHROME.test(line)).slice(-limit).join('\n');
562
+ }
563
+
564
+ /**
565
+ * The rows a collapsed card draws: the stated count, the init or sync sentence, its
566
+ * facts, or its own last rows. Undefined means the card draws no rows at all, which
567
+ * is what a withheld level and an empty result both ask for. A failure always says
568
+ * why, so a withheld failure still keeps its reason.
569
+ *
570
+ * S4: an init is the one exception to the withheld level — `→ initialized` /
571
+ * `→ already initialized` is what the call DID, not its body — so that one row is
572
+ * drawn at either content level. Its index facts still wait for the expansion.
573
+ */
574
+ function codeGraphCollapsedRows(operation, text, failed, withheld, limit = PREVIEW_ROWS) {
575
+ if (withheld && !failed) {
576
+ if (operation !== 'init') return undefined;
577
+ const outcome = codeGraphInitOutcome(text);
578
+ return outcome === undefined ? undefined : { text: `→ ${outcome}`, rows: 1, tail: false };
579
+ }
580
+ if (failed) {
581
+ const reason = outputLines(text).filter((line) => line.trim().length > 0).slice(-limit).join('\n');
582
+ return reason.length > 0 ? { text: reason, rows: limit, tail: true } : undefined;
583
+ }
584
+ const summary = codeGraphResultSummary(operation, text);
585
+ if (summary !== undefined) return { text: `→ ${summary}`, rows: 1, tail: false };
586
+ const outcome = operation === 'init' ? codeGraphInitOutcome(text) : operation === 'sync' ? codeGraphSyncOutcome(text) : undefined;
587
+ if (outcome !== undefined) return { text: `→ ${outcome}`, rows: 1, tail: false };
588
+ const lines = outputLines(text).filter((line) => !CHROME.test(line));
589
+ const facts = operation === 'init' ? lines.filter((line) => INIT_FACT.test(line)).slice(-limit) : [];
590
+ const preview = (facts.length > 0 ? facts : lines.slice(-limit)).join('\n');
591
+ return preview.length > 0 ? { text: preview, rows: limit, tail: true } : undefined;
592
+ }
593
+
594
+ // Tool output can carry the escape sequences a colouring CLI printed; the card
595
+ // draws text, so they are removed rather than interpreted. Tabs and newlines stay:
596
+ // they are the card's own layout.
597
+ const ANSI_ESCAPE = /\u001B(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001B]*(?:\u0007|\u001B\\)?|[@-Z\\-_])/g;
598
+ const CONTROL_CHARACTER = /[\u0000-\u0008\u000B-\u001F\u007F]/g;
599
+
600
+ /** Text as the card draws it: what the tool printed, without the terminal sequences around it. */
601
+ function cardText(value) {
602
+ return typeof value === 'string' ? value.replace(ANSI_ESCAPE, '').replace(CONTROL_CHARACTER, '') : '';
603
+ }
604
+
605
+ /** The whole output as the card draws it when the reader expanded it: normalized, trailing blanks dropped. */
606
+ function codeGraphWholeOutput(text) {
607
+ return cardText(text).replace(/\r\n/g, '\n').replace(TRAILING_BLANK, '');
608
+ }
609
+
610
+ module.exports = {
611
+ CODEGRAPH_MARK,
612
+ CODEGRAPH_MCP_TOOL,
613
+ CODEGRAPH_TITLE_ROLE,
614
+ CODEGRAPH_TOOL,
615
+ PREVIEW_ROWS,
616
+ cardText,
617
+ codeGraphCollapsedRows,
618
+ codeGraphInitFacts,
619
+ codeGraphInitOutcome,
620
+ codeGraphInitRows,
621
+ codeGraphPreview,
622
+ codeGraphResultSummary,
623
+ codeGraphSyncOutcome,
624
+ codeGraphWholeOutput,
625
+ codegraphCallDetail,
626
+ codegraphCallFromCommand,
627
+ projectPathSegment,
628
+ };