pi-odd-worktree 3.1.1 → 3.2.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.
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
- // T1, T5 (S1–S6, S8–S11): the worktree guard, decided from one `bash` command string.
2
+ // T1, T5 (S1–S6, S8–S11): the worktree guard, decided from one `bash` command string,
3
+ // plus (T3, S4) the `edit`/`write` guard, decided from the paths a call touches.
3
4
  //
4
5
  // A worktree is the checkout one ODD owns, and it is created, listed and removed
5
6
  // through this package's surfaces — never through Git typed into `bash`. The guard
@@ -17,6 +18,19 @@
17
18
  // S6 everything else passes: inspection, file restores, every `git branch` form,
18
19
  // `git worktree remove|prune|move`, and every non-`bash` tool call.
19
20
  //
21
+ // T3 (S4, L2) adds the WRITE guard, and it is a different question over different
22
+ // input: an `edit` or `write` whose `path` lies inside the PRINCIPAL checkout of the
23
+ // session's own repository is refused while that checkout is on the repository's
24
+ // default branch. A write is where the rule is broken, so the refusal arrives before
25
+ // the file is touched. It judges NOTHING else (L2 is the human's own word): a path
26
+ // outside every repository, a path under the OS temp directories even when a scratch
27
+ // repository lives there, a path in another repository, a path in a linked worktree, a
28
+ // session outside version control, an unreadable identity, a detached HEAD, another
29
+ // branch and a default branch that does not resolve all pass. The path is judged by
30
+ // its existing parent directory, realpath-resolved, so neither a symlink spelling nor
31
+ // a file that does not exist yet can dodge or false-trip it, and anything it cannot
32
+ // place passes.
33
+ //
20
34
  // S3 (L10) is a permission, not a refusal: creating, moving, copying, deleting or
21
35
  // listing a branch changes no checkout, so every `git branch` form yields no intent
22
36
  // here and is never refused. A branch created and not checked out is exactly what
@@ -79,12 +93,15 @@
79
93
  // or executed to find out what a command would do. What surrounds the sequence never
80
94
  // matters: one occurrence refuses the whole call.
81
95
  //
82
- // Nothing here spawns a child, reads a file or caches anything: `repoIdentity`,
96
+ // Nothing here spawns a child, executes anything or caches an answer: `repoIdentity`,
83
97
  // `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).
98
+ // decision over the command text (or the touched paths) — it runs on the hot path of
99
+ // every tool call — and it never throws, because a thrown `tool_call` handler blocks
100
+ // the tool fail-safe (S8). The one thing it reads from disk is a path's parent
101
+ // directory, and only to resolve a symlink: no file content is ever read.
87
102
 
103
+ const fs = require('node:fs');
104
+ const os = require('node:os');
88
105
  const nodePath = require('node:path');
89
106
 
90
107
  /** S1 (S10): creating a worktree with Git, refused in every cwd. */
@@ -96,6 +113,15 @@ const WORKTREE_LIST_REFUSAL = '`git worktree list` did not run: use `worktree_li
96
113
  /** S4 (S10): leaving the default branch of the principal checkout. */
97
114
  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
115
 
116
+ /** S4 (T3): a path inside the principal checkout on its default branch. */
117
+ const WRITE_GUARD_REFUSAL = (file, branch) => `${file} is in the primary checkout on \`${branch}\`. Work in a worktree (\`worktree_list\` / \`worktree_create\`).`;
118
+
119
+ /** The two tools that write a file the agent names (S4, T3). */
120
+ const WRITE_GUARD_TOOLS = new Set(['edit', 'write']);
121
+
122
+ /** The OS temp directories whose paths are never judged, whatever lives there (L2). */
123
+ const TEMP_DIR_SPELLINGS = ['/tmp', '/var/tmp'];
124
+
99
125
  /** git's global options that take their value as a SEPARATE argv element. */
100
126
  const GIT_GLOBAL_OPTIONS_WITH_VALUE = new Set([
101
127
  '-C',
@@ -459,6 +485,179 @@ function switchLeavesDefault(intent, defaultBranch) {
459
485
  return intent.ref !== defaultBranch;
460
486
  }
461
487
 
488
+ // ---------------------------------------------------------------------
489
+ // The write guard's own reading of a path (T3, S4, L2).
490
+ // ---------------------------------------------------------------------
491
+
492
+ /** The real path of `value`, or undefined when the filesystem cannot resolve it. */
493
+ function realpathOf(value) {
494
+ try {
495
+ return fs.realpathSync(value);
496
+ } catch {
497
+ return undefined;
498
+ }
499
+ }
500
+
501
+ /** Whether `child` IS `parent` or lies below it. Lexical: both are already resolved. */
502
+ function isInside(child, parent) {
503
+ if (child === parent) return true;
504
+ const base = parent.endsWith(nodePath.sep) ? parent : `${parent}${nodePath.sep}`;
505
+ return child.startsWith(base);
506
+ }
507
+
508
+ /**
509
+ * S4: the PRINCIPAL checkout of the repository the session stands in — the checkout
510
+ * that owns the shared git dir (`<root>/.git`, so the principal is that dir's parent,
511
+ * for the principal itself and for a linked worktree alike). Undefined when the session
512
+ * is outside version control, when the identity cannot be read, and when the common dir
513
+ * is not a `.git` of a normal repository (a bare repository, a separate git dir): an
514
+ * unplaceable repository refuses nothing (L2). Never throws.
515
+ */
516
+ function sessionPrincipal(repoIdentity, cwd) {
517
+ if (typeof repoIdentity !== 'function') return undefined;
518
+ if (typeof cwd !== 'string' || cwd.length === 0) return undefined;
519
+ try {
520
+ const identity = repoIdentity(cwd);
521
+ if (!identity || typeof identity.commonDir !== 'string' || identity.commonDir.length === 0) return undefined;
522
+ const commonDir = nodePath.resolve(identity.commonDir);
523
+ if (nodePath.basename(commonDir) !== '.git') return undefined;
524
+ const principal = nodePath.dirname(commonDir);
525
+ return realpathOf(principal) || principal;
526
+ } catch {
527
+ return undefined;
528
+ }
529
+ }
530
+
531
+ /** The real root of the checkout that owns `dir`, or undefined when it cannot be read. Never throws. */
532
+ function ownerRootOf(repoIdentity, dir) {
533
+ try {
534
+ const identity = repoIdentity(dir);
535
+ if (!identity || typeof identity.root !== 'string' || identity.root.length === 0) return undefined;
536
+ const root = nodePath.resolve(identity.root);
537
+ return realpathOf(root) || root;
538
+ } catch {
539
+ return undefined;
540
+ }
541
+ }
542
+
543
+ /**
544
+ * L2: the spellings a path is compared against to learn it is in a temp directory. The
545
+ * OS answer, the two fixed ones, the environment's own, and the realpath of each: on a
546
+ * platform where `/tmp` is a symlink, both spellings mean the same directory.
547
+ */
548
+ function tempRoots(env) {
549
+ const roots = [];
550
+ const push = (value) => {
551
+ if (typeof value !== 'string' || value.length === 0) return;
552
+ let resolved;
553
+ try {
554
+ resolved = nodePath.resolve(value);
555
+ } catch {
556
+ return;
557
+ }
558
+ for (const spelling of [resolved, realpathOf(resolved)]) {
559
+ if (typeof spelling === 'string' && spelling.length > 0 && !roots.includes(spelling)) roots.push(spelling);
560
+ }
561
+ };
562
+ for (const value of TEMP_DIR_SPELLINGS) push(value);
563
+ try {
564
+ push(os.tmpdir());
565
+ } catch {
566
+ // An OS without an answer simply contributes no root.
567
+ }
568
+ if (env && typeof env === 'object') push(env.TMPDIR);
569
+ return roots;
570
+ }
571
+
572
+ /**
573
+ * S4: the absolute path a written file really is, or undefined when it cannot be
574
+ * placed. The FILE may not exist yet — a new file in an existing directory is judged by
575
+ * that directory — so the existing parent is what is resolved, and a symlinked spelling
576
+ * of a checkout resolves to the checkout itself instead of dodging the check.
577
+ */
578
+ function judgedPath(raw, cwd) {
579
+ if (typeof raw !== 'string' || raw.length === 0) return undefined;
580
+ // Pi strips one leading `@` from a file tool's path before it opens the file, so the
581
+ // guard judges the path the tool will really touch, not the spelling it was given.
582
+ const spelled = raw.startsWith('@') && raw.length > 1 ? raw.slice(1) : raw;
583
+ let absolute;
584
+ try {
585
+ absolute = nodePath.resolve(cwd, spelled);
586
+ } catch {
587
+ return undefined;
588
+ }
589
+ const parent = realpathOf(nodePath.dirname(absolute));
590
+ if (parent === undefined) return undefined;
591
+ return nodePath.join(parent, nodePath.basename(absolute));
592
+ }
593
+
594
+ /**
595
+ * Decide one `edit`/`write` tool call (T3, S4, L2): `{block: false}`, or
596
+ * `{block: true, reason}` with the one sentence the session reads. Inputs:
597
+ * `toolName`, `paths` (every path the call touches), `cwd`, and the same seams the
598
+ * `bash` guard takes: `repoIdentity(cwd)`, `defaultBranch(root)` and
599
+ * `currentBranch(root)` — the last one read fresh, because only the checkout knows
600
+ * where it points. Never throws.
601
+ */
602
+ function decideWriteGuard(input) {
603
+ try {
604
+ if (!input || typeof input !== 'object') return { block: false };
605
+ if (!WRITE_GUARD_TOOLS.has(input.toolName)) return { block: false };
606
+ const raw = typeof input.paths === 'string' ? [input.paths] : input.paths;
607
+ if (!Array.isArray(raw) || raw.length === 0) return { block: false };
608
+ const cwd = typeof input.cwd === 'string' && input.cwd.length > 0 ? input.cwd : undefined;
609
+ if (cwd === undefined) return { block: false };
610
+
611
+ // L2: a path under a temp directory is never judged, and that answer must cost no
612
+ // git at all — scratch work (and a scratch repository) is the common case, so it is
613
+ // settled first, before the session's own checkout is even resolved. A path the
614
+ // filesystem cannot place is settled here too.
615
+ let temps;
616
+ const candidates = [];
617
+ for (const value of raw) {
618
+ const judged = judgedPath(value, cwd);
619
+ if (judged === undefined) continue;
620
+ if (temps === undefined) temps = tempRoots(process.env);
621
+ if (temps.some((root) => isInside(judged, root))) continue;
622
+ candidates.push(judged);
623
+ }
624
+ if (candidates.length === 0) return { block: false };
625
+
626
+ // S4: only the session's OWN repository is ever judged. Outside version control,
627
+ // or with an identity the seam cannot answer, nothing blocks.
628
+ const principal = sessionPrincipal(input.repoIdentity, cwd);
629
+ if (principal === undefined) return { block: false };
630
+
631
+ // The first path that really lies in the principal checkout is the one the refusal
632
+ // names; a path in another repository, or in a linked worktree, is placed and passes.
633
+ const target = candidates.find((judged) => isInside(judged, principal));
634
+ if (target === undefined) return { block: false };
635
+
636
+ // A linked worktree or a nested repository can live INSIDE the principal directory,
637
+ // so lying under it is not enough: the checkout that really owns the path's own
638
+ // directory must be the principal. Another owner, or the principal itself, is settled
639
+ // by that directory's identity; one the seam cannot answer is not judged (L2).
640
+ // The owner is asked through its own seam, never a remembered answer: a nested
641
+ // worktree can appear during the session. It falls back to the session's seam.
642
+ const ownerSeam = typeof input.ownerIdentity === 'function' ? input.ownerIdentity : input.repoIdentity;
643
+ const owner = ownerRootOf(ownerSeam, nodePath.dirname(target));
644
+ if (owner === undefined || owner !== principal) return { block: false };
645
+
646
+ // S4: the rule protects the default branch, so the checkout must be ON it. The
647
+ // current branch is read first and never cached; a detached HEAD, an unreadable
648
+ // answer or any other branch passes without resolving the default at all.
649
+ const current = currentBranchOf(input.currentBranch, principal);
650
+ if (current === undefined) return { block: false };
651
+ const defaultBranch = defaultBranchOf(input.defaultBranch, principal);
652
+ if (defaultBranch === undefined || defaultBranch !== current) return { block: false };
653
+ return { block: true, reason: WRITE_GUARD_REFUSAL(target, defaultBranch) };
654
+ } catch {
655
+ // S8: a write guard that threw would block the tool fail-safe, and a path it cannot
656
+ // judge must pass (L2), so nothing escapes here.
657
+ return { block: false };
658
+ }
659
+ }
660
+
462
661
  // ---------------------------------------------------------------------
463
662
  // The decision (S1–S6, S8–S10).
464
663
  // ---------------------------------------------------------------------
@@ -545,4 +744,5 @@ function decideBashGuard(input) {
545
744
 
546
745
  module.exports = {
547
746
  decideBashGuard,
747
+ decideWriteGuard,
548
748
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-odd-worktree",
3
- "version": "3.1.1",
3
+ "version": "3.2.0",
4
4
  "description": "Pi package for odd-worktree: the Git worktree tools a Pi session uses (create and list the checkouts the agent works in), the /warp worktree panel, the /odd ODD viewer, and the /issues GitHub issue reader. Needs only Pi and git: no companion app, no extra service.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -1,16 +1,18 @@
1
1
  'use strict';
2
- // T1 (S1, S2, S5, S6, S7): the decision core of the two CodeGraph reminders. From one finished tool
3
- // call, the session's own checkout, the role and what the session already used, it decides one text or
4
- // none, keeps the once-per-key state, and forgets it on a compaction or a new session. Git is a fake
5
- // toplevel map here: no child, no network, no real agent directory.
2
+ // T1 (S1, S2, S5, S6, S7) and T6 (S3): the decision core of the two CodeGraph reminders. From one
3
+ // finished tool call, the session's own checkout, the role and what the request already used, it decides
4
+ // one text or none, keeps the once-per-key state, re-arms guard 2 at every new request, and forgets
5
+ // everything on a compaction or a new session. Git is a fake toplevel map here: no child, no network, no
6
+ // real agent directory.
6
7
  const { test } = require('node:test');
7
8
  const assert = require('node:assert/strict');
8
9
  const { createCodegraphGuard } = require('../lib/codegraph-guard.js');
9
10
 
10
- // The approved texts of S1 and S2, written out so a reworded reminder fails here.
11
+ // The approved texts of S1 and S2, written out so a reworded reminder fails here. S3 took the trailing
12
+ // ", if it applies" off both sentences.
11
13
  const ANOTHER = (root) => `This call went to ${root}, another checkout. Follow the CodeGraph rule: call \`mcp__codegraph__codegraph_explore\` with \`projectPath\` set to ${root} first.`;
12
- const NATIVE = 'Follow the CodeGraph rule: run `codegraph` `query` or `explore` first, if it applies.';
13
- const MCP = 'Follow the CodeGraph rule: call `mcp__codegraph__codegraph_explore` first, if it applies.';
14
+ const NATIVE = 'Follow the CodeGraph rule: run `codegraph` `query` or `explore` first.';
15
+ const MCP = 'Follow the CodeGraph rule: call `mcp__codegraph__codegraph_explore` first.';
14
16
 
15
17
  const ROOTS = {
16
18
  '/repo': '/repo',
@@ -74,6 +76,17 @@ test('a session holding only the MCP tool is pointed at the MCP call instead', a
74
76
  assert.equal(await guard.onToolResult(grep(), ctx), MCP);
75
77
  });
76
78
 
79
+ test('neither sentence ends in ", if it applies" any more (S3)', async () => {
80
+ const native = setup();
81
+ const mcp = setup({ tools: ['grep', 'mcp__codegraph__codegraph_explore'] });
82
+ const texts = [await native.guard.onToolResult(grep(), native.ctx), await mcp.guard.onToolResult(grep(), mcp.ctx)];
83
+ assert.deepEqual(texts, [NATIVE, MCP]);
84
+ for (const text of texts) {
85
+ assert.ok(!text.includes('if it applies'), text);
86
+ assert.ok(text.endsWith(' first.'), text);
87
+ }
88
+ });
89
+
77
90
  test('an explore agent gets the native wording, every other child the MCP one', async () => {
78
91
  const child = (agent, tools) => setup({
79
92
  env: { GENTLE_PI_AGENTS_CHILD: '1', GENTLE_PI_AGENTS_REQUESTED_TOOLS: tools },
@@ -144,7 +157,7 @@ test('a path with no git checkout triggers nothing, and uses up no slot', async
144
157
 
145
158
  // ---- guard 2's key is the session's own checkout (S7) ----
146
159
 
147
- test('guard 2 is once per session, and a warp to another checkout re-arms it', async () => {
160
+ test('guard 2 reminds on the first search of a checkout, and a warp to another checkout re-arms it', async () => {
148
161
  const { guard, ctx } = setup();
149
162
  assert.equal(await guard.onToolResult(grep(), ctx), NATIVE);
150
163
  assert.equal(await guard.onToolResult(grep(), ctx), undefined);
@@ -152,6 +165,91 @@ test('guard 2 is once per session, and a warp to another checkout re-arms it', a
152
165
  assert.equal(await guard.onToolResult(read('/third/a.ts'), warped), NATIVE, 'the new checkout has not been reminded');
153
166
  });
154
167
 
168
+ // ---- guard 2 reminds once per checkout per request (S3, S7) ----
169
+
170
+ const use = (toolName) => ({ toolName, input: { operation: 'query' }, isError: false, content: [] });
171
+
172
+ /** The texts the guard answered over `count` back-to-back searches in one checkout. */
173
+ async function row(guard, ctx, count) {
174
+ const texts = [];
175
+ for (let call = 0; call < count; call += 1) texts.push(await guard.onToolResult(grep(), ctx));
176
+ return texts;
177
+ }
178
+
179
+ const silent = (count) => Array(count).fill(undefined);
180
+
181
+ test('one reminder per request, whatever the number of searches after it (S3, S7)', async () => {
182
+ const { guard, ctx } = setup();
183
+ // One first search plus 8, 9 and 17 more: the searches at 8, 9 and 17 since the reminder earn nothing.
184
+ const texts = [await guard.onToolResult(grep(), ctx)];
185
+ for (const count of [8, 9, 17]) texts.push(...await row(guard, ctx, count));
186
+ const reminded = texts.map((text, index) => (text === undefined ? undefined : index + 1)).filter((at) => at !== undefined);
187
+ assert.deepEqual(reminded, [1], 'only the first search of the checkout is reminded, never the 8th, 9th or 17th after it');
188
+ assert.deepEqual(texts.filter((text) => text !== undefined), [NATIVE]);
189
+ });
190
+
191
+ test('a CodeGraph use neither earns a reminder nor re-arms the one already given (S3)', async () => {
192
+ const forUse = setup();
193
+ assert.equal(await forUse.guard.onToolResult(grep(), forUse.ctx), NATIVE, 'the first reminder');
194
+ assert.deepEqual(await row(forUse.guard, forUse.ctx, 4), silent(4));
195
+ assert.equal(await forUse.guard.onToolResult(use('codegraph'), forUse.ctx), undefined, 'a use is no search call');
196
+ assert.deepEqual(await row(forUse.guard, forUse.ctx, 9), silent(9), 'the checkout already had its one reminder');
197
+
198
+ const forExplore = setup();
199
+ assert.equal(await forExplore.guard.onToolResult(grep(), forExplore.ctx), NATIVE);
200
+ await forExplore.guard.onToolResult(explore('/repo'), forExplore.ctx);
201
+ assert.deepEqual(await row(forExplore.guard, forExplore.ctx, 17), silent(17), 'the MCP explore call re-arms nothing either');
202
+ });
203
+
204
+ test('each checkout hears its own one reminder in a request (S3)', async () => {
205
+ const { guard, ctx } = setup();
206
+ const warped = { cwd: '/third' };
207
+ assert.equal(await guard.onToolResult(read('src/a.ts'), ctx), NATIVE, 'the /repo checkout reminds on its first search');
208
+ assert.deepEqual(await row(guard, ctx, 17), silent(17), 'and never again in this request');
209
+ assert.equal(await guard.onToolResult(read('/third/a.ts'), warped), NATIVE, 'a warp to /third has its own reminder');
210
+ assert.deepEqual(await row(guard, warped, 17), silent(17), 'once, and then never again either');
211
+ assert.deepEqual(await row(guard, ctx, 17), silent(17), 'and /repo stays silent');
212
+ });
213
+
214
+ // ---- a new request re-arms guard 2 (S7) ----
215
+ //
216
+ // Each new request forgets guard 2's first-search slots and its `used` flag, so the first search of every
217
+ // request is reminded again; guard 1's slots and the explored checkouts stay per session.
218
+
219
+ test('a new request reminds its first search again (S7)', async () => {
220
+ const { guard, ctx } = setup();
221
+ assert.equal(await guard.onToolResult(grep(), ctx), NATIVE, 'the first search of the request reminds');
222
+ assert.deepEqual(await row(guard, ctx, 17), silent(17), 'and no later search of it does');
223
+ guard.onNewRequest();
224
+ assert.equal(await guard.onToolResult(grep(), ctx), NATIVE, 'the next request is reminded on its first search');
225
+ assert.deepEqual(await row(guard, ctx, 17), silent(17), 'it hears it once too');
226
+ });
227
+
228
+ test('a CodeGraph use in the previous request does not silence the first search of the next (S7)', async () => {
229
+ const { guard, ctx } = setup();
230
+ await guard.onToolResult(use('codegraph'), ctx);
231
+ assert.equal(await guard.onToolResult(grep(), ctx), undefined, 'the graph was already used in this request');
232
+ guard.onNewRequest();
233
+ assert.equal(await guard.onToolResult(grep(), ctx), NATIVE, 'a new request starts with the graph unused');
234
+ });
235
+
236
+ test('a new request keeps guard 1 once per other checkout across requests (S7)', async () => {
237
+ const { guard, ctx } = setup();
238
+ assert.equal(await guard.onToolResult(read('/other/a.ts'), ctx), ANOTHER('/other'));
239
+ guard.onNewRequest();
240
+ assert.equal(await guard.onToolResult(read('/other/b.ts'), ctx), undefined, 'a new request is no new checkout');
241
+ assert.equal(await guard.onToolResult(read('/third/a.ts'), ctx), ANOTHER('/third'), 'an unseen checkout still gets its reminder');
242
+ guard.onNewRequest();
243
+ assert.equal(await guard.onToolResult(read('/other/a.ts'), ctx), undefined, 'and it stays once per session');
244
+ });
245
+
246
+ test('a new request does not forget the checkouts the session already explored (S7)', async () => {
247
+ const { guard, ctx } = setup();
248
+ assert.equal(await guard.onToolResult(explore('/other'), ctx), undefined, 'an explore call is no search call');
249
+ guard.onNewRequest();
250
+ assert.equal(await guard.onToolResult(read('/other/a.ts'), ctx), undefined, 'guard 1 stays satisfied by that explore');
251
+ });
252
+
155
253
  // ---- precision (S5) ----
156
254
 
157
255
  test('guard 1 stays silent for a checkout this session already explored, without using its slot', async () => {
@@ -168,12 +266,12 @@ test('guard 1 understands an explore aimed at a directory inside that checkout',
168
266
  assert.equal(await guard.onToolResult(read('/other/a.ts'), ctx), undefined);
169
267
  });
170
268
 
171
- test('guard 2 stays silent once the session used CodeGraph, and the silent attempt used no slot', async () => {
269
+ test('a session that used CodeGraph before its first search is not reminded on that first search', async () => {
172
270
  const { guard, ctx } = setup();
173
- await guard.onToolResult({ toolName: 'codegraph', input: { operation: 'query' }, isError: false, content: [] }, ctx);
271
+ await guard.onToolResult(use('codegraph'), ctx);
174
272
  assert.equal(await guard.onToolResult(grep(), ctx), undefined, 'the graph was already used');
175
273
  guard.onCompacted();
176
- assert.equal(await guard.onToolResult(grep(), ctx), NATIVE, 'the slot was never consumed');
274
+ assert.equal(await guard.onToolResult(grep(), ctx), NATIVE, 'the first-search reminder was never consumed');
177
275
  });
178
276
 
179
277
  test('a call that failed earns no reminder and spends no slot', async () => {
@@ -32,7 +32,7 @@ describe('the seven texts on disk', () => {
32
32
  for (const variant of rules.VARIANTS) {
33
33
  const text = file(variant).replace(/\s+/g, ' ');
34
34
  assert.ok(text.startsWith('## CodeGraph'), variant);
35
- assert.match(text, /before you search or read code/, `${variant} gates searching and reading code`);
35
+ assert.match(text, /before you (search or read code|`grep`, `rg`, `fd`, `find`, `read` or `cat`)/i, `${variant} gates searching and reading code`);
36
36
  for (const binary of ['fd', 'find', 'rg', 'grep', 'read', 'cat']) {
37
37
  assert.ok(text.includes(`\`${binary}\``), `${variant} names ${binary}`);
38
38
  }
@@ -47,9 +47,8 @@ describe('the seven texts on disk', () => {
47
47
  });
48
48
 
49
49
  test('only the roles holding the native tool name its operations; the MCP tool is named in full', () => {
50
- for (const variant of ['orchestrator', 'explore']) {
51
- assert.match(file(variant), /`codegraph` `query`/, variant);
52
- }
50
+ assert.match(file('explore'), /`codegraph` `query`/, 'explore');
51
+ assert.match(file('orchestrator'), /`codegraph` with `operation: "explore"`[\s\S]*`operation: "query"`/, 'orchestrator');
53
52
  for (const variant of ['verify', 'worker', 'fix', 'judge']) {
54
53
  const text = file(variant);
55
54
  assert.ok(text.includes(`\`${MCP}\``), variant);
@@ -80,11 +79,12 @@ describe('the seven texts on disk', () => {
80
79
  describe('the orchestrator and explore texts stay inside their role', () => {
81
80
  const prose = (variant) => file(variant).replace(/\s+/g, ' ');
82
81
 
83
- test('the orchestrator sizes with the graph only when one read batch does not already explain the change', () => {
82
+ test('the orchestrator calls the graph first for a where/who/how/what-reaches question, with one exemption and one literal call', () => {
84
83
  const text = prose('orchestrator');
85
- assert.match(text, /before you plan or size a change that one read batch does not already explain/, text);
86
- assert.match(text, /a file or location you already know/, 'a known location needs no call, not only a known file');
87
- assert.match(text, /which is what scope, size and any handoff depend on/, 'the small path has no handoff');
84
+ assert.match(text, /to answer where code lives, who calls it, how it works, or what a change reaches, call CodeGraph first/, text);
85
+ assert.match(text, /`codegraph` with `operation: "explore"` and `query: "<symbols or the question>"`/, 'the literal call');
86
+ assert.match(text, /Skip it only for an exact string or a file path the user gave you/, 'one exemption');
87
+ assert.match(text, /what scope, size and any handoff depend on/, 'the sizing use is kept');
88
88
  });
89
89
 
90
90
  test('the orchestrator looks at the ODD\'s own worktree through projectPath when the session runs elsewhere', () => {
@@ -334,8 +334,8 @@ test('the work a synchronous handler starts still runs after it has answered the
334
334
  // session's tools come from `before_agent_start` (the only source), the checkouts from one cached fake
335
335
  // git toplevel, and the texts are the approved ones, written out here.
336
336
 
337
- const NATIVE_REMINDER = 'Follow the CodeGraph rule: run `codegraph` `query` or `explore` first, if it applies.';
338
- const MCP_REMINDER = 'Follow the CodeGraph rule: call `mcp__codegraph__codegraph_explore` first, if it applies.';
337
+ const NATIVE_REMINDER = 'Follow the CodeGraph rule: run `codegraph` `query` or `explore` first.';
338
+ const MCP_REMINDER = 'Follow the CodeGraph rule: call `mcp__codegraph__codegraph_explore` first.';
339
339
  const anotherReminder = (root) => `This call went to ${root}, another checkout. Follow the CodeGraph rule: call \`mcp__codegraph__codegraph_explore\` with \`projectPath\` set to ${root} first.`;
340
340
 
341
341
  const SESSION_TOOLS = { systemPromptOptions: { selectedTools: ['read', 'grep', 'bash', 'codegraph'] } };
@@ -417,6 +417,21 @@ test('a new session start re-arms it, and a /reload is not a new session', async
417
417
  assert.ok(await run('tool_result', readEvent('src/a.ts')), 'a new session forgets it');
418
418
  });
419
419
 
420
+ test('a new request re-arms the one reminder of the checkout (S3, S7)', async () => {
421
+ const { run } = setup({ toplevel: checkoutMap() });
422
+ await run('before_agent_start', SESSION_TOOLS);
423
+ const texts = [];
424
+ for (let call = 0; call < 17; call += 1) {
425
+ const patch = await run('tool_result', readEvent('src/a.ts'));
426
+ texts.push(patch === undefined ? undefined : patch.content[1].text);
427
+ }
428
+ assert.deepEqual(texts.filter((text) => text !== undefined), [NATIVE_REMINDER], '17 searches of one request hear it once');
429
+ assert.equal(texts[0], NATIVE_REMINDER, 'and on the first of them, not at 8, 9 or 17');
430
+ await run('before_agent_start', SESSION_TOOLS);
431
+ const next = await run('tool_result', readEvent('src/a.ts'));
432
+ assert.equal(next.content[1].text, NATIVE_REMINDER, 'the first search of the next request hears it again');
433
+ });
434
+
420
435
  test('a worker child is told to call the MCP tool, and a review agent is told nothing', async () => {
421
436
  const worker = setup({
422
437
  env: { GENTLE_PI_AGENTS_CHILD: '1', GENTLE_PI_AGENTS_REQUESTED_TOOLS: 'read,bash,mcp__codegraph__codegraph_explore' },
@@ -447,7 +462,7 @@ test('a git read that throws never fails the tool result', async () => {
447
462
  });
448
463
 
449
464
  test('the guard is one injected collaborator, driven by the host events', async () => {
450
- const seen = { tools: [], results: [], compacted: 0, sessions: 0 };
465
+ const seen = { tools: [], results: [], compacted: 0, sessions: 0, requests: 0 };
451
466
  const { run } = setup({
452
467
  impl: {
453
468
  createCodegraphGuard: (options) => {
@@ -464,6 +479,9 @@ test('the guard is one injected collaborator, driven by the host events', async
464
479
  onNewSession: () => {
465
480
  seen.sessions += 1;
466
481
  },
482
+ onNewRequest: () => {
483
+ seen.requests += 1;
484
+ },
467
485
  };
468
486
  },
469
487
  },
@@ -476,10 +494,34 @@ test('the guard is one injected collaborator, driven by the host events', async
476
494
  assert.deepEqual(seen.tools, [SESSION_TOOLS.systemPromptOptions.selectedTools]);
477
495
  assert.equal(seen.compacted, 1);
478
496
  assert.equal(seen.sessions, 2, 'the startup and the new session both reset');
497
+ assert.equal(seen.requests, 1, 'one new request, no more');
479
498
  assert.deepEqual(seen.results, ['grep']);
480
499
  assert.deepEqual(patch.content, [{ type: 'text', text: 'REMINDER' }], 'the reminder rides the result as one more part');
481
500
  });
482
501
 
502
+ test('S7: every new request re-arms guard 2, and a finished call does not', async () => {
503
+ let requests = 0;
504
+ const { run } = setup({
505
+ impl: {
506
+ createCodegraphGuard: () => ({
507
+ observeTools: () => {},
508
+ onToolResult: async () => undefined,
509
+ onCompacted: () => {},
510
+ onNewSession: () => {},
511
+ onNewRequest: () => {
512
+ requests += 1;
513
+ },
514
+ }),
515
+ },
516
+ });
517
+ await run('tool_result', { toolName: 'grep', input: { pattern: 'x' }, isError: false, content: [] });
518
+ assert.equal(requests, 0, 'a finished tool call is no new request');
519
+ await run('before_agent_start', SESSION_TOOLS);
520
+ assert.equal(requests, 1, 'the prompt of a new request re-arms it');
521
+ await run('before_agent_start', SESSION_TOOLS);
522
+ assert.equal(requests, 2, 'each new request, not each session');
523
+ });
524
+
483
525
  // ---- S2: the bounded join on the pre-execution hook (T6) ----
484
526
  //
485
527
  // Before a CodeGraph search runs, the index work this process already has in flight for that checkout is