pi-odd-worktree 2.1.0 → 3.0.1

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