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,548 @@
1
+ 'use strict';
2
+ // T1, T5 (S1–S6, S8–S11): the worktree guard, decided from one `bash` command string.
3
+ //
4
+ // A worktree is the checkout one ODD owns, and it is created, listed and removed
5
+ // through this package's surfaces — never through Git typed into `bash`. The guard
6
+ // is the net behind that rule: it refuses, before the command runs, the three things
7
+ // a session must not do with Git.
8
+ //
9
+ // S1 a command containing the `git` … `worktree` … `add` sequence, in ANY cwd:
10
+ // the create is `worktree_create`'s.
11
+ // S9 a command containing the `git` … `worktree` … `list` sequence, in ANY cwd:
12
+ // the listing is `worktree_list`'s.
13
+ // S4 in the PRINCIPAL checkout whose CURRENT branch is the default branch, a
14
+ // command that leaves that branch: another ref, `-`, or a detached checkout,
15
+ // also behind `checkout -b|-B|--orphan` and `switch -c|-C|--create|
16
+ // --force-create`, which check out what they create.
17
+ // S6 everything else passes: inspection, file restores, every `git branch` form,
18
+ // `git worktree remove|prune|move`, and every non-`bash` tool call.
19
+ //
20
+ // S3 (L10) is a permission, not a refusal: creating, moving, copying, deleting or
21
+ // listing a branch changes no checkout, so every `git branch` form yields no intent
22
+ // here and is never refused. A branch created and not checked out is exactly what
23
+ // `worktree_create` reclaims.
24
+ //
25
+ // S2 — what "the principal checkout" is: the checkout whose absolute `root` IS the
26
+ // parent of the absolute git common dir. A linked worktree's common dir lives in the
27
+ // principal's `.git`, so its own root never matches, and nothing is refused there. A
28
+ // cwd outside version control, or an identity the seam cannot read, leaves S4 inert
29
+ // (S8); S1 and S9 apply in every cwd, whatever the `cd`s do.
30
+ //
31
+ // S11 — which checkout is judged is the one the command runs in: the segments are
32
+ // walked in order and a `cd <literal path>` moves the effective cwd for the segments
33
+ // after it, resolved against the cwd in force before it. Only a `cd` the shell really
34
+ // runs moves it: text scanned out of a quoted argument (`echo 'cd <path>'`) is
35
+ // argument text and moves nothing, while a `cd` inside a shell script argument
36
+ // (`bash -c '…'`), a `$(…)` substitution or a backtick span does. A `git -C <path>`
37
+ // global option moves one segment the same way — the last `-C` wins, as with git — and
38
+ // that segment is judged in the checkout it names. A `cd` or `-C` argument that is not
39
+ // a literal path (`$VAR`, `~`, `-`, a glob, a backtick) leaves the effective cwd
40
+ // unknown, and an unknown cwd refuses nothing of S4.
41
+ //
42
+ // S4's conditions, exactly as implemented: a switch intent runs in a cwd that is the
43
+ // principal checkout; the repository's default branch resolves (S5, `defaultBranch`);
44
+ // and the branch that checkout is on RIGHT NOW (`currentBranch`) IS that default. Then
45
+ // it is refused when it leaves the branch — a detached checkout, `-`, or any ref but
46
+ // the default. So `git switch main` while on `main` passes, `git switch dev` while on
47
+ // `main` is refused, and the same switch while the checkout is on `dev` passes: the
48
+ // rule protects the default branch, not a habit. A detached HEAD, an unreadable branch
49
+ // or a missing seam is not the default branch, so it refuses nothing (S8). Inside one
50
+ // command the branch advances: a switch that lands on a named branch is where the
51
+ // segments after it stand, so `git switch main && git switch x` cannot hide behind the
52
+ // branch read before the command ran.
53
+ //
54
+ // S5 — the default branch is the repository's own answer, resolved by the caller
55
+ // through the injected `defaultBranch` seam exactly like the create's base: a local
56
+ // `main`, else the branch `origin/HEAD` names, else `init.defaultBranch`. There is no
57
+ // `main`/`master` allowlist here. It is read LAZILY, only for a switch that is already
58
+ // in a principal checkout, so inspection, a restore, a branch create or a worktree
59
+ // command never pays for it. `currentBranch` is asked after it and no earlier, and it
60
+ // is the one fact this module must never see cached: only the checkout knows where it
61
+ // points.
62
+ //
63
+ // The path-vs-ref rule (S4/S6), stated exactly as implemented: `git switch` never
64
+ // takes a path, so what it names is always a ref. `git checkout` names a PATH — a
65
+ // restore, so allowed — only when the argument has no `..` range and that path EXISTS
66
+ // in the cwd in force (the injected `pathExists` seam, asked only for that argument),
67
+ // which is how Git itself settles the ambiguity; a `feat/x`, an `origin/main` or a bare
68
+ // `develop` that is not a path is a ref, and so is every argument when the seam is
69
+ // absent. `git checkout <ref> -- <path>` and `git checkout -- <path>` are always
70
+ // restores. A ref that is not the resolved default branch is a switch away from it, and
71
+ // every segment of a compound command counts.
72
+ //
73
+ // Detection is TEXT ONLY (S1, L2): the command string is split into segments on `&&`,
74
+ // `||`, `|`, `&`, `;` and newlines, and inside `$(…)` and backticks, and the token
75
+ // sequence is looked for in each segment, tolerating git's own global options between
76
+ // `git` and `worktree`/the subcommand (`-C <path>`, `--no-pager`, `-c k=v`). One
77
+ // simple surrounding quote pair is stripped per token; escapes, variables, globs,
78
+ // aliases, redirections, scripts and files are never interpreted, and nothing is read
79
+ // or executed to find out what a command would do. What surrounds the sequence never
80
+ // matters: one occurrence refuses the whole call.
81
+ //
82
+ // Nothing here spawns a child, reads a file or caches anything: `repoIdentity`,
83
+ // `defaultBranch` and `currentBranch` are injected seams, so this module is a pure
84
+ // decision over the command text — it runs on the hot path of every `bash` tool call —
85
+ // and it never throws, because a thrown `tool_call` handler blocks the tool fail-safe
86
+ // (S8).
87
+
88
+ const nodePath = require('node:path');
89
+
90
+ /** S1 (S10): creating a worktree with Git, refused in every cwd. */
91
+ const WORKTREE_ADD_REFUSAL = '`git worktree add` did not run: create the ODD\'s checkout with `worktree_create`.';
92
+
93
+ /** S9 (S10): listing worktrees with Git, refused in every cwd. */
94
+ const WORKTREE_LIST_REFUSAL = '`git worktree list` did not run: use `worktree_list` (`all: true` also shows checkouts outside `<repo-name>-worktrees`).';
95
+
96
+ /** S4 (S10): leaving the default branch of the principal checkout. */
97
+ const BRANCH_SWITCH_REFUSAL = 'The branch switch did not run: the principal checkout stays on its default branch. Create the ODD\'s checkout with `worktree_create`.';
98
+
99
+ /** git's global options that take their value as a SEPARATE argv element. */
100
+ const GIT_GLOBAL_OPTIONS_WITH_VALUE = new Set([
101
+ '-C',
102
+ '-c',
103
+ '--git-dir',
104
+ '--work-tree',
105
+ '--namespace',
106
+ '--super-prefix',
107
+ '--exec-path',
108
+ ]);
109
+
110
+ /** The flags that CREATE a branch AND check it out: they leave the branch too (S4). */
111
+ const CHECKOUT_CREATE_FLAGS = new Set(['-b', '-B', '--orphan']);
112
+ const SWITCH_CREATE_FLAGS = new Set(['-c', '-C', '--create', '--force-create']);
113
+
114
+ /** A nested substitution is scanned, but never descended into without a bound. */
115
+ const MAX_SUBSTITUTION_DEPTH = 8;
116
+
117
+ /** The shells whose `-c` argument is a script that shell really runs (S11). */
118
+ const SHELL_NAMES = /(?:^|\/)(?:bash|sh|zsh|dash|ksh)$/;
119
+
120
+ // ---------------------------------------------------------------------
121
+ // The scanner: one command string -> segment -> token list (S1, S9, L2).
122
+ // ---------------------------------------------------------------------
123
+
124
+ /** The index of the `)` closing the `(` at `open`, or -1 when it never closes. */
125
+ function closingParen(text, open) {
126
+ let depth = 0;
127
+ for (let i = open; i < text.length; i += 1) {
128
+ const ch = text[i];
129
+ if (ch === '(') depth += 1;
130
+ else if (ch === ')') {
131
+ depth -= 1;
132
+ if (depth === 0) return i;
133
+ }
134
+ }
135
+ return -1;
136
+ }
137
+
138
+ /**
139
+ * S11: whether the quote about to be scanned is the script argument of a shell
140
+ * (`bash -c '…'`). That text runs in a shell of its own, so a `cd` inside it moves the
141
+ * cwd; every other quoted span is argument text this shell never runs.
142
+ */
143
+ function isShellScriptArgument(tokens, token) {
144
+ if (token !== null && token !== '-c') return false;
145
+ const last = token === null ? tokens[tokens.length - 1] : token;
146
+ if (last !== '-c') return false;
147
+ const before = token === null ? tokens[tokens.length - 2] : tokens[tokens.length - 1];
148
+ return typeof before === 'string' && SHELL_NAMES.test(before);
149
+ }
150
+
151
+ /**
152
+ * Split one command into segments of tokens. Separators end a segment; a `$(…)`
153
+ * substitution and a backtick span are scanned as text of their own (their inner
154
+ * command is a segment too), which is the whole of the "compound" handling. One
155
+ * simple surrounding quote pair per token is stripped, and nothing else about the
156
+ * text is interpreted. Each segment records whether a shell really runs it (`real`):
157
+ * a substitution or a shell script argument does, plain quoted argument text does
158
+ * not, and only a `cd` a shell runs moves the effective cwd (S11).
159
+ */
160
+ function scanSegments(text, out, depth, real) {
161
+ let tokens = [];
162
+ let token = null;
163
+ const flushToken = () => {
164
+ if (token !== null) {
165
+ tokens.push(token);
166
+ token = null;
167
+ }
168
+ };
169
+ const flushSegment = () => {
170
+ flushToken();
171
+ if (tokens.length > 0) out.push({ tokens, real });
172
+ tokens = [];
173
+ };
174
+ const append = (value) => {
175
+ token = (token === null ? '' : token) + value;
176
+ };
177
+ let i = 0;
178
+ while (i < text.length) {
179
+ const ch = text[i];
180
+ if (ch === "'" || ch === '"') {
181
+ // One simple pair: its content is the token's text, and a separator inside it
182
+ // never splits. No escape is interpreted, so an unterminated quote simply runs
183
+ // to the end of what it opened. Both kinds are scanned again as text of their
184
+ // own: a double-quoted span holds the substitutions a shell would run, and a
185
+ // single-quoted one holds the command `bash -c '…'` hands to a shell. The
186
+ // guard reads text and nothing else (L2), so what surrounds the sequence
187
+ // never matters.
188
+ const end = text.indexOf(ch, i + 1);
189
+ const inner = end < 0 ? text.slice(i + 1) : text.slice(i + 1, end);
190
+ const script = real && isShellScriptArgument(tokens, token);
191
+ append(inner);
192
+ i = end < 0 ? text.length : end + 1;
193
+ if (depth < MAX_SUBSTITUTION_DEPTH) scanSegments(inner, out, depth + 1, script);
194
+ continue;
195
+ }
196
+ if (ch === '`') {
197
+ const end = text.indexOf('`', i + 1);
198
+ const inner = end < 0 ? text.slice(i + 1) : text.slice(i + 1, end);
199
+ i = end < 0 ? text.length : end + 1;
200
+ flushToken();
201
+ if (depth < MAX_SUBSTITUTION_DEPTH) scanSegments(inner, out, depth + 1, real);
202
+ continue;
203
+ }
204
+ if (ch === '$' && text[i + 1] === '(') {
205
+ const close = closingParen(text, i + 1);
206
+ const inner = close < 0 ? text.slice(i + 2) : text.slice(i + 2, close);
207
+ i = close < 0 ? text.length : close + 1;
208
+ flushToken();
209
+ if (depth < MAX_SUBSTITUTION_DEPTH) scanSegments(inner, out, depth + 1, real);
210
+ continue;
211
+ }
212
+ if (ch === ' ' || ch === '\t') {
213
+ flushToken();
214
+ i += 1;
215
+ continue;
216
+ }
217
+ if (ch === '\n' || ch === '\r') {
218
+ flushSegment();
219
+ i += 1;
220
+ continue;
221
+ }
222
+ if (ch === '(' || ch === ')') {
223
+ // A subshell `( … )`: the command inside starts a segment of its own.
224
+ flushSegment();
225
+ i += 1;
226
+ continue;
227
+ }
228
+ if (ch === '&' || ch === '|' || ch === ';') {
229
+ flushSegment();
230
+ i += 1;
231
+ // `&&`, `||`, `|&`, `;;`: one separator, however it is spelled.
232
+ while (i < text.length && (text[i] === '&' || text[i] === '|' || text[i] === ';')) i += 1;
233
+ continue;
234
+ }
235
+ append(ch);
236
+ i += 1;
237
+ }
238
+ flushSegment();
239
+ return out;
240
+ }
241
+
242
+ /** Every segment of one command string, or an empty list when there is none. */
243
+ function scanCommand(command) {
244
+ const segments = [];
245
+ try {
246
+ // A backslash-newline is a line continuation: the shell reads it as nothing.
247
+ scanSegments(command.replace(/\\\r?\n/g, ' '), segments, 0, true);
248
+ } catch {
249
+ // A command this scanner cannot read is not a command it can judge: it passes.
250
+ return [];
251
+ }
252
+ return segments;
253
+ }
254
+
255
+ // ---------------------------------------------------------------------
256
+ // The detectors: what one segment's tokens name (S1, S3, S4, S9).
257
+ // ---------------------------------------------------------------------
258
+
259
+ /**
260
+ * One `git` invocation: the index of its subcommand (-1 when its global options run
261
+ * out) and the cwd it runs in. Only the options that take a separate value consume
262
+ * the next token, so `git -C <path> worktree add` and `git --no-pager worktree add`
263
+ * both reach `worktree`. `git -C <path>` runs the invocation in another checkout — the
264
+ * last `-C` wins, as it does in git, and its argument is resolved like a `cd` target
265
+ * (S11) against the cwd in force for the segment.
266
+ */
267
+ function gitInvocation(tokens, gitIndex, cwd) {
268
+ let i = gitIndex + 1;
269
+ let effective = cwd;
270
+ while (i < tokens.length) {
271
+ const token = tokens[i];
272
+ if (!token.startsWith('-') || token.length < 2) break;
273
+ if (token === '-C') {
274
+ const target = tokens[i + 1];
275
+ effective = effective === undefined || !isLiteralCdTarget(target)
276
+ ? undefined
277
+ : nodePath.resolve(effective, target);
278
+ i += 2;
279
+ continue;
280
+ }
281
+ i += GIT_GLOBAL_OPTIONS_WITH_VALUE.has(token) ? 2 : 1;
282
+ }
283
+ return { subcommand: i < tokens.length ? i : -1, cwd: effective };
284
+ }
285
+
286
+ /** The index of the token after those global options, or -1 when they run out. */
287
+ function gitSubcommandIndex(tokens, gitIndex) {
288
+ return gitInvocation(tokens, gitIndex, undefined).subcommand;
289
+ }
290
+
291
+ /** Every `git` token in a segment, by index. */
292
+ function gitIndices(tokens) {
293
+ const found = [];
294
+ for (let i = 0; i < tokens.length; i += 1) {
295
+ if (tokens[i] === 'git' || tokens[i].endsWith('/git')) found.push(i);
296
+ }
297
+ return found;
298
+ }
299
+
300
+ /** S1/S9: the worktree verb this segment names, or undefined. */
301
+ function worktreeIntent(tokens) {
302
+ for (const gitIndex of gitIndices(tokens)) {
303
+ const subcommand = gitSubcommandIndex(tokens, gitIndex);
304
+ if (subcommand < 0 || tokens[subcommand] !== 'worktree') continue;
305
+ const verb = tokens[subcommand + 1];
306
+ if (verb === 'add') return 'add';
307
+ if (verb === 'list') return 'list';
308
+ }
309
+ return undefined;
310
+ }
311
+
312
+ /**
313
+ * The path-vs-ref rule of S4/S6 for `git checkout`: an argument names a PATH (a
314
+ * restore) only when it has no `..` range and that path exists in the cwd, which is
315
+ * how Git itself settles the ambiguity. Everything else, and every argument without
316
+ * the seam, names a ref.
317
+ */
318
+ function isPathArgument(value, pathExists) {
319
+ if (typeof pathExists !== 'function') return false;
320
+ if (value.includes('..')) return false;
321
+ try {
322
+ return pathExists(value) === true;
323
+ } catch {
324
+ return false;
325
+ }
326
+ }
327
+
328
+ /** S4: what the `git` at `subcommand` does to the branch, or undefined. `git branch`
329
+ * never appears here: it changes no checkout, whatever it creates (S3). */
330
+ function switchIntentAt(tokens, subcommand, pathExists) {
331
+ const name = tokens[subcommand];
332
+ if (name !== 'checkout' && name !== 'switch') return undefined;
333
+ const rest = tokens.slice(subcommand + 1);
334
+ const createFlags = name === 'checkout' ? CHECKOUT_CREATE_FLAGS : SWITCH_CREATE_FLAGS;
335
+ let detached = false;
336
+ let i = 0;
337
+ for (; i < rest.length; i += 1) {
338
+ const token = rest[i];
339
+ // `git checkout -` is the previous branch: a ref, never an option.
340
+ if (token === '-') break;
341
+ // `git checkout -- <path>`: from here on the arguments are paths, so nothing
342
+ // switches.
343
+ if (token === '--') return undefined;
344
+ if (!token.startsWith('-') || token.length < 2) break;
345
+ // A long `--flag=value` token names its value itself: normalise the pair first, so
346
+ // `switch --create=x`, `switch --force-create=x` and `checkout --orphan=x` are the
347
+ // same creates as their spaced spelling and leave the branch too.
348
+ const equals = token.startsWith('--') ? token.indexOf('=') : -1;
349
+ const flag = equals > 0 ? token.slice(0, equals) : token;
350
+ // `-b <name>` / `-cx`: creating a branch and checking it out leaves the current
351
+ // branch too, whatever it creates first.
352
+ const attached = name === 'checkout' ? ['-b', '-B'] : ['-c', '-C'];
353
+ if (createFlags.has(flag)) {
354
+ return { ref: equals > 0 ? token.slice(equals + 1) : rest[i + 1], detached: false };
355
+ }
356
+ if (attached.some((short) => flag.startsWith(short) && !flag.startsWith('--'))) {
357
+ return { ref: rest[i + 1], detached: false };
358
+ }
359
+ if (flag === '--detach' || flag === '-d') detached = true;
360
+ }
361
+ // No branch argument: an inspection, not a switch — except `--detach` alone, which
362
+ // leaves the branch for a detached HEAD.
363
+ if (i >= rest.length) return detached ? { ref: undefined, detached: true } : undefined;
364
+ const ref = rest[i];
365
+ // `git checkout <ref> -- <path>` restores the path from the ref and switches nothing.
366
+ if (name === 'checkout' && rest.slice(i + 1).includes('--')) return undefined;
367
+ // `git switch` never takes a path; `git checkout` restores a path that exists.
368
+ if (name === 'checkout' && ref !== '-' && isPathArgument(ref, pathExists)) return undefined;
369
+ return { ref, detached };
370
+ }
371
+
372
+ // ---------------------------------------------------------------------
373
+ // The seams: which checkout this is, and its default branch (S2, S5, S8).
374
+ // ---------------------------------------------------------------------
375
+
376
+ /**
377
+ * S2: the principal checkout's root, or undefined when the cwd is another checkout,
378
+ * no repository, or an identity the seam cannot answer. Never throws.
379
+ */
380
+ function principalRootOf(repoIdentity, cwd) {
381
+ if (typeof repoIdentity !== 'function') return undefined;
382
+ if (typeof cwd !== 'string' || cwd.length === 0) return undefined;
383
+ try {
384
+ const identity = repoIdentity(cwd);
385
+ if (!identity || typeof identity.root !== 'string' || typeof identity.commonDir !== 'string') return undefined;
386
+ const root = nodePath.resolve(identity.root);
387
+ // A linked worktree shares the principal's common dir, so its root is never that
388
+ // dir's parent; the principal's own root always is.
389
+ if (nodePath.dirname(nodePath.resolve(identity.commonDir)) !== root) return undefined;
390
+ return root;
391
+ } catch {
392
+ return undefined;
393
+ }
394
+ }
395
+
396
+ /** S5: the repository's default branch as the seam answers it. Never throws. */
397
+ function defaultBranchOf(readDefaultBranch, root) {
398
+ if (typeof readDefaultBranch !== 'function') return undefined;
399
+ try {
400
+ const name = readDefaultBranch(root);
401
+ if (typeof name !== 'string') return undefined;
402
+ const trimmed = name.trim();
403
+ return trimmed.length > 0 ? trimmed : undefined;
404
+ } catch {
405
+ return undefined;
406
+ }
407
+ }
408
+
409
+ /**
410
+ * S4: the branch that checkout is on RIGHT NOW, as the seam answers it, or undefined
411
+ * for a detached HEAD and for a read that fails. Never throws.
412
+ */
413
+ function currentBranchOf(readCurrentBranch, root) {
414
+ if (typeof readCurrentBranch !== 'function') return undefined;
415
+ try {
416
+ const name = readCurrentBranch(root);
417
+ if (typeof name !== 'string') return undefined;
418
+ const trimmed = name.trim();
419
+ return trimmed.length > 0 ? trimmed : undefined;
420
+ } catch {
421
+ return undefined;
422
+ }
423
+ }
424
+
425
+ /** S11: a `cd` target the guard can take literally — no variable, home, glob or backtick. */
426
+ function isLiteralCdTarget(value) {
427
+ if (typeof value !== 'string' || value.length === 0) return false;
428
+ if (value === '-') return false;
429
+ return !/[$~`*?[\]]/.test(value);
430
+ }
431
+
432
+ /**
433
+ * S11: each segment with the cwd in force when it runs. A `cd <literal path>` a shell
434
+ * really runs moves it for the segments after it, resolved against the cwd in force
435
+ * before it; anything else — quoted argument text, a missing or non-literal argument,
436
+ * or a cwd already unknown — leaves it unknown, and an unknown cwd refuses nothing of
437
+ * S4 (S8). S1 and S9 were answered before this walk, so they stay any-cwd.
438
+ */
439
+ function segmentsWithCwd(segments, cwd) {
440
+ let effective = typeof cwd === 'string' && cwd.length > 0 ? cwd : undefined;
441
+ const walked = [];
442
+ for (const { tokens, real } of segments) {
443
+ walked.push({ tokens, cwd: effective });
444
+ if (!real) continue;
445
+ const head = tokens[0];
446
+ if (typeof head !== 'string' || (head !== 'cd' && !head.endsWith('/cd'))) continue;
447
+ effective = effective === undefined || !isLiteralCdTarget(tokens[1])
448
+ ? undefined
449
+ : nodePath.resolve(effective, tokens[1]);
450
+ }
451
+ return walked;
452
+ }
453
+
454
+ /** S4/S8: whether this switch leaves the default branch. An unknown default never refuses. */
455
+ function switchLeavesDefault(intent, defaultBranch) {
456
+ if (intent.detached === true) return true;
457
+ if (intent.ref === '-') return true;
458
+ if (defaultBranch === undefined) return false; // no false block (S8)
459
+ return intent.ref !== defaultBranch;
460
+ }
461
+
462
+ // ---------------------------------------------------------------------
463
+ // The decision (S1–S6, S8–S10).
464
+ // ---------------------------------------------------------------------
465
+
466
+ /**
467
+ * Decide one `bash` tool call: `{block: false}`, or `{block: true, reason}` with the
468
+ * one sentence the session reads. Inputs: `toolName`, `command`, `cwd`, and the seams
469
+ * `repoIdentity(cwd)` (sync; `{root, commonDir}` at least), `defaultBranch(root)` (sync;
470
+ * the repository's default branch name or undefined), `currentBranch(root)` (sync; the
471
+ * branch that checkout is on right now, undefined when detached or unreadable) and
472
+ * `pathExists(cwd, value)` (sync; whether `value` is an existing path there).
473
+ * Never throws.
474
+ */
475
+ function decideBashGuard(input) {
476
+ try {
477
+ if (!input || input.toolName !== 'bash') return { block: false };
478
+ const command = input.command;
479
+ if (typeof command !== 'string' || command.length === 0) return { block: false };
480
+ const segments = scanCommand(command);
481
+ if (segments.length === 0) return { block: false };
482
+
483
+ // S1 and S9 are text-only and apply in every cwd, so they are answered first,
484
+ // before anything reads the repository at all.
485
+ for (const { tokens } of segments) {
486
+ const verb = worktreeIntent(tokens);
487
+ if (verb === 'add') return { block: true, reason: WORKTREE_ADD_REFUSAL };
488
+ if (verb === 'list') return { block: true, reason: WORKTREE_LIST_REFUSAL };
489
+ }
490
+
491
+ // S4 is the only rule left, and it needs a switch to judge: without one nothing
492
+ // is read at all.
493
+ const hasPathSeam = typeof input.pathExists === 'function';
494
+ // One answer per checkout for the whole call: a `cd` or a `git -C` may move between
495
+ // two of them, and the default branch never changes inside one command. What DOES
496
+ // change is the branch the checkout is on: a switch that lands on a named branch is
497
+ // where the rest of the command stands, so it is read once and then advanced.
498
+ const defaults = new Map();
499
+ const currents = new Map();
500
+
501
+ // S11: every segment is judged in the cwd in force when it runs, in order, and
502
+ // every `git -C` in it in the checkout that invocation names.
503
+ for (const { tokens, cwd } of segmentsWithCwd(segments, input.cwd)) {
504
+ for (const gitIndex of gitIndices(tokens)) {
505
+ const invocation = gitInvocation(tokens, gitIndex, cwd);
506
+ if (invocation.subcommand < 0) continue;
507
+ const pathExists = hasPathSeam && typeof invocation.cwd === 'string'
508
+ ? (value) => input.pathExists(invocation.cwd, value)
509
+ : undefined;
510
+ const intent = switchIntentAt(tokens, invocation.subcommand, pathExists);
511
+ if (intent === undefined) continue;
512
+
513
+ // S2: the switch is judged in the checkout it runs in. An unknown cwd, a
514
+ // linked worktree and a cwd outside version control all stop here.
515
+ const principal = principalRootOf(input.repoIdentity, invocation.cwd);
516
+ if (principal === undefined) continue;
517
+ // S5: the default branch, read only now that a switch is actually judged. With
518
+ // none resolvable nothing is refused (S8), because the real default must stay
519
+ // reachable.
520
+ if (!defaults.has(principal)) defaults.set(principal, defaultBranchOf(input.defaultBranch, principal));
521
+ const defaultBranch = defaults.get(principal);
522
+ if (defaultBranch === undefined) continue;
523
+ // S4: only a checkout that is ON the default branch can leave it. A detached
524
+ // HEAD or a branch the seam cannot name is not the default branch, so a switch
525
+ // there is allowed and `currentBranch` is the one fact never memoized.
526
+ if (!currents.has(principal)) currents.set(principal, currentBranchOf(input.currentBranch, principal));
527
+ if (currents.get(principal) === defaultBranch && switchLeavesDefault(intent, defaultBranch)) {
528
+ return { block: true, reason: BRANCH_SWITCH_REFUSAL };
529
+ }
530
+ // S4: the branch the command moved to is the branch the segments after it
531
+ // leave, so `git switch main && git switch x` is judged from `main`. A detached
532
+ // checkout and `-` (the previous branch) name no branch to carry.
533
+ if (intent.detached !== true && typeof intent.ref === 'string' && intent.ref !== '-') {
534
+ currents.set(principal, intent.ref);
535
+ }
536
+ }
537
+ }
538
+ return { block: false };
539
+ } catch {
540
+ // S8: a throwing `tool_call` handler blocks the tool fail-safe, so nothing here
541
+ // may escape — an undecidable command simply passes.
542
+ return { block: false };
543
+ }
544
+ }
545
+
546
+ module.exports = {
547
+ decideBashGuard,
548
+ };