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
@@ -1,457 +1,726 @@
1
1
  'use strict';
2
- // S1-S6/S8: the session gate, the git-toplevel root cache, and the background
3
- // sync scheduler. Every child process and every git read is injected, so this
4
- // suite never starts a real process and never reaches the network; the only
5
- // real filesystem is a throwaway temp directory outside the worktree (the
6
- // `.codegraph/` marker, the lock and the daemon pid are files on disk).
7
- const { test, describe, beforeEach, after } = require('node:test');
2
+ // T5: the one place that wires CodeGraph into a session: session start (the global MCP entry, create-or-sync, the warm-up),
3
+ // compaction, the observed native init, the edit/write sync, the two reminders appended to a search call's result, and
4
+ // shutdown. Only with the CLI installed, and nothing here may throw into the host. Every collaborator is injected, so no
5
+ // test runs codegraph, a daemon or touches a real agent directory.
6
+ const { test } = require('node:test');
8
7
  const assert = require('node:assert/strict');
9
- const fs = require('node:fs');
10
- const os = require('node:os');
11
8
  const path = require('node:path');
12
- const { EventEmitter } = require('node:events');
13
-
14
- const session = require('../lib/codegraph-session.js');
15
- const hooksLib = require('../lib/worktree-hooks.js');
9
+ const os = require('node:os');
10
+ const { registerCodegraph } = require('../lib/codegraph-session.js');
11
+
12
+ function fakePi() {
13
+ const handlers = new Map();
14
+ return {
15
+ handlers,
16
+ on(name, fn) {
17
+ if (!handlers.has(name)) handlers.set(name, []);
18
+ handlers.get(name).push(fn);
19
+ },
20
+ };
21
+ }
16
22
 
17
- const scratch = [];
18
- function tempDir(prefix = 'cg-session-') {
19
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
20
- scratch.push(dir);
21
- return dir;
23
+ function setup(overrides = {}) {
24
+ const pi = fakePi();
25
+ const calls = { mcp: [], prepare: [], compaction: [], init: [], edit: [], card: [], dispose: 0, notices: [] };
26
+ const impl = {
27
+ ensureCodegraphServer: async (input) => {
28
+ calls.mcp.push(input);
29
+ return { status: 'added', changes: ['command'] };
30
+ },
31
+ prepareProject: async (input) => {
32
+ calls.prepare.push(input);
33
+ if (typeof input.onStart === 'function') input.onStart('sync');
34
+ return { index: { action: 'sync', ok: true }, warm: 'skipped' };
35
+ },
36
+ compactionSync: async (input) => {
37
+ calls.compaction.push(input);
38
+ return 'synced';
39
+ },
40
+ syncAfterNativeInit: async (input) => {
41
+ calls.init.push(input);
42
+ return 'completed';
43
+ },
44
+ createEditSync: () => ({
45
+ onToolResult: async (event, ctx) => {
46
+ calls.edit.push([event, ctx]);
47
+ },
48
+ dispose: () => {
49
+ calls.dispose += 1;
50
+ },
51
+ }),
52
+ warmUpDaemon: async () => true,
53
+ createCodegraphCardResolver: (options) => {
54
+ calls.card.push(options);
55
+ return { registered: true };
56
+ },
57
+ ...(overrides.impl || {}),
58
+ };
59
+ const result = registerCodegraph(pi, {
60
+ metrics: overrides.metrics || (() => ({ metrics: true })),
61
+ env: { PI_CODING_AGENT_DIR: '/agent', ...(overrides.env || {}) },
62
+ argv: overrides.argv || ['node', '/bin/pi'],
63
+ toplevel: overrides.toplevel,
64
+ isDirectory: overrides.isDirectory || (() => true),
65
+ hasBinary: overrides.hasBinary || (() => true),
66
+ joinIndexWork: overrides.joinIndexWork,
67
+ delay: overrides.delay,
68
+ impl,
69
+ });
70
+ const ctx = {
71
+ cwd: '/work/repo',
72
+ ui: { notify: (text, level) => calls.notices.push([text, level]) },
73
+ };
74
+ const run = async (name, event, c = ctx) => {
75
+ let last;
76
+ for (const handler of pi.handlers.get(name) || []) last = await handler(event, c);
77
+ await new Promise((resolve) => setImmediate(resolve));
78
+ return last;
79
+ };
80
+ return { pi, calls, ctx, run, result };
22
81
  }
23
82
 
24
- after(() => {
25
- for (const dir of scratch) {
26
- try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* teardown is best effort */ }
27
- }
83
+ test('without the CodeGraph CLI nothing is registered at all', () => {
84
+ const { pi, result } = setup({ hasBinary: () => false });
85
+ assert.equal(result.registered, false);
86
+ assert.equal(pi.handlers.size, 0);
28
87
  });
29
88
 
30
- beforeEach(() => {
31
- session.resetCodegraphSession();
89
+ test('the CodeGraph card is registered once through the host hook, with the extension\'s own text metrics', () => {
90
+ const registered = [];
91
+ const { calls, pi } = setup();
92
+ assert.equal(calls.card.length, 1);
93
+ assert.deepEqual(calls.card[0].metrics(), { metrics: true });
94
+ assert.equal(typeof calls.card[0].registerToolRenderer, 'function');
95
+ pi.registerToolRenderer = (resolver) => registered.push(resolver);
96
+ calls.card[0].registerToolRenderer('resolver');
97
+ assert.deepEqual(registered, ['resolver'], 'the hook is looked up when it is used');
32
98
  });
33
99
 
34
- const FORCED_ENV = { PATH: '', CODEGRAPH_FORCE: '1' };
100
+ test('S6: the CodeGraph card gets the session cwd through a live seam', async () => {
101
+ const { calls, run } = setup();
102
+ assert.equal(typeof calls.card[0].cwd, 'function', 'the card factory is handed a cwd seam');
103
+ assert.equal(calls.card[0].cwd(), undefined, 'unknown until the session says');
104
+ await run('session_start', { reason: 'startup' });
105
+ assert.equal(calls.card[0].cwd(), '/work/repo', 'the seam answers with the session checkout');
106
+ });
35
107
 
36
- function makeRoot() {
37
- const root = tempDir('cg-root-');
38
- fs.mkdirSync(path.join(root, '.codegraph'));
39
- return root;
40
- }
108
+ test('a host without the renderer hook is given no registration to call', () => {
109
+ const { calls } = setup();
110
+ assert.equal(calls.card[0].registerToolRenderer('x'), undefined, 'a missing hook is a no-op, never a throw');
111
+ });
41
112
 
42
- // deps for one scheduler test. `onSpawn` lets a test hold a run open (no
43
- // close event) or release it; `overrides` replaces any other seam.
44
- function makeDeps(root, overrides = {}) {
45
- const { onSpawn, spawn: launch, ...rest } = overrides;
46
- const spawns = [];
47
- const children = [];
48
- const deps = {
49
- env: FORCED_ENV,
50
- execFile: (bin) => {
51
- assert.equal(bin, 'git');
52
- return `${root}\n`;
53
- },
54
- debounceMs: 10,
55
- retryDelayMs: 30,
56
- ...rest,
57
- spawn: (bin, args, opts) => {
58
- spawns.push({ bin, args, opts });
59
- const child = typeof launch === 'function' ? launch(bin, args, opts) : new EventEmitter();
60
- if (!child) return child;
61
- const unref = child.unref;
62
- child.unref = () => {
63
- child.unrefed = true;
64
- if (typeof unref === 'function') unref.call(child);
65
- };
66
- children.push(child);
67
- if (typeof onSpawn === 'function') onSpawn(child, children.length - 1);
68
- return child;
69
- },
70
- };
71
- return { deps, spawns, children };
72
- }
113
+ test('without the CLI the card is not registered either', () => {
114
+ const { calls } = setup({ hasBinary: () => false });
115
+ assert.equal(calls.card.length, 0);
116
+ });
73
117
 
74
- const closeSoon = (child) => setImmediate(() => child.emit('close'));
118
+ test('a primary session start ensures the MCP entry once, prepares the index and reports the change', async () => {
119
+ const { calls, run } = setup();
120
+ await run('session_start', { reason: 'startup' });
121
+ await run('session_start', { reason: 'new' });
122
+ assert.equal(calls.mcp.length, 1, 'the entry is checked once per process');
123
+ assert.equal(calls.mcp[0].agentDir, '/agent');
124
+ assert.equal(calls.prepare.length, 2);
125
+ assert.equal(calls.prepare[0].cwd, '/work/repo');
126
+ assert.equal(calls.prepare[0].reason, 'startup');
127
+ assert.ok(calls.notices.some(([text]) => /mcp\.json/.test(text) && /reload/i.test(text)), 'one notice says Pi must reload');
128
+ });
75
129
 
76
- async function waitFor(predicate, timeoutMs = 3000) {
77
- const started = Date.now();
78
- while (!predicate()) {
79
- if (Date.now() - started > timeoutMs) throw new Error('timed out waiting for condition');
80
- await new Promise((resolve) => setTimeout(resolve, 5));
81
- }
82
- }
130
+ test('the agent directory falls back to ~/.pi/agent when the host names none', async () => {
131
+ const { calls, run } = setup({ env: { PI_CODING_AGENT_DIR: undefined } });
132
+ await run('session_start', { reason: 'startup' });
133
+ assert.equal(calls.mcp[0].agentDir, path.join(os.homedir(), '.pi', 'agent'));
134
+ });
83
135
 
84
- describe('session gate (S3/S4)', () => {
85
- test('probes PATH once and caches the answer', () => {
86
- const bin = tempDir('cg-bin-');
87
- const env = { PATH: `${bin}${path.delimiter}/cg-session-empty-dir` };
88
- let probes = 0;
89
- const deps = {
90
- binaryExists: (file) => {
91
- probes += 1;
92
- return path.dirname(file) === bin && path.basename(file) === 'codegraph';
93
- },
94
- };
95
- assert.equal(session.hasCodegraph(env, deps), true);
96
- const first = probes;
97
- assert.ok(first > 0, 'the first answer is probed');
98
- assert.equal(session.hasCodegraph(env, deps), true);
99
- assert.equal(probes, first, 'a second question never re-probes');
100
- // A PATH that changed mid-session is not re-read either.
101
- assert.equal(session.hasCodegraph({ PATH: '/cg-session-other' }, deps), true);
102
- assert.equal(probes, first);
103
- });
136
+ test('a subagent child never touches the MCP entry', async () => {
137
+ const { calls, run } = setup({ env: { GENTLE_PI_AGENTS_CHILD: '1' } });
138
+ await run('session_start', { reason: 'startup' });
139
+ assert.equal(calls.mcp.length, 0);
140
+ });
104
141
 
105
- test('caches a missing CLI as false', () => {
106
- const env = { PATH: tempDir('cg-empty-') };
107
- let probes = 0;
108
- const deps = { binaryExists: () => { probes += 1; return false; } };
109
- assert.equal(session.hasCodegraph(env, deps), false);
110
- const first = probes;
111
- assert.equal(session.hasCodegraph(env, deps), false);
112
- assert.equal(probes, first);
113
- });
142
+ test('an invalid MCP file is reported as a warning and left alone', async () => {
143
+ const { calls, run } = setup({ impl: { ensureCodegraphServer: async () => ({ status: 'invalid' }) } });
144
+ await run('session_start', { reason: 'startup' });
145
+ assert.ok(calls.notices.some(([text, level]) => /mcp\.json/.test(text) && level === 'warning'));
146
+ });
114
147
 
115
- test('CODEGRAPH_FORCE=1 answers present without probing', () => {
116
- const mustNotProbe = { binaryExists: () => { throw new Error('must not probe'); } };
117
- assert.equal(session.hasCodegraph({ PATH: '', CODEGRAPH_FORCE: '1' }, mustNotProbe), true);
118
- // ...and it escapes an answer already cached as false in this session.
119
- assert.equal(session.hasCodegraph({ PATH: '' }, { binaryExists: () => false }), false);
120
- assert.equal(session.hasCodegraph({ PATH: '', CODEGRAPH_FORCE: '1' }, mustNotProbe), true);
121
- });
148
+ test('an unchanged entry says nothing', async () => {
149
+ const { calls, run } = setup({ impl: { ensureCodegraphServer: async () => ({ status: 'unchanged' }) } });
150
+ await run('session_start', { reason: 'startup' });
151
+ assert.equal(calls.notices.filter(([text]) => /mcp\.json/.test(text)).length, 0);
152
+ });
122
153
 
123
- test('a false gate means no spawn ever', async () => {
124
- const root = makeRoot();
125
- const { deps, spawns } = makeDeps(root, { env: { PATH: tempDir('cg-empty-') } });
126
- const decision = session.scheduleSync(path.join(root, 'src', 'a.js'), deps);
127
- assert.deepEqual(decision, { scheduled: false, reason: 'no-codegraph' });
128
- await session.whenIdle();
129
- assert.equal(spawns.length, 0);
154
+ test('session start never waits for the preparation', async () => {
155
+ let release;
156
+ const gate = new Promise((resolve) => {
157
+ release = resolve;
130
158
  });
159
+ const { pi, ctx } = setup({ impl: { prepareProject: () => gate } });
160
+ const started = pi.handlers.get('session_start')[0]({ reason: 'startup' }, ctx);
161
+ const settled = await Promise.race([Promise.resolve(started).then(() => 'returned'), new Promise((resolve) => setTimeout(() => resolve('waiting'), 50))]);
162
+ release({ index: { action: 'none', ok: true }, warm: 'skipped' });
163
+ assert.equal(settled, 'returned');
164
+ });
131
165
 
132
- test('the gate fails closed when codegraph is absent from the process PATH', () => {
133
- // One probe per process is the contract; a forced env is the only escape.
134
- assert.equal(session.hasCodegraph({ PATH: tempDir('cg-empty-') }), false);
135
- });
166
+ test('a compaction asks for one sync of the session checkout', async () => {
167
+ const { calls, run } = setup();
168
+ await run('session_compact', {});
169
+ assert.equal(calls.compaction.length, 1);
170
+ assert.equal(calls.compaction[0].cwd, '/work/repo');
136
171
  });
137
172
 
138
- describe('root resolution (S1)', () => {
139
- test('returns the git toplevel, cached per directory', () => {
140
- const root = tempDir('cg-repo-');
141
- const sub = path.join(root, 'src');
142
- fs.mkdirSync(sub);
143
- let calls = 0;
144
- const deps = { execFile: () => { calls += 1; return `${root}\n`; } };
145
- assert.equal(session.resolveProjectRoot(sub, deps), root);
146
- assert.equal(session.resolveProjectRoot(sub, deps), root);
147
- assert.equal(calls, 1);
148
- assert.equal(session.resolveProjectRoot(root, deps), root);
149
- assert.equal(calls, 2, 'each directory is its own cache entry');
173
+ test('S4: a successful native init is followed by one coordinated sync and appends nothing to the result', async () => {
174
+ const { calls, run } = setup();
175
+ const patch = await run('tool_result', {
176
+ toolName: 'codegraph',
177
+ input: { operation: 'init' },
178
+ isError: false,
179
+ content: [{ type: 'text', text: 'initialized' }],
150
180
  });
181
+ assert.equal(calls.init.length, 1);
182
+ assert.equal(calls.init[0].cwd, '/work/repo');
183
+ assert.equal(patch, undefined, "the tool's own content is the whole answer");
184
+ });
151
185
 
152
- test('returns null outside git and caches the null', () => {
153
- const notRepo = tempDir('cg-not-repo-');
154
- let failures = 0;
155
- const deps = { execFile: () => { failures += 1; throw new Error('fatal: not a git repository'); } };
156
- assert.equal(session.resolveProjectRoot(notRepo, deps), null);
157
- assert.equal(session.resolveProjectRoot(notRepo, deps), null);
158
- assert.equal(failures, 1);
186
+ test('S4: a post-init sync that did not complete appends one short line naming the failure', async () => {
187
+ const { run } = setup({ impl: { syncAfterNativeInit: async () => 'failed' } });
188
+ const patch = await run('tool_result', {
189
+ toolName: 'codegraph',
190
+ input: { operation: 'init' },
191
+ isError: false,
192
+ content: [{ type: 'text', text: 'initialized' }],
159
193
  });
194
+ assert.equal(patch.content.length, 2, 'one extra part, not a paragraph');
195
+ assert.deepEqual(patch.content[0], { type: 'text', text: 'initialized' }, 'the tool result keeps its own words first');
196
+ assert.equal(patch.content[1].text.includes('\n'), false, 'one line');
197
+ assert.doesNotMatch(patch.content[1].text, /pi-odd-worktree/);
198
+ assert.match(patch.content[1].text, /failed/);
199
+ assert.match(patch.content[1].text, /not confirmed current|may be behind/);
200
+ });
160
201
 
161
- test('a non-zero git answer resolves to null', () => {
162
- const dir = tempDir('cg-git-exit-');
163
- assert.equal(session.resolveProjectRoot(dir, { execFile: () => '' }), null);
164
- });
202
+ test('a failed init, another operation or another tool changes nothing and starts no sync', async () => {
203
+ const { calls, run } = setup();
204
+ for (const event of [
205
+ { toolName: 'codegraph', input: { operation: 'init' }, isError: true, content: [] },
206
+ { toolName: 'codegraph', input: { operation: 'query' }, isError: false, content: [] },
207
+ { toolName: 'bash', input: {}, isError: false, content: [] },
208
+ ]) {
209
+ assert.equal(await run('tool_result', event), undefined);
210
+ }
211
+ assert.equal(calls.init.length, 0);
165
212
  });
166
213
 
167
- describe('scheduler (S1/S2/S6/S8)', () => {
168
- test('two rapid edits produce exactly one sync, detached and unref\'d', async () => {
169
- const root = makeRoot();
170
- const file = path.join(root, 'src', 'a.js');
171
- const { deps, spawns, children } = makeDeps(root, { onSpawn: closeSoon });
172
- const first = session.scheduleSync(file, deps);
173
- const second = session.scheduleSync(file, deps);
174
- assert.equal(first.scheduled, true);
175
- assert.equal(second.scheduled, true);
176
- await session.whenIdle();
177
- assert.equal(spawns.length, 1, 'the second edit only resets the debounce');
178
- assert.equal(spawns[0].bin, 'codegraph');
179
- assert.deepEqual(spawns[0].args, ['sync', root]);
180
- assert.equal(spawns[0].opts.detached, true);
181
- assert.equal(spawns[0].opts.stdio, 'ignore');
182
- assert.equal(children[0].unrefed, true, 'the child is unref\'d, never awaited');
183
- });
214
+ test('S4: a read-only role gets the one skipped line and no sync', async () => {
215
+ const { calls, run } = setup({ env: { GENTLE_PI_AGENTS_CHILD: '1', GENTLE_PI_AGENTS_REQUESTED_TOOLS: 'read,bash,codegraph' } });
216
+ const patch = await run('tool_result', { toolName: 'codegraph', input: { operation: 'init' }, isError: false, content: [] });
217
+ assert.equal(calls.init.length, 0);
218
+ assert.equal(patch.content.length, 1);
219
+ assert.match(patch.content[0].text, /read-only/);
220
+ assert.equal(patch.content[0].text.includes('\n'), false, 'one short line');
221
+ });
184
222
 
185
- test('an edit during a running sync produces exactly one more', async () => {
186
- const root = makeRoot();
187
- const file = path.join(root, 'src', 'a.js');
188
- const { deps, spawns, children } = makeDeps(root);
189
- assert.equal(session.scheduleSync(file, deps).scheduled, true);
190
- await waitFor(() => spawns.length === 1);
191
- assert.equal(session.scheduleSync(file, deps).reason, 'queued');
192
- assert.equal(spawns.length, 1, 'nothing starts while the first run is open');
193
- children[0].emit('close');
194
- await waitFor(() => spawns.length === 2);
195
- children[1].emit('close');
196
- await session.whenIdle();
197
- assert.equal(spawns.length, 2);
198
- });
223
+ test('an init aimed at another checkout is left to its own index', async () => {
224
+ const { calls, run } = setup();
225
+ const patch = await run('tool_result', { toolName: 'codegraph', input: { operation: 'init', worktree: 'other' }, isError: false, content: [] });
226
+ assert.equal(patch, undefined);
227
+ assert.equal(calls.init.length, 0);
228
+ });
199
229
 
200
- test('a held foreign lock skips and the deferred retry fires exactly once', async () => {
201
- const root = makeRoot();
202
- const lock = path.join(root, '.codegraph', 'pi-sync.lock');
203
- fs.writeFileSync(lock, JSON.stringify({ pid: process.pid, startedAt: Date.now() }));
204
- let lockReads = 0;
205
- const { deps, spawns } = makeDeps(root, {
206
- readFile: (file) => {
207
- if (file === lock) lockReads += 1;
208
- return fs.readFileSync(file, 'utf8');
209
- },
210
- });
211
- assert.equal(session.scheduleSync(path.join(root, 'a.js'), deps).scheduled, true);
212
- await session.whenIdle();
213
- assert.equal(spawns.length, 0, 'a live foreign lock is never taken over');
214
- assert.equal(lockReads, 2, 'the first attempt plus exactly one deferred retry');
215
- assert.ok(fs.existsSync(lock), 'the foreign lock is left alone');
230
+ test('every tool result also feeds the edit sync, with the session context', async () => {
231
+ const { calls, ctx, run } = setup();
232
+ const event = { toolName: 'edit', input: { path: 'a.js' }, isError: false, content: [] };
233
+ await run('tool_result', event);
234
+ assert.deepEqual(calls.edit, [[event, ctx]]);
235
+ });
236
+
237
+ test('shutdown clears the edit sync windows', async () => {
238
+ const { calls, run } = setup();
239
+ await run('session_shutdown', {});
240
+ assert.equal(calls.dispose, 1);
241
+ });
242
+
243
+ test('a throwing collaborator never reaches the host', async () => {
244
+ const boom = async () => {
245
+ throw new Error('boom');
246
+ };
247
+ const { run } = setup({ impl: { ensureCodegraphServer: boom, prepareProject: boom, compactionSync: boom, syncAfterNativeInit: boom } });
248
+ await assert.doesNotReject(async () => {
249
+ await run('session_start', { reason: 'startup' });
250
+ await run('session_compact', {});
251
+ await run('tool_result', { toolName: 'codegraph', input: { operation: 'init' }, isError: false, content: [] });
216
252
  });
253
+ });
254
+
255
+ // ---- the host contract: a lifecycle handler is never awaited by the host ----
256
+ //
257
+ // The host applies what a `pi.on()` handler returns, and waits for a thenable, so an index preparation
258
+ // handed back from `session_start` would sit on Pi's own startup path. No other test can see that: each
259
+ // one calls the handler and awaits it itself, which works just as well for a promise as for `undefined`.
260
+ // Two handlers may answer with a promise:
261
+ //
262
+ // - `tool_result`, whose only host-visible wait is the bounded post-init race (`POST_INIT_SYNC_WAIT_MS`);
263
+ // - `tool_call` (S2), whose promise is the bounded join of index work this process had ALREADY started —
264
+ // Pi awaits that hook before the tool runs and blocks the tool when it throws (docs/extensions.md:3253),
265
+ // so it answers `undefined` whenever nothing is in flight and can neither throw nor answer a block.
266
+
267
+ test('no lifecycle handler hands the host a promise, and only tool_result and tool_call answer with one', async () => {
268
+ const { pi, ctx } = setup();
269
+ const events = {
270
+ session_start: { reason: 'startup' },
271
+ session_compact: {},
272
+ before_agent_start: { systemPromptOptions: { selectedTools: ['read'] } },
273
+ session_shutdown: {},
274
+ };
275
+ assert.deepEqual([...pi.handlers.keys()].sort(), ['before_agent_start', 'session_compact', 'session_shutdown', 'session_start', 'tool_call', 'tool_result'], 'the wiring registers these and nothing else');
276
+ for (const [name, handlers] of pi.handlers) {
277
+ for (const handler of handlers) {
278
+ const returned = handler(events[name] || {}, ctx);
279
+ if (name === 'tool_result') {
280
+ assert.equal(typeof returned?.then, 'function', 'tool_result is the one handler whose patch is the answer');
281
+ await returned;
282
+ continue;
283
+ }
284
+ if (name === 'tool_call') {
285
+ // S2: the join may answer with a promise, but with nothing in flight it answers `undefined` and
286
+ // Pi runs the tool at once. Either way the answer settles on its own and is never a block.
287
+ if (returned !== undefined) assert.equal(typeof returned.then, 'function', 'tool_call answers a thenable or nothing');
288
+ assert.equal(await returned, undefined, 'and never a block');
289
+ continue;
290
+ }
291
+ assert.equal(returned, undefined, `${name} must hand the host nothing: its work runs off the host's path`);
292
+ }
293
+ }
294
+ await new Promise((resolve) => setImmediate(resolve));
295
+ });
217
296
 
218
- test('a lock released before the retry lets exactly one sync land', async () => {
219
- const root = makeRoot();
220
- const lock = path.join(root, '.codegraph', 'pi-sync.lock');
221
- fs.writeFileSync(lock, JSON.stringify({ pid: process.pid, startedAt: Date.now() }));
222
- let lockReads = 0;
223
- const { deps, spawns } = makeDeps(root, {
224
- retryDelayMs: 60,
225
- onSpawn: closeSoon,
226
- readFile: (file) => {
227
- if (file === lock) lockReads += 1;
228
- return fs.readFileSync(file, 'utf8');
297
+ test('the work a synchronous handler starts still runs after it has answered the host', async () => {
298
+ let releasePrepare;
299
+ const prepareGate = new Promise((resolve) => {
300
+ releasePrepare = resolve;
301
+ });
302
+ let releaseCompaction;
303
+ const compactionGate = new Promise((resolve) => {
304
+ releaseCompaction = resolve;
305
+ });
306
+ const prepared = [];
307
+ const compacted = [];
308
+ const { pi, ctx } = setup({
309
+ impl: {
310
+ prepareProject: (input) => {
311
+ prepared.push(input);
312
+ return prepareGate;
313
+ },
314
+ compactionSync: (input) => {
315
+ compacted.push(input);
316
+ return compactionGate;
229
317
  },
230
- });
231
- assert.equal(session.scheduleSync(path.join(root, 'a.js'), deps).scheduled, true);
232
- await waitFor(() => lockReads === 1);
233
- assert.equal(spawns.length, 0);
234
- fs.unlinkSync(lock);
235
- await session.whenIdle();
236
- assert.equal(spawns.length, 1);
318
+ },
237
319
  });
320
+ pi.handlers.get('session_start')[0]({ reason: 'startup' }, ctx);
321
+ pi.handlers.get('session_compact')[0]({}, ctx);
322
+ await new Promise((resolve) => setImmediate(resolve));
323
+ assert.equal(prepared.length, 1, 'the index preparation is requested without the host waiting for it');
324
+ assert.equal(compacted.length, 1, 'the compaction sync is requested without the host waiting for it');
325
+ releasePrepare({ index: { action: 'none', ok: true }, warm: 'skipped' });
326
+ releaseCompaction('synced');
327
+ await new Promise((resolve) => setImmediate(resolve));
328
+ assert.equal(prepared[0].cwd, '/work/repo', 'and it is the session checkout that is prepared');
329
+ });
330
+
331
+ // ---- the two reminders (T3: S1, S2, S5, S6, S7) ----
332
+ //
333
+ // One extra text part on the result of a search call, never a separate message and never a block. The
334
+ // session's tools come from `before_agent_start` (the only source), the checkouts from one cached fake
335
+ // git toplevel, and the texts are the approved ones, written out here.
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.';
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
+
341
+ const SESSION_TOOLS = { systemPromptOptions: { selectedTools: ['read', 'grep', 'bash', 'codegraph'] } };
342
+
343
+ // What git answers for a directory inside a checkout: its toplevel, at any depth, and nothing outside one.
344
+ function checkoutMap(map = { '/work/repo': '/work/repo', '/work/other': '/work/other' }) {
345
+ return async (dir) => {
346
+ for (let at = dir; ;) {
347
+ if (Object.prototype.hasOwnProperty.call(map, at)) return map[at];
348
+ const parent = path.dirname(at);
349
+ if (parent === at) return undefined;
350
+ at = parent;
351
+ }
352
+ };
353
+ }
354
+
355
+ const readEvent = (path, extra = {}) => ({
356
+ toolName: 'read',
357
+ input: { path },
358
+ isError: false,
359
+ content: [{ type: 'text', text: 'source' }],
360
+ ...extra,
361
+ });
362
+
363
+ test('a code read in the session checkout gets one reminder part appended, and the result stays whole', async () => {
364
+ const { run } = setup({ toplevel: checkoutMap() });
365
+ await run('before_agent_start', SESSION_TOOLS);
366
+ const patch = await run('tool_result', readEvent('src/a.ts', { structuredContent: { output: 'source' } }));
367
+ assert.equal(patch.content.length, 2, 'one extra part, no new message');
368
+ assert.deepEqual(patch.content[0], { type: 'text', text: 'source' }, 'the tool result keeps its own words first');
369
+ assert.deepEqual(patch.content[1], { type: 'text', text: NATIVE_REMINDER });
370
+ assert.deepEqual(patch.structuredContent, { output: 'source' }, 'the structured content of the result is kept');
371
+ });
372
+
373
+ test('ODD_WORKTREE_PROMPT=0 silences the reminders too, because they cite the rule that variable suppresses', async () => {
374
+ const { run } = setup({ toplevel: checkoutMap(), env: { ODD_WORKTREE_PROMPT: '0' } });
375
+ await run('before_agent_start', SESSION_TOOLS);
376
+ assert.equal(await run('tool_result', readEvent('src/a.ts')), undefined, 'no reminder without the CodeGraph section');
377
+ const { run: runOn } = setup({ toplevel: checkoutMap(), env: { ODD_WORKTREE_PROMPT: '1' } });
378
+ await runOn('before_agent_start', SESSION_TOOLS);
379
+ assert.ok(await runOn('tool_result', readEvent('src/a.ts')), 'any other value keeps them on');
380
+ });
381
+
382
+ test('the session tools are recorded from before_agent_start: without them nothing is appended', async () => {
383
+ const { run } = setup({ toplevel: checkoutMap() });
384
+ assert.equal(await run('tool_result', readEvent('src/a.ts')), undefined, 'no CodeGraph tool seen yet');
385
+ await run('before_agent_start', { systemPromptOptions: { selectedTools: ['read', 'grep'] } });
386
+ assert.equal(await run('tool_result', readEvent('src/a.ts')), undefined, 'a session without a CodeGraph tool is not advised');
387
+ await run('before_agent_start', SESSION_TOOLS);
388
+ assert.ok(await run('tool_result', readEvent('src/a.ts')), 'the tool gate opens with the selected tools');
389
+ });
390
+
391
+ test('a call into another checkout names its real root, once, and the session checkout is reminded separately', async () => {
392
+ const { run } = setup({ toplevel: checkoutMap() });
393
+ await run('before_agent_start', SESSION_TOOLS);
394
+ const other = await run('tool_result', readEvent('/work/other/src/a.ts'));
395
+ assert.equal(other.content[1].text, anotherReminder('/work/other'));
396
+ assert.equal(await run('tool_result', readEvent('/work/other/b.ts')), undefined, 'once per checkout');
397
+ const own = await run('tool_result', readEvent('src/a.ts'));
398
+ assert.equal(own.content[1].text, NATIVE_REMINDER, 'the session checkout has its own guard');
399
+ });
238
400
 
239
- test('a dead-pid lock is taken over', async () => {
240
- const root = makeRoot();
241
- const lock = path.join(root, '.codegraph', 'pi-sync.lock');
242
- fs.writeFileSync(lock, JSON.stringify({ pid: 424242, startedAt: Date.now() }));
243
- const { deps, spawns } = makeDeps(root, { isAlive: () => false, onSpawn: closeSoon });
244
- assert.equal(session.scheduleSync(path.join(root, 'a.js'), deps).scheduled, true);
245
- await session.whenIdle();
246
- assert.equal(spawns.length, 1);
401
+ test('a compaction re-arms the reminder', async () => {
402
+ const { run } = setup({ toplevel: checkoutMap() });
403
+ await run('before_agent_start', SESSION_TOOLS);
404
+ assert.ok(await run('tool_result', readEvent('src/a.ts')));
405
+ assert.equal(await run('tool_result', readEvent('src/a.ts')), undefined);
406
+ await run('session_compact', {});
407
+ assert.ok(await run('tool_result', readEvent('src/a.ts')), 'a compacted session hears it again');
408
+ });
409
+
410
+ test('a new session start re-arms it, and a /reload is not a new session', async () => {
411
+ const { run } = setup({ toplevel: checkoutMap() });
412
+ await run('before_agent_start', SESSION_TOOLS);
413
+ assert.ok(await run('tool_result', readEvent('src/a.ts')));
414
+ await run('session_start', { reason: 'reload' });
415
+ assert.equal(await run('tool_result', readEvent('src/a.ts')), undefined, 'a reload keeps the session');
416
+ await run('session_start', { reason: 'new' });
417
+ assert.ok(await run('tool_result', readEvent('src/a.ts')), 'a new session forgets it');
418
+ });
419
+
420
+ test('a worker child is told to call the MCP tool, and a review agent is told nothing', async () => {
421
+ const worker = setup({
422
+ env: { GENTLE_PI_AGENTS_CHILD: '1', GENTLE_PI_AGENTS_REQUESTED_TOOLS: 'read,bash,mcp__codegraph__codegraph_explore' },
423
+ argv: ['node', '/tmp/gentle-pi-subagent-gentle-ai-worker-a1b2c3/bin.js'],
424
+ toplevel: checkoutMap(),
247
425
  });
426
+ const workerPatch = await worker.run('tool_result', readEvent('src/a.ts'));
427
+ assert.equal(workerPatch.content[1].text, MCP_REMINDER);
248
428
 
249
- test('an expired lock TTL is taken over even with a live pid', async () => {
250
- const root = makeRoot();
251
- const lock = path.join(root, '.codegraph', 'pi-sync.lock');
252
- const now = 1_000_000_000_000;
253
- fs.writeFileSync(lock, JSON.stringify({ pid: process.pid, startedAt: now - (10 * 60 * 1000) }));
254
- const { deps, spawns } = makeDeps(root, { now: () => now, onSpawn: closeSoon });
255
- assert.equal(session.scheduleSync(path.join(root, 'a.js'), deps).scheduled, true);
256
- await session.whenIdle();
257
- assert.equal(spawns.length, 1);
429
+ const reviewer = setup({
430
+ env: { GENTLE_PI_AGENTS_CHILD: '1', GENTLE_PI_AGENTS_REQUESTED_TOOLS: 'read,bash,mcp__codegraph__codegraph_explore' },
431
+ argv: ['node', '/tmp/gentle-pi-subagent-review-code-a1b2c3/bin.js'],
432
+ toplevel: checkoutMap(),
258
433
  });
434
+ assert.equal(await reviewer.run('tool_result', readEvent('src/a.ts')), undefined);
435
+ });
259
436
 
260
- test('a root without .codegraph/ spawns nothing (S6)', async () => {
261
- const root = tempDir('cg-no-index-');
262
- const { deps, spawns } = makeDeps(root);
263
- const decision = session.scheduleSync(path.join(root, 'a.js'), deps);
264
- assert.deepEqual(decision, { scheduled: false, reason: 'no-index' });
265
- await session.whenIdle();
266
- assert.equal(spawns.length, 0);
437
+ test('a git read that throws never fails the tool result', async () => {
438
+ const { run } = setup({
439
+ toplevel: async () => {
440
+ throw new Error('git is gone');
441
+ },
267
442
  });
443
+ await run('before_agent_start', SESSION_TOOLS);
444
+ await assert.doesNotReject(async () => {
445
+ assert.equal(await run('tool_result', readEvent('src/a.ts')), undefined);
446
+ });
447
+ });
268
448
 
269
- test('a live daemon.pid spawns nothing (S5)', async () => {
270
- const root = makeRoot();
271
- fs.writeFileSync(path.join(root, '.codegraph', 'daemon.pid'), `${process.pid}\n`);
272
- const { deps, spawns } = makeDeps(root);
273
- const decision = session.scheduleSync(path.join(root, 'a.js'), deps);
274
- assert.deepEqual(decision, { scheduled: false, reason: 'daemon' });
275
- await session.whenIdle();
276
- assert.equal(spawns.length, 0);
449
+ test('the guard is one injected collaborator, driven by the host events', async () => {
450
+ const seen = { tools: [], results: [], compacted: 0, sessions: 0 };
451
+ const { run } = setup({
452
+ impl: {
453
+ createCodegraphGuard: (options) => {
454
+ seen.options = options;
455
+ return {
456
+ observeTools: (tools) => seen.tools.push(tools),
457
+ onToolResult: async (event) => {
458
+ seen.results.push(event.toolName);
459
+ return 'REMINDER';
460
+ },
461
+ onCompacted: () => {
462
+ seen.compacted += 1;
463
+ },
464
+ onNewSession: () => {
465
+ seen.sessions += 1;
466
+ },
467
+ };
468
+ },
469
+ },
277
470
  });
471
+ await run('session_start', { reason: 'startup' });
472
+ await run('before_agent_start', SESSION_TOOLS);
473
+ await run('session_compact', {});
474
+ await run('session_start', { reason: 'new' });
475
+ const patch = await run('tool_result', { toolName: 'grep', input: { pattern: 'x' }, isError: false, content: [] });
476
+ assert.deepEqual(seen.tools, [SESSION_TOOLS.systemPromptOptions.selectedTools]);
477
+ assert.equal(seen.compacted, 1);
478
+ assert.equal(seen.sessions, 2, 'the startup and the new session both reset');
479
+ assert.deepEqual(seen.results, ['grep']);
480
+ assert.deepEqual(patch.content, [{ type: 'text', text: 'REMINDER' }], 'the reminder rides the result as one more part');
481
+ });
482
+
483
+ // ---- S2: the bounded join on the pre-execution hook (T6) ----
484
+ //
485
+ // Before a CodeGraph search runs, the index work this process already has in flight for that checkout is
486
+ // awaited — never started, never exceeded, and never able to fail the call. Pi awaits a `tool_call` handler
487
+ // before the tool runs and BLOCKS the tool when that handler throws (docs/extensions.md:3253), so this handler
488
+ // answers `undefined` for every other tool and whenever nothing is in flight, and the promise it does answer
489
+ // with is bounded and never rejects.
278
490
 
279
- test('the daemon pidfile in its JSON form counts as live too (S5)', async () => {
280
- const root = makeRoot();
281
- // CodeGraph 1.6 writes {pid, version, socketPath, startedAt}; a plain
282
- // decimal is the legacy shape. Both must be understood.
283
- fs.writeFileSync(path.join(root, '.codegraph', 'daemon.pid'), JSON.stringify({
284
- pid: process.pid, version: '1.6.0', socketPath: '/tmp/cg.sock', startedAt: Date.now(),
285
- }));
286
- const { deps, spawns } = makeDeps(root);
287
- assert.deepEqual(session.scheduleSync(path.join(root, 'a.js'), deps), { scheduled: false, reason: 'daemon' });
288
- await session.whenIdle();
289
- assert.equal(spawns.length, 0);
491
+ const searchCall = (toolName = 'codegraph', input = { operation: 'query' }) => ({ toolName, input, toolCallId: 'call-1' });
492
+
493
+ function gateOf() {
494
+ let release;
495
+ const gate = new Promise((resolve) => {
496
+ release = resolve;
290
497
  });
498
+ return { gate, release: (value) => release(value) };
499
+ }
291
500
 
292
- test('a sync that never closes is killed by the run watchdog and the root stays usable (S2)', async () => {
293
- const root = makeRoot();
294
- const killed = [];
295
- const { deps, spawns } = makeDeps(root, {
296
- runTimeoutMs: 25,
297
- onSpawn: (child) => { child.kill = (signal) => { killed.push(signal); }; },
298
- });
299
- assert.equal(session.scheduleSync(path.join(root, 'a.js'), deps).scheduled, true);
300
- // The watchdog timer is unref'd on purpose (a settled sync must never keep
301
- // the host alive), so this test holds the loop itself instead of relying on
302
- // the runner: without a live handle the loop can drain before 25ms on some
303
- // Node versions, which would cancel the pending whenIdle().
304
- await Promise.race([
305
- session.whenIdle(),
306
- new Promise((resolve) => setTimeout(resolve, 500)),
307
- ]);
308
- assert.deepEqual(killed, ['SIGTERM'], 'the stuck child is terminated');
309
- // The lock came back and the root is not wedged: the next edit syncs.
310
- const next = makeDeps(root, { onSpawn: closeSoon });
311
- assert.equal(session.scheduleSync(path.join(root, 'b.js'), next.deps).scheduled, true);
312
- await session.whenIdle();
313
- assert.equal(next.spawns.length, 1);
501
+ test('S2: a search joins the session-start preparation already in flight, and starts none of its own', async () => {
502
+ const gate = gateOf();
503
+ const preparations = [];
504
+ const { pi, calls, ctx } = setup({
505
+ impl: {
506
+ prepareProject: (input) => {
507
+ preparations.push(input);
508
+ return gate.gate;
509
+ },
510
+ },
314
511
  });
512
+ pi.handlers.get('session_start')[0]({ reason: 'startup' }, ctx);
513
+ await new Promise((resolve) => setImmediate(resolve));
514
+ assert.equal(preparations.length, 1);
515
+ const returned = pi.handlers.get('tool_call')[0](searchCall(), ctx);
516
+ assert.equal(typeof returned?.then, 'function', 'the search waits for the preparation in flight');
517
+ // Settlement is tracked as a flag, not as a value: `undefined` is both what the handler answers and what a promise
518
+ // that has not settled yet looks like, so a value cannot tell an early answer from one still pending.
519
+ let releasedAt;
520
+ let settledAfter;
521
+ void returned.then(() => {
522
+ settledAfter = releasedAt;
523
+ });
524
+ await new Promise((resolve) => setTimeout(resolve, 20));
525
+ assert.equal(settledAfter, undefined, 'the join was still in flight while the preparation had not been released');
526
+ releasedAt = Date.now();
527
+ gate.release({ index: { action: 'sync', ok: true }, warm: 'skipped' });
528
+ assert.equal(await returned, undefined, 'the handler answers undefined, never a block');
529
+ assert.equal(settledAfter, releasedAt, 'the release is what ended the wait, nothing else');
530
+ assert.equal(preparations.length, 1, 'joining starts no preparation, sync, init or seed');
531
+ assert.equal(calls.init.length, 0);
532
+ assert.deepEqual(calls.edit, [], 'and nothing reaches the edit sync');
533
+ });
534
+
535
+ test('S2: a search joins a post-init sync already in flight', async () => {
536
+ const gate = gateOf();
537
+ const { pi, ctx, run } = setup({ impl: { syncAfterNativeInit: () => gate.gate } });
538
+ const result = run('tool_result', { toolName: 'codegraph', input: { operation: 'init' }, isError: false, content: [] });
539
+ await new Promise((resolve) => setImmediate(resolve));
540
+ const returned = pi.handlers.get('tool_call')[0](searchCall(), ctx);
541
+ assert.equal(typeof returned?.then, 'function', 'the index write the init hook started is joined');
542
+ gate.release('completed');
543
+ await result;
544
+ assert.equal(await returned, undefined);
545
+ });
315
546
 
316
- test('a dead daemon.pid does not suppress the sync', async () => {
317
- const root = makeRoot();
318
- fs.writeFileSync(path.join(root, '.codegraph', 'daemon.pid'), '424242\n');
319
- const { deps, spawns } = makeDeps(root, { isAlive: () => false, onSpawn: closeSoon });
320
- assert.equal(session.scheduleSync(path.join(root, 'a.js'), deps).scheduled, true);
321
- await session.whenIdle();
322
- assert.equal(spawns.length, 1);
547
+ test('S2: a search joins the compaction sync already in flight, bounded by the same budget', async () => {
548
+ const gate = gateOf();
549
+ const budgets = [];
550
+ const compacted = [];
551
+ const { pi, ctx } = setup({
552
+ impl: {
553
+ compactionSync: (input) => {
554
+ compacted.push(input);
555
+ return gate.gate;
556
+ },
557
+ },
558
+ delay: (ms) => {
559
+ budgets.push(ms);
560
+ return gate.gate;
561
+ },
562
+ });
563
+ assert.equal(pi.handlers.get('session_compact')[0]({}, ctx), undefined, 'the host is still handed nothing');
564
+ await new Promise((resolve) => setImmediate(resolve));
565
+ assert.equal(compacted.length, 1, 'the compaction asked for one sync');
566
+ const returned = pi.handlers.get('tool_call')[0](searchCall(), ctx);
567
+ assert.equal(typeof returned?.then, 'function', 'the search waits for the compaction sync in flight');
568
+ let settled = false;
569
+ void returned.then(() => {
570
+ settled = true;
323
571
  });
572
+ await new Promise((resolve) => setTimeout(resolve, 20));
573
+ assert.equal(settled, false, 'the join was still in flight while the compaction sync had not finished');
574
+ gate.release({ outcome: 'synced' });
575
+ assert.equal(await returned, undefined, 'the handler answers undefined, never a block');
576
+ assert.deepEqual(budgets, [5000], 'the same five-second budget bounds the wait');
577
+ await new Promise((resolve) => setImmediate(resolve));
578
+ assert.equal(pi.handlers.get('tool_call')[0](searchCall(), ctx), undefined, 'once it settled, a search waits for nothing');
579
+ });
324
580
 
325
- test('a thrown spawn error does not propagate and leaves the root usable', async () => {
326
- const root = makeRoot();
327
- const lock = path.join(root, '.codegraph', 'pi-sync.lock');
328
- let attempts = 0;
329
- const { deps, spawns } = makeDeps(root, {
330
- spawn: () => { attempts += 1; throw new Error('boom'); },
331
- });
332
- assert.doesNotThrow(() => session.scheduleSync(path.join(root, 'a.js'), deps));
333
- await session.whenIdle();
334
- assert.equal(attempts, 1);
335
- assert.equal(spawns.length, 1, 'one launch was attempted');
336
- assert.ok(!fs.existsSync(lock), 'the lock is released after a failed spawn');
337
- assert.equal(session.scheduleSync(path.join(root, 'a.js'), deps).scheduled, true);
338
- await session.whenIdle();
339
- assert.equal(attempts, 2, 'the root is not stuck in a running state');
581
+ test('S2: a compaction sync that throws never reaches the host and leaves a search unblocked', async () => {
582
+ const { pi, ctx } = setup({
583
+ impl: {
584
+ compactionSync: () => {
585
+ throw new Error('boom');
586
+ },
587
+ },
340
588
  });
589
+ assert.equal(pi.handlers.get('session_compact')[0]({}, ctx), undefined, 'the host is handed nothing');
590
+ for (let tick = 0; tick < 3; tick += 1) await new Promise((resolve) => setImmediate(resolve));
591
+ assert.equal(pi.handlers.get('tool_call')[0](searchCall(), ctx), undefined, 'a failed compaction is not something to join');
592
+ });
341
593
 
342
- test('a missing or unknown path is a decision, never a throw', async () => {
343
- const { deps, spawns } = makeDeps(makeRoot());
344
- assert.doesNotThrow(() => session.scheduleSync(undefined, deps));
345
- assert.deepEqual(session.scheduleSync('', deps), { scheduled: false, reason: 'no-path' });
346
- await session.whenIdle();
347
- assert.equal(spawns.length, 0);
594
+ test('S2: a search joins a running edit-sync window, bounded by the same budget', async () => {
595
+ const gate = gateOf();
596
+ const asked = [];
597
+ let busy = true;
598
+ const { pi, ctx } = setup({
599
+ impl: {
600
+ createEditSync: () => ({
601
+ onToolResult: async () => {},
602
+ dispose: () => {},
603
+ inFlight: () => busy,
604
+ whenIdle: (root, budgetMs) => {
605
+ asked.push([root, budgetMs]);
606
+ return gate.gate;
607
+ },
608
+ }),
609
+ },
348
610
  });
611
+ const returned = pi.handlers.get('tool_call')[0](searchCall('mcp__codegraph__codegraph_explore'), ctx);
612
+ assert.equal(typeof returned?.then, 'function');
613
+ assert.deepEqual(asked, [['/work/repo', 5000]], 'the window of the same checkout, with the default budget');
614
+ busy = false;
615
+ assert.equal(pi.handlers.get('tool_call')[0](searchCall(), ctx), undefined, 'an idle window is not waited for');
616
+ gate.release('done');
617
+ assert.equal(await returned, undefined);
618
+ });
619
+
620
+ test('S2: an idle checkout adds no wait at all', () => {
621
+ const { pi, ctx } = setup();
622
+ const returned = pi.handlers.get('tool_call')[0](searchCall(), ctx);
623
+ assert.equal(returned, undefined, 'nothing in flight: the tool runs at once');
349
624
  });
350
625
 
351
- // The creation hooks consult the one session gate (S3). An injected
352
- // `hasBinary` stays authoritative, so every pre-existing caller keeps its
353
- // behavior.
354
- describe('codegraph init follows the session gate (S3)', () => {
355
- function roots() {
356
- return { principalRoot: tempDir('cg-principal-'), worktreePath: tempDir('cg-worktree-') };
626
+ test('S2: every other tool answers undefined at once, even while the index is being written', async () => {
627
+ const gate = gateOf();
628
+ const { pi, ctx } = setup({ impl: { prepareProject: () => gate.gate } });
629
+ pi.handlers.get('session_start')[0]({ reason: 'startup' }, ctx);
630
+ await new Promise((resolve) => setImmediate(resolve));
631
+ for (const event of [
632
+ { toolName: 'bash', input: { command: 'ls' } },
633
+ { toolName: 'read', input: { path: 'src/a.js' } },
634
+ { toolName: 'grep', input: { pattern: 'x' } },
635
+ { toolName: 'mcp__context7__query-docs', input: {} },
636
+ { toolName: 'codegraph', input: { operation: 'init' } },
637
+ { toolName: 'codegraph', input: { operation: 'sync' } },
638
+ { toolName: 'codegraph', input: { operation: 'status' } },
639
+ { toolName: 'codegraph', input: {} },
640
+ { toolName: 'codegraph' },
641
+ {},
642
+ ]) {
643
+ assert.equal(pi.handlers.get('tool_call')[0](event, ctx), undefined, JSON.stringify(event));
357
644
  }
645
+ assert.equal(typeof pi.handlers.get('tool_call')[0](searchCall('codegraph', { operation: 'explore' }), ctx)?.then, 'function', 'the two search operations are the ones that join');
646
+ gate.release({ index: { action: 'none', ok: true }, warm: 'skipped' });
647
+ });
358
648
 
359
- test('a false gate skips init with a reason that names the session gate', () => {
360
- const { principalRoot, worktreePath } = roots();
361
- const runs = [];
362
- const out = hooksLib.runCreationHooks({
363
- principalRoot,
364
- worktreePath,
365
- env: { PATH: tempDir('cg-empty-') },
366
- run: (bin, args) => { runs.push([bin, ...args]); return { status: 1, stdout: '', stderr: '', error: null }; },
367
- unversionedCandidates: [],
368
- });
369
- const step = out.steps.find((entry) => entry.name === 'codegraph-init');
370
- assert.equal(step.status, 'skipped');
371
- assert.match(step.detail, /session gate/);
372
- assert.ok(!runs.some(([bin]) => bin === 'codegraph'), 'no codegraph child runs');
649
+ test('S2: a join that throws leaves the call unblocked', () => {
650
+ const { pi, ctx } = setup({
651
+ joinIndexWork: () => {
652
+ throw new Error('boom');
653
+ },
373
654
  });
655
+ assert.equal(pi.handlers.get('tool_call')[0](searchCall(), ctx), undefined, 'a failing seam never reaches the host');
656
+ });
374
657
 
375
- test('the async twin reads the same gate decision', async () => {
376
- const { principalRoot, worktreePath } = roots();
377
- const runs = [];
378
- const out = await hooksLib.runCreationHooksAsync({
379
- principalRoot,
380
- worktreePath,
381
- env: { PATH: tempDir('cg-empty-') },
382
- runAsync: async (bin, args) => {
383
- runs.push([bin, ...args]);
384
- return { status: 1, stdout: '', stderr: '', error: null };
385
- },
386
- unversionedCandidates: [],
387
- });
388
- const step = out.steps.find((entry) => entry.name === 'codegraph-init');
389
- assert.equal(step.status, 'skipped');
390
- assert.match(step.detail, /session gate/);
391
- assert.ok(!runs.some(([bin]) => bin === 'codegraph'));
392
- });
658
+ test('S2: a join that rejects is swallowed', async () => {
659
+ const { pi, ctx } = setup({ joinIndexWork: () => Promise.reject(new Error('boom')) });
660
+ assert.equal(await pi.handlers.get('tool_call')[0](searchCall(), ctx), undefined);
661
+ });
393
662
 
394
- test('an injected hasBinary still decides, unchanged', () => {
395
- const { principalRoot, worktreePath } = roots();
396
- const runs = [];
397
- const out = hooksLib.runCreationHooks({
398
- principalRoot,
399
- worktreePath,
400
- env: { PATH: '' },
401
- hasBinary: (bin) => bin === 'codegraph',
402
- run: (bin, args) => {
403
- runs.push([bin, ...args]);
404
- return { status: bin === 'codegraph' ? 0 : 1, stdout: '', stderr: '', error: null };
405
- },
406
- unversionedCandidates: [],
407
- });
408
- const step = out.steps.find((entry) => entry.name === 'codegraph-init');
409
- assert.equal(step.status, 'done');
410
- assert.ok(runs.some(([bin, arg]) => bin === 'codegraph' && arg === 'init'));
663
+ test('S2: a join that never settles is capped by its budget and never blocks the tool', async () => {
664
+ let askedMs;
665
+ const { pi, ctx } = setup({
666
+ joinIndexWork: () => new Promise(() => {}),
667
+ delay: (ms) => {
668
+ askedMs = ms;
669
+ return new Promise((resolve) => setImmediate(resolve));
670
+ },
411
671
  });
672
+ const returned = pi.handlers.get('tool_call')[0](searchCall(), ctx);
673
+ assert.equal(typeof returned?.then, 'function');
674
+ assert.equal(await returned, undefined, 'the budget ends the wait, not the work');
675
+ assert.equal(askedMs, 5000, 'the default budget is five seconds');
676
+ });
412
677
 
413
- test('an injected hasBinary that says no keeps the old skip reason', () => {
414
- const { principalRoot, worktreePath } = roots();
415
- const out = hooksLib.runCreationHooks({
416
- principalRoot,
417
- worktreePath,
418
- env: { PATH: '' },
419
- hasBinary: () => false,
420
- run: () => ({ status: 1, stdout: '', stderr: '', error: null }),
421
- unversionedCandidates: [],
422
- });
423
- const step = out.steps.find((entry) => entry.name === 'codegraph-init');
424
- assert.equal(step.status, 'skipped');
425
- assert.equal(step.detail, 'codegraph not on PATH');
678
+ test('S2: a delay seam that throws still ends the wait instead of awaiting work that never settles', async () => {
679
+ const { pi, ctx } = setup({
680
+ env: { ODD_WORKTREE_CODEGRAPH_JOIN_MS: '250' },
681
+ joinIndexWork: () => new Promise(() => {}),
682
+ delay: () => {
683
+ throw new Error('no timer here');
684
+ },
685
+ });
686
+ const started = Date.now();
687
+ const returned = pi.handlers.get('tool_call')[0](searchCall(), ctx);
688
+ assert.equal(typeof returned?.then, 'function', 'the search still gets an answer to wait for');
689
+ let guard;
690
+ const capped = new Promise((resolve) => {
691
+ guard = setTimeout(() => resolve('unbounded'), 1_000);
426
692
  });
693
+ try {
694
+ assert.equal(await Promise.race([returned, capped]), undefined, 'a throwing timer seam answers at once, never with the joined work');
695
+ } finally {
696
+ clearTimeout(guard);
697
+ }
698
+ const elapsed = Date.now() - started;
699
+ assert.ok(elapsed < 500, `the wait settled well inside the small bound (${elapsed}ms)`);
427
700
  });
428
701
 
429
- // T2: the extension turns a successful edit/write into one scheduling call and
430
- // nothing else. scheduleSync is stubbed here so the assertion is only about the
431
- // wiring (its own behavior is covered above).
432
- describe('extension wiring (T2)', () => {
433
- test('a successful edit and write schedule a sync; everything else does not', async () => {
434
- const { loadExtension } = require('./fixtures/load-extension.js');
435
- const { hooks } = await loadExtension({});
436
- const handlers = hooks.filter(([name]) => name === 'tool_result').map(([, handler]) => handler);
437
- assert.ok(handlers.length >= 1, 'a tool_result handler is registered');
438
- const calls = [];
439
- const original = session.scheduleSync;
440
- session.scheduleSync = (filePath) => { calls.push(filePath); return { scheduled: true, reason: 'scheduled' }; };
441
- try {
442
- const ctx = { cwd: os.tmpdir() };
443
- for (const handler of handlers) {
444
- await handler({ toolName: 'edit', isError: false, input: { path: '/tmp/a.js' } }, ctx);
445
- await handler({ toolName: 'write', isError: false, input: { path: '/tmp/b.js' } }, ctx);
446
- await handler({ toolName: 'edit', isError: true, input: { path: '/tmp/c.js' } }, ctx);
447
- await handler({ toolName: 'bash', isError: false, input: { command: 'ls' } }, ctx);
448
- await handler({ toolName: 'edit', isError: false, input: {} }, ctx);
449
- await handler({ toolName: 'edit', isError: false }, ctx);
450
- await handler({}, ctx);
451
- }
452
- } finally {
453
- session.scheduleSync = original;
702
+ test('S2: the join budget is five seconds, overridable, and 0 disables the join entirely', () => {
703
+ const asked = [];
704
+ const joinIndexWork = (root, budgetMs) => {
705
+ asked.push([root, budgetMs]);
706
+ return undefined;
707
+ };
708
+ for (const [env, expected] of [
709
+ [{}, 5000],
710
+ [{ ODD_WORKTREE_CODEGRAPH_JOIN_MS: '250' }, 250],
711
+ [{ ODD_WORKTREE_CODEGRAPH_JOIN_MS: '0' }, 0],
712
+ [{ ODD_WORKTREE_CODEGRAPH_JOIN_MS: 'later' }, 5000],
713
+ [{ ODD_WORKTREE_CODEGRAPH_JOIN_MS: '-5' }, 5000],
714
+ ]) {
715
+ const { pi, ctx } = setup({ joinIndexWork, env });
716
+ const returned = pi.handlers.get('tool_call')[0](searchCall(), ctx);
717
+ const label = JSON.stringify(env);
718
+ assert.equal(returned, undefined, `${label}: the seam answered nothing to wait for`);
719
+ if (expected === 0) {
720
+ assert.equal(asked.length, 0, 'a disabled join is not even attempted');
721
+ continue;
454
722
  }
455
- assert.deepEqual(calls, ['/tmp/a.js', '/tmp/b.js']);
456
- });
723
+ assert.deepEqual(asked.pop(), ['/work/repo', expected], label);
724
+ }
725
+ assert.deepEqual(asked, []);
457
726
  });