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,378 @@
1
+ 'use strict';
2
+ // A compaction leaves the index stale while the session goes on (S2, S3): one background sync, never an init,
3
+ // never a notification, and never a second sync of the same project at the same time as another session's. The
4
+ // coordination itself is `lib/codegraph-lock.js`; here it is driven through `compactionSync` and the public lease.
5
+
6
+ const { test, after } = require('node:test');
7
+ const assert = require('node:assert/strict');
8
+ const fs = require('node:fs');
9
+ const os = require('node:os');
10
+ const path = require('node:path');
11
+
12
+ const { compactionSync } = require('../lib/codegraph-compaction.js');
13
+ const { isInitLocked, isInitRunning, syncLease, tryAcquireInitLock } = require('../lib/codegraph-lock.js');
14
+ const { SYNC_TIMEOUT_MS } = require('../lib/codegraph-index.js');
15
+
16
+ const CWD = path.join('some', 'repo');
17
+ const has = (...present) => (p) => present.some((name) => p.endsWith(name));
18
+ const yes = () => true;
19
+ const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
20
+
21
+ const scratchDirs = [];
22
+ after(() => {
23
+ for (const dir of scratchDirs) {
24
+ try {
25
+ fs.rmSync(dir, { recursive: true, force: true });
26
+ } catch {
27
+ // Best effort.
28
+ }
29
+ }
30
+ });
31
+
32
+ function temp(prefix) {
33
+ const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), prefix)));
34
+ scratchDirs.push(dir);
35
+ return dir;
36
+ }
37
+
38
+ /** A state folder and a project of their own, so these cases never meet the user's locks. */
39
+ function scratch() {
40
+ return { dir: temp('cg-compaction-state-'), project: temp('cg-compaction-project-') };
41
+ }
42
+
43
+ function captured() {
44
+ const entries = [];
45
+ return { entries, log: (entry) => entries.push(entry) };
46
+ }
47
+
48
+ /** The real index lock over one temp folder, as the extension wires it. */
49
+ function indexLock(dir) {
50
+ return {
51
+ acquire: (project, options) => tryAcquireInitLock(project, { dir }, options && options.kind),
52
+ isHeld: (project) => isInitLocked(project, { dir }),
53
+ isInitRunning: (project) => isInitRunning(project, { dir }),
54
+ };
55
+ }
56
+
57
+ /** A coordinator that does no coordination: the attempt runs here, now. */
58
+ const direct = {
59
+ request: async (_project, attempt) => {
60
+ const result = await attempt(() => {});
61
+ return result.ran ? { status: 'ran', ok: result.ok } : { status: 'queued' };
62
+ },
63
+ };
64
+ const coalescing = { request: async () => ({ status: 'coalesced' }) };
65
+ const queuedElsewhere = { request: async () => ({ status: 'queued' }) };
66
+ const unavailable = { request: async () => ({ status: 'unavailable' }) };
67
+
68
+ test('S2: a compaction of a session with an index runs one quiet sync, never an init', async () => {
69
+ const calls = [];
70
+ const { entries, log } = captured();
71
+ const result = await compactionSync({
72
+ cwd: CWD,
73
+ env: {},
74
+ exists: has('.codegraph'),
75
+ sync: direct,
76
+ log,
77
+ hasBinary: yes,
78
+ run: async (args, cwd, timeoutMs) => {
79
+ calls.push({ args, cwd, timeoutMs });
80
+ return true;
81
+ },
82
+ });
83
+ assert.deepEqual(calls, [{ args: ['sync', '-q'], cwd: CWD, timeoutMs: SYNC_TIMEOUT_MS }]);
84
+ assert.deepEqual(result, { outcome: 'synced' });
85
+ assert.equal(entries.length, 1);
86
+ assert.deepEqual({ cwd: entries[0].cwd, outcome: entries[0].outcome }, { cwd: CWD, outcome: 'synced' });
87
+ assert.ok(entries[0].ms >= 0);
88
+ });
89
+
90
+ test('S2: a git project without an index is left alone: a compaction never initialises it', async () => {
91
+ for (const present of [['.git', 'package.json'], ['.git'], []]) {
92
+ const calls = [];
93
+ const { entries, log } = captured();
94
+ const result = await compactionSync({
95
+ cwd: CWD,
96
+ env: {},
97
+ exists: has(...present),
98
+ sync: direct,
99
+ log,
100
+ lock: null,
101
+ hasBinary: yes,
102
+ run: async (args) => {
103
+ calls.push(args);
104
+ return true;
105
+ },
106
+ });
107
+ assert.deepEqual(calls, [], JSON.stringify(present));
108
+ assert.deepEqual(result, { outcome: 'skipped-no-index' }, JSON.stringify(present));
109
+ assert.equal(entries[0].outcome, 'skipped-no-index');
110
+ }
111
+ });
112
+
113
+ test('S2: a subagent child never starts a compaction sync, even with an index', async () => {
114
+ const calls = [];
115
+ const { entries, log } = captured();
116
+ let coordinated = false;
117
+ const result = await compactionSync({
118
+ cwd: CWD,
119
+ env: { GENTLE_PI_AGENTS_CHILD: '1' },
120
+ exists: has('.codegraph'),
121
+ log,
122
+ hasBinary: yes,
123
+ sync: {
124
+ request: async (project, attempt) => {
125
+ coordinated = true;
126
+ return direct.request(project, attempt);
127
+ },
128
+ },
129
+ run: async (args) => {
130
+ calls.push(args);
131
+ return true;
132
+ },
133
+ });
134
+ assert.deepEqual(result, { outcome: 'skipped-child' });
135
+ assert.deepEqual(calls, []);
136
+ assert.equal(coordinated, false, 'a child does not even look at the coordination');
137
+ assert.equal(entries[0].outcome, 'skipped-child');
138
+ });
139
+
140
+ test('S6: a read-only role starts no index write, and says so', async () => {
141
+ const calls = [];
142
+ const { entries, log } = captured();
143
+ let asked = false;
144
+ const result = await compactionSync({
145
+ cwd: CWD,
146
+ env: {},
147
+ exists: has('.codegraph'),
148
+ log,
149
+ hasBinary: yes,
150
+ role: 'read-only',
151
+ sync: {
152
+ request: async () => {
153
+ asked = true;
154
+ return { status: 'coalesced' };
155
+ },
156
+ },
157
+ run: async (args) => {
158
+ calls.push(args);
159
+ return true;
160
+ },
161
+ });
162
+ assert.deepEqual(result, { outcome: 'skipped-read-only' });
163
+ assert.equal(asked, false);
164
+ assert.deepEqual(calls, []);
165
+ assert.equal(entries[0].outcome, 'skipped-read-only');
166
+ });
167
+
168
+ test('S2: without the codegraph CLI in this process nothing runs, and it is probed once', async () => {
169
+ const probes = [];
170
+ const hasBinary = (command) => {
171
+ probes.push(command);
172
+ return false;
173
+ };
174
+ const calls = [];
175
+ const { entries, log } = captured();
176
+ const input = {
177
+ cwd: CWD,
178
+ env: {},
179
+ exists: has('.codegraph'),
180
+ sync: direct,
181
+ log,
182
+ hasBinary,
183
+ run: async (args) => {
184
+ calls.push(args);
185
+ return true;
186
+ },
187
+ };
188
+ assert.deepEqual(await compactionSync(input), { outcome: 'skipped-no-cli' });
189
+ assert.deepEqual(await compactionSync(input), { outcome: 'skipped-no-cli' });
190
+ assert.deepEqual(probes, ['codegraph']);
191
+ assert.deepEqual(calls, []);
192
+ assert.deepEqual(entries.map((entry) => entry.outcome), ['skipped-no-cli', 'skipped-no-cli']);
193
+ });
194
+
195
+ test('S3: a compaction during an init is not dropped: it waits for the init, then syncs under the lock', async () => {
196
+ const { dir, project } = scratch();
197
+ const lock = indexLock(dir);
198
+ const init = tryAcquireInitLock(project, { dir }, 'init');
199
+ assert.equal(init.status, 'acquired');
200
+ const runs = [];
201
+ const { entries, log } = captured();
202
+ const request = compactionSync({
203
+ cwd: project,
204
+ env: {},
205
+ exists: has('.codegraph'),
206
+ lock,
207
+ log,
208
+ hasBinary: yes,
209
+ sync: syncLease({ dir, pollMs: 5, requestWaitMs: 30_000 }),
210
+ run: async () => {
211
+ // The sync holds the package's index lock while it runs: no init can begin in the middle of it.
212
+ assert.equal(isInitLocked(project, { dir }), true, 'the sync runs holding the index lock');
213
+ assert.equal(isInitRunning(project, { dir }), false, 'a sync holder is not an init');
214
+ runs.push('ran');
215
+ return true;
216
+ },
217
+ });
218
+ await pause(200);
219
+ assert.deepEqual(runs, [], 'the index is being initialised: nothing may sync meanwhile');
220
+ init.release();
221
+ const result = await request;
222
+ assert.deepEqual(result, { outcome: 'synced' });
223
+ assert.deepEqual(runs, ['ran']);
224
+ assert.equal(entries[0].outcome, 'synced');
225
+ });
226
+
227
+ test('S3: a compaction that cannot get the index before it gives up says so and leaves the demand on disk', async () => {
228
+ const { dir, project } = scratch();
229
+ const lock = indexLock(dir);
230
+ const init = tryAcquireInitLock(project, { dir }, 'init');
231
+ assert.equal(init.status, 'acquired');
232
+ const runs = [];
233
+ const { entries, log } = captured();
234
+ const result = await compactionSync({
235
+ cwd: project,
236
+ env: {},
237
+ exists: has('.codegraph'),
238
+ lock,
239
+ log,
240
+ hasBinary: yes,
241
+ sync: syncLease({ dir, pollMs: 5, requestWaitMs: 200 }),
242
+ run: async () => {
243
+ runs.push('ran');
244
+ return true;
245
+ },
246
+ });
247
+ assert.deepEqual(runs, [], 'the init still owns the index');
248
+ assert.deepEqual(result, { outcome: 'queued' }, 'not coalesced: nothing ran for it yet');
249
+ assert.equal(entries[0].outcome, 'queued');
250
+ init.release();
251
+ // A later sync of the same project serves the request the session left behind.
252
+ const later = [];
253
+ const served = await compactionSync({
254
+ cwd: project,
255
+ env: {},
256
+ exists: has('.codegraph'),
257
+ lock,
258
+ hasBinary: yes,
259
+ sync: syncLease({ dir, pollMs: 5, requestWaitMs: 30_000 }),
260
+ run: async () => {
261
+ later.push('ran');
262
+ return true;
263
+ },
264
+ log: () => {},
265
+ });
266
+ assert.deepEqual(served, { outcome: 'synced' });
267
+ assert.deepEqual(later, ['ran'], 'the pending request was served, not lost');
268
+ });
269
+
270
+ test('S3: a failing compaction sync is logged as failed and never thrown, and nothing else is told', async () => {
271
+ for (const failure of ['exit', 'throw']) {
272
+ const { entries, log } = captured();
273
+ const result = await compactionSync({
274
+ cwd: CWD,
275
+ env: {},
276
+ exists: has('.codegraph'),
277
+ log,
278
+ lock: null,
279
+ sync: direct,
280
+ hasBinary: yes,
281
+ run: async () => {
282
+ if (failure === 'throw') throw new Error('boom');
283
+ return false;
284
+ },
285
+ });
286
+ assert.deepEqual(result, { outcome: 'failed' }, failure);
287
+ // The only thing a failure produces is the diagnostic line: no message, no notice, no result to show.
288
+ assert.deepEqual(Object.keys(result), ['outcome'], failure);
289
+ assert.deepEqual(entries.map((entry) => entry.outcome), ['failed'], failure);
290
+ }
291
+ });
292
+
293
+ test('S2: when another session is already syncing, the compaction leaves the run to it', async () => {
294
+ const calls = [];
295
+ const { entries, log } = captured();
296
+ const result = await compactionSync({
297
+ cwd: CWD,
298
+ env: {},
299
+ exists: has('.codegraph'),
300
+ sync: coalescing,
301
+ log,
302
+ hasBinary: yes,
303
+ run: async (args) => {
304
+ calls.push(args);
305
+ return true;
306
+ },
307
+ });
308
+ assert.deepEqual(calls, []);
309
+ assert.deepEqual(result, { outcome: 'coalesced' });
310
+ assert.equal(entries[0].outcome, 'coalesced');
311
+ });
312
+
313
+ test('S2: a compaction whose request is still waiting is logged as queued, never as coalesced', async () => {
314
+ for (const [sync, expected] of [[queuedElsewhere, 'queued'], [unavailable, 'skipped-coordination-unavailable']]) {
315
+ const calls = [];
316
+ const { entries, log } = captured();
317
+ const result = await compactionSync({
318
+ cwd: CWD,
319
+ env: {},
320
+ exists: has('.codegraph'),
321
+ sync,
322
+ log,
323
+ hasBinary: yes,
324
+ run: async (args) => {
325
+ calls.push(args);
326
+ return true;
327
+ },
328
+ });
329
+ assert.deepEqual(calls, [], expected);
330
+ assert.deepEqual(result, { outcome: expected });
331
+ assert.equal(entries[0].outcome, expected);
332
+ }
333
+ });
334
+
335
+ test('S2: the compaction sync reaches the coordinator with the project and the quiet command', async () => {
336
+ const projects = [];
337
+ const { log } = captured();
338
+ await compactionSync({
339
+ cwd: CWD,
340
+ env: {},
341
+ exists: has('.codegraph'),
342
+ log,
343
+ lock: null,
344
+ hasBinary: yes,
345
+ sync: {
346
+ request: async (project, attempt) => {
347
+ projects.push(project);
348
+ assert.deepEqual(await attempt(() => {}), { ran: true, ok: true });
349
+ return { status: 'ran', ok: true };
350
+ },
351
+ },
352
+ run: async (args, cwd) => args[0] === 'sync' && cwd === CWD,
353
+ });
354
+ assert.deepEqual(projects, [CWD]);
355
+ });
356
+
357
+ test('S2: unusable coordination state starts no sync at all (fail closed), and says so', async () => {
358
+ const file = path.join(temp('cg-compaction-file-'), 'not-a-directory');
359
+ fs.writeFileSync(file, '');
360
+ let ran = false;
361
+ const { entries, log } = captured();
362
+ const result = await compactionSync({
363
+ cwd: CWD,
364
+ env: {},
365
+ exists: has('.codegraph'),
366
+ log,
367
+ lock: null,
368
+ hasBinary: yes,
369
+ sync: syncLease({ dir: file, pollMs: 5, requestWaitMs: 500 }),
370
+ run: async () => {
371
+ ran = true;
372
+ return true;
373
+ },
374
+ });
375
+ assert.equal(ran, false, 'without its coordination state the package does not risk a second sync');
376
+ assert.deepEqual(result, { outcome: 'skipped-coordination-unavailable' });
377
+ assert.equal(entries[0].outcome, 'skipped-coordination-unavailable');
378
+ });
@@ -0,0 +1,248 @@
1
+ 'use strict';
2
+ // S5: a checkout's daemon is resolved from CodeGraph's own registry — per checkout, with no help from the MCP
3
+ // configuration — and asked over its own socket, with every failure answer instead of a throw.
4
+
5
+ const { test, after } = require('node:test');
6
+ const assert = require('node:assert/strict');
7
+ const fs = require('node:fs');
8
+ const path = require('node:path');
9
+
10
+ const {
11
+ DAEMON_HELLO_TIMEOUT_MS,
12
+ DAEMON_PROTOCOL,
13
+ daemonStatus,
14
+ exploreViaDaemon,
15
+ liveDaemon,
16
+ normalizeRoot,
17
+ projectArgument,
18
+ registeredRoot,
19
+ } = require('../lib/codegraph-daemon.js');
20
+ const { fakeDaemon, registry, scratch, socketPath, cleanup } = require('./fixtures/daemon-fake.js');
21
+
22
+ after(cleanup);
23
+
24
+ const ROOT = scratch('odd-daemon-root-');
25
+
26
+ // --- The protocol, over a real socket and a real registry ---
27
+
28
+ test('S5: asks the daemon registered for the project and returns its text', async () => {
29
+ const received = [];
30
+ const daemon = await fakeDaemon({ received });
31
+ const result = await exploreViaDaemon(ROOT, 'coapi login flow', 5_000, { registryDir: registry([{ root: ROOT, socketPath: daemon.path }]) });
32
+ assert.deepEqual(result, { status: 'ok', text: 'FAKE EXPLORE OUTPUT' });
33
+ const call = JSON.parse(received.find((line) => line.includes('tools/call')));
34
+ assert.equal(call.params.name, 'codegraph_explore');
35
+ assert.deepEqual(call.params.arguments, { query: 'coapi login flow' });
36
+ // The conversation opens with the initialize request the daemon expects, and says hello first.
37
+ assert.equal(JSON.parse(received[0]).method, 'initialize');
38
+ });
39
+
40
+ test('S5: a reply that arrives in pieces is put back together', async () => {
41
+ const daemon = await fakeDaemon({ explore: { split: 'SPLIT OUTPUT' } });
42
+ const result = await exploreViaDaemon(ROOT, 'q', 5_000, { registryDir: registry([{ root: ROOT, socketPath: daemon.path }]) });
43
+ assert.deepEqual(result, { status: 'ok', text: 'SPLIT OUTPUT' });
44
+ });
45
+
46
+ test('S5: a hello with another protocol is refused before anything else is said', async () => {
47
+ const received = [];
48
+ const daemon = await fakeDaemon({ hello: JSON.stringify({ codegraph: '9.9.9', pid: 1, protocol: DAEMON_PROTOCOL + 1 }), received });
49
+ const result = await exploreViaDaemon(ROOT, 'q', 5_000, { registryDir: registry([{ root: ROOT, socketPath: daemon.path }]) });
50
+ assert.deepEqual(result, { status: 'unavailable' });
51
+ assert.deepEqual(received, []);
52
+ });
53
+
54
+ test('S5: a hello that is not JSON or lacks fields is unavailable, never a throw', async () => {
55
+ for (const hello of ['not json', JSON.stringify({ protocol: DAEMON_PROTOCOL })]) {
56
+ const daemon = await fakeDaemon({ hello });
57
+ const result = await exploreViaDaemon(ROOT, 'q', 5_000, { registryDir: registry([{ root: ROOT, socketPath: daemon.path }]) });
58
+ assert.deepEqual(result, { status: 'unavailable' }, hello);
59
+ }
60
+ });
61
+
62
+ test('S5: a daemon that hangs up right after the hello is unavailable', async () => {
63
+ const daemon = await fakeDaemon({ explore: { closeAfterHello: true } });
64
+ assert.deepEqual(
65
+ await exploreViaDaemon(ROOT, 'q', 5_000, { registryDir: registry([{ root: ROOT, socketPath: daemon.path }]) }),
66
+ { status: 'unavailable' },
67
+ );
68
+ });
69
+
70
+ test("S5: an error reply, or CodeGraph's 'no project' text, is unavailable", async () => {
71
+ for (const explore of [{ error: 'boom' }, { text: 'No CodeGraph project is loaded for this session.' }]) {
72
+ const daemon = await fakeDaemon({ explore });
73
+ const result = await exploreViaDaemon(ROOT, 'q', 5_000, { registryDir: registry([{ root: ROOT, socketPath: daemon.path }]) });
74
+ assert.deepEqual(result, { status: 'unavailable' }, JSON.stringify(explore));
75
+ }
76
+ });
77
+
78
+ test('S5: an MCP reply with isError is unavailable, so its text is never used as a result', async () => {
79
+ // CodeGraph answers a crashed query worker this way: a text result, flagged as an error.
80
+ const daemon = await fakeDaemon({ explore: { text: 'codegraph worker crashed; please retry the call.', isError: true } });
81
+ assert.deepEqual(
82
+ await exploreViaDaemon(ROOT, 'q', 5_000, { registryDir: registry([{ root: ROOT, socketPath: daemon.path }]) }),
83
+ { status: 'unavailable' },
84
+ );
85
+ });
86
+
87
+ test('S5: output beyond the cap is unavailable, so nothing is kept instead of memory growing', async () => {
88
+ const daemon = await fakeDaemon({ explore: { text: 'x'.repeat(1_500_000) } });
89
+ assert.deepEqual(
90
+ await exploreViaDaemon(ROOT, 'q', 10_000, { registryDir: registry([{ root: ROOT, socketPath: daemon.path }]) }),
91
+ { status: 'unavailable' },
92
+ );
93
+ });
94
+
95
+ test('S5: a daemon that never answers is a timeout, reported on time', async () => {
96
+ const daemon = await fakeDaemon({ explore: 'silence' });
97
+ const started = Date.now();
98
+ const result = await exploreViaDaemon(ROOT, 'q', 400, { registryDir: registry([{ root: ROOT, socketPath: daemon.path }]) });
99
+ assert.deepEqual(result, { status: 'timeout' });
100
+ assert.ok(Date.now() - started < 3_000);
101
+ });
102
+
103
+ test('S5: a daemon that never says hello gives way to the next one instead of using the whole budget', async () => {
104
+ const silent = await fakeDaemon({ hello: null });
105
+ const live = await fakeDaemon({});
106
+ const started = Date.now();
107
+ const result = await exploreViaDaemon(ROOT, 'q', 10_000, {
108
+ registryDir: registry([
109
+ { root: ROOT, socketPath: silent.path, startedAt: 2 },
110
+ { root: ROOT, socketPath: live.path, startedAt: 1 },
111
+ ]),
112
+ });
113
+ assert.deepEqual(result, { status: 'ok', text: 'FAKE EXPLORE OUTPUT' });
114
+ assert.ok(Date.now() - started < DAEMON_HELLO_TIMEOUT_MS + 2_000, `took ${Date.now() - started} ms`);
115
+ });
116
+
117
+ test('S5: when the only daemon never says hello, it is a timeout after the hello wait, not after the whole budget', async () => {
118
+ const silent = await fakeDaemon({ hello: null });
119
+ const started = Date.now();
120
+ const result = await exploreViaDaemon(ROOT, 'q', 10_000, { registryDir: registry([{ root: ROOT, socketPath: silent.path }]) });
121
+ assert.deepEqual(result, { status: 'timeout' });
122
+ const took = Date.now() - started;
123
+ assert.ok(took >= DAEMON_HELLO_TIMEOUT_MS - 50 && took < DAEMON_HELLO_TIMEOUT_MS + 2_000, `took ${took} ms`);
124
+ });
125
+
126
+ test("S5: no registry, an empty one, or another project's daemon is unavailable", async () => {
127
+ const daemon = await fakeDaemon({});
128
+ const other = scratch('odd-daemon-other-');
129
+ assert.deepEqual(
130
+ await exploreViaDaemon(ROOT, 'q', 2_000, { registryDir: path.join(ROOT, 'does-not-exist') }),
131
+ { status: 'unavailable' },
132
+ );
133
+ assert.deepEqual(await exploreViaDaemon(ROOT, 'q', 2_000, { registryDir: registry([]) }), { status: 'unavailable' });
134
+ assert.deepEqual(
135
+ await exploreViaDaemon(ROOT, 'q', 2_000, { registryDir: registry([{ root: other, socketPath: daemon.path }]) }),
136
+ { status: 'unavailable' },
137
+ );
138
+ });
139
+
140
+ test('S5: a registry entry whose daemon is gone is unavailable; with several entries a live one is still found', async () => {
141
+ const dead = socketPath('odd-daemon-dead');
142
+ assert.deepEqual(await exploreViaDaemon(ROOT, 'q', 2_000, { registryDir: registry([{ root: ROOT, socketPath: dead }]) }), { status: 'unavailable' });
143
+ const live = await fakeDaemon({});
144
+ for (const entries of [
145
+ [{ root: ROOT, socketPath: dead, startedAt: 2 }, { root: ROOT, socketPath: live.path, startedAt: 1 }],
146
+ [{ root: ROOT, socketPath: live.path, startedAt: 2 }, { root: ROOT, socketPath: dead, startedAt: 1 }],
147
+ ]) {
148
+ const result = await exploreViaDaemon(ROOT, 'q', 5_000, { registryDir: registry(entries) });
149
+ assert.equal(result.status, 'ok');
150
+ }
151
+ });
152
+
153
+ test('S5: the project root matches whatever its spelling: a trailing separator, and on Windows letter case', () => {
154
+ assert.equal(normalizeRoot(`${ROOT}${path.sep}`), normalizeRoot(ROOT));
155
+ if (process.platform === 'win32') {
156
+ assert.equal(normalizeRoot(ROOT.toUpperCase()), normalizeRoot(ROOT.toLowerCase()));
157
+ } else {
158
+ assert.notEqual(normalizeRoot(ROOT.toUpperCase()), normalizeRoot(ROOT));
159
+ }
160
+ });
161
+
162
+ test('S5: a trailing separator in the registry still resolves to the checkout', async () => {
163
+ const daemon = await fakeDaemon({});
164
+ const result = await exploreViaDaemon(ROOT, 'q', 5_000, { registryDir: registry([{ root: `${ROOT}${path.sep}`, socketPath: daemon.path }]) });
165
+ assert.equal(result.status, 'ok');
166
+ });
167
+
168
+ // --- S5: the daemon of one checkout, resolved from that checkout only, never from MCP configuration ---
169
+
170
+ test("S5: a checkout's live registered daemon is reported with its socket, and its status is live", async () => {
171
+ const daemon = await fakeDaemon({});
172
+ const registryDir = registry([{ root: ROOT, socketPath: daemon.path, startedAt: 7 }]);
173
+ assert.deepEqual(liveDaemon(ROOT, { registryDir }), { root: ROOT, socketPath: daemon.path, pid: process.pid });
174
+ assert.equal(daemonStatus(ROOT, { registryDir }), 'live');
175
+ });
176
+
177
+ test('S5: a record whose daemon is gone is dead, an empty registry is none, and neither is a live daemon', () => {
178
+ const dead = socketPath('odd-daemon-gone');
179
+ assert.equal(daemonStatus(ROOT, { registryDir: registry([{ root: ROOT, socketPath: dead }]) }), 'dead');
180
+ assert.equal(daemonStatus(ROOT, { registryDir: registry([]) }), 'none');
181
+ assert.equal(daemonStatus(ROOT, { registryDir: path.join(ROOT, 'no-registry-here') }), 'none');
182
+ assert.equal(liveDaemon(ROOT, { registryDir: registry([{ root: ROOT, socketPath: dead }]) }), undefined);
183
+ });
184
+
185
+ test('S5: a record whose process is gone is dead, whatever its socket says', async () => {
186
+ const daemon = await fakeDaemon({});
187
+ const registryDir = registry([{ root: ROOT, socketPath: daemon.path }]);
188
+ const alive = { alive: () => false };
189
+ assert.equal(daemonStatus(ROOT, { registryDir, ...alive }), 'dead');
190
+ assert.equal(liveDaemon(ROOT, { registryDir, ...alive }), undefined);
191
+ assert.equal(daemonStatus(ROOT, { registryDir }), 'live');
192
+ });
193
+
194
+ test("S5: a worktree is its own checkout: its parent's daemon is never its own", async () => {
195
+ const parent = scratch('odd-daemon-parent-');
196
+ const child = scratch('odd-daemon-child-');
197
+ const daemon = await fakeDaemon({});
198
+ const registryDir = registry([{ root: parent, socketPath: daemon.path }]);
199
+ assert.equal(daemonStatus(child, { registryDir }), 'none');
200
+ assert.equal(liveDaemon(child, { registryDir }), undefined);
201
+ assert.equal(registeredRoot(child, { registryDir }), undefined, "the parent's spelling is never handed to a child");
202
+ assert.equal(projectArgument(child, { registryDir }), child);
203
+ assert.deepEqual(await exploreViaDaemon(child, 'q', 2_000, { registryDir }), { status: 'unavailable' });
204
+ });
205
+
206
+ test('S5: an MCP server entry is not evidence of a reachable daemon', () => {
207
+ // A checkout whose MCP configuration names the CodeGraph server, and whose daemon registry says nothing.
208
+ const checkout = scratch('odd-daemon-mcp-');
209
+ fs.writeFileSync(
210
+ path.join(checkout, 'mcp.json'),
211
+ JSON.stringify({ mcpServers: { codegraph: { command: 'codegraph', args: ['serve', '--mcp'] } } }),
212
+ );
213
+ assert.equal(daemonStatus(checkout, { registryDir: registry([]) }), 'none');
214
+ assert.equal(liveDaemon(checkout, { registryDir: registry([]) }), undefined);
215
+ });
216
+
217
+ test('S5: a live daemon needs no MCP entry to be resolved and used', async () => {
218
+ const daemon = await fakeDaemon({});
219
+ const registryDir = registry([{ root: ROOT, socketPath: daemon.path }]);
220
+ assert.equal(daemonStatus(ROOT, { registryDir }), 'live');
221
+ assert.deepEqual(await exploreViaDaemon(ROOT, 'q', 5_000, { registryDir }), { status: 'ok', text: 'FAKE EXPLORE OUTPUT' });
222
+ });
223
+
224
+ test('S5: the registry is only read: a bad record is skipped and the directory is left as it was', async () => {
225
+ const daemon = await fakeDaemon({});
226
+ const registryDir = registry([{ root: ROOT, socketPath: daemon.path }]);
227
+ fs.writeFileSync(path.join(registryDir, 'damaged.json'), 'not json');
228
+ const before = fs.readdirSync(registryDir).sort();
229
+ assert.equal(daemonStatus(ROOT, { registryDir }), 'live');
230
+ assert.deepEqual(fs.readdirSync(registryDir).sort(), before);
231
+ assert.deepEqual(await exploreViaDaemon(ROOT, 'q', 5_000, { registryDir }), { status: 'ok', text: 'FAKE EXPLORE OUTPUT' });
232
+ });
233
+
234
+ // --- The clock and the connection are seams, so no daemon is started here ---
235
+
236
+ test('S5: a registry that cannot be read is no daemon at all, and nothing throws', () => {
237
+ const unreadable = { readdirSync: () => { throw new Error('EACCES'); } };
238
+ assert.equal(daemonStatus(ROOT, { registryDir: ROOT, fs: unreadable }), 'none');
239
+ assert.equal(liveDaemon(ROOT, { registryDir: ROOT, fs: unreadable }), undefined);
240
+ });
241
+
242
+ test('S5: explore reports unavailable when the connection itself fails, and never throws', async () => {
243
+ const connect = () => { throw new Error('ECONNREFUSED'); };
244
+ assert.deepEqual(
245
+ await exploreViaDaemon(ROOT, 'q', 1_000, { registryDir: registry([{ root: ROOT, socketPath: socketPath('odd-daemon-nowhere') }]), connect }),
246
+ { status: 'unavailable' },
247
+ );
248
+ });