pi-odd-worktree 2.1.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/README.md +54 -319
  2. package/extensions/odd-worktree-tools.ts +4145 -2529
  3. package/lib/bash-activity.js +1164 -0
  4. package/lib/bash-design.js +684 -0
  5. package/lib/bash-destructive.js +559 -0
  6. package/lib/bash-frame.js +205 -0
  7. package/lib/card-content.js +23 -0
  8. package/lib/card-style.js +175 -0
  9. package/lib/checkout-facts.js +30 -70
  10. package/lib/codegraph-card-preview.js +628 -0
  11. package/lib/codegraph-card.js +515 -0
  12. package/lib/codegraph-compaction.js +76 -0
  13. package/lib/codegraph-daemon.js +246 -0
  14. package/lib/codegraph-edit-sync.js +182 -0
  15. package/lib/codegraph-guard-target.js +337 -0
  16. package/lib/codegraph-guard.js +211 -0
  17. package/lib/codegraph-index.js +1020 -0
  18. package/lib/codegraph-lock.js +607 -0
  19. package/lib/codegraph-mcp-config.js +134 -0
  20. package/lib/codegraph-mcp.js +123 -0
  21. package/lib/codegraph-paths.js +69 -0
  22. package/lib/codegraph-prompt/explore.md +11 -0
  23. package/lib/codegraph-prompt/fix.md +6 -0
  24. package/lib/codegraph-prompt/generic.md +8 -0
  25. package/lib/codegraph-prompt/judge.md +9 -0
  26. package/lib/codegraph-prompt/orchestrator.md +17 -0
  27. package/lib/codegraph-prompt/verify.md +10 -0
  28. package/lib/codegraph-prompt/worker.md +7 -0
  29. package/lib/codegraph-role.js +55 -0
  30. package/lib/codegraph-rules.js +146 -0
  31. package/lib/codegraph-session.js +303 -383
  32. package/lib/codegraph-warmup.js +139 -0
  33. package/lib/file-card-markdown.js +141 -0
  34. package/lib/file-card-resolver.js +245 -0
  35. package/lib/file-card.js +659 -0
  36. package/lib/files-index.js +387 -0
  37. package/lib/files-insert.js +81 -0
  38. package/lib/files-orders.js +326 -0
  39. package/lib/files-picker-view.js +1416 -0
  40. package/lib/files-preview.js +338 -0
  41. package/lib/files-scope-detail.js +171 -0
  42. package/lib/files-scope-view.js +507 -0
  43. package/lib/gh-issues.js +308 -14
  44. package/lib/issue-preview.js +26 -7
  45. package/lib/issues-bash-mutation.js +206 -0
  46. package/lib/issues-cache-store.js +261 -0
  47. package/lib/issues-section.js +710 -0
  48. package/lib/issues-view.js +649 -52
  49. package/lib/odd-prompt/odd-worktrees.md +21 -0
  50. package/lib/odd-worktrees-prompt.js +10 -28
  51. package/lib/related-issues-cache.js +210 -0
  52. package/lib/shell-card.js +825 -0
  53. package/lib/skill-odd-card.js +183 -0
  54. package/lib/tui-paint.js +4 -5
  55. package/lib/warp-create-panel.js +538 -250
  56. package/lib/warp-create-picker.js +56 -9
  57. package/lib/warp-delete-confirm.js +19 -28
  58. package/lib/warp-selector-view.js +160 -82
  59. package/lib/which-command.js +90 -0
  60. package/lib/worktree-card.js +267 -897
  61. package/lib/worktree-cards.js +383 -0
  62. package/lib/worktree-create.js +287 -0
  63. package/lib/worktree-git.js +3 -3
  64. package/lib/worktree-guard.js +548 -0
  65. package/lib/worktree-hooks.js +421 -712
  66. package/lib/worktree-list.js +120 -0
  67. package/lib/worktree-registry.js +162 -879
  68. package/lib/{worktree-close-herdr.js → worktree-remove.js} +9 -11
  69. package/lib/worktree-setup-runner.js +376 -0
  70. package/lib/worktree-setup.js +140 -0
  71. package/lib/worktree-warp-busy.js +462 -85
  72. package/lib/worktree-warp-sessions.js +1 -2
  73. package/package.json +2 -2
  74. package/tools/bash-activity.test.js +1419 -0
  75. package/tools/bash-design.test.js +1091 -0
  76. package/tools/bash-destructive.test.js +139 -0
  77. package/tools/card-content.test.js +44 -0
  78. package/tools/card-style.test.js +298 -0
  79. package/tools/codegraph-card-preview.test.js +254 -0
  80. package/tools/codegraph-card.test.js +1080 -0
  81. package/tools/codegraph-compaction.test.js +378 -0
  82. package/tools/codegraph-daemon.test.js +248 -0
  83. package/tools/codegraph-edit-sync.test.js +295 -0
  84. package/tools/codegraph-guard-target.test.js +174 -0
  85. package/tools/codegraph-guard.test.js +238 -0
  86. package/tools/codegraph-index.test.js +1948 -0
  87. package/tools/codegraph-lock.test.js +932 -0
  88. package/tools/codegraph-mcp-config.test.js +181 -0
  89. package/tools/codegraph-mcp.test.js +194 -0
  90. package/tools/codegraph-paths.test.js +44 -0
  91. package/tools/codegraph-role.test.js +30 -0
  92. package/tools/codegraph-rules.test.js +250 -0
  93. package/tools/codegraph-session.test.js +660 -391
  94. package/tools/codegraph-warmup.test.js +316 -0
  95. package/tools/commands.test.js +510 -31
  96. package/tools/file-card-markdown.test.js +188 -0
  97. package/tools/file-card.test.js +1289 -0
  98. package/tools/files-bridge.test.js +575 -0
  99. package/tools/files-command.test.js +610 -0
  100. package/tools/files-index.test.js +473 -0
  101. package/tools/files-insert.test.js +139 -0
  102. package/tools/files-orders.test.js +597 -0
  103. package/tools/files-picker-view.test.js +1871 -0
  104. package/tools/files-preview.test.js +452 -0
  105. package/tools/files-scope-detail.test.js +264 -0
  106. package/tools/files-scope-view.test.js +614 -0
  107. package/tools/fixtures/card-codegraph-outputs.js +110 -0
  108. package/tools/fixtures/codegraph-cli-stub.js +16 -0
  109. package/tools/fixtures/codegraph-init-process.js +28 -0
  110. package/tools/fixtures/codegraph-lock-worker.js +117 -0
  111. package/tools/fixtures/daemon-fake.js +98 -0
  112. package/tools/fixtures/daemon-mcp-server.js +39 -0
  113. package/tools/fixtures/daemon-warmup-worker.js +12 -0
  114. package/tools/fixtures/load-extension.js +136 -3
  115. package/tools/gh-issues-feedback.test.js +31 -7
  116. package/tools/gh-issues.test.js +391 -1
  117. package/tools/issue-preview.test.js +44 -7
  118. package/tools/issues-bash-mutation.test.js +101 -0
  119. package/tools/issues-cache-store.test.js +222 -0
  120. package/tools/issues-command.test.js +1512 -66
  121. package/tools/issues-open-guard.test.js +1096 -0
  122. package/tools/issues-section.test.js +4195 -0
  123. package/tools/issues-seed-query-regression.test.js +67 -0
  124. package/tools/issues-view.test.js +1489 -60
  125. package/tools/odd-worktrees-prompt.test.js +98 -65
  126. package/tools/package-surface.test.js +431 -36
  127. package/tools/related-issues-cache.test.js +324 -0
  128. package/tools/shell-card.test.js +834 -0
  129. package/tools/skill-odd-card.test.js +200 -0
  130. package/tools/t5-session-identity.test.js +44 -22
  131. package/tools/warp-busy-guard.test.js +2565 -309
  132. package/tools/warp-create-panel.test.js +499 -74
  133. package/tools/warp-create-picker.test.js +101 -5
  134. package/tools/warp-delete-confirm.test.js +49 -15
  135. package/tools/warp-empty-session.test.js +0 -1
  136. package/tools/warp-fallback-regression.test.js +533 -0
  137. package/tools/warp-selector-view.test.js +460 -196
  138. package/tools/which-command.test.js +126 -0
  139. package/tools/worktree-card.test.js +551 -0
  140. package/tools/worktree-cards.test.js +845 -0
  141. package/tools/worktree-changes.test.js +4 -5
  142. package/tools/worktree-create.test.js +489 -0
  143. package/tools/worktree-guard.test.js +823 -0
  144. package/tools/worktree-hooks.test.js +905 -0
  145. package/tools/worktree-list.test.js +170 -0
  146. package/tools/worktree-registry.test.js +89 -230
  147. package/tools/worktree-remove-async.test.js +318 -0
  148. package/tools/worktree-setup-runner.test.js +276 -0
  149. package/tools/worktree-setup.test.js +140 -0
  150. package/tools/worktree-tools.test.js +419 -199
  151. package/lib/codegraph-commands.js +0 -165
  152. package/lib/odd-prompt/odd-worktrees.with-codegraph.md +0 -19
  153. package/lib/odd-prompt/odd-worktrees.without-codegraph.md +0 -15
  154. package/lib/worktree-model-result.js +0 -291
  155. package/tools/codegraph-commands.test.js +0 -371
  156. package/tools/herdr-free-create.test.js +0 -161
  157. package/tools/worktree-close-herdr-async.test.js +0 -204
  158. package/tools/worktree-odd-migration.test.js +0 -224
  159. package/tools/worktree-registry-cache.test.js +0 -163
  160. package/tools/worktree-registry-odd.test.js +0 -231
@@ -0,0 +1,337 @@
1
+ 'use strict';
2
+ // T2 (S3, S4, S8): which checkout a finished search or read call went to.
3
+ //
4
+ // The call alone says where it looked. `grep`, `find` and `ls` name a path (or default to the session's
5
+ // checkout); `read` opens one file, and only a code file counts; `bash` is read as a shell, so a `cd`
6
+ // target and the absolute paths its search or read verbs pass are the places it went. The git toplevel
7
+ // of a directory is the only checkout identity, read once per directory through one fixed-argv child
8
+ // (`git -C <dir> rev-parse --show-toplevel`) and cached, so a later call never waits for git twice.
9
+ //
10
+ // A directory outside every checkout is no checkout at all: nothing here invents one, and nothing here
11
+ // ever throws into the host. Parsing is pure; the resolution takes an injected `toplevel`.
12
+
13
+ const nodeFs = require('node:fs');
14
+ const nodePath = require('node:path');
15
+
16
+ const { gitToplevel } = require('./codegraph-edit-sync.js');
17
+
18
+ /** The built-in tools a finished call is read from, besides this package's own `bash` reading. */
19
+ const SEARCH_TOOLS = ['grep', 'find', 'ls', 'read'];
20
+
21
+ /** The extensions the CodeGraph rule exempts: a config or a doc is not the code the graph indexes. */
22
+ const DOC_EXTENSIONS = ['.md', '.json', '.yml', '.yaml', '.toml', '.txt'];
23
+
24
+ /** The programs whose presence makes a `bash` command a search or a read of code. */
25
+ const READ_VERBS = ['grep', 'rg', 'find', 'fd', 'ls', 'cat', 'sed', 'head', 'tail', 'awk', 'tree'];
26
+
27
+ /** The verbs whose first non-flag argument is a pattern or a script, never a path. */
28
+ const EXPRESSION_FIRST = ['grep', 'rg', 'fd', 'sed', 'awk'];
29
+
30
+ /** Whether a file is code: an extension the rule exempts is a doc or a config, everything else is code. */
31
+ function isCodeFile(file) {
32
+ const extension = nodePath.extname(typeof file === 'string' ? file : '').toLowerCase();
33
+ return extension.length === 0 || !DOC_EXTENSIONS.includes(extension);
34
+ }
35
+
36
+ // ---- the shell reading (S3) ----
37
+
38
+ // The index of the `)` closing a `$(` whose body starts at `start`, or -1.
39
+ function substitutionEnd(command, start) {
40
+ let depth = 1;
41
+ for (let i = start; i < command.length; i += 1) {
42
+ const char = command[i];
43
+ if (char === '\\') i += 1;
44
+ else if (char === '(') depth += 1;
45
+ else if (char === ')') {
46
+ depth -= 1;
47
+ if (depth === 0) return i;
48
+ }
49
+ }
50
+ return -1;
51
+ }
52
+
53
+ /**
54
+ * A shell command as the simple commands it runs, split on `;`, `&&`, `||`, `|` and newlines. Quotes are
55
+ * respected, and a `$(...)` body is read as one opaque word: a command hidden there is not one this
56
+ * reader claims, so it is never counted on its own.
57
+ */
58
+ function shellSegments(command) {
59
+ const segments = [];
60
+ const piped = [];
61
+ let afterPipe = false;
62
+ const flush = (nextAfterPipe) => {
63
+ segments.push(current);
64
+ piped.push(afterPipe);
65
+ afterPipe = nextAfterPipe;
66
+ current = '';
67
+ };
68
+ let current = '';
69
+ let quote;
70
+ let i = 0;
71
+ while (i < command.length) {
72
+ const char = command[i];
73
+ if (quote !== undefined) {
74
+ current += char;
75
+ if (char === '\\' && quote === '"' && command[i + 1] !== undefined) {
76
+ current += command[i + 1];
77
+ i += 1;
78
+ } else if (char === quote) {
79
+ quote = undefined;
80
+ }
81
+ i += 1;
82
+ continue;
83
+ }
84
+ if (char === '\\') {
85
+ current += char + (command[i + 1] === undefined ? '' : command[i + 1]);
86
+ i += 2;
87
+ continue;
88
+ }
89
+ if (char === '$' && command[i + 1] === '(') {
90
+ const end = substitutionEnd(command, i + 2);
91
+ if (end < 0) {
92
+ current += command.slice(i);
93
+ break;
94
+ }
95
+ current += ' $(...) ';
96
+ i = end + 1;
97
+ continue;
98
+ }
99
+ if (char === "'" || char === '"') {
100
+ quote = char;
101
+ current += char;
102
+ i += 1;
103
+ continue;
104
+ }
105
+ if (char === ';' || char === '\n') {
106
+ flush(false);
107
+ i += 1;
108
+ continue;
109
+ }
110
+ if (char === '|') {
111
+ // A single pipe feeds the next command; `||` is only another command.
112
+ const isPipe = command[i + 1] !== '|';
113
+ flush(isPipe);
114
+ i += isPipe ? 1 : 2;
115
+ continue;
116
+ }
117
+ if (char === '&') {
118
+ // `2>&1` and `&>` are redirections, not separators.
119
+ if (command[i - 1] === '>' || command[i + 1] === '>') {
120
+ current += char;
121
+ i += 1;
122
+ continue;
123
+ }
124
+ flush(false);
125
+ i += command[i + 1] === '&' ? 2 : 1;
126
+ continue;
127
+ }
128
+ if (char === '#' && (i === 0 || /\s/.test(command[i - 1]))) {
129
+ const newline = command.indexOf('\n', i);
130
+ if (newline < 0) break;
131
+ i = newline;
132
+ continue;
133
+ }
134
+ current += char;
135
+ i += 1;
136
+ }
137
+ if (current.length > 0) {
138
+ segments.push(current);
139
+ piped.push(afterPipe);
140
+ }
141
+ // `piped[i]` says segment i reads the output of the one before it, so it filters instead of reading code.
142
+ return Object.assign(segments, { piped });
143
+ }
144
+
145
+ /** The words of one segment, each quoted span folded into the word that carries it. */
146
+ function shellWords(segment) {
147
+ const words = [];
148
+ let word = '';
149
+ let started = false;
150
+ let quote;
151
+ for (let i = 0; i < segment.length; i += 1) {
152
+ const char = segment[i];
153
+ if (quote !== undefined) {
154
+ if (char === '\\' && quote === '"' && segment[i + 1] !== undefined) {
155
+ word += segment[i + 1];
156
+ i += 1;
157
+ } else if (char === quote) {
158
+ quote = undefined;
159
+ } else {
160
+ word += char;
161
+ }
162
+ started = true;
163
+ continue;
164
+ }
165
+ if (char === '\\') {
166
+ word += segment[i + 1] === undefined ? '' : segment[i + 1];
167
+ i += 1;
168
+ started = true;
169
+ continue;
170
+ }
171
+ if (char === "'" || char === '"') {
172
+ quote = char;
173
+ started = true;
174
+ continue;
175
+ }
176
+ if (/\s/.test(char)) {
177
+ if (started) {
178
+ words.push(word);
179
+ word = '';
180
+ started = false;
181
+ }
182
+ continue;
183
+ }
184
+ word += char;
185
+ started = true;
186
+ }
187
+ if (started) words.push(word);
188
+ return words;
189
+ }
190
+
191
+ /** The absolute paths one read-verb segment passes; a pattern or a script is not a path. */
192
+ function absolutePaths(program, args) {
193
+ const words = EXPRESSION_FIRST.includes(program) ? args.slice(1) : args;
194
+ return words.filter((word) => word.startsWith('/') && !word.startsWith('-'));
195
+ }
196
+
197
+ /**
198
+ * The places a shell command read code: its `cd` targets and the absolute paths its search or read verbs
199
+ * pass, plus the directory the shell stands in while they run. Undefined when no segment of the command
200
+ * searches or reads at all — so `git -C`, `curl`, `echo` and `npm view` never count, however they name
201
+ * another checkout.
202
+ */
203
+ function bashTargets(command, cwd) {
204
+ const base = typeof cwd === 'string' && cwd.length > 0 ? cwd : process.cwd();
205
+ let dir = base;
206
+ let reads = false;
207
+ const paths = [];
208
+ const segments = shellSegments(command);
209
+ for (const [index, segment] of segments.entries()) {
210
+ const words = shellWords(segment);
211
+ let at = 0;
212
+ while (at < words.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[at])) at += 1;
213
+ const program = (words[at] === undefined ? '' : words[at]).split('/').pop();
214
+ const args = words.slice(at + 1);
215
+ if (program === 'cd') {
216
+ const target = args.find((word) => !word.startsWith('-'));
217
+ if (target !== undefined) {
218
+ dir = nodePath.resolve(dir, target);
219
+ paths.push(dir);
220
+ }
221
+ continue;
222
+ }
223
+ // A command that follows a pipe filters the output of the one before it: if that one read code it counts itself.
224
+ if (!READ_VERBS.includes(program) || segments.piped[index]) continue;
225
+ reads = true;
226
+ paths.push(...absolutePaths(program, args));
227
+ paths.push(dir);
228
+ }
229
+ if (!reads) return undefined;
230
+ return { tool: 'bash', paths: [...new Set(paths)] };
231
+ }
232
+
233
+ // ---- the call (S3) ----
234
+
235
+ /**
236
+ * The search or read call a finished tool event made, with the absolute paths it looked at, or undefined
237
+ * when the call is not one of the five tools (or is a `read` of a doc or a config, which the rule exempts).
238
+ */
239
+ function searchCall(event, cwd) {
240
+ const tool = event && event.toolName;
241
+ const input = event && typeof event.input === 'object' && event.input !== null ? event.input : {};
242
+ const base = typeof cwd === 'string' && cwd.length > 0 ? cwd : process.cwd();
243
+ if (tool === 'grep' || tool === 'find' || tool === 'ls') {
244
+ const raw = typeof input.path === 'string' && input.path.length > 0 ? input.path : base;
245
+ return { tool, paths: [nodePath.resolve(base, raw)] };
246
+ }
247
+ if (tool === 'read') {
248
+ const raw = typeof input.path === 'string' ? input.path : typeof input.file_path === 'string' ? input.file_path : '';
249
+ if (raw.length === 0 || !isCodeFile(raw)) return undefined;
250
+ return { tool, paths: [nodePath.dirname(nodePath.resolve(base, raw))] };
251
+ }
252
+ if (tool === 'bash') {
253
+ return typeof input.command === 'string' ? bashTargets(input.command, base) : undefined;
254
+ }
255
+ return undefined;
256
+ }
257
+
258
+ // ---- the checkout a path belongs to (S4) ----
259
+
260
+ /**
261
+ * The git toplevel of each directory this session asked about, read once through the async child and kept
262
+ * for the life of the session: a directory outside every checkout is remembered as such, so a search in
263
+ * tmp is never a second git read. A failing git is an answer too (no checkout), never an error.
264
+ */
265
+ function createCheckoutResolver(deps = {}) {
266
+ const toplevel = deps.toplevel || gitToplevel;
267
+ const isDirectory = deps.isDirectory || ((path) => {
268
+ try {
269
+ return nodeFs.statSync(path).isDirectory();
270
+ } catch {
271
+ return false;
272
+ }
273
+ });
274
+ const roots = new Map(); // resolved directory -> toplevel | undefined
275
+
276
+ async function rootOf(dir) {
277
+ if (typeof dir !== 'string' || dir.length === 0) return undefined;
278
+ const key = nodePath.resolve(dir);
279
+ if (roots.has(key)) return roots.get(key);
280
+ let top;
281
+ try {
282
+ top = await toplevel(key);
283
+ } catch {
284
+ top = undefined;
285
+ }
286
+ const root = typeof top === 'string' && top.length > 0 ? top : undefined;
287
+ roots.set(key, root);
288
+ return root;
289
+ }
290
+
291
+ /**
292
+ * The checkout of a path that may be a file. One local stat decides which directory to ask git about,
293
+ * so a call never spends more than one git read; a path that does not exist is read as a file name.
294
+ */
295
+ async function rootOfPath(path) {
296
+ if (typeof path !== 'string' || path.length === 0) return undefined;
297
+ if (isDirectory(path)) return rootOf(path);
298
+ const resolved = nodePath.resolve(path);
299
+ const parent = nodePath.dirname(resolved);
300
+ return parent === resolved ? undefined : rootOf(parent);
301
+ }
302
+
303
+ return { rootOf, rootOfPath };
304
+ }
305
+
306
+ /**
307
+ * The checkout a call went to: the first path that resolves to one. `other` states whether it differs
308
+ * from the session's own checkout; with no own checkout known, every resolved checkout is another one.
309
+ */
310
+ async function callCheckout(call, options = {}) {
311
+ const resolve = typeof options.rootOfPath === 'function'
312
+ ? options.rootOfPath
313
+ : (typeof options.rootOf === 'function' ? options.rootOf : undefined);
314
+ if (!call || !Array.isArray(call.paths) || typeof resolve !== 'function') return undefined;
315
+ const ownRoot = typeof options.ownRoot === 'string' && options.ownRoot.length > 0 ? options.ownRoot : undefined;
316
+ let own;
317
+ for (const path of call.paths) {
318
+ const root = await resolve(path);
319
+ if (root === undefined) continue;
320
+ if (root !== ownRoot) return { root, other: true };
321
+ own = root;
322
+ }
323
+ return own === undefined ? undefined : { root: own, other: false };
324
+ }
325
+
326
+ module.exports = {
327
+ DOC_EXTENSIONS,
328
+ READ_VERBS,
329
+ SEARCH_TOOLS,
330
+ bashTargets,
331
+ callCheckout,
332
+ createCheckoutResolver,
333
+ isCodeFile,
334
+ searchCall,
335
+ shellSegments,
336
+ shellWords,
337
+ };
@@ -0,0 +1,211 @@
1
+ 'use strict';
2
+ // T1 (S1, S2, S5, S6, S7): the two CodeGraph reminders, decided from a finished tool call.
3
+ //
4
+ // Guard 1 says a call went to ANOTHER checkout and points the session at
5
+ // `mcp__codegraph__codegraph_explore` with that checkout as `projectPath`; it belongs to the primary
6
+ // session and fires once per checkout per session. Guard 2 says to reach CodeGraph first inside the
7
+ // session's OWN checkout; it belongs to the primary session and to every child except the `review-*`
8
+ // agents, and its key is the checkout, so a `/warp` re-arms it.
9
+ //
10
+ // Both are precise: a checkout the session already explored with the MCP tool silences guard 1, a
11
+ // session that already used CodeGraph silences guard 2, and a reminder that does not fire uses up no
12
+ // slot. A call that failed is no subject at all: the model got no result to read, so nothing is
13
+ // reminded, spent or recorded from it. A compaction forgets everything, and so does a new session in
14
+ // the same process.
15
+ //
16
+ // The reminder is only a sentence. Appending it to the tool result is the wiring's job
17
+ // (`lib/codegraph-session.js`); nothing here blocks, notifies or writes. Git is reached through one
18
+ // injected `toplevel` (`lib/codegraph-guard-target.js` caches it per directory), so nothing here spawns
19
+ // a child of its own and nothing throws into the host.
20
+
21
+ const nodePath = require('node:path');
22
+
23
+ const { agentNameFromArgv, holdsCodegraph, sessionTools, variantFor } = require('./codegraph-rules.js');
24
+ const target = require('./codegraph-guard-target.js');
25
+
26
+ const NATIVE_TOOL = 'codegraph';
27
+ const MCP_TOOL = 'mcp__codegraph__codegraph_explore';
28
+ /** The MCP explore call, bare or namespaced by a server: the one call a `projectPath` is read from. */
29
+ const EXPLORE_TOOL = /^(?:mcp__[a-z0-9_]+__)?codegraph_explore$/;
30
+ /** The roles whose own rule text names the native operations, so the reminder may name them too. */
31
+ const NATIVE_VARIANTS = ['orchestrator', 'explore'];
32
+
33
+ /** S1: one call went to another checkout. */
34
+ function anotherCheckoutReminder(root) {
35
+ return `This call went to ${root}, another checkout. Follow the CodeGraph rule: call \`${MCP_TOOL}\` with \`projectPath\` set to ${root} first.`;
36
+ }
37
+
38
+ /** S2: the call went to the session's own checkout; the wording follows the role's own rule text. */
39
+ function sameCheckoutReminder(input = {}) {
40
+ const variant = input.variant;
41
+ const tools = Array.isArray(input.tools) ? input.tools : [];
42
+ return NATIVE_VARIANTS.includes(variant) && tools.includes(NATIVE_TOOL)
43
+ ? 'Follow the CodeGraph rule: run `codegraph` `query` or `explore` first, if it applies.'
44
+ : `Follow the CodeGraph rule: call \`${MCP_TOOL}\` first, if it applies.`;
45
+ }
46
+
47
+ function isExploreCall(event) {
48
+ return Boolean(event) && typeof event.toolName === 'string' && EXPLORE_TOOL.test(event.toolName);
49
+ }
50
+
51
+ function isCodegraphCall(event) {
52
+ return Boolean(event) && (event.toolName === NATIVE_TOOL || isExploreCall(event));
53
+ }
54
+
55
+ /** The once-per-key slots and what the session already used, forgotten together. */
56
+ function createGuardState() {
57
+ return {
58
+ checkouts: new Set(), // guard 1: the other checkouts already reminded
59
+ own: new Set(), // guard 2: the session checkouts already reminded
60
+ explored: new Set(), // the absolute projectPath of every MCP explore call this session made
61
+ used: false, // the session already used CodeGraph at all
62
+ };
63
+ }
64
+
65
+ function resetGuardState(state) {
66
+ state.checkouts.clear();
67
+ state.own.clear();
68
+ state.explored.clear();
69
+ state.used = false;
70
+ }
71
+
72
+ /**
73
+ * What one finished call says about the session's use of CodeGraph: the native tool or the MCP tool is a
74
+ * use (S5), and an explore call aimed at a `projectPath` records that checkout. Returns whether this call
75
+ * was CodeGraph's own, in which case it is no search call and no reminder is about it.
76
+ */
77
+ function recordCodegraphUse(state, event, cwd) {
78
+ if (!isCodegraphCall(event)) return false;
79
+ state.used = true;
80
+ if (isExploreCall(event)) {
81
+ const projectPath = event.input && event.input.projectPath;
82
+ if (typeof projectPath === 'string' && projectPath.length > 0) {
83
+ state.explored.add(nodePath.resolve(typeof cwd === 'string' && cwd.length > 0 ? cwd : process.cwd(), projectPath));
84
+ }
85
+ }
86
+ return true;
87
+ }
88
+
89
+ /** Whether the session already explored that checkout, with the projectPath it named. */
90
+ async function exploredCheckout(state, root, resolver) {
91
+ for (const path of state.explored) {
92
+ if (await resolver.rootOfPath(path) === root) return true;
93
+ }
94
+ return false;
95
+ }
96
+
97
+ /**
98
+ * The reminder one call earns, or undefined. It marks the slot it used, so the same key is never
99
+ * reminded twice; a call whose reminder would duplicate one, or whose checkout the session already
100
+ * explored, marks nothing.
101
+ */
102
+ async function decideGuard(input) {
103
+ const { state, call, ownRoot, tools, variant, resolver } = input;
104
+ if (!call || !state || ownRoot === undefined) return undefined;
105
+ const checkout = await target.callCheckout(call, { rootOfPath: resolver.rootOfPath, ownRoot });
106
+ if (checkout === undefined) return undefined;
107
+ if (checkout.other) {
108
+ // Guard 1 is the primary session's (S1): a child never hears that it reached another checkout.
109
+ if (input.primary !== true) return undefined;
110
+ if (state.checkouts.has(checkout.root)) return undefined;
111
+ if (await exploredCheckout(state, checkout.root, resolver)) return undefined;
112
+ state.checkouts.add(checkout.root);
113
+ return { kind: 'another-checkout', checkout: checkout.root, text: anotherCheckoutReminder(checkout.root) };
114
+ }
115
+ if (state.own.has(checkout.root) || state.used) return undefined;
116
+ state.own.add(checkout.root);
117
+ return { kind: 'same-checkout', checkout: checkout.root, text: sameCheckoutReminder({ variant, tools }) };
118
+ }
119
+
120
+ function sessionCwd(event, ctx) {
121
+ if (ctx && typeof ctx.cwd === 'string' && ctx.cwd.length > 0) return ctx.cwd;
122
+ if (event && typeof event.cwd === 'string' && event.cwd.length > 0) return event.cwd;
123
+ return process.cwd();
124
+ }
125
+
126
+ /**
127
+ * The two guards of one session, with their own state. `observeTools` takes the session's tool list from
128
+ * the host's `before_agent_start` event (the only source of it); `onToolResult` decides one reminder from
129
+ * one finished call; `onCompacted` and `onNewSession` forget everything. Every collaborator is injectable:
130
+ * `env`, `argv` (the child's agent name), `toplevel` (the cached git read) and `isDirectory` (whether a path
131
+ * is a directory, so a file costs one read).
132
+ */
133
+ function createCodegraphGuard(deps = {}) {
134
+ const env = deps.env || process.env;
135
+ const argv = deps.argv || process.argv;
136
+ const resolver = deps.resolver || target.createCheckoutResolver({ toplevel: deps.toplevel, isDirectory: deps.isDirectory });
137
+ const state = createGuardState();
138
+ let selected = [];
139
+
140
+ const child = () => env.GENTLE_PI_AGENTS_CHILD === '1';
141
+ const agent = () => (child() ? agentNameFromArgv(argv) : undefined);
142
+ const tools = () => sessionTools(selected, env.GENTLE_PI_AGENTS_REQUESTED_TOOLS, child());
143
+
144
+ return {
145
+ /** The session's tools, as the host selected them for this turn. */
146
+ observeTools(selectedTools) {
147
+ selected = Array.isArray(selectedTools) ? selectedTools.filter((tool) => typeof tool === 'string') : [];
148
+ },
149
+
150
+ /** A compaction forgets what was reminded and what was used (S7). */
151
+ onCompacted() {
152
+ resetGuardState(state);
153
+ },
154
+
155
+ /** A new session in the same process is a new session (S7). */
156
+ onNewSession() {
157
+ resetGuardState(state);
158
+ },
159
+
160
+ /**
161
+ * The one reminder this finished call earns, or undefined. Never throws and never returns more than
162
+ * one text; only a call that resolves a checkout spends a git read, and that read is cached.
163
+ */
164
+ async onToolResult(event, ctx) {
165
+ try {
166
+ if (!event) return undefined;
167
+ // A call that failed returned nothing the model could read: no reminder rides an error result, no
168
+ // once-per-key slot is spent, and no use of CodeGraph is recorded on the strength of it (S5).
169
+ if (event.isError === true) return undefined;
170
+ const cwd = sessionCwd(event, ctx);
171
+ if (recordCodegraphUse(state, event, cwd)) return undefined;
172
+ // The same gate as the prompt section: the session must hold a CodeGraph tool to be advised.
173
+ const held = tools();
174
+ if (!holdsCodegraph(held)) return undefined;
175
+ const name = agent();
176
+ if (typeof name === 'string' && name.startsWith('review-')) return undefined;
177
+ const call = target.searchCall(event, cwd);
178
+ if (call === undefined) return undefined;
179
+ const ownRoot = await resolver.rootOfPath(cwd);
180
+ if (ownRoot === undefined) return undefined;
181
+ const decision = await decideGuard({
182
+ state,
183
+ call,
184
+ ownRoot,
185
+ tools: held,
186
+ variant: variantFor({ child: child(), agent: name }),
187
+ primary: !child(),
188
+ resolver,
189
+ });
190
+ return decision === undefined ? undefined : decision.text;
191
+ } catch {
192
+ return undefined;
193
+ }
194
+ },
195
+ };
196
+ }
197
+
198
+ module.exports = {
199
+ EXPLORE_TOOL,
200
+ NATIVE_TOOL,
201
+ MCP_TOOL,
202
+ anotherCheckoutReminder,
203
+ createCodegraphGuard,
204
+ createGuardState,
205
+ decideGuard,
206
+ isCodegraphCall,
207
+ isExploreCall,
208
+ recordCodegraphUse,
209
+ resetGuardState,
210
+ sameCheckoutReminder,
211
+ };