pi-odd-worktree 2.0.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 -311
  2. package/extensions/odd-worktree-tools.ts +4149 -2447
  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 -711
  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 +2569 -308
  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 +477 -93
  151. package/lib/codegraph-commands.js +0 -165
  152. package/lib/odd-prompt/odd-worktrees.with-codegraph.md +0 -19
  153. package/lib/odd-prompt/odd-worktrees.without-codegraph.md +0 -15
  154. package/lib/worktree-model-result.js +0 -291
  155. package/tools/codegraph-commands.test.js +0 -371
  156. package/tools/herdr-free-create.test.js +0 -161
  157. package/tools/worktree-close-herdr-async.test.js +0 -204
  158. package/tools/worktree-odd-migration.test.js +0 -224
  159. package/tools/worktree-registry-cache.test.js +0 -163
  160. package/tools/worktree-registry-odd.test.js +0 -231
@@ -0,0 +1,1948 @@
1
+ 'use strict';
2
+ // Index preparation (S2, S3) through the public surface: create-or-sync per root, a linked worktree seeded from the
3
+ // main checkout's index, every write under the init lock and the per-project sync lease, and notices that never
4
+ // overstate what happened. No real codegraph, daemon or network runs here: the command, the lock, the lease and the
5
+ // PATH probe are all injected.
6
+
7
+ const { test, after } = require('node:test');
8
+ const assert = require('node:assert/strict');
9
+ const fs = require('node:fs');
10
+ const os = require('node:os');
11
+ const path = require('node:path');
12
+ const { spawn } = require('node:child_process');
13
+
14
+ const {
15
+ INIT_TIMEOUT_MS,
16
+ KILL_ESCALATION_MS,
17
+ KILL_WAIT_MS,
18
+ POST_INIT_SYNC_WAIT_MS,
19
+ SYNC_TIMEOUT_MS,
20
+ autoIndex,
21
+ codegraphWritingIndex,
22
+ findIndexRoot,
23
+ indexOutcomeNotice,
24
+ indexStartNotice,
25
+ initHookDecision,
26
+ isNativeInitResult,
27
+ linkedWorktrees,
28
+ noticeTools,
29
+ planIndexAction,
30
+ postInitSyncNotice,
31
+ prepareProject,
32
+ runCodegraph,
33
+ seedLinkedWorktrees,
34
+ seedWorktreeIndex,
35
+ syncAfterNativeInit,
36
+ warmOutcomeNotice,
37
+ worktreeIndexAction,
38
+ worktreeOf,
39
+ } = require('../lib/codegraph-index.js');
40
+
41
+ const CWD = path.join('some', 'repo');
42
+ const has = (...present) => (p) => present.some((name) => p.endsWith(name));
43
+ const yes = () => true;
44
+ const no = () => false;
45
+
46
+ function fakeRun(calls, ok = true) {
47
+ return async (args, cwd) => {
48
+ calls.push({ args, cwd });
49
+ return ok;
50
+ };
51
+ }
52
+
53
+ let sequence = 0;
54
+ const scratchDirs = [];
55
+ after(() => {
56
+ for (const dir of scratchDirs) {
57
+ try {
58
+ fs.rmSync(dir, { recursive: true, force: true });
59
+ } catch {
60
+ // Best effort.
61
+ }
62
+ }
63
+ });
64
+
65
+ function temp(prefix) {
66
+ sequence += 1;
67
+ const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), `${prefix}${sequence}-`)));
68
+ scratchDirs.push(dir);
69
+ return dir;
70
+ }
71
+
72
+ /** A project with no coordination at all: the unit-test shape of one session that runs its own command. */
73
+ function bare(extra) {
74
+ return { cwd: CWD, env: {}, reason: 'startup', hasBinary: yes, lock: null, sync: null, ...extra };
75
+ }
76
+
77
+ /** An index lock that records what it was asked and who holds it. */
78
+ function recordingLock(log, held, initRunning = held) {
79
+ return {
80
+ acquire: (project, options) => {
81
+ log.push(`acquire:${(options && options.kind) || 'init'}:${project}`);
82
+ return held
83
+ ? { status: 'busy' }
84
+ : { status: 'acquired', adopt: () => {}, release: () => log.push('release') };
85
+ },
86
+ isHeld: () => {
87
+ log.push('isHeld');
88
+ return held;
89
+ },
90
+ isInitRunning: () => initRunning,
91
+ };
92
+ }
93
+
94
+ function fakeLock(log, held) {
95
+ return {
96
+ acquire: () => {
97
+ log.push('lock:acquire');
98
+ return held
99
+ ? { status: 'busy' }
100
+ : {
101
+ status: 'acquired',
102
+ adopt: (pid, options) => log.push(`lock:adopt:${pid}${options && options.proxy ? ':proxy' : ''}`),
103
+ release: () => log.push('lock:release'),
104
+ };
105
+ },
106
+ isHeld: () => {
107
+ log.push('lock:isHeld');
108
+ return held;
109
+ },
110
+ };
111
+ }
112
+
113
+ /** A coordinator that runs the attempt here and now, like a session that found the lease free. */
114
+ const runsHere = (log) => ({
115
+ request: async (project, attempt) => {
116
+ if (log !== undefined) log.push(`coordinate:${project}`);
117
+ const result = await attempt(() => {});
118
+ return result.ran ? { status: 'ran', ok: result.ok === true } : { status: 'queued' };
119
+ },
120
+ });
121
+
122
+ // ---- Create-or-sync (S2) ----
123
+
124
+ test('S2: with .codegraph in the directory where the session starts, a new session runs `codegraph sync` there', async () => {
125
+ const calls = [];
126
+ const result = await autoIndex(bare({ exists: has('.codegraph'), run: fakeRun(calls) }));
127
+ assert.deepEqual(calls, [{ args: ['sync', '-q'], cwd: CWD }]);
128
+ assert.deepEqual(result, { action: 'sync', ok: true });
129
+ });
130
+
131
+ test('S2: .codegraph present never triggers init, even with .git and package.json', async () => {
132
+ const calls = [];
133
+ await autoIndex(bare({ exists: has('.codegraph', '.git', 'package.json'), run: fakeRun(calls) }));
134
+ assert.deepEqual(calls.map((call) => call.args), [['sync', '-q']]);
135
+ });
136
+
137
+ test('S2: no .codegraph, .git and package.json -> `codegraph init -y`', async () => {
138
+ const calls = [];
139
+ const result = await autoIndex(bare({ exists: has('.git', 'package.json'), run: fakeRun(calls) }));
140
+ assert.deepEqual(calls, [{ args: ['init', '-y'], cwd: CWD }]);
141
+ assert.deepEqual(result, { action: 'init', ok: true });
142
+ });
143
+
144
+ test('S2: no .codegraph, .git and composer.json -> `codegraph init -y`', async () => {
145
+ const calls = [];
146
+ await autoIndex(bare({ exists: has('.git', 'composer.json'), run: fakeRun(calls) }));
147
+ assert.deepEqual(calls.map((call) => call.args), [['init', '-y']]);
148
+ });
149
+
150
+ test('S2: every other project marker next to .git also triggers init, and never without .git', async () => {
151
+ for (const marker of ['pyproject.toml', 'go.mod', 'Cargo.toml', 'Gemfile', 'pom.xml', 'build.gradle', 'build.gradle.kts']) {
152
+ const calls = [];
153
+ await autoIndex(bare({ exists: has('.git', marker), run: fakeRun(calls) }));
154
+ assert.deepEqual(calls.map((call) => call.args), [['init', '-y']], marker);
155
+ const noGit = [];
156
+ await autoIndex(bare({ exists: has(marker), run: fakeRun(noGit) }));
157
+ assert.deepEqual(noGit, [], `${marker} without .git`);
158
+ }
159
+ });
160
+
161
+ test('S2: .git without any project marker does nothing, and so do the markers without .git', async () => {
162
+ const calls = [];
163
+ const result = await autoIndex(bare({ exists: has('.git', 'README.md'), run: fakeRun(calls) }));
164
+ assert.deepEqual(calls, []);
165
+ assert.deepEqual(result, { action: 'none', ok: true });
166
+ const more = [];
167
+ await autoIndex(bare({ exists: has('package.json', 'composer.json'), run: fakeRun(more) }));
168
+ assert.deepEqual(more, []);
169
+ });
170
+
171
+ test('S2: planIndexAction is a pure decision over the three paths', () => {
172
+ assert.equal(planIndexAction(CWD, has('.codegraph')), 'sync');
173
+ assert.equal(planIndexAction(CWD, has('.git', 'package.json')), 'init');
174
+ assert.equal(planIndexAction(CWD, has()), 'none');
175
+ });
176
+
177
+ test('S2: a subagent child never syncs or inits in the parent project', async () => {
178
+ const calls = [];
179
+ const result = await autoIndex(bare({ env: { GENTLE_PI_AGENTS_CHILD: '1' }, exists: has('.codegraph'), run: fakeRun(calls) }));
180
+ assert.deepEqual(calls, []);
181
+ assert.deepEqual(result, { action: 'none', ok: true });
182
+ });
183
+
184
+ test('S2: a /reload does nothing; startup, new, resume and fork do', async () => {
185
+ const calls = [];
186
+ await autoIndex(bare({ reason: 'reload', exists: has('.codegraph'), run: fakeRun(calls) }));
187
+ assert.deepEqual(calls, []);
188
+ for (const reason of ['startup', 'new', 'resume', 'fork']) {
189
+ const runs = [];
190
+ await autoIndex(bare({ reason, exists: has('.codegraph'), run: fakeRun(runs) }));
191
+ assert.equal(runs.length, 1, reason);
192
+ }
193
+ });
194
+
195
+ test('S2: a failing or throwing command is reported as not ok and never rejects', async () => {
196
+ const failed = await autoIndex(bare({ exists: has('.codegraph'), run: fakeRun([], false) }));
197
+ assert.deepEqual(failed, { action: 'sync', ok: false });
198
+ const thrown = await autoIndex(bare({
199
+ exists: has('.codegraph'),
200
+ run: async () => {
201
+ throw new Error('boom');
202
+ },
203
+ }));
204
+ assert.deepEqual(thrown, { action: 'sync', ok: false });
205
+ });
206
+
207
+ test('S2: onStart announces the action before the command runs, and only when one runs', async () => {
208
+ for (const [present, expected] of [[['.codegraph'], 'sync'], [['.git', 'package.json'], 'init']]) {
209
+ const order = [];
210
+ await autoIndex(bare({
211
+ exists: has(...present),
212
+ onStart: (action) => order.push(`start:${action}`),
213
+ run: async () => {
214
+ order.push('run');
215
+ return true;
216
+ },
217
+ }));
218
+ assert.deepEqual(order, [`start:${expected}`, 'run']);
219
+ }
220
+ const silent = [];
221
+ const skipped = [
222
+ { present: ['.git'], env: {}, reason: 'startup' },
223
+ { present: ['.codegraph'], env: { GENTLE_PI_AGENTS_CHILD: '1' }, reason: 'startup' },
224
+ { present: ['.codegraph'], env: {}, reason: 'reload' },
225
+ ];
226
+ for (const { present, env, reason } of skipped) {
227
+ await autoIndex(bare({ env, reason, exists: has(...present), onStart: (action) => silent.push(action), run: fakeRun([]) }));
228
+ }
229
+ assert.deepEqual(silent, []);
230
+ });
231
+
232
+ test('S2: a throwing onStart does not stop the command', async () => {
233
+ const calls = [];
234
+ const result = await autoIndex(bare({
235
+ exists: has('.codegraph'),
236
+ onStart: () => {
237
+ throw new Error('ui gone');
238
+ },
239
+ run: fakeRun(calls),
240
+ }));
241
+ assert.equal(calls.length, 1);
242
+ assert.deepEqual(result, { action: 'sync', ok: true });
243
+ });
244
+
245
+ test('S6: a read-only role starts no index write at all', async () => {
246
+ const calls = [];
247
+ const readOnly = await autoIndex(bare({ exists: has('.codegraph'), role: 'read-only', run: fakeRun(calls) }));
248
+ assert.deepEqual(readOnly, { action: 'none', ok: true, skipped: 'read-only' });
249
+ const notAllowed = await autoIndex(bare({ exists: has('.git', 'package.json'), mayWrite: false, run: fakeRun(calls) }));
250
+ assert.deepEqual(notAllowed, { action: 'none', ok: true, skipped: 'read-only' });
251
+ assert.deepEqual(calls, []);
252
+ });
253
+
254
+ test('S2: the codegraph CLI presence is probed once per process, and without it nothing runs', async () => {
255
+ const probes = [];
256
+ const hasBinary = (command) => {
257
+ probes.push(command);
258
+ return false;
259
+ };
260
+ const calls = [];
261
+ const first = await autoIndex(bare({ exists: has('.codegraph'), hasBinary, run: fakeRun(calls) }));
262
+ const second = await autoIndex(bare({ exists: has('.git', 'package.json'), hasBinary, run: fakeRun(calls) }));
263
+ assert.deepEqual(probes, ['codegraph']);
264
+ assert.deepEqual(calls, []);
265
+ assert.deepEqual(first, { action: 'none', ok: true, skipped: 'no-cli' });
266
+ assert.deepEqual(second, { action: 'none', ok: true, skipped: 'no-cli' });
267
+ });
268
+
269
+ // ---- Every write under the locks (S3) ----
270
+
271
+ test('S3: the init runs holding the lock, taken before anything is announced and released afterwards, whatever the outcome', async () => {
272
+ for (const outcome of ['ok', 'fail', 'throw']) {
273
+ const log = [];
274
+ const result = await autoIndex(bare({
275
+ exists: has('.git', 'package.json'),
276
+ lock: fakeLock(log, false),
277
+ onStart: (action) => log.push(`start:${action}`),
278
+ run: async (args) => {
279
+ log.push(`run:${args[0]}`);
280
+ if (outcome === 'throw') throw new Error('boom');
281
+ return outcome === 'ok';
282
+ },
283
+ }));
284
+ assert.deepEqual(log, ['lock:acquire', 'start:init', 'run:init', 'lock:release'], outcome);
285
+ assert.equal(result.action, 'init', outcome);
286
+ assert.equal(result.ok, outcome === 'ok', outcome);
287
+ }
288
+ });
289
+
290
+ test('S3: a session that finds the init lock held does nothing: no init, no announcement', async () => {
291
+ const log = [];
292
+ const result = await autoIndex(bare({
293
+ exists: has('.git', 'package.json'),
294
+ lock: fakeLock(log, true),
295
+ onStart: (action) => log.push(`start:${action}`),
296
+ run: async (args) => {
297
+ log.push(`run:${args[0]}`);
298
+ return true;
299
+ },
300
+ }));
301
+ assert.deepEqual(log, ['lock:acquire']);
302
+ assert.deepEqual(result, { action: 'init', ok: true, joined: true });
303
+ });
304
+
305
+ test('S3: while another session holds the init lock, an existing .codegraph is not synced either', async () => {
306
+ const log = [];
307
+ const result = await autoIndex(bare({
308
+ exists: has('.codegraph'),
309
+ lock: fakeLock(log, true),
310
+ onStart: (action) => log.push(`start:${action}`),
311
+ run: async (args) => {
312
+ log.push(`run:${args[0]}`);
313
+ return true;
314
+ },
315
+ }));
316
+ assert.deepEqual(log, ['lock:isHeld']);
317
+ assert.deepEqual(result, { action: 'sync', ok: true, joined: true });
318
+ });
319
+
320
+ test('S3: with no init lock held an existing index is synced under the index lock as a sync', async () => {
321
+ const log = [];
322
+ const result = await autoIndex(bare({
323
+ exists: has('.codegraph'),
324
+ lock: recordingLock(log, false),
325
+ run: async (args) => {
326
+ log.push(`run:${args[0]}`);
327
+ return true;
328
+ },
329
+ }));
330
+ assert.deepEqual(log, ['isHeld', `acquire:sync:${CWD}`, 'run:sync', 'release']);
331
+ assert.deepEqual(result, { action: 'sync', ok: true });
332
+ });
333
+
334
+ test("S3: an init that fails while CodeGraph's own lock names a live process is a join, and nothing else runs", async () => {
335
+ const calls = [];
336
+ let created = false;
337
+ const result = await autoIndex(bare({
338
+ exists: (p) => p.endsWith('.git') || p.endsWith('package.json') || (created && p.endsWith('.codegraph')),
339
+ codegraphBusy: () => true,
340
+ run: async (args, cwd) => {
341
+ calls.push({ args, cwd });
342
+ if (args[0] === 'init') {
343
+ created = true;
344
+ return false;
345
+ }
346
+ return true;
347
+ },
348
+ }));
349
+ assert.deepEqual(calls.map((call) => call.args), [['init', '-y']]);
350
+ assert.deepEqual(result, { action: 'init', ok: true, joined: true });
351
+ });
352
+
353
+ test("S3: an init of this session that creates .codegraph and fails is a failure, not a join", async () => {
354
+ const calls = [];
355
+ let created = false;
356
+ const result = await autoIndex(bare({
357
+ exists: (p) => p.endsWith('.git') || p.endsWith('package.json') || (created && p.endsWith('.codegraph')),
358
+ codegraphBusy: () => false,
359
+ run: async (args, cwd) => {
360
+ calls.push({ args, cwd });
361
+ if (args[0] === 'init') {
362
+ created = true;
363
+ return false;
364
+ }
365
+ return true;
366
+ },
367
+ }));
368
+ assert.deepEqual(calls.map((call) => call.args), [['init', '-y']]);
369
+ assert.deepEqual(result, { action: 'init', ok: false });
370
+ });
371
+
372
+ test('S3: when another party created .codegraph after planning, this session joins without running or announcing', async () => {
373
+ const log = [];
374
+ let lookups = 0;
375
+ const result = await autoIndex(bare({
376
+ // The first lookup is the plan; by the time this session has the lock, the index is there.
377
+ exists: (p) => {
378
+ if (p.endsWith('.codegraph')) {
379
+ lookups += 1;
380
+ return lookups > 1;
381
+ }
382
+ return p.endsWith('.git') || p.endsWith('package.json');
383
+ },
384
+ lock: fakeLock(log, false),
385
+ onStart: (action) => log.push(`start:${action}`),
386
+ run: async (args) => {
387
+ log.push(`run:${args[0]}`);
388
+ return true;
389
+ },
390
+ }));
391
+ assert.deepEqual(log, ['lock:acquire', 'lock:release']);
392
+ assert.deepEqual(result, { action: 'init', ok: true, joined: true });
393
+ assert.equal(lookups, 2);
394
+ });
395
+
396
+ test('S3: the join does not depend on having a lock: an index created after planning is left alone too', async () => {
397
+ const calls = [];
398
+ let lookups = 0;
399
+ const result = await autoIndex(bare({
400
+ exists: (p) => {
401
+ if (p.endsWith('.codegraph')) {
402
+ lookups += 1;
403
+ return lookups > 1;
404
+ }
405
+ return p.endsWith('.git') || p.endsWith('package.json');
406
+ },
407
+ run: fakeRun(calls),
408
+ }));
409
+ assert.deepEqual(calls, []);
410
+ assert.deepEqual(result, { action: 'init', ok: true, joined: true });
411
+ });
412
+
413
+ test("S3: the pid of this session's init is adopted by the lock, and only the shell is recorded as a proxy", async () => {
414
+ const log = [];
415
+ await autoIndex(bare({
416
+ exists: has('.git', 'package.json'),
417
+ lock: fakeLock(log, false),
418
+ run: async (args, cwd, timeoutMs, onSpawn) => {
419
+ log.push(`run:${args[0]}:${timeoutMs}`);
420
+ onSpawn(4242);
421
+ return true;
422
+ },
423
+ }));
424
+ assert.deepEqual(log, ['lock:acquire', 'run:init:600000', 'lock:adopt:4242', 'lock:release']);
425
+
426
+ const proxied = [];
427
+ await autoIndex(bare({
428
+ exists: has('.git', 'package.json'),
429
+ lock: fakeLock(proxied, false),
430
+ run: async (args, cwd, timeoutMs, onSpawn) => {
431
+ onSpawn(4242, { proxy: true });
432
+ return true;
433
+ },
434
+ }));
435
+ assert.ok(proxied.includes('lock:adopt:4242:proxy'), proxied.join(','));
436
+ });
437
+
438
+ test('S3: an index locked by another sync leaves the request pending, and it is never reported as synced', async () => {
439
+ const log = [];
440
+ const result = await autoIndex(bare({
441
+ exists: has('.codegraph'),
442
+ // Another session's sync holds the index, not an init: the index exists and only the lease is missing.
443
+ lock: recordingLock(log, true, false),
444
+ run: async (args) => {
445
+ log.push(`run:${args[0]}`);
446
+ return true;
447
+ },
448
+ }));
449
+ assert.ok(!log.includes('run:sync'), 'nothing was run: the index belongs to another writer');
450
+ assert.deepEqual(result, { action: 'sync', ok: true, queued: true });
451
+ });
452
+
453
+ test('S3: a startup sync goes through the coordinator, which runs the quiet command once', async () => {
454
+ const calls = [];
455
+ const seen = [];
456
+ const result = await autoIndex(bare({ exists: has('.codegraph'), sync: runsHere(seen), run: fakeRun(calls) }));
457
+ assert.deepEqual(seen, [`coordinate:${CWD}`]);
458
+ assert.deepEqual(calls, [{ args: ['sync', '-q'], cwd: CWD }]);
459
+ assert.deepEqual(result, { action: 'sync', ok: true });
460
+ });
461
+
462
+ test('S3: while another session syncs, this one leaves the run to it and says so', async () => {
463
+ const calls = [];
464
+ const announced = [];
465
+ const result = await autoIndex(bare({
466
+ exists: has('.codegraph'),
467
+ onStart: (action) => announced.push(action),
468
+ sync: { request: async () => ({ status: 'coalesced' }) },
469
+ run: fakeRun(calls),
470
+ }));
471
+ assert.deepEqual(calls, [], 'this session ran nothing: the other session syncs');
472
+ assert.deepEqual(announced, ['sync']);
473
+ assert.deepEqual(result, { action: 'sync', ok: true, coalesced: true });
474
+ });
475
+
476
+ test('S3: a coalesced startup sync still reports the failure the runner hit', async () => {
477
+ const result = await autoIndex(bare({ exists: has('.codegraph'), sync: runsHere(), run: fakeRun([], false) }));
478
+ assert.deepEqual(result, { action: 'sync', ok: false });
479
+ });
480
+
481
+ test('S3: a startup sync that is still waiting for the index is reported as queued, not as a failure', async () => {
482
+ const calls = [];
483
+ const result = await autoIndex(bare({
484
+ exists: has('.codegraph'),
485
+ sync: { request: async () => ({ status: 'queued' }) },
486
+ run: fakeRun(calls),
487
+ }));
488
+ assert.deepEqual(calls, []);
489
+ assert.deepEqual(result, { action: 'sync', ok: true, queued: true });
490
+ });
491
+
492
+ test('S3: unusable sync coordination starts no sync and is reported as such (fail closed)', async () => {
493
+ const calls = [];
494
+ const result = await autoIndex(bare({
495
+ exists: has('.codegraph'),
496
+ sync: { request: async () => ({ status: 'unavailable' }) },
497
+ run: fakeRun(calls),
498
+ }));
499
+ assert.deepEqual(calls, []);
500
+ assert.deepEqual(result, { action: 'sync', ok: false, unavailable: true });
501
+ });
502
+
503
+ test("S3: a startup sync during another session's sync is coalesced, not skipped as if an init ran", async () => {
504
+ const log = [];
505
+ const calls = [];
506
+ const result = await autoIndex(bare({
507
+ exists: has('.codegraph'),
508
+ lock: { ...fakeLock(log, true), isInitRunning: () => false },
509
+ sync: {
510
+ request: async () => {
511
+ log.push('coordinate');
512
+ return { status: 'coalesced' };
513
+ },
514
+ },
515
+ run: fakeRun(calls),
516
+ }));
517
+ assert.deepEqual(log, ['lock:isHeld', 'coordinate'], 'the index is locked by a sync, so this request is coalesced');
518
+ assert.deepEqual(result, { action: 'sync', ok: true, coalesced: true });
519
+ });
520
+
521
+ test('S3: with an init running, startup does not even ask for a coordinated sync', async () => {
522
+ const calls = [];
523
+ let asked = false;
524
+ const result = await autoIndex(bare({
525
+ exists: has('.codegraph'),
526
+ lock: { ...fakeLock([], true), isInitRunning: () => true },
527
+ sync: {
528
+ request: async () => {
529
+ asked = true;
530
+ return { status: 'coalesced' };
531
+ },
532
+ },
533
+ run: fakeRun(calls),
534
+ }));
535
+ assert.equal(asked, false);
536
+ assert.deepEqual(calls, []);
537
+ assert.deepEqual(result, { action: 'sync', ok: true, joined: true });
538
+ });
539
+
540
+ test('S3: a coordinated startup sync holds the index lock as a sync while it runs', async () => {
541
+ const log = [];
542
+ const lock = {
543
+ acquire: (_project, options) => {
544
+ log.push(`lock:acquire:${(options && options.kind) || 'init'}`);
545
+ return {
546
+ status: 'acquired',
547
+ adopt: (pid) => log.push(`lock:adopt:${pid}`),
548
+ release: () => log.push('lock:release'),
549
+ };
550
+ },
551
+ isHeld: () => false,
552
+ isInitRunning: () => false,
553
+ };
554
+ const result = await autoIndex(bare({
555
+ exists: has('.codegraph'),
556
+ lock,
557
+ sync: runsHere(),
558
+ run: async (args, cwd, timeoutMs, onSpawn) => {
559
+ log.push(`run:${args[0]}`);
560
+ onSpawn(4242);
561
+ return true;
562
+ },
563
+ }));
564
+ assert.deepEqual(log, ['lock:acquire:sync', 'run:sync', 'lock:adopt:4242', 'lock:release']);
565
+ assert.deepEqual(result, { action: 'sync', ok: true });
566
+ });
567
+
568
+ test('S3: an init never goes through the sync coordinator', async () => {
569
+ const calls = [];
570
+ let asked = false;
571
+ await autoIndex(bare({
572
+ exists: has('.git', 'package.json'),
573
+ sync: {
574
+ request: async () => {
575
+ asked = true;
576
+ return { status: 'coalesced' };
577
+ },
578
+ },
579
+ run: fakeRun(calls),
580
+ }));
581
+ assert.equal(asked, false);
582
+ assert.deepEqual(calls.map((call) => call.args), [['init', '-y']]);
583
+ });
584
+
585
+ // ---- A linked worktree indexes its own tree, seeded from the main checkout (S2, S3) ----
586
+
587
+ /** A repository and one linked worktree of it, built on disk without running git. */
588
+ function linkedWorktree(base) {
589
+ const repo = path.join(base, 'repo');
590
+ const worktree = path.join(base, 'wt');
591
+ fs.mkdirSync(path.join(repo, '.git', 'worktrees', 'wt'), { recursive: true });
592
+ fs.mkdirSync(worktree);
593
+ fs.writeFileSync(path.join(worktree, '.git'), `gitdir: ${path.join(repo, '.git', 'worktrees', 'wt')}\n`);
594
+ return { repo, worktree };
595
+ }
596
+
597
+ /** Every real SQLite database, and so every CodeGraph index, starts with these 16 bytes. */
598
+ const INDEX_MAGIC = 'SQLite format 3\u0000';
599
+
600
+ /** A plausible fake index: what a seed copy seam must write now that the copy is validated before it is published. */
601
+ const fakeIndex = (payload = 'fake index payload') => INDEX_MAGIC + payload;
602
+
603
+ test('S2: a directory without .git, a plain repository, a broken pointer and the main checkout are not worktrees', () => {
604
+ const base = temp('cg-worktree-');
605
+ assert.deepEqual(worktreeOf(base), { worktree: false });
606
+ const plain = path.join(base, 'plain');
607
+ fs.mkdirSync(path.join(plain, '.git'), { recursive: true });
608
+ assert.deepEqual(worktreeOf(plain), { worktree: false });
609
+ const broken = path.join(base, 'broken');
610
+ fs.mkdirSync(broken);
611
+ fs.writeFileSync(path.join(broken, '.git'), 'not a gitdir pointer\n');
612
+ assert.deepEqual(worktreeOf(broken), { worktree: false });
613
+ const missing = path.join(base, 'missing');
614
+ fs.mkdirSync(missing);
615
+ fs.writeFileSync(path.join(missing, '.git'), `gitdir: ${path.join(base, 'nowhere')}\n`);
616
+ assert.deepEqual(worktreeOf(missing), { worktree: false });
617
+
618
+ const { repo, worktree } = linkedWorktree(path.join(base, 'real'));
619
+ const found = worktreeOf(worktree);
620
+ assert.equal(found.worktree, true, JSON.stringify(found));
621
+ assert.equal(found.commonRoot.toLowerCase(), repo.toLowerCase());
622
+ assert.deepEqual(worktreeOf(repo), { worktree: false });
623
+ });
624
+
625
+ test('S2: the worktree decision is seed, sync or the plain marker decision', () => {
626
+ const base = temp('cg-decision-');
627
+ const { repo, worktree } = linkedWorktree(path.join(base, 'a'));
628
+ fs.mkdirSync(path.join(repo, '.codegraph'));
629
+ fs.writeFileSync(path.join(repo, '.codegraph', 'codegraph.db'), 'seed bytes');
630
+ assert.deepEqual(worktreeIndexAction(worktree, fs.existsSync), { action: 'seed', commonRoot: repo });
631
+
632
+ const plainWorktree = linkedWorktree(path.join(base, 'b')).worktree;
633
+ assert.deepEqual(worktreeIndexAction(plainWorktree, fs.existsSync), { action: 'none' });
634
+ fs.writeFileSync(path.join(plainWorktree, 'package.json'), '{}\n');
635
+ assert.deepEqual(worktreeIndexAction(plainWorktree, fs.existsSync), { action: 'init' });
636
+
637
+ fs.mkdirSync(path.join(worktree, '.codegraph'));
638
+ assert.deepEqual(worktreeIndexAction(worktree, fs.existsSync), { action: 'sync' });
639
+
640
+ const plain = path.join(base, 'plain-repo');
641
+ fs.mkdirSync(path.join(plain, '.git'), { recursive: true });
642
+ assert.deepEqual(worktreeIndexAction(plain, fs.existsSync), { action: 'none' });
643
+ fs.writeFileSync(path.join(plain, 'package.json'), '{}\n');
644
+ assert.deepEqual(worktreeIndexAction(plain, fs.existsSync), { action: 'init' });
645
+ });
646
+
647
+ test('S2: seeding copies the db only from a main index nobody is writing, into the worktree', () => {
648
+ const base = temp('cg-seed-');
649
+ const { repo, worktree } = linkedWorktree(path.join(base, 'a'));
650
+ fs.mkdirSync(path.join(repo, '.codegraph'));
651
+ fs.writeFileSync(path.join(repo, '.codegraph', 'codegraph.db'), 'seed bytes');
652
+ const copied = [];
653
+ const seeded = seedWorktreeIndex({
654
+ worktree,
655
+ commonRoot: repo,
656
+ sourceBusy: () => copied.length > 0,
657
+ copy: (from, to) => {
658
+ copied.push(from);
659
+ fs.writeFileSync(to, fakeIndex('seed bytes'));
660
+ return true;
661
+ },
662
+ });
663
+ assert.equal(seeded, true, 'seeding ran');
664
+ assert.equal(copied.length, 1, 'exactly one copy, of the main index db');
665
+ assert.ok(copied[0].includes(path.join('.codegraph', 'codegraph.db')), JSON.stringify(copied));
666
+ assert.equal(fs.readFileSync(path.join(worktree, '.codegraph', 'codegraph.db'), 'utf8'), fakeIndex('seed bytes'));
667
+ });
668
+
669
+ test('S2: seeding refuses to copy while the main index is being written, and a failed copy leaves nothing', () => {
670
+ const base = temp('cg-seed-busy-');
671
+ const { repo, worktree } = linkedWorktree(path.join(base, 'a'));
672
+ fs.mkdirSync(path.join(repo, '.codegraph'));
673
+ fs.writeFileSync(path.join(repo, '.codegraph', 'codegraph.db'), 'seed bytes');
674
+ const busy = seedWorktreeIndex({
675
+ worktree,
676
+ commonRoot: repo,
677
+ sourceBusy: () => true,
678
+ copy: () => {
679
+ throw new Error('must not copy');
680
+ },
681
+ });
682
+ assert.equal(busy, false);
683
+ assert.equal(fs.existsSync(path.join(worktree, '.codegraph')), false, 'nothing half-seeded');
684
+
685
+ const failed = seedWorktreeIndex({ worktree, commonRoot: repo, sourceBusy: () => false, copy: () => false });
686
+ assert.equal(failed, false);
687
+ assert.equal(fs.existsSync(path.join(worktree, '.codegraph')), false);
688
+ });
689
+
690
+ test('S2: a linked worktree of a session is seeded under its own index lock, and that lock is released', () => {
691
+ const base = temp('cg-linked-');
692
+ const { repo, worktree } = linkedWorktree(path.join(base, 'a'));
693
+ fs.mkdirSync(path.join(repo, '.codegraph'));
694
+ fs.writeFileSync(path.join(repo, '.codegraph', 'codegraph.db'), 'main db');
695
+ const log = [];
696
+ const result = seedLinkedWorktrees({
697
+ worktrees: [worktree],
698
+ lock: recordingLock(log, false),
699
+ exists: fs.existsSync,
700
+ sourceBusy: () => false,
701
+ copy: (_from, to) => {
702
+ fs.writeFileSync(to, fakeIndex('seeded db'));
703
+ return true;
704
+ },
705
+ });
706
+ assert.deepEqual(result.seeded, [path.join(worktree, '.codegraph', 'codegraph.db')]);
707
+ assert.deepEqual(result.skipped, []);
708
+ assert.deepEqual(log, [`acquire:init:${worktree}`, 'release']);
709
+ assert.equal(fs.existsSync(path.join(worktree, '.codegraph', 'codegraph.db')), true);
710
+ });
711
+
712
+ test('S2: a worktree whose index another session is writing is skipped and never copied into', () => {
713
+ const base = temp('cg-linked-busy-');
714
+ const { worktree } = linkedWorktree(path.join(base, 'a'));
715
+ let copied = false;
716
+ const result = seedLinkedWorktrees({
717
+ worktrees: [worktree],
718
+ lock: recordingLock([], true),
719
+ exists: fs.existsSync,
720
+ sourceBusy: () => false,
721
+ copy: () => {
722
+ copied = true;
723
+ return true;
724
+ },
725
+ });
726
+ assert.equal(copied, false);
727
+ assert.deepEqual(result.seeded, []);
728
+ assert.deepEqual(result.skipped, [{ worktree, reason: "another session is writing this worktree's index" }]);
729
+ assert.equal(fs.existsSync(path.join(worktree, '.codegraph')), false, 'nothing was created in a worktree this session does not own');
730
+ });
731
+
732
+ test('S2: a worktree that already has an index is skipped without taking any lock', () => {
733
+ const base = temp('cg-linked-has-');
734
+ const { worktree } = linkedWorktree(path.join(base, 'a'));
735
+ fs.mkdirSync(path.join(worktree, '.codegraph'));
736
+ const log = [];
737
+ const result = seedLinkedWorktrees({
738
+ worktrees: [worktree],
739
+ lock: recordingLock(log, false),
740
+ exists: fs.existsSync,
741
+ sourceBusy: () => false,
742
+ copy: () => {
743
+ throw new Error('must not copy');
744
+ },
745
+ });
746
+ assert.deepEqual(result.skipped, [{ worktree, reason: 'already has an index' }]);
747
+ assert.deepEqual(log, []);
748
+ });
749
+
750
+ test("S2: while the main checkout's index is being written, nothing is copied into a worktree", () => {
751
+ const base = temp('cg-linked-source-');
752
+ const { worktree } = linkedWorktree(path.join(base, 'a'));
753
+ const result = seedLinkedWorktrees({
754
+ worktrees: [worktree],
755
+ lock: recordingLock([], false),
756
+ exists: fs.existsSync,
757
+ sourceBusy: () => true,
758
+ copy: () => {
759
+ throw new Error('must not copy');
760
+ },
761
+ });
762
+ assert.deepEqual(result.skipped, [{ worktree, reason: "the main checkout's index is being written" }]);
763
+ assert.equal(fs.existsSync(path.join(worktree, '.codegraph')), false);
764
+ });
765
+
766
+ test('S2: the main checkout itself is never seeded from its own index', () => {
767
+ const base = temp('cg-linked-main-');
768
+ const { repo } = linkedWorktree(path.join(base, 'a'));
769
+ const result = seedLinkedWorktrees({
770
+ worktrees: [repo],
771
+ lock: recordingLock([], false),
772
+ exists: fs.existsSync,
773
+ sourceBusy: () => false,
774
+ copy: () => {
775
+ throw new Error('must not copy');
776
+ },
777
+ });
778
+ assert.deepEqual(result, { seeded: [], skipped: [] });
779
+ });
780
+
781
+ test("S2: without an explicit source check, the main index's own lock decides whether a worktree is seeded", () => {
782
+ const base = temp('cg-linked-fallback-');
783
+ const { worktree } = linkedWorktree(path.join(base, 'a'));
784
+ let copied = false;
785
+ // The worktree's own lock is free; the main checkout's is held, and that is what the fallback reads.
786
+ const lock = {
787
+ acquire: () => ({ status: 'acquired', adopt: () => {}, release: () => {} }),
788
+ isHeld: () => true,
789
+ };
790
+ const result = seedLinkedWorktrees({
791
+ worktrees: [worktree],
792
+ lock,
793
+ exists: fs.existsSync,
794
+ copy: () => {
795
+ copied = true;
796
+ return true;
797
+ },
798
+ });
799
+ assert.equal(copied, false);
800
+ assert.deepEqual(result.seeded, []);
801
+ assert.deepEqual(result.skipped, [{ worktree, reason: "the main checkout's index is being written" }]);
802
+ assert.equal(fs.existsSync(path.join(worktree, '.codegraph')), false);
803
+ });
804
+
805
+ test('S2: a copy failure in one worktree does not stop the others and leaves nothing half-built', () => {
806
+ const base = temp('cg-linked-two-');
807
+ const first = linkedWorktree(path.join(base, 'a'));
808
+ const second = linkedWorktree(path.join(base, 'b'));
809
+ fs.mkdirSync(path.join(first.repo, '.codegraph'));
810
+ fs.writeFileSync(path.join(first.repo, '.codegraph', 'codegraph.db'), 'main db');
811
+ fs.mkdirSync(path.join(second.repo, '.codegraph'));
812
+ fs.writeFileSync(path.join(second.repo, '.codegraph', 'codegraph.db'), 'main db');
813
+ let attempts = 0;
814
+ const result = seedLinkedWorktrees({
815
+ worktrees: [first.worktree, second.worktree],
816
+ lock: recordingLock([], false),
817
+ exists: fs.existsSync,
818
+ sourceBusy: () => false,
819
+ copy: (_from, to) => {
820
+ attempts += 1;
821
+ if (attempts === 1) return false; // the first worktree fails
822
+ fs.writeFileSync(to, fakeIndex('seeded db'));
823
+ return true;
824
+ },
825
+ });
826
+ assert.deepEqual(result.seeded, [path.join(second.worktree, '.codegraph', 'codegraph.db')]);
827
+ assert.deepEqual(result.skipped, [{ worktree: first.worktree, reason: 'the seed copy failed' }]);
828
+ assert.equal(fs.existsSync(path.join(first.worktree, '.codegraph')), false, 'the failed one left nothing behind');
829
+ });
830
+
831
+ test('S2: the worktree scan reports what git lists, and nothing when git cannot answer', async () => {
832
+ const porcelain = 'worktree /repo\nHEAD abc\n\nworktree /repo-worktrees/odd\nHEAD def\n\n';
833
+ assert.deepEqual(await linkedWorktrees({ cwd: path.join('some', 'repo'), list: () => porcelain }), ['/repo', '/repo-worktrees/odd']);
834
+ assert.deepEqual(await linkedWorktrees({ cwd: path.join('some', 'repo'), list: () => ['/repo', '/repo-worktrees/odd'] }), ['/repo', '/repo-worktrees/odd']);
835
+ assert.deepEqual(await linkedWorktrees({ cwd: path.join('some', 'repo'), list: () => undefined }), [], 'git failed: no worktrees, no throw');
836
+ assert.deepEqual(await linkedWorktrees({
837
+ cwd: path.join('some', 'repo'),
838
+ list: () => {
839
+ throw new Error('git is gone');
840
+ },
841
+ }), [], 'a throwing lister never reaches the session');
842
+ });
843
+
844
+ test('S2: a session that finds an unindexed linked worktree seeds it and syncs it once', async () => {
845
+ const base = temp('cg-child-worktree-');
846
+ const { repo, worktree } = linkedWorktree(path.join(base, 'a'));
847
+ fs.mkdirSync(path.join(repo, '.codegraph'));
848
+ fs.writeFileSync(path.join(repo, '.codegraph', 'codegraph.db'), 'main db');
849
+ const log = [];
850
+ const calls = [];
851
+ const result = await autoIndex({
852
+ cwd: worktree,
853
+ env: { GENTLE_PI_AGENTS_CHILD: '1' },
854
+ reason: 'startup',
855
+ exists: fs.existsSync,
856
+ hasBinary: yes,
857
+ lock: fakeLock(log, false),
858
+ copySeed: (_from, to) => {
859
+ fs.writeFileSync(to, fakeIndex('seeded'));
860
+ return true;
861
+ },
862
+ run: fakeRun(calls),
863
+ });
864
+ assert.deepEqual(result, { action: 'seed', ok: true });
865
+ assert.deepEqual(calls.map((call) => call.args), [['sync', '-q']]);
866
+ assert.deepEqual(log, ['lock:acquire', 'lock:isHeld', 'lock:isHeld', 'lock:release'], JSON.stringify(log));
867
+ assert.equal(fs.readFileSync(path.join(worktree, '.codegraph', 'codegraph.db'), 'utf8'), fakeIndex('seeded'));
868
+ });
869
+
870
+ test('S3: a seed whose post-seed sync fails leaves no published db and no directory this session created', async () => {
871
+ const base = temp('cg-seed-rollback-');
872
+ const { repo, worktree } = linkedWorktree(path.join(base, 'a'));
873
+ fs.mkdirSync(path.join(repo, '.codegraph'));
874
+ fs.writeFileSync(path.join(repo, '.codegraph', 'codegraph.db'), fakeIndex('main'));
875
+ const log = [];
876
+ const calls = [];
877
+ const result = await autoIndex({
878
+ cwd: worktree,
879
+ env: {},
880
+ reason: 'startup',
881
+ exists: fs.existsSync,
882
+ hasBinary: yes,
883
+ lock: fakeLock(log, false),
884
+ copySeed: (_from, to) => {
885
+ fs.writeFileSync(to, fakeIndex('seeded'));
886
+ return true;
887
+ },
888
+ run: fakeRun(calls, false),
889
+ });
890
+ assert.deepEqual(result, { action: 'seed', ok: false });
891
+ assert.deepEqual(calls.map((call) => call.args), [['sync', '-q']], 'the one reconciliation it attempted is still the one reported');
892
+ assert.equal(fs.existsSync(path.join(worktree, '.codegraph', 'codegraph.db')), false, 'the published db is gone');
893
+ assert.equal(fs.existsSync(path.join(worktree, '.codegraph')), false, 'the directory this session created is gone');
894
+ });
895
+
896
+ test('S3: a staged copy that is not a plausible index is never published and never synced', async () => {
897
+ const base = temp('cg-seed-garbage-');
898
+ for (const [name, stagedContent] of [['empty', ''], ['not-sqlite', 'not a codegraph index at all\n']]) {
899
+ const { repo, worktree } = linkedWorktree(path.join(base, name));
900
+ fs.mkdirSync(path.join(repo, '.codegraph'));
901
+ fs.writeFileSync(path.join(repo, '.codegraph', 'codegraph.db'), fakeIndex('main'));
902
+ const calls = [];
903
+ const result = await autoIndex({
904
+ cwd: worktree,
905
+ env: {},
906
+ reason: 'startup',
907
+ exists: fs.existsSync,
908
+ hasBinary: yes,
909
+ lock: fakeLock([], false),
910
+ copySeed: (_from, to) => {
911
+ fs.writeFileSync(to, stagedContent);
912
+ return true;
913
+ },
914
+ run: fakeRun(calls),
915
+ });
916
+ assert.deepEqual(result, { action: 'seed', ok: false }, name);
917
+ assert.deepEqual(calls, [], `${name}: no sync runs over an index that was never published`);
918
+ assert.equal(fs.existsSync(path.join(worktree, '.codegraph', 'codegraph.db')), false, `${name}: nothing published`);
919
+ assert.equal(fs.existsSync(path.join(worktree, '.codegraph')), false, `${name}: nothing left behind`);
920
+ }
921
+ });
922
+
923
+ test('S3: the staged copy is judged by what the injected fs seam reads, and an unreadable one fails closed', () => {
924
+ const base = temp('cg-seed-read-');
925
+ const { repo, worktree } = linkedWorktree(path.join(base, 'a'));
926
+ fs.mkdirSync(path.join(repo, '.codegraph'));
927
+ fs.writeFileSync(path.join(repo, '.codegraph', 'codegraph.db'), fakeIndex('main'));
928
+ const targetDir = path.join(worktree, '.codegraph');
929
+ const copy = (from, to) => {
930
+ fs.copyFileSync(from, to);
931
+ return true;
932
+ };
933
+ // Each case starts from an absent directory: a seed only ever creates its own, so a fresh one is what a publish means.
934
+ const seed = (fsSeam) => {
935
+ fs.rmSync(targetDir, { recursive: true, force: true });
936
+ return seedWorktreeIndex({ worktree, commonRoot: repo, sourceBusy: no, copy, fs: fsSeam });
937
+ };
938
+
939
+ // A read that answers nothing, or throws, is not an index: it fails closed exactly like a failed copy.
940
+ assert.equal(seed({ readFileSync: () => undefined }), false);
941
+ assert.equal(fs.existsSync(targetDir), false, 'an unreadable staged copy publishes nothing');
942
+ assert.equal(seed({
943
+ readFileSync: () => {
944
+ throw new Error('EACCES');
945
+ },
946
+ }), false);
947
+ assert.equal(fs.existsSync(targetDir), false, 'a throwing read publishes nothing');
948
+ assert.equal(seed({ readFileSync: () => 42 }), false, 'an unexpected answer is not guessed into an index');
949
+ assert.equal(fs.existsSync(targetDir), false);
950
+
951
+ // Raw bytes and a decoded string are both read, and a real header is a plausible index either way.
952
+ assert.equal(seed({ readFileSync: () => Buffer.from(fakeIndex('bytes')) }), true);
953
+ assert.equal(fs.readFileSync(path.join(targetDir, 'codegraph.db'), 'utf8'), fakeIndex('main'), 'the main db is what gets published');
954
+ assert.equal(seed({ readFileSync: (file) => fs.readFileSync(file, 'utf8') }), true);
955
+ assert.equal(fs.readFileSync(path.join(targetDir, 'codegraph.db'), 'utf8'), fakeIndex('main'));
956
+ });
957
+
958
+ test('S3: the seed is published with one rename, so no second write can leave a half-published db', () => {
959
+ const base = temp('cg-seed-rename-');
960
+ const { repo, worktree } = linkedWorktree(path.join(base, 'a'));
961
+ fs.mkdirSync(path.join(repo, '.codegraph'));
962
+ fs.writeFileSync(path.join(repo, '.codegraph', 'codegraph.db'), fakeIndex('main'));
963
+ const renames = [];
964
+ const seeded = seedWorktreeIndex({
965
+ worktree,
966
+ commonRoot: repo,
967
+ sourceBusy: no,
968
+ copy: (from, to) => {
969
+ fs.copyFileSync(from, to);
970
+ return true;
971
+ },
972
+ fs: {
973
+ renameSync: (from, to) => {
974
+ renames.push([from, to]);
975
+ fs.renameSync(from, to);
976
+ },
977
+ copyFileSync: () => {
978
+ throw new Error('the staged file is moved, never copied a second time');
979
+ },
980
+ },
981
+ });
982
+ assert.equal(seeded, true);
983
+ assert.equal(renames.length, 1, 'one rename publishes the staged copy');
984
+ assert.match(renames[0][0], /codegraph\.db\.seeding$/, 'the staged file is what moves');
985
+ assert.match(renames[0][1], /codegraph\.db$/, 'onto the index path');
986
+ assert.deepEqual(fs.readdirSync(path.join(worktree, '.codegraph')), ['codegraph.db'], 'no staging file is left behind');
987
+ });
988
+
989
+ test('S3: a seam with no rename keeps the older two-write publish of the staged copy', () => {
990
+ const base = temp('cg-seed-copy-fallback-');
991
+ const { repo, worktree } = linkedWorktree(path.join(base, 'a'));
992
+ fs.mkdirSync(path.join(repo, '.codegraph'));
993
+ fs.writeFileSync(path.join(repo, '.codegraph', 'codegraph.db'), fakeIndex('main'));
994
+ const copies = [];
995
+ const seeded = seedWorktreeIndex({
996
+ worktree,
997
+ commonRoot: repo,
998
+ sourceBusy: no,
999
+ copy: (from, to) => {
1000
+ fs.copyFileSync(from, to);
1001
+ return true;
1002
+ },
1003
+ fs: {
1004
+ copyFileSync: (from, to) => {
1005
+ copies.push([from, to]);
1006
+ fs.copyFileSync(from, to);
1007
+ },
1008
+ },
1009
+ });
1010
+ assert.equal(seeded, true);
1011
+ assert.equal(copies.length, 1, 'the publish copies the staged file once, as before');
1012
+ assert.match(copies[0][0], /codegraph\.db\.seeding$/);
1013
+ assert.match(copies[0][1], /codegraph\.db$/);
1014
+ assert.equal(fs.existsSync(path.join(worktree, '.codegraph', 'codegraph.db.seeding')), false, 'the staging file is removed');
1015
+ });
1016
+
1017
+ test('S3: a directory another session published is never removed, not even by a failed seed', async () => {
1018
+ const base = temp('cg-seed-owned-');
1019
+ const { repo, worktree } = linkedWorktree(path.join(base, 'a'));
1020
+ fs.mkdirSync(path.join(repo, '.codegraph'));
1021
+ fs.writeFileSync(path.join(repo, '.codegraph', 'codegraph.db'), fakeIndex('main'));
1022
+ const otherDb = path.join(worktree, '.codegraph', 'codegraph.db');
1023
+ let checks = 0;
1024
+ // Another session publishes while this one waits for the lock, so the existence re-check under the lock sees it.
1025
+ const exists = (p) => {
1026
+ if (p === path.join(worktree, '.codegraph')) {
1027
+ checks += 1;
1028
+ if (checks > 1) {
1029
+ fs.mkdirSync(path.dirname(otherDb), { recursive: true });
1030
+ fs.writeFileSync(otherDb, fakeIndex('other session'));
1031
+ return true;
1032
+ }
1033
+ return false;
1034
+ }
1035
+ return fs.existsSync(p);
1036
+ };
1037
+ const calls = [];
1038
+ const result = await autoIndex({
1039
+ cwd: worktree,
1040
+ env: {},
1041
+ reason: 'startup',
1042
+ exists,
1043
+ hasBinary: yes,
1044
+ lock: fakeLock([], false),
1045
+ copySeed: () => {
1046
+ throw new Error('must not copy into a directory another session published');
1047
+ },
1048
+ run: fakeRun(calls, false),
1049
+ });
1050
+ assert.deepEqual(result, { action: 'seed', ok: true, joined: true });
1051
+ assert.deepEqual(calls, [], 'this session ran nothing over an index it does not own');
1052
+ assert.equal(fs.readFileSync(otherDb, 'utf8'), fakeIndex('other session'), "another session's index is untouched");
1053
+ });
1054
+
1055
+ test('S3: a directory another actor created after the recheck is never published into', async () => {
1056
+ const base = temp('cg-seed-race-');
1057
+ const { repo, worktree } = linkedWorktree(path.join(base, 'a'));
1058
+ fs.mkdirSync(path.join(repo, '.codegraph'));
1059
+ fs.writeFileSync(path.join(repo, '.codegraph', 'codegraph.db'), fakeIndex('main'));
1060
+ const targetDir = path.join(worktree, '.codegraph');
1061
+ const accepted = path.join(targetDir, 'accepted');
1062
+ let checks = 0;
1063
+ // The second check is the one inside the seed: another actor creates the directory in between, so the directory this
1064
+ // session finds is not one it created, and it holds no index yet.
1065
+ const sourceBusy = () => {
1066
+ checks += 1;
1067
+ if (checks === 2) {
1068
+ fs.mkdirSync(targetDir, { recursive: true });
1069
+ fs.writeFileSync(accepted, 'other session');
1070
+ }
1071
+ return false;
1072
+ };
1073
+ const calls = [];
1074
+ const result = await autoIndex({
1075
+ cwd: worktree,
1076
+ env: {},
1077
+ reason: 'startup',
1078
+ exists: fs.existsSync,
1079
+ hasBinary: yes,
1080
+ lock: fakeLock([], false),
1081
+ sourceBusy,
1082
+ run: fakeRun(calls),
1083
+ });
1084
+ assert.deepEqual(result, { action: 'seed', ok: false }, 'a directory holding no index is an honest failure, not a join');
1085
+ assert.deepEqual(calls, [], 'no sync runs over a directory this session did not publish');
1086
+ assert.equal(fs.existsSync(path.join(targetDir, 'codegraph.db')), false, 'nothing of this session is written into it');
1087
+ assert.equal(fs.existsSync(targetDir), true, 'a directory this session did not create is never removed');
1088
+ assert.equal(fs.readFileSync(accepted, 'utf8'), 'other session', "another actor's file survives untouched");
1089
+ });
1090
+
1091
+ test("S3: a foreign index created inside this session's creation window is never published over", async () => {
1092
+ const base = temp('cg-seed-window-');
1093
+ const { repo, worktree } = linkedWorktree(path.join(base, 'a'));
1094
+ fs.mkdirSync(path.join(repo, '.codegraph'));
1095
+ fs.writeFileSync(path.join(repo, '.codegraph', 'codegraph.db'), fakeIndex('main'));
1096
+ const targetDir = path.join(worktree, '.codegraph');
1097
+ const foreignDb = path.join(targetDir, 'codegraph.db');
1098
+ const foreign = Buffer.from(fakeIndex('other accepted index'));
1099
+ // The other actor lands in the very window this session's creation opens: the injected fs seam is where the module
1100
+ // tries to create the directory, and the EEXIST it answers with is what says the directory is not this session's.
1101
+ const seam = {
1102
+ mkdirSync: (target, options) => {
1103
+ if (path.basename(target) === '.codegraph' && !fs.existsSync(target)) {
1104
+ fs.mkdirSync(target);
1105
+ fs.writeFileSync(foreignDb, foreign);
1106
+ const error = new Error(`EEXIST: file already exists, mkdir '${target}'`);
1107
+ error.code = 'EEXIST';
1108
+ throw error;
1109
+ }
1110
+ return fs.mkdirSync(target, options);
1111
+ },
1112
+ };
1113
+ const calls = [];
1114
+ const result = await autoIndex({
1115
+ cwd: worktree,
1116
+ env: {},
1117
+ reason: 'startup',
1118
+ exists: fs.existsSync,
1119
+ hasBinary: yes,
1120
+ lock: fakeLock([], false),
1121
+ fs: seam,
1122
+ run: fakeRun(calls),
1123
+ });
1124
+ assert.deepEqual(result, { action: 'seed', ok: true, joined: true }, 'the joined shape this module already uses for an index it does not own');
1125
+ assert.deepEqual(calls, [], 'no sync runs over an index this session never published');
1126
+ assert.deepEqual(fs.readFileSync(foreignDb), foreign, 'the index another actor accepted is byte-identical');
1127
+ });
1128
+
1129
+ test('S3: a directory another actor replaced during the post-seed sync is left byte-identically', async () => {
1130
+ const base = temp('cg-seed-replaced-');
1131
+ const { repo, worktree } = linkedWorktree(path.join(base, 'a'));
1132
+ fs.mkdirSync(path.join(repo, '.codegraph'));
1133
+ fs.writeFileSync(path.join(repo, '.codegraph', 'codegraph.db'), fakeIndex('main'));
1134
+ const targetDir = path.join(worktree, '.codegraph');
1135
+ const replacement = path.join(targetDir, 'codegraph.db');
1136
+ let theirs;
1137
+ const run = async () => {
1138
+ // The replacement lands while this session syncs the seed it published: the directory on disk is no longer ours.
1139
+ fs.renameSync(targetDir, `${targetDir}.ours`);
1140
+ fs.mkdirSync(targetDir);
1141
+ fs.writeFileSync(replacement, fakeIndex('other accepted index'));
1142
+ theirs = fs.readFileSync(replacement);
1143
+ return false;
1144
+ };
1145
+ const result = await autoIndex({
1146
+ cwd: worktree,
1147
+ env: {},
1148
+ reason: 'startup',
1149
+ exists: fs.existsSync,
1150
+ hasBinary: yes,
1151
+ lock: fakeLock([], false),
1152
+ run,
1153
+ });
1154
+ assert.deepEqual(result, { action: 'seed', ok: false }, 'the seed is still reported as failed');
1155
+ assert.equal(fs.existsSync(replacement), true, 'the index another actor published is never removed');
1156
+ assert.deepEqual(fs.readFileSync(replacement), theirs, 'and it is left byte-identical');
1157
+ });
1158
+
1159
+ test('S3: a replacement database this session cannot read is unknown, so nothing is removed', async () => {
1160
+ const base = temp('cg-seed-eacces-');
1161
+ const { repo, worktree } = linkedWorktree(path.join(base, 'a'));
1162
+ fs.mkdirSync(path.join(repo, '.codegraph'));
1163
+ fs.writeFileSync(path.join(repo, '.codegraph', 'codegraph.db'), fakeIndex('main'));
1164
+ const targetDir = path.join(worktree, '.codegraph');
1165
+ const db = path.join(targetDir, 'codegraph.db');
1166
+ const foreign = Buffer.from(fakeIndex('foreign accepted index'));
1167
+ let syncing = false;
1168
+ // During the post-seed sync another actor replaces only the database, and every later stat of it is denied: an
1169
+ // unreadable identity is UNKNOWN, which is never "gone" and never "the same one", so it cannot authorize a removal.
1170
+ const seam = {
1171
+ statSync: (entry) => {
1172
+ if (syncing && entry === db) throw Object.assign(new Error('stat denied'), { code: 'EACCES' });
1173
+ return fs.statSync(entry);
1174
+ },
1175
+ };
1176
+ const calls = [];
1177
+ const result = await autoIndex({
1178
+ cwd: worktree,
1179
+ env: {},
1180
+ reason: 'startup',
1181
+ exists: fs.existsSync,
1182
+ hasBinary: yes,
1183
+ lock: fakeLock([], false),
1184
+ fs: seam,
1185
+ run: async (args, cwd) => {
1186
+ calls.push({ args, cwd });
1187
+ fs.renameSync(db, `${db}.ours`);
1188
+ fs.writeFileSync(db, foreign);
1189
+ syncing = true;
1190
+ return false;
1191
+ },
1192
+ });
1193
+ assert.deepEqual(result, { action: 'seed', ok: false }, 'the seed is still reported as failed');
1194
+ assert.deepEqual(calls.map((call) => call.args), [['sync', '-q']], 'it is still the one reconciliation that ran');
1195
+ assert.equal(fs.existsSync(db), true, 'an unreadable database is unknown, never absent: it stays');
1196
+ assert.deepEqual(fs.readFileSync(db), foreign, 'and so does the directory that holds it');
1197
+ });
1198
+
1199
+ test('S3: a published database that is positively gone still rolls back the directory this session created', async () => {
1200
+ const base = temp('cg-seed-gone-');
1201
+ const { repo, worktree } = linkedWorktree(path.join(base, 'a'));
1202
+ fs.mkdirSync(path.join(repo, '.codegraph'));
1203
+ fs.writeFileSync(path.join(repo, '.codegraph', 'codegraph.db'), fakeIndex('main'));
1204
+ const targetDir = path.join(worktree, '.codegraph');
1205
+ // ENOENT is a fact, not an unknown: the database this session published is gone, so nothing is left to protect.
1206
+ const result = await autoIndex({
1207
+ cwd: worktree,
1208
+ env: {},
1209
+ reason: 'startup',
1210
+ exists: fs.existsSync,
1211
+ hasBinary: yes,
1212
+ lock: fakeLock([], false),
1213
+ run: async () => {
1214
+ fs.rmSync(path.join(targetDir, 'codegraph.db'), { force: true });
1215
+ return false;
1216
+ },
1217
+ });
1218
+ assert.deepEqual(result, { action: 'seed', ok: false });
1219
+ assert.equal(fs.existsSync(targetDir), false, 'a positively absent database leaves nothing to keep');
1220
+ });
1221
+
1222
+ // ---- The CLI seam (S1, S2) ----
1223
+
1224
+ test('S2: a timed-out runCodegraph resolves only once the killed process is gone', async () => {
1225
+ const dir = temp('cg-run-');
1226
+ const pidFile = path.join(dir, 'fake.pid');
1227
+ const shim = path.join(dir, 'bin');
1228
+ fs.mkdirSync(shim);
1229
+ const stub = path.join(__dirname, 'fixtures', 'codegraph-cli-stub.js');
1230
+ if (process.platform === 'win32') {
1231
+ fs.writeFileSync(path.join(shim, 'codegraph.cmd'), `@echo off\r\n"${process.execPath}" "${stub}" %*\r\n`);
1232
+ } else {
1233
+ const file = path.join(shim, 'codegraph');
1234
+ fs.writeFileSync(file, `#!/bin/sh\nexec "${process.execPath}" "${stub}" "$@"\n`);
1235
+ fs.chmodSync(file, 0o755);
1236
+ }
1237
+ const oldPath = process.env.PATH || '';
1238
+ const oldPidFile = process.env.CODEGRAPH_STUB_PID_FILE;
1239
+ process.env.PATH = `${shim}${path.delimiter}${oldPath}`;
1240
+ process.env.CODEGRAPH_STUB_PID_FILE = pidFile;
1241
+ try {
1242
+ const started = Date.now();
1243
+ let spawned;
1244
+ assert.equal(await runCodegraph(['init', '-y'], dir, 500, (pid, options) => {
1245
+ spawned = { pid, proxy: options && options.proxy };
1246
+ }), false);
1247
+ assert.ok(spawned !== undefined && spawned.pid > 0, 'the pid of the spawned command is reported');
1248
+ // On Windows `codegraph` runs through the npm shell shim, so that pid is the shell, not the init.
1249
+ assert.equal(spawned.proxy, process.platform === 'win32', JSON.stringify(spawned));
1250
+ assert.ok(Date.now() - started < 20_000, 'did not wait long after killing');
1251
+ const pid = Number(fs.readFileSync(pidFile, 'utf8'));
1252
+ assert.ok(pid > 0, 'the fake wrote its pid');
1253
+ assert.throws(() => process.kill(pid, 0), `the killed init (pid ${pid}) is gone`);
1254
+ } finally {
1255
+ process.env.PATH = oldPath;
1256
+ if (oldPidFile === undefined) delete process.env.CODEGRAPH_STUB_PID_FILE;
1257
+ else process.env.CODEGRAPH_STUB_PID_FILE = oldPidFile;
1258
+ }
1259
+ });
1260
+
1261
+ /** A stand-in for a spawned child: it records every signal it is asked for and lets the test end it. */
1262
+ function fakeChild(pid) {
1263
+ const handlers = { error: [], close: [] };
1264
+ const signals = [];
1265
+ const child = {
1266
+ pid,
1267
+ exitCode: null,
1268
+ signalCode: null,
1269
+ signals,
1270
+ kill(signal = 'SIGTERM') {
1271
+ signals.push(signal);
1272
+ return true;
1273
+ },
1274
+ on(event, handler) {
1275
+ if (!handlers[event]) handlers[event] = [];
1276
+ handlers[event].push(handler);
1277
+ return child;
1278
+ },
1279
+ end(code, signal) {
1280
+ child.exitCode = code;
1281
+ child.signalCode = signal;
1282
+ for (const handler of handlers.close) handler(code, signal);
1283
+ return child;
1284
+ },
1285
+ };
1286
+ return child;
1287
+ }
1288
+
1289
+ const sleep = (ms) => new Promise((resolve) => {
1290
+ setTimeout(resolve, ms);
1291
+ });
1292
+
1293
+ /** Whether a pid is gone, polled because a hard kill is asynchronous on every platform. */
1294
+ async function gone(pid, deadlineMs = 5_000) {
1295
+ const limit = Date.now() + deadlineMs;
1296
+ for (;;) {
1297
+ try {
1298
+ process.kill(pid, 0);
1299
+ } catch {
1300
+ return true;
1301
+ }
1302
+ if (Date.now() > limit) return false;
1303
+ await sleep(25);
1304
+ }
1305
+ }
1306
+
1307
+ /**
1308
+ * Waits for a marker a child process writes once it is ready. It polls with a deadline, so a slow start costs the
1309
+ * deadline and never a guessed sleep, and the caller proceeds on the evidence instead of on elapsed time.
1310
+ */
1311
+ async function ready(file, deadlineMs = 10_000) {
1312
+ const limit = Date.now() + deadlineMs;
1313
+ for (;;) {
1314
+ if (fs.existsSync(file)) return true;
1315
+ if (Date.now() > limit) return false;
1316
+ await sleep(5);
1317
+ }
1318
+ }
1319
+
1320
+ test('S5: a child that ignores SIGTERM is escalated to SIGKILL, and the timed-out run still reports failure', {
1321
+ // A POSIX signal trap is what this case is about; on Windows the escalation is the repeated taskkill the fake-child
1322
+ // case pins, and a soft `kill` ends the process outright, so there would be nothing to trap.
1323
+ skip: process.platform === 'win32' ? 'POSIX signal trapping' : false,
1324
+ }, async () => {
1325
+ const dir = temp('cg-run-trap-');
1326
+ const pidFile = path.join(dir, 'trap.pid');
1327
+ const readyFile = path.join(dir, 'trap.ready');
1328
+ const termLog = path.join(dir, 'trap.term');
1329
+ const stub = path.join(dir, 'trap-cli.js');
1330
+ // A real child that traps SIGTERM: only a hard kill ends it. The trap is installed before the marker is written, so
1331
+ // the marker is the proof that a soft kill cannot end this process — and the trap records the signal it survived.
1332
+ fs.writeFileSync(stub, [
1333
+ "'use strict';",
1334
+ "const fs = require('node:fs');",
1335
+ `const pidFile = ${JSON.stringify(pidFile)};`,
1336
+ `const readyFile = ${JSON.stringify(readyFile)};`,
1337
+ `const termLog = ${JSON.stringify(termLog)};`,
1338
+ 'fs.writeFileSync(pidFile, String(process.pid));',
1339
+ "process.on('SIGTERM', () => fs.appendFileSync(termLog, 'SIGTERM\\n'));",
1340
+ "fs.writeFileSync(readyFile, 'trap installed');",
1341
+ 'setInterval(() => {}, 1000);',
1342
+ ].join('\n'));
1343
+ // The child is started and announces itself first, so the run below cannot signal it before its trap exists: no
1344
+ // startup is guessed, and the timeout this case measures starts on a process that is already ready.
1345
+ const child = spawn(process.execPath, [stub], { stdio: 'ignore' });
1346
+ try {
1347
+ assert.equal(await ready(readyFile), true, 'the stub installed its SIGTERM trap before anything signals it');
1348
+ const pid = Number(fs.readFileSync(pidFile, 'utf8'));
1349
+ assert.equal(pid, child.pid, 'the stub that installed the trap is the process this run will kill');
1350
+ const ok = await runCodegraph(['init', '-y'], dir, 30, () => {}, {
1351
+ escalationMs: 200,
1352
+ killWaitMs: 1_000,
1353
+ spawn: () => child,
1354
+ });
1355
+ assert.equal(ok, false, 'the escalation still reports the timeout, never a success');
1356
+ assert.equal(fs.readFileSync(termLog, 'utf8'), 'SIGTERM\n', 'the trap ran: the soft kill reached the child and did not end it');
1357
+ assert.equal(await gone(pid, 2_000), true, `the child that trapped SIGTERM (pid ${pid}) is gone`);
1358
+ } finally {
1359
+ try {
1360
+ child.kill('SIGKILL'); // cleanup of this case's own child
1361
+ } catch {
1362
+ // Already gone.
1363
+ }
1364
+ }
1365
+ });
1366
+
1367
+ test('S5: a child that dies on SIGTERM is not killed a second time and its failure is reported as before', async () => {
1368
+ const dir = temp('cg-run-term-');
1369
+ let child;
1370
+ const run = runCodegraph(['sync', '-q'], dir, 30, () => {}, {
1371
+ platform: 'linux',
1372
+ escalationMs: 60,
1373
+ spawn: () => {
1374
+ child = fakeChild(7001);
1375
+ const asked = child.kill;
1376
+ // The process really dies of the signal it was sent: the close event follows the kill.
1377
+ child.kill = (signal = 'SIGTERM') => {
1378
+ const ok = asked(signal);
1379
+ setImmediate(() => child.end(null, signal));
1380
+ return ok;
1381
+ };
1382
+ return child;
1383
+ },
1384
+ });
1385
+ assert.equal(await run, false, 'a killed run is a failed run');
1386
+ assert.deepEqual(child.signals, ['SIGTERM'], 'only the soft kill was sent');
1387
+ await sleep(120); // well past the escalation delay this run armed
1388
+ assert.deepEqual(child.signals, ['SIGTERM'], 'a child that already died is never escalated');
1389
+ });
1390
+
1391
+ test('S5: a run that finishes normally neither escalates nor kills anything after it settled', async () => {
1392
+ const dir = temp('cg-run-ok-');
1393
+ let child;
1394
+ const run = runCodegraph(['sync', '-q'], dir, 1_000, () => {}, {
1395
+ platform: 'linux',
1396
+ escalationMs: 20,
1397
+ spawn: () => {
1398
+ child = fakeChild(7002);
1399
+ setTimeout(() => child.end(0, null), 5);
1400
+ return child;
1401
+ },
1402
+ });
1403
+ assert.equal(await run, true, 'a command that came back with 0 succeeded');
1404
+ await sleep(60);
1405
+ assert.deepEqual(child.signals, [], 'nothing is signalled after a successful run settled');
1406
+ });
1407
+
1408
+ test('S5: the escalation delay is measured from the soft kill, so no hard kill lands before it', async () => {
1409
+ const dir = temp('cg-run-escalate-');
1410
+ const ESCALATION_MS = 200;
1411
+ // The only discount is the millisecond a signal timestamp and the timer queue can disagree by. Nothing is taken off
1412
+ // the delay itself: a shorter gap than this is a hard kill that did not wait.
1413
+ const SIGNAL_CLOCK_TOLERANCE_MS = 5;
1414
+ const received = [];
1415
+ const run = runCodegraph(['sync', '-q'], dir, 40, () => {}, {
1416
+ platform: 'linux',
1417
+ killWaitMs: 1_000,
1418
+ escalationMs: ESCALATION_MS,
1419
+ spawn: () => {
1420
+ const child = fakeChild(7003);
1421
+ const asked = child.kill;
1422
+ // The child's own record of when each signal reached it: the gap between the two is what "the delay" means here,
1423
+ // and it is the one interval this case can measure without the run's own start standing in for it.
1424
+ child.kill = (signal = 'SIGTERM') => {
1425
+ received.push({ signal, at: Date.now() });
1426
+ // Only the hard kill ends it, which is what a SIGTERM-trapping child looks like.
1427
+ if (signal === 'SIGKILL') setImmediate(() => child.end(null, signal));
1428
+ return asked(signal);
1429
+ };
1430
+ return child;
1431
+ },
1432
+ });
1433
+ assert.equal(await run, false, 'the escalated run reports the timeout');
1434
+ assert.deepEqual(received.map((entry) => entry.signal), ['SIGTERM', 'SIGKILL'], 'exactly one soft kill and one hard kill, in that order');
1435
+ const gap = received[1].at - received[0].at;
1436
+ assert.ok(gap >= ESCALATION_MS - SIGNAL_CLOCK_TOLERANCE_MS, `the hard kill waited the escalation delay after the soft one (${gap}ms)`);
1437
+ });
1438
+
1439
+ test('S5: a requested escalation beyond the reporting grace is clamped, so the hard kill still lands', async () => {
1440
+ const dir = temp('cg-run-clamp-');
1441
+ const killWaitMs = 200;
1442
+ const requestedMs = 10_000;
1443
+ const killedAt = [];
1444
+ const started = Date.now();
1445
+ const run = runCodegraph(['sync', '-q'], dir, 40, () => {}, {
1446
+ platform: 'linux',
1447
+ killWaitMs,
1448
+ escalationMs: requestedMs,
1449
+ spawn: () => {
1450
+ const child = fakeChild(7006);
1451
+ const asked = child.kill;
1452
+ child.kill = (signal = 'SIGTERM') => {
1453
+ killedAt.push({ signal, at: Date.now() });
1454
+ // Only the hard kill ends it, which is what a SIGTERM-trapping child looks like.
1455
+ if (signal === 'SIGKILL') setImmediate(() => child.end(null, signal));
1456
+ return asked(signal);
1457
+ };
1458
+ return child;
1459
+ },
1460
+ });
1461
+ // The hard kill has to land inside the grace, so it is looked for before the run is allowed to report.
1462
+ const deadline = Date.now() + 1_000;
1463
+ while (!killedAt.some((entry) => entry.signal === 'SIGKILL') && Date.now() < deadline) await sleep(10);
1464
+ const hard = killedAt.filter((entry) => entry.signal === 'SIGKILL');
1465
+ assert.equal(hard.length, 1, `a requested ${requestedMs}ms escalation is clamped into the ${killWaitMs}ms grace: ${JSON.stringify(killedAt)}`);
1466
+ assert.equal(await run, false, 'the escalation still reports the timeout, never a success');
1467
+ assert.ok(hard[0].at - started <= killWaitMs, `the hard kill landed inside the reporting grace (${hard[0].at - started}ms)`);
1468
+ });
1469
+
1470
+ test('S5: a run that already timed out never reports success, even when the child exits 0 afterwards', async () => {
1471
+ const dir = temp('cg-run-late-ok-');
1472
+ const run = runCodegraph(['sync', '-q'], dir, 30, () => {}, {
1473
+ platform: 'linux',
1474
+ escalationMs: 500,
1475
+ spawn: () => {
1476
+ const child = fakeChild(7004);
1477
+ // A child that traps SIGTERM and then exits cleanly on its own: the timeout already happened.
1478
+ setTimeout(() => child.end(0, null), 80);
1479
+ return child;
1480
+ },
1481
+ });
1482
+ assert.equal(await run, false, 'the timeout is the outcome, not the exit code that came after it');
1483
+ });
1484
+
1485
+ test('S5: on Windows the hard kill is a second taskkill /T /F, run only while the pid lives', async () => {
1486
+ const dir = temp('cg-run-win-');
1487
+ const taskkills = [];
1488
+ const cli = fakeChild(7005);
1489
+ const run = runCodegraph(['sync', '-q'], dir, 20, () => {}, {
1490
+ platform: 'win32',
1491
+ escalationMs: 40,
1492
+ spawn: (command, args) => {
1493
+ if (command === 'taskkill') {
1494
+ taskkills.push((args || []).join(' '));
1495
+ return { on: () => {} };
1496
+ }
1497
+ // A shell proxy that only goes away once it is asked twice.
1498
+ setTimeout(() => cli.end(null, 'SIGKILL'), 200);
1499
+ return cli;
1500
+ },
1501
+ });
1502
+ assert.equal(await run, false, 'the timeout is reported');
1503
+ assert.deepEqual(taskkills, ['/pid 7005 /T /F', '/pid 7005 /T /F'], 'the escalation re-runs the hard kill while the pid lives');
1504
+ assert.deepEqual(cli.signals, [], 'Windows escalates through taskkill, not a POSIX signal');
1505
+ });
1506
+
1507
+ test('S5: the escalation fires inside the reporting grace, never instead of it', () => {
1508
+ assert.ok(KILL_ESCALATION_MS > 0, 'the default delay is a positive number of milliseconds');
1509
+ assert.ok(KILL_ESCALATION_MS <= 2_000, 'a couple of seconds, not minutes');
1510
+ assert.ok(KILL_ESCALATION_MS < KILL_WAIT_MS, 'the hard kill lands inside the grace the run already reports on');
1511
+ });
1512
+
1513
+ test('S2: the constant bounds of a run are the ones the commands use', () => {
1514
+ assert.equal(SYNC_TIMEOUT_MS, 120_000);
1515
+ assert.equal(INIT_TIMEOUT_MS, 600_000);
1516
+ assert.equal(POST_INIT_SYNC_WAIT_MS, 10_000);
1517
+ });
1518
+
1519
+ // ---- The notices (S2, S3) ----
1520
+
1521
+ test('S2: the start of each action names that action, so create-or-sync is visible while it happens', () => {
1522
+ assert.match(indexStartNotice('init'), /creating the CodeGraph index/);
1523
+ assert.match(indexStartNotice('seed'), /seeding this worktree's CodeGraph index/);
1524
+ assert.match(indexStartNotice('sync'), /syncing the CodeGraph index/);
1525
+ });
1526
+
1527
+ test('S2: only a run that came back is reported as synced, created or seeded', () => {
1528
+ assert.deepEqual(indexOutcomeNotice({ action: 'sync', ok: true }, 'C:\\p'), { text: 'CodeGraph index synced', level: 'info' });
1529
+ assert.deepEqual(indexOutcomeNotice({ action: 'init', ok: true }, 'C:\\p'), { text: 'CodeGraph index created', level: 'info' });
1530
+ assert.deepEqual(indexOutcomeNotice({ action: 'seed', ok: true }, 'C:\\p'), { text: 'CodeGraph index seeded from the main repo and synced', level: 'info' });
1531
+ });
1532
+
1533
+ test('S3: a queued, joined or coalesced request is never presented as a sync of this session', () => {
1534
+ const queued = indexOutcomeNotice({ action: 'sync', ok: true, queued: true }, 'C:\\p');
1535
+ assert.match(queued.text, /queued, not run yet/);
1536
+ assert.doesNotMatch(queued.text, /synced/i);
1537
+
1538
+ const coalesced = indexOutcomeNotice({ action: 'sync', ok: true, coalesced: true }, 'C:\\p');
1539
+ assert.match(coalesced.text, /another session's run completed/);
1540
+ assert.doesNotMatch(coalesced.text, /^CodeGraph index synced$/);
1541
+
1542
+ const joinedInit = indexOutcomeNotice({ action: 'init', ok: true, joined: true }, 'C:\\p');
1543
+ assert.match(joinedInit.text, /another session is creating the CodeGraph index/);
1544
+ const joinedSync = indexOutcomeNotice({ action: 'sync', ok: true, joined: true }, 'C:\\p');
1545
+ assert.match(joinedSync.text, /this session did not sync it/);
1546
+ assert.doesNotMatch(joinedSync.text, /^CodeGraph index synced$/);
1547
+ });
1548
+
1549
+ test('S3: unusable coordination is a warning that says no sync was started, not a synced index', () => {
1550
+ const notice = indexOutcomeNotice({ action: 'sync', ok: false, unavailable: true }, 'C:\\p');
1551
+ assert.deepEqual(notice, { text: 'could not coordinate the CodeGraph index sync in C:\\p; no sync was started', level: 'warning' });
1552
+ });
1553
+
1554
+ test('S3: a failed command is a warning naming the action, and never says the index is up to date', () => {
1555
+ for (const action of ['sync', 'init', 'seed']) {
1556
+ const notice = indexOutcomeNotice({ action, ok: false }, 'C:\\p');
1557
+ assert.equal(notice.level, 'warning');
1558
+ assert.match(notice.text, new RegExp(`codegraph ${action} failed in C:\\\\p`));
1559
+ assert.match(notice.text, /the index is not up to date/);
1560
+ }
1561
+ });
1562
+
1563
+ test('S3: the warm-up outcome is reported apart from the index one', () => {
1564
+ assert.deepEqual(warmOutcomeNotice('ok', 'C:\\p'), { text: 'CodeGraph ready', level: 'info' });
1565
+ assert.deepEqual(warmOutcomeNotice('failed', 'C:\\p'), { text: `CodeGraph warm-up failed in C:\\p`, level: 'warning' });
1566
+ });
1567
+
1568
+ test('S4: a completed post-init sync appends nothing, and a sync that did not complete is one short line', () => {
1569
+ assert.equal(postInitSyncNotice('completed'), undefined, 'the tool result stays the whole answer when the sync completed');
1570
+ for (const outcome of ['pending', 'failed', 'unavailable', 'skipped-read-only']) {
1571
+ const notice = postInitSyncNotice(outcome);
1572
+ assert.equal(typeof notice, 'string', outcome);
1573
+ assert.equal(notice.includes('\n'), false, `${outcome}: one line, no second paragraph`);
1574
+ assert.doesNotMatch(notice, /pi-odd-worktree/, `${outcome}: no plugin prefix`);
1575
+ assert.doesNotMatch(notice, /coordinated index sync completed/, `${outcome}: a completed sync is the only thing that says completed`);
1576
+ }
1577
+ assert.match(postInitSyncNotice('pending'), /pending/);
1578
+ assert.match(postInitSyncNotice('pending'), /not confirmed current/);
1579
+ assert.doesNotMatch(postInitSyncNotice('pending'), /synced|up to date/i);
1580
+ assert.match(postInitSyncNotice('failed'), /failed; this index may be behind/);
1581
+ assert.doesNotMatch(postInitSyncNotice('failed'), /synced/);
1582
+ assert.match(postInitSyncNotice('unavailable'), /could not start/);
1583
+ assert.match(postInitSyncNotice('unavailable'), /not confirmed current/);
1584
+ assert.doesNotMatch(postInitSyncNotice('unavailable'), /synced/);
1585
+ assert.match(postInitSyncNotice('skipped-read-only'), /read-only/);
1586
+ assert.match(postInitSyncNotice('skipped-read-only'), /not confirmed current/);
1587
+ });
1588
+
1589
+ test('S2: the index root is the nearest directory at or above the cwd holding the database', () => {
1590
+ const root = temp('cg-notice-');
1591
+ fs.mkdirSync(path.join(root, '.codegraph'), { recursive: true });
1592
+ fs.writeFileSync(path.join(root, '.codegraph', 'codegraph.db'), '');
1593
+ fs.mkdirSync(path.join(root, 'src', 'deep'), { recursive: true });
1594
+ assert.equal(findIndexRoot(root), root);
1595
+ assert.equal(findIndexRoot(path.join(root, 'src')), root);
1596
+ assert.equal(findIndexRoot(path.join(root, 'src', 'deep')), root);
1597
+ });
1598
+
1599
+ test('S2: a .codegraph folder without a database is not an index, and no index means no root', () => {
1600
+ const root = temp('cg-notice-empty-');
1601
+ fs.mkdirSync(path.join(root, '.codegraph'), { recursive: true });
1602
+ fs.writeFileSync(path.join(root, '.codegraph', 'codegraph.db'), '');
1603
+ fs.mkdirSync(path.join(root, 'sub', '.codegraph'), { recursive: true });
1604
+ assert.equal(findIndexRoot(path.join(root, 'sub')), root, 'the walk continues past a folder without the database');
1605
+ assert.equal(findIndexRoot(path.join('some', 'not-indexed'), () => false), undefined);
1606
+ });
1607
+
1608
+ test('S2: the tools of a session are its selected ones plus the ones a child asked for', () => {
1609
+ const MCP = 'mcp__codegraph__codegraph_explore';
1610
+ assert.deepEqual(noticeTools(['read', 'grep'], ` read, ${MCP} ,mcp__codegraph__*, `, true), ['read', 'grep', MCP, 'mcp__codegraph__*']);
1611
+ assert.deepEqual(noticeTools(['bash'], MCP, false), ['bash']);
1612
+ assert.deepEqual(noticeTools(['read', MCP], `${MCP},codegraph`, true), ['read', MCP, 'codegraph'], 'no duplicates');
1613
+ assert.deepEqual(noticeTools([], '', true), []);
1614
+ assert.deepEqual(noticeTools([], undefined, true), []);
1615
+ });
1616
+
1617
+ // ---- The observed native `init` (S3, S6) ----
1618
+
1619
+ const nativeInit = (over) => ({ toolName: 'codegraph', isError: false, input: { operation: 'init' }, ...over });
1620
+
1621
+ test('S3: only a successful native `codegraph init` is observed; every other call is left alone', () => {
1622
+ assert.equal(isNativeInitResult(nativeInit()), true);
1623
+ assert.equal(initHookDecision(nativeInit(), undefined), 'sync');
1624
+ assert.equal(isNativeInitResult(nativeInit({ isError: true })), false);
1625
+ assert.equal(initHookDecision(nativeInit({ isError: true }), undefined), 'skip-failed-init');
1626
+ assert.equal(initHookDecision(nativeInit({ input: { operation: 'explore' } }), undefined), 'skip-not-a-native-init');
1627
+ assert.equal(initHookDecision(nativeInit({ toolName: 'mcp__codegraph__codegraph_explore', input: {} }), undefined), 'skip-not-a-native-init');
1628
+ assert.equal(initHookDecision(nativeInit({ toolName: 'bash', input: { command: 'codegraph init' } }), undefined), 'skip-not-a-native-init');
1629
+ });
1630
+
1631
+ test('S6: a read-only role gets the read-only decision, every other role syncs', () => {
1632
+ assert.equal(initHookDecision(nativeInit(), 'read-only'), 'skip-read-only');
1633
+ assert.equal(initHookDecision(nativeInit(), 'explorer'), 'sync');
1634
+ assert.equal(initHookDecision(nativeInit(), 'writer'), 'sync');
1635
+ assert.equal(initHookDecision(nativeInit(), undefined), 'sync', 'the main session is not a read-only role');
1636
+ });
1637
+
1638
+ test('S3: after a successful native init one coordinated sync runs and the result says completed', async () => {
1639
+ const cwd = temp('cg-init-hook-');
1640
+ const runs = [];
1641
+ const seen = [];
1642
+ const outcome = await syncAfterNativeInit({
1643
+ cwd,
1644
+ exists: () => true,
1645
+ sync: runsHere(),
1646
+ lock: null,
1647
+ run: async (args) => {
1648
+ runs.push(args);
1649
+ return true;
1650
+ },
1651
+ log: (entry) => seen.push(entry.outcome),
1652
+ });
1653
+ assert.equal(outcome, 'completed');
1654
+ assert.deepEqual(runs, [['sync', '-q']]);
1655
+ assert.deepEqual(seen, ['init-sync-synced']);
1656
+ });
1657
+
1658
+ test('S3: the outcome the hook waits for is bounded, and only a finished run is called completed', async () => {
1659
+ const cwd = temp('cg-init-hook-wait-');
1660
+ const started = Date.now();
1661
+ const outcome = await syncAfterNativeInit({
1662
+ cwd,
1663
+ exists: () => true,
1664
+ sync: { request: async () => ({ status: 'queued' }) },
1665
+ run: async () => true,
1666
+ waitMs: 20,
1667
+ });
1668
+ assert.equal(outcome, 'pending');
1669
+ assert.ok(Date.now() - started < 2_000, 'the tool result does not wait for a full sync');
1670
+ });
1671
+
1672
+ test("S3: a sync another session's run completed after this request is completed, not a sync of this session", async () => {
1673
+ const cwd = temp('cg-init-hook-coalesced-');
1674
+ let ran = false;
1675
+ const outcome = await syncAfterNativeInit({
1676
+ cwd,
1677
+ exists: () => true,
1678
+ sync: { request: async () => ({ status: 'coalesced' }) },
1679
+ run: async () => {
1680
+ ran = true;
1681
+ return true;
1682
+ },
1683
+ });
1684
+ assert.equal(outcome, 'completed');
1685
+ assert.equal(ran, false);
1686
+ });
1687
+
1688
+ test('S3: a failed sync is reported as failed, and the command really ran once', async () => {
1689
+ const cwd = temp('cg-init-hook-failed-');
1690
+ const runs = [];
1691
+ const outcome = await syncAfterNativeInit({
1692
+ cwd,
1693
+ exists: () => true,
1694
+ sync: runsHere(),
1695
+ lock: null,
1696
+ run: async (args) => {
1697
+ runs.push(args);
1698
+ return false;
1699
+ },
1700
+ });
1701
+ assert.equal(outcome, 'failed');
1702
+ assert.equal(runs.length, 1);
1703
+ });
1704
+
1705
+ test('S3: unusable coordination is reported as unavailable and nothing is run beside it', async () => {
1706
+ const cwd = temp('cg-init-hook-unavailable-');
1707
+ let ran = false;
1708
+ const outcome = await syncAfterNativeInit({
1709
+ cwd,
1710
+ exists: () => true,
1711
+ sync: { request: async () => ({ status: 'unavailable' }) },
1712
+ run: async () => {
1713
+ ran = true;
1714
+ return true;
1715
+ },
1716
+ });
1717
+ assert.equal(outcome, 'unavailable');
1718
+ assert.equal(ran, false, 'no uncoordinated sync may be started as a fallback');
1719
+ });
1720
+
1721
+ test('S6: a read-only role starts no index write at all, and its tool result says why', async () => {
1722
+ const cwd = temp('cg-init-hook-role-');
1723
+ let asked = false;
1724
+ const outcome = await syncAfterNativeInit({
1725
+ cwd,
1726
+ exists: () => true,
1727
+ role: 'read-only',
1728
+ sync: {
1729
+ request: async () => {
1730
+ asked = true;
1731
+ return { status: 'coalesced' };
1732
+ },
1733
+ },
1734
+ run: async () => {
1735
+ throw new Error('must not run');
1736
+ },
1737
+ });
1738
+ assert.equal(outcome, 'skipped-read-only');
1739
+ assert.equal(asked, false, 'the coordination is not even asked');
1740
+ assert.match(postInitSyncNotice(outcome), /read-only/);
1741
+ });
1742
+
1743
+ test('S3: an init that left no index requests nothing, because syncing a missing index would fail', async () => {
1744
+ const cwd = temp('cg-init-hook-noindex-');
1745
+ let asked = false;
1746
+ const outcome = await syncAfterNativeInit({
1747
+ cwd,
1748
+ exists: () => false,
1749
+ sync: {
1750
+ request: async () => {
1751
+ asked = true;
1752
+ return { status: 'coalesced' };
1753
+ },
1754
+ },
1755
+ run: async () => true,
1756
+ });
1757
+ assert.equal(outcome, 'failed');
1758
+ assert.equal(asked, false);
1759
+ });
1760
+
1761
+ // ---- prepareProject: the index first, then whatever the caller warms (S2, S3) ----
1762
+
1763
+ function prepareSetup(options) {
1764
+ const log = [];
1765
+ const input = {
1766
+ cwd: CWD,
1767
+ env: options.env || {},
1768
+ reason: options.reason || 'startup',
1769
+ exists: has(...options.present),
1770
+ hasBinary: yes,
1771
+ lock: null,
1772
+ sync: null,
1773
+ onStart: (action) => log.push(`start:${action}`),
1774
+ run: async (args) => {
1775
+ log.push(`run:${args[0]}`);
1776
+ return options.run === undefined ? true : options.run;
1777
+ },
1778
+ onIndexed: (result) => log.push(`indexed:${result.action}:${result.ok}`),
1779
+ onWarmStart: () => log.push('warm-start'),
1780
+ warm: async (cwd) => {
1781
+ log.push(`warm:${cwd}`);
1782
+ if (options.warm === 'throw') throw new Error('boom');
1783
+ return options.warm === undefined ? true : options.warm;
1784
+ },
1785
+ };
1786
+ return { log, input };
1787
+ }
1788
+
1789
+ test('S2: with an index, the caller warms after the sync, in that order', async () => {
1790
+ const { log, input } = prepareSetup({ present: ['.codegraph'] });
1791
+ const result = await prepareProject(input);
1792
+ assert.deepEqual(log, ['start:sync', 'run:sync', 'indexed:sync:true', 'warm-start', `warm:${CWD}`]);
1793
+ assert.deepEqual(result, { index: { action: 'sync', ok: true }, warm: 'ok' });
1794
+ });
1795
+
1796
+ test('S2: a fresh init that worked is warmed too; one that failed is not', async () => {
1797
+ const okSetup = prepareSetup({ present: ['.git', 'package.json'] });
1798
+ const ok = await prepareProject(okSetup.input);
1799
+ assert.deepEqual(okSetup.log, ['start:init', 'run:init', 'indexed:init:true', 'warm-start', `warm:${CWD}`]);
1800
+ assert.equal(ok.warm, 'ok');
1801
+
1802
+ const failedSetup = prepareSetup({ present: ['.git', 'package.json'], run: false });
1803
+ const failed = await prepareProject(failedSetup.input);
1804
+ assert.deepEqual(failedSetup.log, ['start:init', 'run:init', 'indexed:init:false']);
1805
+ assert.deepEqual(failed, { index: { action: 'init', ok: false }, warm: 'skipped' });
1806
+ });
1807
+
1808
+ test('S3: while another session holds the init lock, this one neither syncs nor warms', async () => {
1809
+ const log = [];
1810
+ const result = await prepareProject({
1811
+ cwd: CWD,
1812
+ env: {},
1813
+ reason: 'startup',
1814
+ exists: has('.codegraph'),
1815
+ hasBinary: yes,
1816
+ sync: null,
1817
+ lock: { acquire: () => ({ status: 'busy' }), isHeld: () => true },
1818
+ run: async (args) => {
1819
+ log.push(`run:${args[0]}`);
1820
+ return true;
1821
+ },
1822
+ onWarmStart: () => log.push('warm-start'),
1823
+ warm: async () => {
1824
+ log.push('warm');
1825
+ return true;
1826
+ },
1827
+ });
1828
+ assert.deepEqual(log, []);
1829
+ assert.deepEqual(result, { index: { action: 'sync', ok: true, joined: true }, warm: 'skipped' });
1830
+ });
1831
+
1832
+ test('S2: a failed sync still warms, because the index exists', async () => {
1833
+ const { log, input } = prepareSetup({ present: ['.codegraph'], run: false });
1834
+ const result = await prepareProject(input);
1835
+ assert.ok(log.includes(`warm:${CWD}`));
1836
+ assert.equal(result.warm, 'ok');
1837
+ });
1838
+
1839
+ test('S2: no index and nothing to init -> nothing is warmed', async () => {
1840
+ const { log, input } = prepareSetup({ present: ['.git'] });
1841
+ const result = await prepareProject(input);
1842
+ assert.deepEqual(log, []);
1843
+ assert.deepEqual(result, { index: { action: 'none', ok: true }, warm: 'skipped' });
1844
+ });
1845
+
1846
+ test('S2: subagent children and /reload never warm', async () => {
1847
+ for (const options of [{ env: { GENTLE_PI_AGENTS_CHILD: '1' } }, { reason: 'reload' }]) {
1848
+ const { log, input } = prepareSetup({ present: ['.codegraph'], ...options });
1849
+ const result = await prepareProject(input);
1850
+ assert.deepEqual(log, [], JSON.stringify(options));
1851
+ assert.equal(result.warm, 'skipped');
1852
+ }
1853
+ });
1854
+
1855
+ test('S2: a warm-up that fails or throws is reported as failed and never rejects', async () => {
1856
+ for (const warm of [false, 'throw']) {
1857
+ const { input } = prepareSetup({ present: ['.codegraph'], warm });
1858
+ const result = await prepareProject(input);
1859
+ assert.equal(result.warm, 'failed', String(warm));
1860
+ }
1861
+ });
1862
+
1863
+ test('S3: a startup sync that coalesced, is queued or has no coordination still warms, because the index exists', async () => {
1864
+ for (const [sync, expected] of [
1865
+ [{ request: async () => ({ status: 'coalesced' }) }, { action: 'sync', ok: true, coalesced: true }],
1866
+ [{ request: async () => ({ status: 'queued' }) }, { action: 'sync', ok: true, queued: true }],
1867
+ [{ request: async () => ({ status: 'unavailable' }) }, { action: 'sync', ok: false, unavailable: true }],
1868
+ ]) {
1869
+ const log = [];
1870
+ const result = await prepareProject({
1871
+ cwd: CWD,
1872
+ env: {},
1873
+ reason: 'startup',
1874
+ exists: has('.codegraph'),
1875
+ hasBinary: yes,
1876
+ lock: null,
1877
+ sync,
1878
+ run: async (args) => {
1879
+ log.push(`run:${args[0]}`);
1880
+ return true;
1881
+ },
1882
+ onIndexed: (index) => log.push(`indexed:${index.action}:${index.ok}`),
1883
+ warm: async () => {
1884
+ log.push('warm');
1885
+ return true;
1886
+ },
1887
+ });
1888
+ assert.deepEqual(result.index, expected);
1889
+ assert.equal(result.warm, 'ok');
1890
+ assert.equal(log[log.length - 1], 'warm');
1891
+ }
1892
+ });
1893
+
1894
+ test('S2: an init is never handed to the sync coordinator', async () => {
1895
+ const { log, input } = prepareSetup({ present: ['.git', 'package.json'] });
1896
+ let asked = false;
1897
+ const result = await prepareProject({
1898
+ ...input,
1899
+ sync: {
1900
+ request: async () => {
1901
+ asked = true;
1902
+ return { status: 'coalesced' };
1903
+ },
1904
+ },
1905
+ });
1906
+ assert.equal(asked, false);
1907
+ assert.deepEqual(log, ['start:init', 'run:init', 'indexed:init:true', 'warm-start', `warm:${CWD}`]);
1908
+ assert.equal(result.index.ok, true);
1909
+ });
1910
+
1911
+ test('S2: startup, new, resume and fork warm', async () => {
1912
+ for (const reason of ['startup', 'new', 'resume', 'fork']) {
1913
+ const { log, input } = prepareSetup({ present: ['.codegraph'], reason });
1914
+ await prepareProject(input);
1915
+ assert.ok(log.includes(`warm:${CWD}`), reason);
1916
+ }
1917
+ });
1918
+
1919
+ test('S2: without the codegraph CLI a session prepares nothing, and the probe happens once per process', async () => {
1920
+ const probes = [];
1921
+ const hasBinary = (command) => {
1922
+ probes.push(command);
1923
+ return false;
1924
+ };
1925
+ let warmed = false;
1926
+ const input = {
1927
+ cwd: CWD,
1928
+ env: {},
1929
+ reason: 'startup',
1930
+ exists: has('.codegraph'),
1931
+ hasBinary,
1932
+ lock: null,
1933
+ sync: null,
1934
+ run: async () => {
1935
+ throw new Error('must not run');
1936
+ },
1937
+ warm: async () => {
1938
+ warmed = true;
1939
+ return true;
1940
+ },
1941
+ };
1942
+ const first = await prepareProject(input);
1943
+ const second = await prepareProject(input);
1944
+ assert.deepEqual(probes, ['codegraph']);
1945
+ assert.equal(warmed, false);
1946
+ assert.deepEqual(first, { index: { action: 'none', ok: true, skipped: 'no-cli' }, warm: 'skipped' });
1947
+ assert.deepEqual(second, first);
1948
+ });