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,1164 @@
1
+ 'use strict';
2
+ // S2 / S3 / S4 (T2): which named ACTIVITY a `bash` call is, decided from its command
3
+ // alone — the classifier the bash card's heading wears.
4
+ //
5
+ // Ported from the user's own gentle-shell branch (`cards-bash-v2`,
6
+ // `lib/odd-phase-inference.ts`, read read-only): the shell families, the mark and
7
+ // theme role each one wears, the quote-aware segmenter every family is decided with,
8
+ // and the reference's conservatism. What is NOT ported is that module's ODD *phase*
9
+ // inference — "which step of the protocol does this tool imply" — because this
10
+ // package answers one question only: which activity family does this command name,
11
+ // or none at all.
12
+ //
13
+ // The whole module is one rule: never guess. An unknown program, a composition with
14
+ // a segment nothing can name, a command hidden in a substitution the segmenter
15
+ // cannot follow, a redirect that would put the call's output in a file, or a family
16
+ // whose own flags say it is not the thing it looks like — all answer `undefined`,
17
+ // which is what the card draws as its generic `$ bash` fallback. A guess would paint
18
+ // a heading that claims work the call did not do, and a heading is the one part of a
19
+ // collapsed card a reader trusts without expanding it.
20
+ //
21
+ // The rules the module obeys:
22
+ // * pure: no Pi, no theme, no colour, no filesystem, no process, no clock. It
23
+ // reads a string and returns a family name.
24
+ // * colour is a THEME ROLE, never a palette. `SHELL_ACTIVITY_IDENTITY` holds the
25
+ // host's own slot names (`mdHeading`, `mdLink`, `mdCode`, `success`, `warning`,
26
+ // `syntaxFunction`, `error`), so a light theme, a neon theme or a design pack
27
+ // repaints the heading with everything else. A hex value here would survive a
28
+ // theme change and read as the only unstyled row on screen.
29
+ // * it is the ONE segmenter. A second, quoting-blind splitter would read a
30
+ // separator inside a commit message as a command boundary and disagree with the
31
+ // identity the same call wears.
32
+ //
33
+ // Plain CommonJS and Node builtins only: this package ships no dependency, and the
34
+ // reference's classifier carries no Node API either.
35
+
36
+ // The two readings a family alone cannot decide: a database client's statements, which
37
+ // arrive through a pipe or a heredoc, and the segment that deletes something. The
38
+ // evidence module is presentation only — it is read here to decide a heading and
39
+ // nothing else in this package may read it.
40
+ const { isDestructiveCommand, isDestructiveSegment, isSqlClientSegment } = require('./bash-destructive.js');
41
+
42
+ /**
43
+ * The activity families, in the reference's precedence order. A family is a card
44
+ * identity, not an ODD phase: none of these reaches the working label or the
45
+ * exploration budget.
46
+ *
47
+ * The destructive family heads this list because a deletion is the one consequence a
48
+ * reader cannot undo, so it outranks every identity beside it. It is decided from two
49
+ * readings the other families do not need: the segment that names a deleting program,
50
+ * and the whole command whose pipe or heredoc feeds a database client its statements.
51
+ */
52
+ const SHELL_ACTIVITIES = ['destructive', 'checking', 'formatting', 'preparing', 'publishing', 'versioning', 'codegraph', 'exploring'];
53
+
54
+ /**
55
+ * The mark and theme role each activity wears. The classifier families are separate
56
+ * from this table; it changes no classification.
57
+ *
58
+ * `mdLink` and `mdHeading` paint the two identities the ODD protocol also names,
59
+ * `warning` is the warm role a local history change wears, `success` the green one a
60
+ * remote write wears, and `syntaxFunction` is the code palette — the one slot
61
+ * `preparing` and `formatting` share, because the shipped themes define six colours a
62
+ * heading can wear and the two maintenance identities are told apart by their mark and
63
+ * their word rather than by a colour no theme has. `mdCode` is the one slot a CodeGraph
64
+ * call wears on either of its cards, whose mark is the tool's own.
65
+ *
66
+ * A mark carries its own gap where a font may paint it wider than the host counts:
67
+ * U+2692 is drawn two cells wide by an emoji-fallback font while the host's width
68
+ * function counts it as one, so a single space after it is painted inside the glyph's
69
+ * own second cell and the heading reads `⚒preparing`. Preparing's mark therefore ends
70
+ * in one space — the minimum that still shows a column — so the heading's counted
71
+ * width matches what the terminal paints.
72
+ */
73
+ const SHELL_ACTIVITY_IDENTITY = {
74
+ // The error role is the one slot that reads as a warning in every shipped theme,
75
+ // and U+26A0 is the mark a reader recognizes before expanding the row.
76
+ destructive: { glyph: '⚠', titleRole: 'error' },
77
+ checking: { glyph: '✓', titleRole: 'mdHeading' },
78
+ formatting: { glyph: '≋', titleRole: 'syntaxFunction' },
79
+ preparing: { glyph: '⚒ ', titleRole: 'syntaxFunction' },
80
+ publishing: { glyph: '↑', titleRole: 'success' },
81
+ versioning: { glyph: '⎇', titleRole: 'warning' },
82
+ codegraph: { glyph: '\u{F01BC}', titleRole: 'mdCode' },
83
+ exploring: { glyph: '⌕', titleRole: 'mdLink' },
84
+ };
85
+
86
+ // Test, typecheck, lint and build runners. Matched per shell segment.
87
+ const CHECKING_COMMANDS = [
88
+ /^node\b.*\s--test\b/,
89
+ /^node\s+\S*(test|check|lint|typecheck)[\w-]*\.m?[jt]s\b/,
90
+ /^((npx|pnpx|bunx)\s+|(pnpm|yarn)\s+exec\s+)?(vitest|jest|mocha|tsc|pytest)\b/,
91
+ /^python(3(\.\d+)?)?\s+-m\s+(pytest|unittest)\b/,
92
+ /^go\s+(test|build|vet)\b/,
93
+ /^cargo\s+(test|build|check|clippy|nextest)\b/,
94
+ // `cargo fmt` rewrites code, so only the check form verifies anything.
95
+ /^cargo\s+fmt\b.*\s--check\b/,
96
+ /^ruff\s+format\s+--check\b/,
97
+ /^deno\s+(test|check)\b/,
98
+ /^deno\s+fmt\s+--check\b/,
99
+ /^deno\s+task\s+(test|typecheck|lint|build|check)\b/,
100
+ // eslint verifies work whatever write flag it carries, quoted or not.
101
+ /^((npx|pnpx|bunx)\s+|(pnpm|yarn|npm)\s+(exec|run)\s+)?eslint\b/,
102
+ // Waiting on or reading CI results verifies work; it is not exploration.
103
+ /^gh\s+pr\s+checks\b/,
104
+ /^gh\s+run\s+(view|watch|list)\b/,
105
+ ];
106
+
107
+ // These runners verify only when they are not asked to rewrite files: `ruff check
108
+ // --fix` and `deno lint --fix` repair code, so they are not checks. The flag is the
109
+ // one the shell passes, so a quoted `--fix` counts too, while `--fix-dry-run` writes
110
+ // nothing and stays a check.
111
+ const FIXABLE_CHECKING_COMMANDS = [/^ruff\s+check\b/, /^deno\s+lint\b/];
112
+ const FIX_FLAGS = new Set(['--fix', '--fix-only', '--unsafe-fixes']);
113
+
114
+ // A formatter verifies only when it is told to report. The report flag is the tool's
115
+ // own: `-l` lists files for gofmt, gofumpt and shfmt but is the line length for black,
116
+ // and a write flag rewrites what a report flag would only name, so `gofmt -l -w .`
117
+ // reforms code instead of verifying it.
118
+ const FORMATTER_FLAGS = {
119
+ prettier: { report: ['--check', '-l', '--list-different'], write: ['--write', '-w'] },
120
+ black: { report: ['--check', '--diff'], write: [] },
121
+ rustfmt: { report: ['--check'], write: [] },
122
+ gofmt: { report: ['-l', '-d'], write: ['-w'] },
123
+ gofumpt: { report: ['-l', '-d'], write: ['-w'] },
124
+ shfmt: { report: ['-l', '-d'], write: ['-w'] },
125
+ 'clang-format': { report: ['--dry-run', '-n'], write: ['-i', '--in-place'] },
126
+ swiftformat: { report: ['--lint', '--dryrun'], write: [] },
127
+ };
128
+ // `timeout` options that take the word after them; every other flag stands alone.
129
+ const TIMEOUT_VALUE_OPTIONS = new Set(['-s', '--signal', '-k', '--kill-after']);
130
+
131
+ // Package managers that run a script by name, and the scripts that verify work.
132
+ // `install`, `deploy`, `publish`, `start` and a dev server are not checks, and an
133
+ // unlisted script leaves the call unnamed.
134
+ const PACKAGE_MANAGERS = new Set(['pnpm', 'npm', 'yarn', 'bun']);
135
+ const CHECK_SCRIPTS = new Set(['test', 'typecheck', 'lint', 'build', 'check', 'verify']);
136
+ // A script named `ci` is a check only where the package manager runs it AS a script
137
+ // (`pnpm run ci`): a bare `npm ci` installs from the lockfile, which is the build-up the
138
+ // preparing family already names.
139
+ const CHECK_RUN_SCRIPTS = new Set(['ci']);
140
+ // A script whose name promises a repair, a reformat, a watch or a server is not a check,
141
+ // whatever family it is namespaced under: `test:watch` never ends, `lint:fix` rewrites
142
+ // what it reads, and `dev`/`start`/`serve` hold a process open.
143
+ const NON_CHECK_SCRIPT = /(fix|write|format|watch|dev|start|serve)/;
144
+ // Options that take the token after them, so `pnpm -C pkg test` names its script after
145
+ // the workspace directory instead of reading that directory as the script.
146
+ const PACKAGE_MANAGER_VALUE_OPTIONS = new Set(['-C', '--dir', '--prefix', '-F', '--filter', '--cwd']);
147
+ // Options that take no value and change nothing about which script runs.
148
+ const PACKAGE_MANAGER_FLAGS = new Set(['-w', '--workspace-root', '-r', '--recursive', '-s', '--silent']);
149
+
150
+ // `make` targets that verify work. Any other target — `install`, `deploy`, `clean`,
151
+ // `release`, an unknown recipe — changes the machine or does something this classifier
152
+ // cannot name, so it leaves the call unnamed.
153
+ const MAKE_CHECK_TARGETS = new Set(['test', 'tests', 'check', 'checks', 'build']);
154
+ // Options that take their value as the next word.
155
+ const MAKE_VALUE_OPTIONS = new Set([
156
+ '-C', '--directory', '-f', '--file', '--makefile', '-I', '--include-dir',
157
+ '-o', '--old-file', '--assume-old', '-W', '--what-if', '--new-file', '--assume-new',
158
+ ]);
159
+ // Options whose value is attached (`-j4`, `-Oline`) or, for the job and load limits,
160
+ // may also be the next word when it is a bare count (`-j 4`).
161
+ const MAKE_COUNTED_OPTIONS = new Set(['-j', '--jobs', '-l', '--load-average', '-O', '--output-sync']);
162
+
163
+ // `gh api` writes whenever it is given a method, a field, or an input body, so only
164
+ // the plain GET form is a query.
165
+ const GH_API_WRITE_FLAGS = new Set(['-X', '--method', '-f', '--raw-field', '-F', '--field', '--input']);
166
+
167
+ // Formatters and lint fixers rewrite the files they read, so they are not checks. The
168
+ // read-only forms — `--check`, `--diff`, `-l`, `--list-different` — are the checks the
169
+ // families above already read, and a segment carrying one is never a rewrite. A flag
170
+ // named inside quoted text is not a flag the call passes.
171
+ const FORMATTING_COMMANDS = [
172
+ /^((npx|pnpx|bunx)\s+|(pnpm|yarn|npm)\s+(exec|run)\s+)?(prettier|biome|stylelint|oxlint|standard|markdownlint)\b.*\s(--write|--fix|-w)(?=\s|=|$)/,
173
+ /^((npx|pnpx|bunx)\s+)?dprint\s+fmt\b/,
174
+ // Formatters that rewrite in place by default; the read-only forms are excluded
175
+ // above, so `black --check` and `rustfmt --check` stay the checks they are.
176
+ /^((npx|pnpx|bunx)\s+)?(black|rustfmt|swiftformat)\b/,
177
+ /^clang-format\b.*\s-i(?=\s|$)/,
178
+ /^(cargo\s+fmt|go\s+fmt)\b/,
179
+ // These print the formatted text unless told to write it.
180
+ /^(gofmt|gofumpt|shfmt)\b.*\s-w(?=\s|$)/,
181
+ /^ruff\s+(check|format)\b/,
182
+ /^deno\s+(fmt|lint)\b/,
183
+ /^(mix|dart|terraform)\s+(format|fmt)\b/,
184
+ ];
185
+ // A formatter told to report instead of rewrite is the check it really is, or nothing
186
+ // at all when this classifier cannot read its flags.
187
+ const FORMAT_READ_ONLY_FLAGS = new Set(['--check', '--diff', '--list-different', '--dry-run', '-l']);
188
+
189
+ // Preparing the environment: installing dependencies in any ecosystem, creating a
190
+ // directory, file or repository, and storing configuration in a tool's own file. Only
191
+ // the forms that name themselves count: an unknown script, an unlisted `make` recipe
192
+ // and a bare `git config --unset` stay unnamed.
193
+ const PREPARING_COMMANDS = [
194
+ /^(pip|pip3)\s+install\b/,
195
+ /^python(3(\.\d+)?)?\s+-m\s+pip\s+install\b/,
196
+ /^uv\s+(pip\s+install|sync|add|init)\b/,
197
+ /^poetry\s+(install|add)\b/,
198
+ /^(bundle\s+install|gem\s+install|composer\s+install)\b/,
199
+ /^(brew|port)\s+install\b/,
200
+ /^(apt|apt-get|dnf|yum|zypper)\s+(install|add)\b/,
201
+ /^apk\s+add\b/,
202
+ /^pacman\s+-S\b/,
203
+ /^go\s+(get|install|mod\s+download)\b/,
204
+ /^cargo\s+(install|fetch|new|init)\b/,
205
+ /^dotnet\s+(restore|add)\b/,
206
+ // A repository the call creates.
207
+ /^git\s+(init|clone)\b/,
208
+ // A worktree the call creates is a checkout this machine did not have; moving or
209
+ // repairing one writes the same git metadata. `remove`/`prune` delete and stay unnamed
210
+ // because no table here names them.
211
+ /^git\s+worktree\s+(add|move|repair)\b/,
212
+ // A temporary path, a mode, an owner and a rename build the machine up the way `cp`
213
+ // and `mkdir` already do: none of them removes what a reader could not rename back.
214
+ /^(mkdir|touch|cp|ln|mv|mktemp|chmod|chown)\b/,
215
+ // The version manager installs and pins a toolchain like the other installers.
216
+ /^mise\s+(install|use|add)\b/,
217
+ // Configuration the call stores on this machine. A read is inspection and is matched
218
+ // before this family; a key deletion is not preparation either.
219
+ /^git\s+config\s+[^-\s]+\s+\S/,
220
+ /^(pip|pip3)\s+config\s+set\b/,
221
+ /^go\s+env\s+-w\b/,
222
+ ];
223
+ // The package managers install, scaffold and store configuration through the same
224
+ // subcommand position, so one reader serves every ecosystem.
225
+ const PREPARING_SCRIPTS = new Set(['install', 'i', 'ci', 'add', 'init']);
226
+ // The flags that ask an installer to report instead of change the machine:
227
+ // `cargo install --list` lists what is already installed and `--dry-run` resolves a
228
+ // tree without writing it, so neither prepares the environment.
229
+ const PREPARING_READ_ONLY_FLAGS = new Set(['--list', '--dry-run']);
230
+
231
+ // Local history. The index, a commit (`--amend` included), a rebase and a cherry-pick
232
+ // (each with its `--continue`/`--abort`) change this machine only.
233
+ const VERSIONING_COMMANDS = [
234
+ /^git\s+(add|commit|rebase|cherry-pick)\b/,
235
+ // Moving work inside this machine: fetching and pulling bring history here, a merge,
236
+ // a checkout, a switch and a restore move the working tree, a patch (and `revert`, its
237
+ // inverse) rewrites history, and `mv`/`rm` stage a rename or a removal. A deletion the
238
+ // destructive table names — a discarded checkout, `rm` without `--cached` — is read
239
+ // before this family.
240
+ /^git\s+(fetch|pull|merge|checkout|switch|restore|revert|apply|am|mv|rm)\b/,
241
+ // `reset` moves the index unless it is told to throw the worktree away: that form is the
242
+ // deletion the destructive reading already names, and a segment whose own `--hard --help`
243
+ // leaves both readings declined stays unnamed.
244
+ /^git\s+reset\b(?!.*\s--hard\b)/,
245
+ // A branch or a tag the call creates, deletes or renames. The listing forms are
246
+ // inspection and are matched before this family, so what is left moves a ref.
247
+ /^git\s+branch\s+(-[dDmMcuU]\w*|--(delete|move|copy|set-upstream-to|unset-upstream|edit-description|create-reflog)\b)/,
248
+ /^git\s+branch\s+[^-\s]/,
249
+ /^git\s+tag\s+(-[adfsuv]\w*|--(annotate|delete|sign|force|local-user|message|file|cleanup|verify)\b)/,
250
+ /^git\s+tag\s+[^-\s]/,
251
+ /^git\s+remote\s+(add|remove|rm|rename|set-url|set-head|prune|update)\b/,
252
+ // The local stash holds work this machine keeps; dropping or clearing it is destructive
253
+ // and is read before this family.
254
+ /^git\s+stash\b/,
255
+ // A lock is a file in the worktree's own git directory, like the index.
256
+ /^git\s+worktree\s+(lock|unlock)\b/,
257
+ // Checking a PR out brings its branch here and publishes nothing.
258
+ /^gh\s+pr\s+checkout\b/,
259
+ // A stack's local half creates and rebases branches; it publishes nothing.
260
+ /^gh\s+stack\s+(init|add|rebase)\b/,
261
+ ];
262
+
263
+ // Remote writes: they create or move something on GitHub, including the label,
264
+ // assignment and review mutations that ride on `edit` and its siblings.
265
+ const PUBLISHING_COMMANDS = [
266
+ /^git\s+push\b/,
267
+ /^gh\s+(pr|issue)\s+(create|edit|close|reopen|delete|merge|ready|review|comment|update-branch|pin|unpin|lock|unlock|transfer)\b/,
268
+ /^gh\s+label\s+(create|edit|delete|clone)\b/,
269
+ /^gh\s+release\s+(create|edit|delete|upload)\b/,
270
+ /^gh\s+repo\s+(create|edit|delete|archive|rename|fork)\b/,
271
+ // A stack's remote half pushes its branches and rewrites its PRs.
272
+ /^gh\s+stack\s+(submit|push|merge|link|unstack|sync)\b/,
273
+ // Rerunning or cancelling a CI run moves work on the remote, beside `gh pr` and
274
+ // `gh workflow`, which already name their own writes.
275
+ /^gh\s+run\s+(rerun|cancel)\b/,
276
+ ];
277
+
278
+ // `--help` prints a program's usage and stops, so it is a query on any command family.
279
+ // Only a program this classifier already names is asked: an unknown program's flag is
280
+ // a guess, and a runner that executes the rest of the segment can swallow the flag as
281
+ // an argument to the code it runs.
282
+ //
283
+ // The deleting programs are listed with the rest because their usage page is the same
284
+ // query, even though their own family arrives with T3: `rm --help` prints help and
285
+ // removes nothing, and the destructive seam below reads only what is left after this
286
+ // reading. No other table here resolves a destructive program.
287
+ const HELP_AWARE_COMMANDS = new Set([
288
+ 'git', 'gh',
289
+ 'node', 'npx', 'pnpx', 'bunx', 'pnpm', 'npm', 'yarn', 'bun', 'deno',
290
+ 'go', 'cargo', 'ruff', 'python', 'python3', 'pytest', 'vitest', 'jest',
291
+ 'mocha', 'tsc', 'eslint', 'make',
292
+ // The families that delete or rewrite files print their usage the same way.
293
+ 'rm', 'find', 'shred', 'truncate', 'dd',
294
+ 'prettier', 'biome', 'dprint', 'stylelint', 'oxlint', 'standard', 'markdownlint',
295
+ 'black', 'rustfmt', 'swiftformat', 'clang-format', 'gofmt', 'gofumpt', 'shfmt',
296
+ 'mix', 'dart', 'terraform', 'uv', 'poetry', 'pip', 'pip3',
297
+ // The harness tools print their usage the same way every other known program does.
298
+ 'herdr', 'pi', 'gentle-ai', 'gentle-shell', 'odd-worktree',
299
+ // Containers and clusters print their usage the same way.
300
+ 'docker', 'kubectl',
301
+ ]);
302
+ // Programs that run the code they are handed. Only for these does a payload flag make
303
+ // the rest of the segment unreadable.
304
+ const SCRIPT_RUNNERS = new Set(['node', 'deno', 'bun', 'python', 'python3']);
305
+ const PAYLOAD_FLAGS = new Set(['-e', '--eval', '-p', '--print', '-c']);
306
+
307
+ // Git listing flags that may take one non-flag argument (`--contains <rev>`) without
308
+ // turning `git branch`/`git tag` into a create.
309
+ const GIT_LIST_FLAG = String.raw`(\s+(-a|-r|-l|-v|-vv|-n\d*|--all|--remotes|--list|--show-current|--contains|--merged|--no-merged|--points-at|--sort=\S+)(\s+[^-\s]\S*)?)*$`;
310
+
311
+ // Read-only inspection. Matched per shell segment.
312
+ const EXPLORING_COMMANDS = [
313
+ /^git\s+(status|log|diff|show|blame|rev-parse|rev-list|merge-base|ls-files|ls-remote|ls-tree|cat-file|describe|shortlog|reflog|grep|check-ignore|for-each-ref|name-rev|count-objects)\b/,
314
+ new RegExp(String.raw`^git\s+(branch|tag)${GIT_LIST_FLAG}`),
315
+ /^git\s+remote(\s+(-v|--verbose|show|get-url)\b.*)?$/,
316
+ /^git\s+(worktree|stash)\s+list\b/,
317
+ /^git\s+config\s+(--get|--get-all|--get-regexp|-l|--list)\b/,
318
+ // `git config <key>` without a value reports what is stored.
319
+ /^git\s+config\s+[^-\s]+\s*$/,
320
+ /^gh\s+(pr|issue|repo|release)\s+(view|list|diff|status)\b/,
321
+ /^gh\s+(auth\s+status|search\s+\w+|label\s+list|workflow\s+(list|view))\b/,
322
+ // Viewing a stack reads the local stack and its PRs.
323
+ /^gh\s+stack\s+view\b/,
324
+ // Metadata probes: what is installed, configured, or resolved here.
325
+ /^locale\b/,
326
+ /^cargo\s+tree\b/,
327
+ /^go\s+version\b/,
328
+ /^(ls|cat|head|tail|grep|egrep|rg|wc|pwd|tree|stat|file|which|type|readlink|realpath|dirname|basename|cut|uniq|tr|nl|column|strings|diff|cmp|od|xxd|hexdump|shasum|sha256sum|md5|md5sum|du|df|date|uname|whoami|ps|pgrep|lsof|jq|awk|bat|batcat|eza|exa|lsd|ag|ack|zgrep|fgrep|less|more|man|id|hostname|uptime|free|printenv|nproc|comm|paste|rev|tac|seq)\b/,
329
+ /^command\s+-v\b/,
330
+ /^(\[\[?|test)\s/,
331
+ /^sort\b(?!.*\s(-o|--output)\b)/,
332
+ /^sed\b(?!.*\s(-[a-zA-Z]*i|--in-place)\b)/,
333
+ /^find\b(?!.*\s-(delete|exec|execdir|ok|okdir|fprint\w*)\b)/,
334
+ // `fd` is `find`: it only reads unless it is handed a command to run for each match.
335
+ /^(fd|fdfind)\b(?!.*\s(-x|-X|--exec|--exec-batch)\b)/,
336
+ // More read-only git: the plumbing and stash views that change no ref.
337
+ /^git\s+(diff-tree|diff-index|show-ref|show-branch|symbolic-ref|cherry|range-diff|whatchanged|var|verify-commit|verify-tag)(?=\s|$)/,
338
+ /^git\s+stash\s+show\b/,
339
+ /^gh\s+(cache|secret|variable)\s+list\b/,
340
+ // The journal, the kernel log and the unit state answer "what happened here?" without
341
+ // changing it. `systemctl`'s own options (`--user`, `-H host`) come before its verb.
342
+ /^(journalctl|dmesg)\b/,
343
+ /^systemctl\s+(-{1,2}[\w-]+\s+)*(status|is-active|is-enabled|is-failed|list-units|list-unit-files|list-timers|list-dependencies|show|cat)\b/,
344
+ // A package manager's own query verbs: what is installed, what a package is and what a
345
+ // repository offers. A sync, an install or a cache clean writes and is not one of them.
346
+ /^pacman\s+(-Q\w*|-F\w*|-S[isgl]{1,3})\b/,
347
+ /^brew\s+(list|ls|info|search|outdated)\b/,
348
+ /^apt\s+(list|show|search|policy)\b/,
349
+ // The version manager reports what is resolved where without installing anything.
350
+ /^mise\s+(ls|list|current|which|where|doctor|ls-remote)\b/,
351
+ /^nvim\s+--version\b/,
352
+ /^tmux\s+(list-[\w-]+|show-[\w-]+|display-message)\b/,
353
+ // The harness tools the transcripts call: only a read-only word names the card, and the
354
+ // noun before it is transparent, so `herdr plugin list` is the list it is while
355
+ // `herdr plugin install` still names nothing.
356
+ /^(herdr|pi|gentle-ai|gentle-shell|odd-worktree)\s+([\w-]+\s+)?(version|list|ls|status|doctor|show|info|--version|--help|--status|-v|-h)(?=\s|$)/,
357
+ // Containers, clusters and package managers print state without changing it.
358
+ /^docker\s+(ps|images|logs|inspect|version|info|stats|top|port|diff|history|(image|container|volume|network)\s+(ls|inspect|logs)|compose\s+(ps|logs|config|images|top))\b/,
359
+ /^kubectl\s+(get|describe|logs|version|top|explain|api-resources|config\s+(view|get-contexts|current-context))\b/,
360
+ /^(npm|pnpm)\s+(ls|list|ll|la|view|info|show|outdated|explain|why|root|prefix|bin|licenses|search)\b/,
361
+ /^(npm|pnpm|yarn)\s+config\s+(get|list)\b/,
362
+ /^yarn\s+(list|why|info|outdated|licenses)\b/,
363
+ /^(pip|pip3)\s+(list|show|freeze|check|inspect|config\s+list)\b/,
364
+ ];
365
+
366
+ // Segments that neither inspect nor change anything worth labeling: shell control
367
+ // words, no-op builtins, and bare variable assignments (their command substitutions
368
+ // are classified as commands of their own).
369
+ const NEUTRAL_COMMANDS = [
370
+ /^(cd|pushd|popd|echo|printf|sleep|true|false|export|set|unset|local|read|wait|return|exit|umask)\b/,
371
+ // `:` is the shell's own no-op, and it is not a word, so it needs its own boundary.
372
+ /^:(\s|$)/,
373
+ // A line that starts with `#` is a comment the shell never runs, so a script's prose
374
+ // never keeps the work beside it generic.
375
+ /^#/,
376
+ /^(done|fi|esac|\}|\))$/,
377
+ /^for\s+\w+(\s+in\b.*)?$/,
378
+ // Each assignment must end at whitespace or the end: an optional separator would let
379
+ // `a=a=a=…` split anywhere and backtrack exponentially.
380
+ /^([A-Za-z_][A-Za-z0-9_]*=("[^"]*"|'[^']*'|[^\s"'])*(\s+|$))+$/,
381
+ ];
382
+
383
+ // Shell keywords that prefix the command they introduce (`do grep x`), and the opening
384
+ // `(` of a subshell, which the program follows directly in `(git status; ...)`. `time`
385
+ // is not one of them: it is a wrapper that may carry options, and `stripWrapper` reads
386
+ // it.
387
+ const LEADING_KEYWORDS = /^((do|then|else|elif|if|while|until|!|\{)\s+|\(\s*)/;
388
+
389
+ /**
390
+ * The family a shell command names for its own card, or `undefined` when any segment
391
+ * carries no reliable signal and the call must keep the generic card.
392
+ *
393
+ * A deletion outranks everything, and so does a call that runs CodeGraph: the directory
394
+ * is the project's graph and the command is the card's own detail. Beside those, a
395
+ * segment nothing can name keeps the card generic: the heading never claims a check —
396
+ * or any other identity — for work the call also did silently. Among the rest the
397
+ * strongest wins: a check, a remote write, a history change, a rewrite, a build-up.
398
+ */
399
+ function inferBashActivity(command) {
400
+ const segments = shellSegments(command);
401
+ if (segments.length === 0) return undefined;
402
+ const activities = segments.map(segmentActivity);
403
+ // A database client runs the statements a pipe or a heredoc hands it, so its own
404
+ // segment states none of them: the WHOLE command proves that deletion, and the
405
+ // client with the payload it reads is what the proof names. Those segments already
406
+ // count as named; a segment outside the payload still keeps the whole card generic,
407
+ // because the call also did work no heading may hide.
408
+ const deletesData = isDestructiveCommand(command);
409
+ const sqlPayload = deletesData ? sqlPayloadCoverage(segments) : [];
410
+ const runsCodeGraph = activities.includes('codegraph');
411
+ // A segment nothing can name keeps the whole card generic, so the heading never hides
412
+ // the work the call also did silently — unless the call runs CodeGraph, whose card
413
+ // names the command itself whichever company it keeps.
414
+ if (!runsCodeGraph && activities.some((activity, index) => activity === undefined && sqlPayload[index] !== true)) return undefined;
415
+ // A deletion outranks every other identity on the same call: it is the one
416
+ // consequence a reader cannot undo, so a check beside it never takes the card.
417
+ if (activities.includes('destructive') || deletesData) return 'destructive';
418
+ // A call that also runs CodeGraph is CodeGraph's card: the command is its detail, so
419
+ // a check or a build beside it never takes the row.
420
+ if (runsCodeGraph) return 'codegraph';
421
+ if (activities.includes('checking')) return 'checking';
422
+ if (activities.includes('publishing')) return 'publishing';
423
+ if (activities.includes('versioning')) return 'versioning';
424
+ if (activities.includes('formatting')) return 'formatting';
425
+ if (activities.includes('preparing')) return 'preparing';
426
+ return 'exploring';
427
+ }
428
+
429
+ /**
430
+ * Whether this command is a CodeGraph call, as this classifier reads it: the shell
431
+ * half of the one identity `lib/codegraph-card.js` already draws. The card's own
432
+ * reader (`codegraphCallFromCommand` in `lib/codegraph-card-preview.js`) answers the
433
+ * same question for the words it needs; the two must never disagree, so a call is
434
+ * handed to the CodeGraph card only when both name it.
435
+ */
436
+ function isCodegraphCommand(command) {
437
+ return inferBashActivity(command) === 'codegraph';
438
+ }
439
+
440
+ /**
441
+ * Which segments a deletion the whole command proves already names: the database client
442
+ * that runs the statements. The heredoc body it reads is folded into its own segment as
443
+ * the data it is, so the statements are never commands of their own — nothing could name
444
+ * them anyway — and nothing else may be excused from the undefined scan.
445
+ */
446
+ function sqlPayloadCoverage(segments) {
447
+ return segments.map(isSqlClientSegment);
448
+ }
449
+
450
+ /** The command split into the simple commands the classifier reads, with the ones that do nothing dropped. */
451
+ function shellSegments(command) {
452
+ if (command === undefined || command === null) return [];
453
+ if (typeof command !== 'string') return [];
454
+ return shellCommandSegments(command)
455
+ .map(stripSegment)
456
+ .filter((segment) => segment.length > 0 && !isNeutral(segment));
457
+ }
458
+
459
+ /**
460
+ * What one simple command does. A help flag outranks the verb it qualifies —
461
+ * `git push --help` prints usage — a help flag an option consumed leaves the verb to
462
+ * name the segment, and a help flag this classifier cannot read as a query leaves the
463
+ * segment unnamed rather than naming the verb beside it.
464
+ */
465
+ function segmentActivity(segment) {
466
+ // The command position decides first: a call that runs the program is its card
467
+ // whatever it passes it, so `codegraph --help` is the program's own usage page and
468
+ // not the generic inspection a help flag beside another program would name.
469
+ if (codeGraphCommandWords(segment) !== undefined) return 'codegraph';
470
+ const help = helpFlag(segment);
471
+ if (help === 'request') return 'exploring';
472
+ if (help === 'unreadable') return undefined;
473
+ // A command-position word naming a deleting program decides the segment before any
474
+ // other family reads it, so a deletion is never filed as the check or the inspection
475
+ // its verb resembles.
476
+ if (isDestructiveSegment(segment)) return 'destructive';
477
+ if (isCheckingSegment(segment)) return 'checking';
478
+ if (isFormattingSegment(segment)) return 'formatting';
479
+ if (isReadOnlyInspection(segment)) return 'exploring';
480
+ // A segment whose payload this classifier cannot read, or that redirects its output
481
+ // into a file, is a write it cannot name.
482
+ if (HIDDEN_SUBSTITUTION.test(segment) || writesFile(segment)) return undefined;
483
+ if (isPreparingSegment(segment)) return 'preparing';
484
+ if (matchesAny(VERSIONING_COMMANDS, segment)) return 'versioning';
485
+ if (matchesAny(PUBLISHING_COMMANDS, segment)) return 'publishing';
486
+ if (codeGraphCommandWords(segment) !== undefined) return 'codegraph';
487
+ return undefined;
488
+ }
489
+
490
+ /**
491
+ * Whether a segment asks a known program for its own usage page: a request, a flag the
492
+ * segment's own text merely mentions or an option consumed, or an unreadable one this
493
+ * classifier refuses to guess about.
494
+ */
495
+ function helpFlag(segment) {
496
+ const words = shellWordTokens(segment);
497
+ const at = words.findIndex((word) => !word.quoted && word.text === '--help');
498
+ if (at < 0) return 'absent';
499
+ // An option may take the help flag as its own value: `git commit -m --help` commits a
500
+ // message spelled `--help` and `gh issue comment --body --help` posts it, printing
501
+ // nothing. Escaped whitespace keeps the two in one word — `git commit -m foo\ --help`
502
+ // commits `foo --help` — and a word that may expand to an option (`$OPTS`) can
503
+ // consume it too. Which options take a value cannot be known here, so a help flag
504
+ // directly after such a word is read as that word's value and the segment keeps its
505
+ // own verb's activity. The reading only ever removes a query, never adds one, so a
506
+ // genuine usage page beside an option stays with the verb instead of turning a
507
+ // mutation into exploration.
508
+ const previous = words[at - 1];
509
+ if (previous !== undefined && (previous.text.startsWith('-') || previous.text.startsWith('$'))) return 'absent';
510
+ const program = (words[0] === undefined ? '' : words[0].text).split('/').pop();
511
+ if (!HELP_AWARE_COMMANDS.has(program === undefined ? '' : program)) return 'unreadable';
512
+ // `node -e '…' --help` runs the payload with `--help` as its own argument.
513
+ if (SCRIPT_RUNNERS.has(program) && words.slice(1).some((word) => PAYLOAD_FLAGS.has(word.text))) return 'unreadable';
514
+ if (writesFile(segment) || HIDDEN_SUBSTITUTION.test(segment)) return 'unreadable';
515
+ return 'request';
516
+ }
517
+
518
+ /**
519
+ * Splits a segment into the words the program receives, dropping the quoting
520
+ * characters the shell would drop. A quoted `--help` is text handed to the program, and
521
+ * a quoted `-m` is still an option, so both the text and whether the word was quoted
522
+ * are kept.
523
+ */
524
+ function shellWordTokens(segment) {
525
+ const words = [];
526
+ let text = '';
527
+ let quoted = false;
528
+ let started = false;
529
+ const push = () => {
530
+ if (started) words.push({ text, quoted });
531
+ text = '';
532
+ quoted = false;
533
+ started = false;
534
+ };
535
+ for (let i = 0; i < segment.length; i += 1) {
536
+ const char = segment[i];
537
+ if (char === '\\') {
538
+ // `\X` is the literal X and `\<newline>` is a line continuation, so an escaped
539
+ // space never ends a word: `foo\ --help` is one argument.
540
+ const next = segment[i + 1];
541
+ if (next === undefined) {
542
+ text += char;
543
+ started = true;
544
+ continue;
545
+ }
546
+ i += 1;
547
+ if (next !== '\n') text += next;
548
+ started = true;
549
+ continue;
550
+ }
551
+ if (char === "'") {
552
+ // Nothing is escaped inside single quotes.
553
+ const end = segment.indexOf("'", i + 1);
554
+ text += segment.slice(i + 1, end < 0 ? segment.length : end);
555
+ quoted = true;
556
+ started = true;
557
+ i = end < 0 ? segment.length : end;
558
+ continue;
559
+ }
560
+ if (char === '"') {
561
+ // A double-quoted span is one word whatever spaces it holds, and only `\X` and a
562
+ // continuation escape; the quotes the shell would drop are dropped, so a
563
+ // `--help` inside it stays text.
564
+ let inner = '';
565
+ let end = i + 1;
566
+ while (end < segment.length && segment[end] !== '"') {
567
+ const innerChar = segment[end];
568
+ if (innerChar !== '\\') {
569
+ inner += innerChar;
570
+ end += 1;
571
+ continue;
572
+ }
573
+ const next = segment[end + 1];
574
+ if (next === undefined) {
575
+ inner += innerChar;
576
+ end += 1;
577
+ continue;
578
+ }
579
+ end += 2;
580
+ if (next !== '\n') inner += next;
581
+ }
582
+ text += inner;
583
+ quoted = true;
584
+ started = true;
585
+ i = end;
586
+ continue;
587
+ }
588
+ if (/\s/.test(char)) {
589
+ push();
590
+ continue;
591
+ }
592
+ text += char;
593
+ started = true;
594
+ }
595
+ push();
596
+ return words;
597
+ }
598
+
599
+ /** A formatter or a lint fixer rewrites what it reads; its read-only form never does. */
600
+ function isFormattingSegment(segment) {
601
+ // A flag named inside quoted text is not the flag the call passes, while a quoted
602
+ // flag still is: the family match reads the text with quoted spans blanked, and the
603
+ // flags come from the words the shell would hand the formatter.
604
+ if (!matchesAny(FORMATTING_COMMANDS, unquotedSegment(segment))) return false;
605
+ const invocation = formatterInvocation(segment);
606
+ // A formatter whose flags this table knows rewrites unless it reports: `black -l 100
607
+ // .` still rewrites, while `gofmt -l .` only lists what it would change.
608
+ if (invocation === undefined) return !hasFlag(shellWords(segment), FORMAT_READ_ONLY_FLAGS);
609
+ if (invocation.flags.some((flag) => invocation.formatter.write.includes(flag))) return true;
610
+ return !invocation.flags.some((flag) => invocation.formatter.report.includes(flag));
611
+ }
612
+
613
+ /**
614
+ * Whether a segment prepares the environment. A package manager is read through its
615
+ * own subcommand position, so `pnpm -C pkg install` installs like `pnpm install` — the
616
+ * workspace flags a monorepo needs never hide it.
617
+ */
618
+ function isPreparingSegment(segment) {
619
+ // An installer told to list or dry-run changes nothing, so it prepares nothing.
620
+ if (hasFlag(shellWords(segment), PREPARING_READ_ONLY_FLAGS)) return false;
621
+ const script = packageManagerCommand(segment);
622
+ if (script !== undefined) {
623
+ if (PREPARING_SCRIPTS.has(script)) return true;
624
+ // `pnpm config set fund false` stores configuration in the tool's own file.
625
+ return script === 'config' && /\sconfig\s+set\b/.test(segment);
626
+ }
627
+ return matchesAny(PREPARING_COMMANDS, segment);
628
+ }
629
+
630
+ /** A segment verifies work when it runs one of the check families below. */
631
+ function isCheckingSegment(segment) {
632
+ if (matchesAny(CHECKING_COMMANDS, segment)) return true;
633
+ if (matchesAny(FIXABLE_CHECKING_COMMANDS, segment)) return !hasFlag(shellWords(segment), FIX_FLAGS);
634
+ if (isFormatterCheck(segment) || isPackageManagerCheck(segment) || isMakeCheck(segment)) return true;
635
+ // A watchdog bounds how long a check may run without changing what it does, so a
636
+ // runner behind `timeout` still checks. Only the check families are unwrapped:
637
+ // `timeout 5 git status` is not a check and is not inspection either.
638
+ const bounded = timeoutCommand(segment);
639
+ return bounded !== undefined && isCheckingSegment(bounded);
640
+ }
641
+
642
+ /**
643
+ * The command a segment's `timeout` wrapper bounds, or undefined when the segment is
644
+ * not a timeout call. The wrapper's flags, their values and the duration it bounds all
645
+ * precede the command that runs.
646
+ */
647
+ function timeoutCommand(segment) {
648
+ const words = segment.split(/\s+/);
649
+ if (words[0] !== 'timeout') return undefined;
650
+ let index = 1;
651
+ while (index < words.length && (words[index] === undefined ? '' : words[index]).startsWith('-')) {
652
+ const flag = words[index];
653
+ index += 1;
654
+ if (flag === '--') break;
655
+ if (TIMEOUT_VALUE_OPTIONS.has(flag === undefined ? '' : flag)) index += 1;
656
+ }
657
+ // The duration is required and is not part of the command it bounds.
658
+ index += 1;
659
+ return index < words.length ? words.slice(index).join(' ') : undefined;
660
+ }
661
+
662
+ /**
663
+ * The words a simple command passes, with each quoted span folded into the word that
664
+ * carries it: `black "--check" .` passes the flag `--check`, while
665
+ * `prettier 'a --write b.ts'` passes one file name whose text is that name.
666
+ */
667
+ function shellWords(segment) {
668
+ return shellWordTokens(segment).map((word) => word.text);
669
+ }
670
+
671
+ /**
672
+ * The segment's text with every quoted span blanked, except a span that is a
673
+ * flag-shaped word of its own: `black "--check" .` passes that flag, while
674
+ * `prettier 'a --write b.ts'` names one file whose text only looks like one.
675
+ */
676
+ function unquotedSegment(segment) {
677
+ return segment.replace(/"[^"]*"|'[^']*'/g, (quoted) => (/^-\S+$/.test(quoted.slice(1, -1)) ? quoted.slice(1, -1) : ' '));
678
+ }
679
+
680
+ /** Whether any word is one of these flags, with an attached `=value` ignored. */
681
+ function hasFlag(words, flags) {
682
+ return words.some((word) => flags.has(word.split('=')[0] === undefined ? '' : word.split('=')[0]));
683
+ }
684
+
685
+ /**
686
+ * A formatter invocation and the flags it passes, behind an `npx`/`pnpx`/`bunx` or
687
+ * `pnpm exec` style wrapper when it has one. A flag carries its name up to any attached
688
+ * `=value`, and a separately written value (`black -l 100`) is never a flag of its own.
689
+ */
690
+ function formatterInvocation(segment) {
691
+ const words = shellWords(segment);
692
+ let index = 0;
693
+ if (['npx', 'pnpx', 'bunx'].includes(words[0])) index = 1;
694
+ else if (PACKAGE_MANAGERS.has(words[0]) && /^(exec|run)$/.test(words[1] === undefined ? '' : words[1])) index = 2;
695
+ const name = words[index] === undefined ? '' : words[index];
696
+ // The table is a plain object, so a program literally named `constructor` or
697
+ // `__proto__` would otherwise resolve to an inherited member and hand back a
698
+ // "formatter" with no flag lists. A classifier that throws here would break the
699
+ // transcript row it was asked to draw.
700
+ const formatter = Object.hasOwn(FORMATTER_FLAGS, name) ? FORMATTER_FLAGS[name] : undefined;
701
+ if (formatter === undefined) return undefined;
702
+ return { formatter, flags: words.slice(index + 1).map((word) => (word.split('=')[0] === undefined ? word : word.split('=')[0])) };
703
+ }
704
+
705
+ /** A formatter verifies work only when its flags ask it to report. */
706
+ function isFormatterCheck(segment) {
707
+ const invocation = formatterInvocation(segment);
708
+ if (invocation === undefined) return false;
709
+ if (invocation.flags.some((flag) => invocation.formatter.write.includes(flag))) return false;
710
+ return invocation.flags.some((flag) => invocation.formatter.report.includes(flag));
711
+ }
712
+
713
+ /**
714
+ * `pnpm -C pkg test` runs the same script as `pnpm test`, so the workspace flags a
715
+ * monorepo needs must not hide it. Only a listed check script counts: `pnpm install`,
716
+ * `pnpm deploy`, and an unlisted script stay unnamed.
717
+ */
718
+ function isPackageManagerCheck(segment) {
719
+ const script = packageManagerCommand(segment);
720
+ if (script === undefined) return false;
721
+ if (CHECK_RUN_SCRIPTS.has(script) && /(^|\s)run(\s|$)/.test(segment)) return true;
722
+ return isCheckScript(script);
723
+ }
724
+
725
+ /** The package-manager subcommand the segment runs, after its workspace flags. */
726
+ function packageManagerCommand(segment) {
727
+ const words = segment.split(/\s+/);
728
+ if (!PACKAGE_MANAGERS.has(words[0] === undefined ? '' : words[0])) return undefined;
729
+ for (let i = 1; i < words.length; i += 1) {
730
+ const word = words[i] === undefined ? '' : words[i];
731
+ if (PACKAGE_MANAGER_FLAGS.has(word) || word === 'run') continue;
732
+ if (PACKAGE_MANAGER_VALUE_OPTIONS.has(word)) {
733
+ i += 1;
734
+ continue;
735
+ }
736
+ const option = /^(--[a-z-]+)=/.exec(word);
737
+ if (option && PACKAGE_MANAGER_VALUE_OPTIONS.has(option[1])) continue;
738
+ return word;
739
+ }
740
+ return undefined;
741
+ }
742
+
743
+ /**
744
+ * `pnpm run test:unit` and `pnpm check:provider-contract` are the same check families
745
+ * under a namespace, so a `:` suffix keeps its base script's meaning — unless the name
746
+ * itself says the script repairs, reformats, watches or serves something, which is not
747
+ * a check however it is namespaced.
748
+ */
749
+ function isCheckScript(word) {
750
+ if (NON_CHECK_SCRIPT.test(word)) return false;
751
+ return CHECK_SCRIPTS.has(word.split(':')[0] === undefined ? '' : word.split(':')[0]);
752
+ }
753
+
754
+ /**
755
+ * Only a check recipe counts. A bare `make`, and one whose options name no recipe,
756
+ * builds the default target and stays a check, while every recipe named on the command
757
+ * line must be one of them: `make install`, `make deploy` and `make test install` leave
758
+ * the call unnamed.
759
+ */
760
+ function isMakeCheck(segment) {
761
+ const words = segment.split(/\s+/);
762
+ if (words[0] !== 'make') return false;
763
+ for (let i = 1; i < words.length; i += 1) {
764
+ const word = words[i] === undefined ? '' : words[i];
765
+ // `make VAR=1 test` passes a variable, not a recipe.
766
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(word)) continue;
767
+ if (MAKE_VALUE_OPTIONS.has(word)) {
768
+ i += 1;
769
+ continue;
770
+ }
771
+ // A job or load limit takes a count, never a recipe: `make -j 4 test` still names
772
+ // `test`, while `make -j install` names `install`.
773
+ if (MAKE_COUNTED_OPTIONS.has(word)) {
774
+ if (/^\d+$/.test(words[i + 1] === undefined ? '' : words[i + 1])) i += 1;
775
+ continue;
776
+ }
777
+ // Any other option changes how make runs rather than which recipe it runs, so it
778
+ // names no recipe — including an option this list does not know, which is still an
779
+ // option and never a recipe.
780
+ if (word.startsWith('-')) continue;
781
+ if (!MAKE_CHECK_TARGETS.has(word)) return false;
782
+ }
783
+ return true;
784
+ }
785
+
786
+ /**
787
+ * Splits a shell command into simple commands. Top-level `&&`, `||`, `;`, `|`, `&`, and
788
+ * newlines separate them; quoted text never does; and every `$(...)` substitution
789
+ * contributes its own commands, leaving a `$_` placeholder behind. Not a full shell
790
+ * parser: whatever it cannot follow lands in a segment that matches no pattern, so the
791
+ * call stays unnamed.
792
+ *
793
+ * This is the one segmenter: the activity inference above reads it, and so does any
794
+ * other reader that needs the same quote-aware split. A second splitter that ignored
795
+ * quoting would read a separator inside a commit message as a segment boundary and
796
+ * disagree with the card's own identity for the same call.
797
+ */
798
+ function shellCommandSegments(command) {
799
+ const commands = [];
800
+ let current = '';
801
+ let quote;
802
+ for (let i = 0; i < command.length; i += 1) {
803
+ const char = command[i];
804
+ if (quote === "'") {
805
+ current += char;
806
+ if (char === "'") quote = undefined;
807
+ } else if (char === '\\') {
808
+ current += char + (command[i + 1] === undefined ? '' : command[i + 1]);
809
+ i += 1;
810
+ } else if (char === '$' && command[i + 1] === '(') {
811
+ const end = findSubstitutionEnd(command, i + 2);
812
+ if (end < 0) return [...commands, current + command.slice(i)];
813
+ commands.push(...shellCommandSegments(command.slice(i + 2, end)));
814
+ current += '$_';
815
+ i = end;
816
+ } else if (quote === '"') {
817
+ current += char;
818
+ if (char === '"') quote = undefined;
819
+ } else if (char === "'" || char === '"') {
820
+ quote = char;
821
+ current += char;
822
+ } else if (char === '<' && command[i + 1] === '<' && command[i + 2] !== '<') {
823
+ // A heredoc hands its body to the command as data, so the body belongs to the
824
+ // segment that opens it: its own newlines and separators are never commands of
825
+ // their own. A body this reader cannot delimit is left in place, and the split below
826
+ // reads it exactly as it always did.
827
+ const end = heredocEnd(command, i);
828
+ if (end === undefined) {
829
+ current += char;
830
+ } else {
831
+ current += command.slice(i, end);
832
+ i = end - 1;
833
+ }
834
+ } else if (isSeparator(command, i)) {
835
+ commands.push(current);
836
+ current = '';
837
+ if ((char === '|' || char === '&') && command[i + 1] === char) i += 1;
838
+ } else {
839
+ current += char;
840
+ }
841
+ }
842
+ commands.push(current);
843
+ return commands;
844
+ }
845
+
846
+ /**
847
+ * Where the heredoc that opens at `start` ends — the index just past its delimiter line —
848
+ * or undefined when this reader cannot delimit it: a header it cannot read, or a delimiter
849
+ * line that never comes.
850
+ */
851
+ function heredocEnd(command, start) {
852
+ const header = /^<<(-?)\s*(?:'([^']*)'|"([^"]*)"|\\?([A-Za-z_][\w.-]*))/.exec(command.slice(start));
853
+ if (header === null) return undefined;
854
+ const delimiter = header[2] ?? header[3] ?? header[4];
855
+ if (delimiter === undefined || delimiter === '') return undefined;
856
+ // `<<-` strips the leading tabs of every line of the body, the delimiter's own included.
857
+ const stripTabs = header[1] === '-';
858
+ let newline = command.indexOf('\n', start + header[0].length);
859
+ while (newline >= 0) {
860
+ const lineStart = newline + 1;
861
+ const lineEnd = command.indexOf('\n', lineStart);
862
+ const end = lineEnd < 0 ? command.length : lineEnd;
863
+ const line = command.slice(lineStart, end);
864
+ if ((stripTabs ? line.replace(/^\t+/, '') : line) === delimiter) return end;
865
+ newline = lineEnd;
866
+ }
867
+ return undefined;
868
+ }
869
+
870
+ // `&` inside a redirection (`2>&1`, `&>/dev/null`) is not a separator.
871
+ function isSeparator(command, i) {
872
+ const char = command[i];
873
+ if (char === '&') return command[i - 1] !== '>' && command[i + 1] !== '>';
874
+ return char === ';' || char === '|' || char === '\n';
875
+ }
876
+
877
+ // Index of the `)` closing a `$(` whose body starts at `start`, or -1.
878
+ function findSubstitutionEnd(command, start) {
879
+ let depth = 1;
880
+ let quote;
881
+ for (let i = start; i < command.length; i += 1) {
882
+ const char = command[i];
883
+ if (quote) {
884
+ if (char === quote) quote = undefined;
885
+ else if (char === '\\' && quote === '"') i += 1;
886
+ } else if (char === '\\') i += 1;
887
+ else if (char === "'" || char === '"') quote = char;
888
+ else if (char === '(') depth += 1;
889
+ else if (char === ')' && (depth -= 1) === 0) return i;
890
+ }
891
+ return -1;
892
+ }
893
+
894
+ // Drops what the shell reads before the program it runs — harmless redirections
895
+ // (`2>&1`, `2>/dev/null`), leading shell keywords (`do grep x`), environment assignments
896
+ // (`CI=1 pnpm test`), a program named by a path (`/usr/bin/git`, `.venv/bin/pytest`), the
897
+ // global options git and gh accept before their subcommand (`git -C dir status`), a
898
+ // wrapper that only changes how the command runs (`nohup`, `env FOO=1`, `time -p`) — and
899
+ // whitespace. A bare assignment is left intact for NEUTRAL_COMMANDS.
900
+ //
901
+ // Each round removes one layer of that prefix and the loop stops as soon as a round
902
+ // changes nothing, so the work stays linear; a pathological pile of wrappers stops at the
903
+ // bound instead of walking it, which leaves the segment unnamed rather than reading it
904
+ // wrong.
905
+ function stripSegment(segment) {
906
+ let stripped = segment.replace(HARMLESS_REDIRECTS, '').trim();
907
+ for (let round = 0; round < 6; round += 1) {
908
+ const before = stripped;
909
+ while (LEADING_KEYWORDS.test(stripped)) stripped = stripped.replace(LEADING_KEYWORDS, '');
910
+ stripped = stripAssignmentPrefix(stripped);
911
+ stripped = stripProgramPath(stripped);
912
+ stripped = stripToolGlobalOptions(stripped);
913
+ stripped = stripWrapper(stripped);
914
+ if (stripped === before) break;
915
+ }
916
+ return stripped;
917
+ }
918
+
919
+ // Each environment assignment must end at whitespace or the end: an optional separator
920
+ // would let `a=a=a=…` split anywhere and backtrack exponentially.
921
+ const ASSIGNMENT_PREFIX = /^([A-Za-z_][A-Za-z0-9_]*=("[^"]*"|'[^']*'|[^\s"'])*\s+)+(?=\S)/;
922
+
923
+ function stripAssignmentPrefix(segment) {
924
+ return segment.replace(ASSIGNMENT_PREFIX, '');
925
+ }
926
+
927
+ // A program the call names by a path is the program that path resolves to: `/usr/bin/git`
928
+ // and `.venv/bin/pytest` are the same inspection and the same check as their basenames.
929
+ // A path to a program no table names still matches nothing, so this reading never guesses.
930
+ function stripProgramPath(segment) {
931
+ // An assignment's value is not the command the segment runs, and the neutral reading of a
932
+ // bare assignment depends on leaving it whole.
933
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(segment)) return segment;
934
+ const word = /^((?:~|[^\s/]*)(?:\/[^\s/]*)+)(?=\s|$)/.exec(segment);
935
+ if (word === null) return segment;
936
+ const base = word[1].slice(word[1].lastIndexOf('/') + 1);
937
+ if (base === '') return segment;
938
+ return base + segment.slice(word[1].length);
939
+ }
940
+
941
+ // The options git and gh accept BEFORE their subcommand. Each takes the word after it or
942
+ // stands alone; none of them names what the tool does, so `git -C /repo status` is the
943
+ // inspection `git status` is, and a pager or pagination switch never hides a verb. An
944
+ // option neither table knows ends the reading, which leaves the segment unnamed.
945
+ const TOOL_GLOBAL_VALUE_OPTIONS = {
946
+ git: new Set(['-C', '-c', '--git-dir', '--work-tree', '--namespace', '--exec-path']),
947
+ gh: new Set(['-R', '--repo', '--hostname']),
948
+ };
949
+ const TOOL_GLOBAL_FLAGS = {
950
+ git: new Set(['--no-pager', '-P', '--no-optional-locks', '--literal-pathspecs', '--no-replace-objects']),
951
+ gh: new Set(['--paginate']),
952
+ };
953
+
954
+ function stripToolGlobalOptions(segment) {
955
+ const tool = /^(git|gh)(?=\s)/.exec(segment);
956
+ if (tool === null) return segment;
957
+ const values = TOOL_GLOBAL_VALUE_OPTIONS[tool[1]];
958
+ const flags = TOOL_GLOBAL_FLAGS[tool[1]];
959
+ const words = shellWordSpans(segment);
960
+ let index = 1;
961
+ while (index < words.length) {
962
+ const word = words[index].text;
963
+ if (flags.has(word)) {
964
+ index += 1;
965
+ continue;
966
+ }
967
+ const name = word.split('=')[0];
968
+ if (values.has(name === undefined ? '' : name)) {
969
+ index += word.includes('=') ? 1 : 2;
970
+ continue;
971
+ }
972
+ break;
973
+ }
974
+ const rest = words[index];
975
+ return rest === undefined ? segment : `${tool[1]} ${segment.slice(rest.start)}`;
976
+ }
977
+
978
+ // The programs that run the command after them without changing what it does, and the
979
+ // options each one passes on its own. `sudo` is deliberately absent: it runs the command
980
+ // as another user, and a heading must never file a privileged action as the read it
981
+ // resembles. `timeout` is absent too, because this suite pins its reading: a watchdog is
982
+ // unwrapped for a check and for nothing else.
983
+ const WRAPPERS = new Set(['env', 'nice', 'ionice', 'nohup', 'stdbuf', 'command', 'exec', 'time']);
984
+ // Options that take their value as the next word (or attached with `=`) and change
985
+ // nothing about which command runs.
986
+ const WRAPPER_VALUE_OPTIONS = {
987
+ env: new Set(['-u', '--unset', '-C', '--chdir']),
988
+ nice: new Set(['-n', '--adjustment']),
989
+ ionice: new Set(['-c', '--class', '-n', '--classdata']),
990
+ stdbuf: new Set(['-i', '--input', '-o', '--output', '-e', '--error']),
991
+ time: new Set(['-f', '--format']),
992
+ exec: new Set(['-a']),
993
+ };
994
+ // Options whose value is attached to the flag itself (`-c2`, `-oL`, `-10`).
995
+ const WRAPPER_ATTACHED_VALUES = { ionice: /^-[cn].+/, stdbuf: /^-[ioe].+/, nice: /^-\d+$/ };
996
+ // Options that make the command behind the wrapper unreadable: `env -S` splits one string
997
+ // into the command line, `command -v` asks where a program is instead of running it, and
998
+ // `ionice -p`/`time -o` name a process and a report file the call writes.
999
+ const WRAPPER_OPAQUE_OPTIONS = {
1000
+ env: new Set(['-S', '--split-string']),
1001
+ command: new Set(['-v', '-V']),
1002
+ ionice: new Set(['-p', '--pid']),
1003
+ time: new Set(['-o', '--output', '-a', '--append']),
1004
+ };
1005
+
1006
+ /**
1007
+ * The segment's words as spans — where each one starts and ends — so a reader can drop the
1008
+ * prefix the shell reads before the program and keep the rest of the text exactly as it
1009
+ * was written. Rewriting the text would change what an escaped space or a quoted span
1010
+ * means, and `--help` is one reading that depends on it.
1011
+ */
1012
+ const SHELL_WORD_SPAN = /(?:[^\s"'\\]|\\.|"[^"]*"|'[^']*')+/g;
1013
+
1014
+ function shellWordSpans(segment) {
1015
+ const spans = [];
1016
+ SHELL_WORD_SPAN.lastIndex = 0;
1017
+ let match = SHELL_WORD_SPAN.exec(segment);
1018
+ while (match !== null) {
1019
+ spans.push({ text: match[0], start: match.index, end: match.index + match[0].length });
1020
+ match = SHELL_WORD_SPAN.exec(segment);
1021
+ }
1022
+ return spans;
1023
+ }
1024
+
1025
+ /**
1026
+ * The command a wrapper segment runs, or the segment itself when it wraps nothing this
1027
+ * classifier can name — a wrapper with no command left, and one whose own options make
1028
+ * what follows unreadable.
1029
+ */
1030
+ function stripWrapper(segment) {
1031
+ const words = shellWordSpans(segment);
1032
+ if (words.length === 0 || !WRAPPERS.has(words[0].text)) return segment;
1033
+ const program = words[0].text;
1034
+ const values = WRAPPER_VALUE_OPTIONS[program];
1035
+ const opaque = WRAPPER_OPAQUE_OPTIONS[program];
1036
+ const attached = WRAPPER_ATTACHED_VALUES[program];
1037
+ let index = 1;
1038
+ while (index < words.length) {
1039
+ const word = words[index].text;
1040
+ if (word === '--') {
1041
+ index += 1;
1042
+ break;
1043
+ }
1044
+ if (!word.startsWith('-') || word === '-') break;
1045
+ if (opaque !== undefined && opaque.has(word) && !word.includes('=')) return segment;
1046
+ const name = word.split('=')[0];
1047
+ if (values !== undefined && values.has(name === undefined ? '' : name)) {
1048
+ index += word.includes('=') ? 1 : 2;
1049
+ continue;
1050
+ }
1051
+ if (attached !== undefined && attached.test(word)) {
1052
+ index += 1;
1053
+ continue;
1054
+ }
1055
+ // A flag this reader does not know is one the wrapper itself reads: `env -i`,
1056
+ // `nohup --help`, `command -p`. It is skipped, and the command behind it still runs.
1057
+ index += 1;
1058
+ }
1059
+ const rest = words[index];
1060
+ return rest === undefined ? segment : segment.slice(rest.start);
1061
+ }
1062
+
1063
+ // A segment that writes a file (`echo x > out`) is never a no-op.
1064
+ function isNeutral(segment) {
1065
+ return !writesFile(segment) && matchesAny(NEUTRAL_COMMANDS, segment);
1066
+ }
1067
+
1068
+ // Package runners that execute the program they name, and the words their own syntax
1069
+ // puts between them and it: `npx codegraph status` runs it directly, while pnpm, npm,
1070
+ // yarn and bun need their execution subcommand (`pnpm exec codegraph status`). `npm run
1071
+ // codegraph` runs a script of that name, so `run` is deliberately absent: only an
1072
+ // explicit execution of the program is the program. The value is how many launcher
1073
+ // words (the subcommand included) stand before the program.
1074
+ const PROGRAM_RUNNERS = { npx: 1, bunx: 1, pnpx: 1, pnpm: 2, npm: 2, yarn: 2, bun: 2 };
1075
+ const RUN_SUBCOMMANDS = new Set(['exec', 'dlx']);
1076
+ // A launcher that also runs the program it names directly: `yarn codegraph status`
1077
+ // runs the binary, while `yarn exec codegraph status` spells the execution out. Both
1078
+ // are the program; `yarn run codegraph` stays a script of that name.
1079
+ const DIRECT_RUNNERS = new Set(['yarn']);
1080
+
1081
+ // The index of the `codegraph` program a segment runs — written plainly or behind a
1082
+ // path, or executed by a package runner — and -1 when it runs something else: only the
1083
+ // command position names a program, so `echo codegraph init` and `cat codegraph.json`
1084
+ // never match.
1085
+ function codeGraphProgramIndex(words, start) {
1086
+ const program = (value) => /^(?:\S*\/)?codegraph$/.test(value);
1087
+ const word = words[start] === undefined ? '' : words[start];
1088
+ if (program(word)) return start;
1089
+ if (!Object.prototype.hasOwnProperty.call(PROGRAM_RUNNERS, word)) return -1;
1090
+ let index = start + 1;
1091
+ if (PROGRAM_RUNNERS[word] > 1) {
1092
+ // The launcher's own options come before its execution subcommand.
1093
+ while (index < words.length && words[index].startsWith('-')) index += 1;
1094
+ const subcommand = words[index] === undefined ? '' : words[index];
1095
+ if (RUN_SUBCOMMANDS.has(subcommand)) index += 1;
1096
+ else if (!DIRECT_RUNNERS.has(word)) return -1;
1097
+ }
1098
+ while (index < words.length && (words[index].startsWith('-') || words[index] === '--')) index += 1;
1099
+ return program(words[index] === undefined ? '' : words[index]) ? index : -1;
1100
+ }
1101
+
1102
+ /**
1103
+ * The words after a command-position `codegraph` program, or undefined when the segment
1104
+ * runs something else. Every invocation is the program's — the card's detail is the
1105
+ * command it ran — so a flag-only call and an unreadable subcommand are the program too.
1106
+ */
1107
+ function codeGraphCommandWords(segment) {
1108
+ const words = shellWords(segment);
1109
+ let index = 0;
1110
+ while (index < words.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[index] === undefined ? '' : words[index])) index += 1;
1111
+ const at = codeGraphProgramIndex(words, index);
1112
+ return at < 0 ? undefined : words.slice(at + 1);
1113
+ }
1114
+
1115
+ function isReadOnlyInspection(segment) {
1116
+ return !writesFile(segment)
1117
+ && !HIDDEN_SUBSTITUTION.test(segment)
1118
+ && (matchesAny(EXPLORING_COMMANDS, segment) || isGhApiRead(segment) || isGoEnvRead(segment));
1119
+ }
1120
+
1121
+ // The splitter follows `$(...)` but not backticks or `<(...)`, so a command hidden in
1122
+ // one of those never reaches this classifier; `>(...)` is already a file write. A
1123
+ // segment carrying one is ambiguous rather than inspection.
1124
+ const HIDDEN_SUBSTITUTION = /`|<\(/;
1125
+
1126
+ /** `gh api` without a method, field, or input body reads; with one it writes. */
1127
+ function isGhApiRead(segment) {
1128
+ const words = segment.split(/\s+/);
1129
+ if (words[0] !== 'gh' || words[1] !== 'api') return false;
1130
+ return !words.slice(2).some((word) => GH_API_WRITE_FLAGS.has(word.split('=')[0] === undefined ? '' : word.split('=')[0]) || /^-[XfF]./.test(word));
1131
+ }
1132
+
1133
+ /**
1134
+ * `go env` reports the Go configuration, but `-w` stores a value in the env config file
1135
+ * and `-u` unsets one: both write, so neither is inspection.
1136
+ */
1137
+ function isGoEnvRead(segment) {
1138
+ const words = segment.split(/\s+/);
1139
+ if (words[0] !== 'go' || words[1] !== 'env') return false;
1140
+ return !words.slice(2).some((word) => /^-[wu]$/.test(word));
1141
+ }
1142
+
1143
+ // Stream merges and discarded output; neither writes a file.
1144
+ const HARMLESS_REDIRECTS = /\s*(\d?>&\d|&?\d?>\s*\/dev\/null)/g;
1145
+
1146
+ // Output redirection to a file is a write. A `>` inside a quoted span is the program's
1147
+ // own argument (`git commit -m "a > b"`, `git log --format="%h > %s"`), never a
1148
+ // redirect, so only the text the shell would act on counts. Deliberately naive beyond
1149
+ // that: an unbalanced quote keeps its `>`, which only ever leaves the call unnamed.
1150
+ function writesFile(segment) {
1151
+ return unquotedSegment(segment).replace(HARMLESS_REDIRECTS, '').includes('>');
1152
+ }
1153
+
1154
+ function matchesAny(patterns, segment) {
1155
+ return patterns.some((pattern) => pattern.test(segment));
1156
+ }
1157
+
1158
+ module.exports = {
1159
+ SHELL_ACTIVITIES,
1160
+ SHELL_ACTIVITY_IDENTITY,
1161
+ inferBashActivity,
1162
+ isCodegraphCommand,
1163
+ shellCommandSegments,
1164
+ };