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,110 @@
1
+ 'use strict';
2
+ // S10: the CodeGraph output shapes the card's collapsed rows are decided from.
3
+ //
4
+ // Every string here is a row the real binary printed (codegraph 1.6.0, the
5
+ // `@clack/prompts` chrome it paints its progress in) in a fresh temporary Git
6
+ // repository, or the same shape its MCP `codegraph_explore` handler answers
7
+ // with. Nothing reads a repository, an index or a terminal: the preview is a
8
+ // pure function of the operation, the command and the output retained here, so
9
+ // the fixtures are plain strings and this file spawns nothing.
10
+
11
+ /** A fresh `codegraph init -y`: its progress box and the sentence it ends with. */
12
+ const INIT_FRESH = [
13
+ '┌ Initializing CodeGraph',
14
+ '│',
15
+ '◆ Initialized in /tmp/ws',
16
+ '│',
17
+ 'Scanning files...',
18
+ 'Parsing code...',
19
+ '│',
20
+ '◆ Indexed 1 files',
21
+ '│',
22
+ '● 3 nodes, 2 edges in 208ms',
23
+ '│',
24
+ '└ Done',
25
+ '',
26
+ ].join('\n');
27
+
28
+ /** `codegraph init -y` on a workspace that already has an index. */
29
+ const INIT_EXISTING = [
30
+ '┌ Initializing CodeGraph',
31
+ '│',
32
+ '▲ Already initialized in /tmp/ws',
33
+ '│',
34
+ '● Use "codegraph index" to re-index or "codegraph sync" to update',
35
+ '│',
36
+ '└ ',
37
+ ].join('\n');
38
+
39
+ /** An init log with facts but no concluding sentence. */
40
+ const INIT_FACTS = [
41
+ '┌ Initializing CodeGraph',
42
+ 'Scanning files...',
43
+ '◆ Indexed 2 files',
44
+ '● 5 nodes, 7 edges in 239ms',
45
+ '└ Done',
46
+ ].join('\n');
47
+
48
+ /** A failed init: the reason it printed, and the instruction that follows it. */
49
+ const INIT_FAILED = [
50
+ '┌ Initializing CodeGraph',
51
+ '✗ Failed: EACCES: permission denied, open /tmp/ws/.codegraph/codegraph.db',
52
+ '● Move or delete that file, then run "codegraph init" again.',
53
+ '└ ',
54
+ ].join('\n');
55
+
56
+ /** `codegraph sync`: the files it re-read, and the nodes it updated. */
57
+ const SYNC_CHANGED = [
58
+ '┌ Syncing CodeGraph',
59
+ '│',
60
+ '◆ Synced 3 changed files',
61
+ '● Added: 1, Modified: 2 — 10 nodes in 123ms',
62
+ '│',
63
+ '└ Done',
64
+ ].join('\n');
65
+
66
+ /** `codegraph sync` on a workspace where nothing changed. */
67
+ const SYNC_UP_TO_DATE = ['┌ Syncing CodeGraph', '│', '● Already up to date', '│', '└ Done'].join('\n');
68
+
69
+ /** `codegraph sync` on a workspace whose index a newer engine wrote. */
70
+ const SYNC_NO_FILES = ['┌ Syncing CodeGraph', '│', '◆ Synced 1 changed files', '● Added: 1, Modified: 0, Removed: 0 — 4 nodes in 88ms', '│', '└ Done'].join('\n');
71
+
72
+ /** A successful `codegraph query`: two entries, each symbol line plus its location. */
73
+ const QUERY = [
74
+ 'Search Results for "alpha":',
75
+ '',
76
+ 'function alpha',
77
+ ' src/a.ts:1',
78
+ '',
79
+ 'import ./a.ts',
80
+ ' src/b.ts:1',
81
+ ].join('\n');
82
+
83
+ /** `codegraph query` with nothing to report. */
84
+ const QUERY_EMPTY = 'ℹ No results found for "zzz"';
85
+
86
+ /** The MCP `codegraph_explore` answer: its header sentence, then the source it sent. */
87
+ const EXPLORE = [
88
+ '**Exploration: auth login**',
89
+ '',
90
+ 'Found 2 symbols across 1 file.',
91
+ '',
92
+ '**`src/auth.ts`** — login(session)',
93
+ ].join('\n');
94
+
95
+ /** The MCP explore header sentence with the further clause the handler may add. */
96
+ const EXPLORE_PINNED = '**Exploration: auth login**\n\nFound 1 symbol across 2 files. 1 file pinned from the query.';
97
+
98
+ module.exports = {
99
+ EXPLORE,
100
+ EXPLORE_PINNED,
101
+ INIT_EXISTING,
102
+ INIT_FACTS,
103
+ INIT_FAILED,
104
+ INIT_FRESH,
105
+ QUERY,
106
+ QUERY_EMPTY,
107
+ SYNC_CHANGED,
108
+ SYNC_NO_FILES,
109
+ SYNC_UP_TO_DATE,
110
+ };
@@ -0,0 +1,16 @@
1
+ 'use strict';
2
+ // The body of a fake `codegraph` binary for the timeout case: it records its own pid where the test can read it
3
+ // and then stays alive, so a timeout has a real process to terminate. It touches no index and reaches nothing.
4
+
5
+ const fs = require('node:fs');
6
+
7
+ const file = process.env.CODEGRAPH_STUB_PID_FILE;
8
+ if (file) {
9
+ try {
10
+ fs.writeFileSync(file, String(process.pid));
11
+ } catch {
12
+ // The test reports the missing pid.
13
+ }
14
+ }
15
+
16
+ setTimeout(() => {}, 120_000);
@@ -0,0 +1,28 @@
1
+ 'use strict';
2
+ // A stand-in for the `codegraph init` process a session started: it announces itself in CodeGraph's own
3
+ // `<project>/.codegraph/codegraph.lock` (which is how the real one names the process writing the index) and then
4
+ // stays alive until it is killed or its own time runs out. It writes no index and reaches nothing.
5
+ //
6
+ // argv: <project> <holdMs>
7
+
8
+ const fs = require('node:fs');
9
+ const path = require('node:path');
10
+
11
+ const [, , project, holdMs] = process.argv;
12
+ const dir = path.join(project, '.codegraph');
13
+ const announced = path.join(dir, 'codegraph.lock');
14
+
15
+ try {
16
+ fs.mkdirSync(dir, { recursive: true });
17
+ fs.writeFileSync(announced, String(process.pid));
18
+ } catch {
19
+ // A test that cannot write the announcement reports it through the lock it does not find.
20
+ }
21
+
22
+ setTimeout(() => {
23
+ try {
24
+ fs.rmSync(announced, { force: true });
25
+ } catch {
26
+ // Going away is enough.
27
+ }
28
+ }, Math.max(1, Number(holdMs) || 30_000));
@@ -0,0 +1,117 @@
1
+ 'use strict';
2
+ // One "session" for the coordination tests (S3): a process that speaks the public surface of
3
+ // `lib/codegraph-lock.js` on its own, so a test can watch what two real processes do to one lock or one lease.
4
+ //
5
+ // argv: <lockDir> <project> <startAt> <holdMs|stdin> <mode>
6
+ //
7
+ // Modes:
8
+ // lock (default) try to take the init lock; hold it for `holdMs`, or until stdin closes, and release.
9
+ // orphan take the lock, hand it to a long-lived child of its own and exit WITHOUT releasing, like a Pi
10
+ // that dies while its init goes on.
11
+ // shell start the init the way this package does on Windows (through a shell) and adopt that shell's
12
+ // pid as a proxy, which can die while the init itself goes on.
13
+ // sync one session asking for a coordinated sync: its fake sync records start and end in
14
+ // `<project>/runs.log` and lasts `holdMs`, so a test sees whether two ever overlapped.
15
+ // sync-cli its run starts a detached CLI that keeps writing for `holdMs` after the session is killed,
16
+ // and reports that pid as the process the sync started.
17
+
18
+ const { spawn } = require('node:child_process');
19
+ const fs = require('node:fs');
20
+ const path = require('node:path');
21
+
22
+ const { syncLease, tryAcquireInitLock } = require('../../lib/codegraph-lock.js');
23
+
24
+ const [, , lockDir, project, startAt, holdMs, mode] = process.argv;
25
+ const INIT_PROCESS = path.join(__dirname, 'codegraph-init-process.js');
26
+ const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
27
+
28
+ function record(file, line) {
29
+ try {
30
+ fs.appendFileSync(file, `${line}\n`);
31
+ } catch {
32
+ // The test reads what it can and reports the rest.
33
+ }
34
+ }
35
+
36
+ function say(value) {
37
+ process.stdout.write(`${JSON.stringify(value)}\n`);
38
+ }
39
+
40
+ async function main() {
41
+ // Every session waits for the same start line, so they really try at one instant.
42
+ while (Date.now() < Number(startAt || 0)) {
43
+ /* spin */
44
+ }
45
+
46
+ if (mode === 'sync' || mode === 'sync-cli') {
47
+ const ledger = path.join(project, 'runs.log');
48
+ const requestedAt = Date.now();
49
+ const lease = syncLease({ dir: lockDir, pollMs: 10, requestWaitMs: 60_000 });
50
+ const outcome = await lease.request(project, async (onSpawn) => {
51
+ if (mode === 'sync') {
52
+ record(ledger, `start ${Date.now()} ${process.pid}`);
53
+ await pause(Number(holdMs));
54
+ record(ledger, `end ${Date.now()} ${process.pid}`);
55
+ return { ran: true, ok: true };
56
+ }
57
+ // The command this session runs outlives it: a detached process writing the index for `holdMs`.
58
+ const script = 'const fs = require("node:fs"); const ledger = ' + JSON.stringify(ledger) + '; '
59
+ + 'fs.appendFileSync(ledger, "cli-start " + Date.now() + "\\n"); '
60
+ + `setTimeout(() => { fs.appendFileSync(ledger, "cli-end " + Date.now() + "\\n"); }, ${Number(holdMs)});`;
61
+ const cli = spawn(process.execPath, ['-e', script], { detached: true, stdio: 'ignore', windowsHide: true });
62
+ cli.unref();
63
+ onSpawn(cli.pid);
64
+ say({ status: 'running', pid: process.pid, cliPid: cli.pid, requestedAt });
65
+ // The session stays inside its run until the test kills it.
66
+ await new Promise(() => {});
67
+ return { ran: true, ok: true };
68
+ });
69
+ say({ status: 'synced', pid: process.pid, requestedAt, returnedAt: Date.now(), outcome });
70
+ process.exit(0);
71
+ }
72
+
73
+ const attempt = tryAcquireInitLock(project, { dir: lockDir });
74
+
75
+ if (mode === 'orphan' && attempt.status === 'acquired') {
76
+ const init = spawn(process.execPath, ['-e', `setTimeout(() => {}, ${Number(holdMs)})`], { detached: true, stdio: 'ignore' });
77
+ init.unref();
78
+ attempt.adopt(init.pid);
79
+ say({ status: attempt.status, pid: process.pid, initPid: init.pid });
80
+ process.exit(0);
81
+ }
82
+
83
+ if (mode === 'shell' && attempt.status === 'acquired') {
84
+ // `&& exit 0` keeps the shell a real process around the init: a shell that exec'd the command would BE the
85
+ // init, and then killing the shell would prove nothing about the init outliving it.
86
+ const command = `${[process.execPath, INIT_PROCESS, project, String(Number(holdMs))]
87
+ .map((part) => `"${part}"`)
88
+ .join(' ')} && exit 0`;
89
+ const shell = spawn(command, { shell: true, stdio: 'ignore', windowsHide: true });
90
+ attempt.adopt(shell.pid, { proxy: true });
91
+ // Let the init announce itself before this session exits, so the shell's death cannot take it down.
92
+ const announced = path.join(project, '.codegraph', 'codegraph.lock');
93
+ const deadline = Date.now() + 20_000;
94
+ while (Date.now() < deadline) {
95
+ if (fs.existsSync(announced)) break;
96
+ await pause(50);
97
+ }
98
+ say({ status: attempt.status, pid: process.pid, initPid: shell.pid });
99
+ process.exit(0);
100
+ }
101
+
102
+ say({ status: attempt.status, pid: process.pid });
103
+ if (attempt.status === 'acquired') {
104
+ if (holdMs === 'stdin') {
105
+ await new Promise((resolve) => {
106
+ process.stdin.on('end', resolve);
107
+ process.stdin.on('close', resolve);
108
+ process.stdin.resume();
109
+ });
110
+ } else {
111
+ await pause(Number(holdMs));
112
+ }
113
+ attempt.release();
114
+ }
115
+ }
116
+
117
+ main();
@@ -0,0 +1,98 @@
1
+ 'use strict';
2
+ // A fake CodeGraph daemon on a real socket plus a fake registry: the hello/explore protocol and every
3
+ // failure shape, without CodeGraph. Tests only ever point the daemon module at these.
4
+
5
+ const net = require('node:net');
6
+ const fs = require('node:fs');
7
+ const os = require('node:os');
8
+ const path = require('node:path');
9
+
10
+ const HELLO = JSON.stringify({ codegraph: '1.6.0', pid: process.pid, socketPath: 'x', protocol: 1 });
11
+
12
+ let counter = 0;
13
+ const createdDirs = [];
14
+ const openedServers = [];
15
+
16
+ function socketPath(prefix = 'odd-daemon') {
17
+ const name = `${prefix}-${process.pid}-${++counter}`;
18
+ return process.platform === 'win32' ? `\\\\.\\pipe\\${name}` : path.join(os.tmpdir(), `${name}.sock`);
19
+ }
20
+
21
+ function scratch(prefix) {
22
+ const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), prefix)));
23
+ createdDirs.push(dir);
24
+ return dir;
25
+ }
26
+
27
+ /**
28
+ * A daemon that speaks the protocol: `hello` is its first line (null sends nothing), `explore` is what it
29
+ * does with the explore call. Every received line is pushed to `received` when that array is given.
30
+ */
31
+ function fakeDaemon(options = {}) {
32
+ const usedPath = socketPath();
33
+ const server = net.createServer((socket) => {
34
+ socket.on('error', () => {});
35
+ if (options.hello !== null) socket.write(`${options.hello ?? HELLO}\n`);
36
+ const explore = options.explore ?? { text: 'FAKE EXPLORE OUTPUT' };
37
+ if (typeof explore === 'object' && explore.closeAfterHello === true) {
38
+ socket.end();
39
+ return;
40
+ }
41
+ let buffer = '';
42
+ socket.on('data', (chunk) => {
43
+ buffer += chunk.toString('utf8');
44
+ let newline;
45
+ while ((newline = buffer.indexOf('\n')) >= 0) {
46
+ const line = buffer.slice(0, newline);
47
+ buffer = buffer.slice(newline + 1);
48
+ options.received?.push(line);
49
+ const message = JSON.parse(line);
50
+ if (message.method === 'initialize') {
51
+ socket.write(`${JSON.stringify({ jsonrpc: '2.0', id: message.id, result: { protocolVersion: '2024-11-05', capabilities: {} } })}\n`);
52
+ } else if (message.method === 'tools/call') {
53
+ if (explore === 'silence') continue;
54
+ if (explore.error !== undefined) {
55
+ socket.write(`${JSON.stringify({ jsonrpc: '2.0', id: message.id, error: { code: -32000, message: explore.error } })}\n`);
56
+ } else if (explore.split !== undefined) {
57
+ const full = `${JSON.stringify({ jsonrpc: '2.0', id: message.id, result: { content: [{ type: 'text', text: explore.split }] } })}\n`;
58
+ socket.write(full.slice(0, 10));
59
+ setTimeout(() => socket.write(full.slice(10)), 30);
60
+ } else {
61
+ const result = explore.isError === true
62
+ ? { isError: true, content: [{ type: 'text', text: explore.text }] }
63
+ : { content: [{ type: 'text', text: explore.text }] };
64
+ socket.write(`${JSON.stringify({ jsonrpc: '2.0', id: message.id, result })}\n`);
65
+ }
66
+ }
67
+ }
68
+ });
69
+ });
70
+ openedServers.push(server);
71
+ return new Promise((resolve) => server.listen(usedPath, () => resolve({ path: usedPath, close: () => server.close() })));
72
+ }
73
+
74
+ /** A registry directory holding one record per entry, all claiming this process as their daemon. */
75
+ function registry(entries) {
76
+ const dir = scratch('odd-daemon-registry-');
77
+ entries.forEach((entry, index) => {
78
+ fs.writeFileSync(path.join(dir, `entry${index}.json`), JSON.stringify({
79
+ root: entry.root,
80
+ pid: process.pid,
81
+ version: '1.6.0',
82
+ socketPath: entry.socketPath,
83
+ startedAt: entry.startedAt ?? Date.now(),
84
+ }));
85
+ });
86
+ return dir;
87
+ }
88
+
89
+ function cleanup() {
90
+ for (const server of openedServers) {
91
+ try { server.close(); } catch { /* already closed */ }
92
+ }
93
+ openedServers.length = 0;
94
+ for (const dir of createdDirs) fs.rmSync(dir, { recursive: true, force: true });
95
+ createdDirs.length = 0;
96
+ }
97
+
98
+ module.exports = { HELLO, socketPath, scratch, fakeDaemon, registry, cleanup };
@@ -0,0 +1,39 @@
1
+ 'use strict';
2
+ // A tiny stdio MCP server standing in for `codegraph serve --mcp`; the mode is argv[2]. It never touches an
3
+ // index or the network, and modes other than `stuck` leave as soon as their stdin ends, like the real server.
4
+
5
+ const { createInterface } = require('node:readline');
6
+
7
+ const mode = process.argv[2] ?? 'ok';
8
+
9
+ function send(message) {
10
+ process.stdout.write(`${JSON.stringify(message)}\n`);
11
+ }
12
+
13
+ function exploreResult() {
14
+ // CodeGraph answers a crashed worker with `isError: true` and a text, not with a JSON-RPC error.
15
+ if (mode === 'isError') return { isError: true, content: [{ type: 'text', text: 'codegraph worker crashed; please retry the call.' }] };
16
+ if (mode === 'empty') return {};
17
+ return { content: [{ type: 'text', text: 'FAKE EXPLORE OUTPUT' }] };
18
+ }
19
+
20
+ // A stuck server answers the first call, ignores its stdin closing and leaves on its own twenty seconds later.
21
+ // A silent one answers nothing and leaves after 400 ms whichever happens first, so a short-timeout test never
22
+ // leaves a process behind. Every other mode goes away as soon as its stdin ends.
23
+ if (mode === 'stuck') setTimeout(() => process.exit(0), 20_000);
24
+ else if (mode === 'silent') {
25
+ setTimeout(() => process.exit(0), 400);
26
+ process.stdin.on('end', () => process.exit(0));
27
+ } else process.stdin.on('end', () => process.exit(0));
28
+
29
+ createInterface({ input: process.stdin }).on('line', (line) => {
30
+ const trimmed = line.trim();
31
+ if (trimmed.length === 0) return;
32
+ let message;
33
+ try { message = JSON.parse(trimmed); } catch { return; }
34
+ if (message.method === 'initialize') {
35
+ send({ jsonrpc: '2.0', id: message.id, result: { protocolVersion: '2024-11-05', capabilities: {} } });
36
+ } else if (message.method === 'tools/call' && mode !== 'stuck' && mode !== 'silent') {
37
+ send({ jsonrpc: '2.0', id: message.id, result: exploreResult() });
38
+ }
39
+ });
@@ -0,0 +1,12 @@
1
+ 'use strict';
2
+ // Runs one warm-up against the MCP server named in argv[2] and must then exit on its own; it never exits on
3
+ // purpose, so only a warm-up that releases the server's pipes ends this process.
4
+
5
+ const { exploreOnce } = require('../../lib/codegraph-warmup.js');
6
+
7
+ const command = process.argv[2] ?? '';
8
+ const project = process.argv[3] ?? process.cwd();
9
+
10
+ exploreOnce(project, 'main', 300, command, { project }).then((result) => {
11
+ process.stdout.write(`RESULT ${JSON.stringify(result)}\n`);
12
+ });
@@ -10,6 +10,9 @@ const { pathToFileURL } = require('node:url');
10
10
 
11
11
  const LIB_DIR = path.resolve(__dirname, '../../lib');
12
12
  const SRC = path.resolve(__dirname, '../../extensions/odd-worktree-tools.ts');
13
+ // The bridge's real slot, read here the way the extension and its own suites read
14
+ // it: the one published object, never an import.
15
+ const BRIDGE_SLOT = Symbol.for('gentle-shell-bridge/api/v1');
13
16
 
14
17
  const TYPE_STUB = [
15
18
  'const Type = {',
@@ -36,9 +39,125 @@ function stubbedSource() {
36
39
  return cached;
37
40
  }
38
41
 
42
+ // S18 (issues-startup-performance T14): this package loads NOTHING without
43
+ // gentle-shell-bridge, so a host double that publishes no bridge would see an
44
+ // empty extension and every suite here would be asserting nothing. The fake host
45
+ // therefore HAS the plugin: `defaultBridge()` is the published object with the
46
+ // schema and version the code validates and the members the surfaces this package
47
+ // contributes actually use — the rail's `registerSection`, the `Cards` rows'
48
+ // `registerRows`, the design's `registerToolDesign`, the picker's keymap action and
49
+ // palette row, and the store. Nothing here weakens `issuesSidebarBridge()`'s gate:
50
+ // the object is a real enough bridge, not a thin one.
51
+ //
52
+ // `loadExtension(pi, { bridge: false })` is the opt-out for a suite that must
53
+ // prove the absent case: it publishes nothing and touches no slot, so the test
54
+ // itself decides what is on it.
55
+ function defaultBridge() {
56
+ const sections = [];
57
+ const rows = [];
58
+ const designs = [];
59
+ const keymaps = [];
60
+ const commands = [];
61
+ const api = {
62
+ schema: 'gentle-shell-bridge/api',
63
+ version: 1,
64
+ registerSection: (section) => {
65
+ sections.push(section);
66
+ return () => {};
67
+ },
68
+ registerRows: (registration) => {
69
+ rows.push(registration);
70
+ return () => {};
71
+ },
72
+ registerToolDesign: (design) => {
73
+ designs.push(design);
74
+ return () => {};
75
+ },
76
+ // The picker's two optional members: present, but this bridge resolves no key,
77
+ // so no suite that did not ask for one gets a shortcut bound.
78
+ registerKeymap: (registration) => {
79
+ keymaps.push(registration);
80
+ return () => {};
81
+ },
82
+ registerCommands: (registration) => {
83
+ commands.push(registration);
84
+ return () => {};
85
+ },
86
+ resolveKeymap: () => ({ unavailable: 'the default test bridge publishes no key' }),
87
+ createStore: () => ({
88
+ get: () => undefined,
89
+ set: () => {},
90
+ delete: () => {},
91
+ }),
92
+ requestRepaint: () => {},
93
+ };
94
+ return { api, sections, rows, designs, keymaps, commands };
95
+ }
96
+
97
+ // Publish the default bridge on the real slot, unless a suite already published
98
+ // its own (a suite's fake always wins: it is the one that bridge's assertions
99
+ // measure). The published object is left in place afterwards, exactly like a real
100
+ // bridge's: it is the host's, not this load's.
101
+ function installDefaultBridge() {
102
+ if (globalThis[BRIDGE_SLOT] !== undefined && globalThis[BRIDGE_SLOT] !== null) return null;
103
+ const bridge = defaultBridge();
104
+ globalThis[BRIDGE_SLOT] = bridge.api;
105
+ return bridge;
106
+ }
107
+
108
+ // S13 (issues-startup-performance T11, corrected): the two issues surfaces are
109
+ // registered ONLY when the local presence probe finds `gh`, so a suite that asserts
110
+ // on a surface which exists must not depend on the machine it runs on. That probe
111
+ // is the real one — a directory walk over `process.env.PATH`, no child — and the
112
+ // extension compiles its own `lib/gh-issues.js` instance per load (it purges the
113
+ // lib require cache), so a `setGhWhich` seam set here could never reach it: PATH is
114
+ // the lever, exactly as it is in production.
115
+ //
116
+ // `ghPath(mode)` builds the directory that answers the probe — `present` writes an
117
+ // executable `gh` stub, `absent` writes nothing — and `withGhPath` puts it on PATH
118
+ // for the length of one call and restores the environment afterwards.
119
+ function ghPath(mode) {
120
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), `odd-gh-${mode}-`));
121
+ if (mode === 'present') {
122
+ const file = path.join(dir, process.platform === 'win32' ? 'gh.EXE' : 'gh');
123
+ fs.writeFileSync(file, '#!/bin/sh\nexit 0\n');
124
+ fs.chmodSync(file, 0o755);
125
+ }
126
+ return dir;
127
+ }
128
+
129
+ async function withGhPath(mode, run) {
130
+ const saved = process.env.PATH;
131
+ const dir = ghPath(mode === 'absent' ? 'absent' : 'present');
132
+ // `absent` means NOTHING on PATH: prepending an empty directory would still let
133
+ // the probe find the real `gh` further down, and this suite proves what a host
134
+ // without the CLI registers — which is nothing, so no lookup may succeed.
135
+ process.env.PATH = mode === 'absent' ? dir : `${dir}${path.delimiter}${saved === undefined ? '' : saved}`;
136
+ try {
137
+ return await run();
138
+ } finally {
139
+ if (saved === undefined) delete process.env.PATH;
140
+ else process.env.PATH = saved;
141
+ fs.rmSync(dir, { recursive: true, force: true });
142
+ }
143
+ }
144
+
39
145
  // Load the extension with the injected `pi` double. Returns the registered
40
146
  // commands and tools keyed by name, exactly as the host received them.
41
- async function loadExtension(pi) {
147
+ //
148
+ // S18 (T14): the bridge is published BEFORE the factory runs, because registration
149
+ // waits for it; with no bridge the extension is expected to register nothing at
150
+ // all, so a suite that wants that passes `{ bridge: false }`.
151
+ //
152
+ // S13 (T11): `gh` is present on PATH unless the suite passes `{ gh: false }`, for the
153
+ // same reason — the issues surfaces do not exist without it.
154
+ async function loadExtension(pi, options = {}) {
155
+ const opts = options && typeof options === 'object' ? options : {};
156
+ if (opts.bridge !== false) installDefaultBridge();
157
+ return withGhPath(opts.gh === false ? 'absent' : 'present', () => loadWithPath(pi));
158
+ }
159
+
160
+ async function loadWithPath(pi) {
42
161
  process.env.GENTLE_WORKTREE_LIB_DIR = LIB_DIR;
43
162
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'odd-worktree-ext-'));
44
163
  try {
@@ -48,19 +167,33 @@ async function loadExtension(pi) {
48
167
  const commands = new Map();
49
168
  const tools = new Map();
50
169
  const messageRenderers = new Map();
170
+ const entryRenderers = new Map();
171
+ const entries = [];
51
172
  const hooks = [];
52
173
  const host = {
53
174
  registerCommand: (name, handler) => { commands.set(name, handler); },
54
175
  registerTool: (tool) => { tools.set(tool.name, tool); },
55
176
  registerMessageRenderer: (type, renderer) => { messageRenderers.set(type, renderer); },
177
+ registerEntryRenderer: (type, renderer) => { entryRenderers.set(type, renderer); },
178
+ appendEntry: (customType, data) => { entries.push({ customType, data }); },
56
179
  on: (event, handler) => { hooks.push([event, handler]); },
57
180
  ...pi,
58
181
  };
59
182
  factory(host);
60
- return { commands, tools, messageRenderers, hooks, host };
183
+ return { commands, tools, messageRenderers, entryRenderers, entries, hooks, host };
61
184
  } finally {
62
185
  fs.rmSync(dir, { recursive: true, force: true });
63
186
  }
64
187
  }
65
188
 
66
- module.exports = { LIB_DIR, SRC, loadExtension, stubbedSource };
189
+ module.exports = {
190
+ LIB_DIR,
191
+ SRC,
192
+ BRIDGE_SLOT,
193
+ loadExtension,
194
+ stubbedSource,
195
+ defaultBridge,
196
+ installDefaultBridge,
197
+ ghPath,
198
+ withGhPath,
199
+ };
@@ -104,34 +104,58 @@ test('malformed assignee changes are rejected before any read or write', async (
104
104
  });
105
105
 
106
106
  test('permission and relation metadata is explicit and omits absent project/PR data', async () => {
107
- runner(() => ok({ data: { repository: { viewerPermission: 'TRIAGE', issue: { assignees: { nodes: [{ login: 'alice' }, { login: 'bob' }] }, projectItems: { nodes: [{ project: { title: 'Roadmap', url: 'https://example.invalid/project' } }] }, closedByPullRequestsReferences: { totalCount: 2 } } } } }));
107
+ runner(() => ok({ data: { repository: { viewerPermission: 'TRIAGE', issue: { assignees: { nodes: [{ login: 'alice' }, { login: 'bob' }] }, projectItems: { nodes: [{ project: { title: 'Roadmap', url: 'https://example.invalid/project' } }] }, closedByPullRequestsReferences: { nodes: [{ number: 77 }, { number: 69 }], pageInfo: { hasNextPage: false } } } } } }));
108
108
  const result = await gh.getIssueMetadata(3);
109
109
  assert.equal(result.ok, true);
110
110
  assert.deepEqual(result.permissions, { canEditLabels: true, canEditAssignees: true, canCreateLabels: false, canCloseIssues: true });
111
111
  assert.deepEqual(result.assignees, ['alice', 'bob']);
112
112
  assert.equal(result.projects[0].title, 'Roadmap');
113
- assert.equal(result.linkedPullRequestCount, 2);
114
- runner(() => ok({ data: { repository: { viewerPermission: 'READ', issue: { assignees: { nodes: [] }, projectItems: { nodes: [] }, closedByPullRequestsReferences: { totalCount: 0 } } } } }));
113
+ assert.deepEqual(result.linkedPullRequests, [69, 77], 'every linked PR is carried by number, ascending');
114
+ assert.equal('linkedPullRequestCount' in result, false, 'no count replaces the list');
115
+ assert.equal('metadataError' in result, false, 'a complete read reports nothing unavailable');
116
+ runner(() => ok({ data: { repository: { viewerPermission: 'READ', issue: { assignees: { nodes: [] }, projectItems: { nodes: [] }, closedByPullRequestsReferences: { nodes: [], pageInfo: { hasNextPage: false } } } } } }));
115
117
  const empty = await gh.getIssueMetadata(3);
116
118
  assert.equal(empty.permissions.canEditLabels, false);
117
119
  assert.equal(empty.permissions.canCloseIssues, false);
118
120
  assert.equal('projects' in empty, false);
119
- assert.equal('linkedPullRequestCount' in empty, false);
121
+ assert.equal('linkedPullRequests' in empty, false);
120
122
  });
121
123
 
122
124
  test('project scope failures preserve confirmed triage rights, assignees and linked PRs', async () => {
123
125
  runner((argv) => {
124
126
  if (field(argv, 'query').includes('projectItems')) return ok({ errors: [{ message: 'read:project scope required' }] });
125
- return ok({ data: { repository: { viewerPermission: 'WRITE', issue: { assignees: { nodes: [{ login: 'alice' }] }, closedByPullRequestsReferences: { totalCount: 2 } } } } });
127
+ return ok({ data: { repository: { viewerPermission: 'WRITE', issue: { assignees: { nodes: [{ login: 'alice' }] }, closedByPullRequestsReferences: { nodes: [{ number: 77 }], pageInfo: { hasNextPage: false } } } } } });
126
128
  });
127
129
  const result = await gh.getIssueMetadata(3);
128
130
  assert.equal(result.ok, true);
129
131
  assert.equal(result.permissions.canEditAssignees, true);
130
132
  assert.equal(result.permissions.canCreateLabels, true);
131
133
  assert.deepEqual(result.assignees, ['alice']);
132
- assert.equal(result.linkedPullRequestCount, 2);
134
+ assert.deepEqual(result.linkedPullRequests, [77]);
133
135
  assert.equal('projects' in result, false);
134
- assert.match(result.metadataError, /read:project/);
136
+ assert.deepEqual(result.unavailable, ['projects'], 'only the lost relation is named');
137
+ assert.equal('metadataError' in result, false, 'a lost optional relation is not a failed read');
138
+ });
139
+
140
+ test('an unreadable linked-PR page is named instead of being counted', async () => {
141
+ runner((argv) => {
142
+ if (field(argv, 'query').includes('projectItems')) return ok({ data: { repository: { issue: { projectItems: { nodes: [], pageInfo: { hasNextPage: false } } } } } });
143
+ return ok({ data: { repository: { viewerPermission: 'READ', issue: { assignees: { nodes: [] }, closedByPullRequestsReferences: { nodes: [{ number: 0 }, { number: 'x' }], pageInfo: { hasNextPage: false } } } } } });
144
+ });
145
+ const result = await gh.getIssueMetadata(3);
146
+ assert.equal(result.ok, true);
147
+ assert.equal('linkedPullRequests' in result, false, 'an unusable page carries no list');
148
+ assert.deepEqual(result.unavailable, ['linked PRs'], 'and the loss is named');
149
+ });
150
+
151
+ test('a capped linked-PR page is marked truncated, never passed off as the whole list', async () => {
152
+ runner((argv) => {
153
+ if (field(argv, 'query').includes('projectItems')) return ok({ data: { repository: { issue: { projectItems: { nodes: [], pageInfo: { hasNextPage: false } } } } } });
154
+ return ok({ data: { repository: { viewerPermission: 'READ', issue: { assignees: { nodes: [] }, closedByPullRequestsReferences: { nodes: [{ number: 69 }], pageInfo: { hasNextPage: true } } } } } });
155
+ });
156
+ const result = await gh.getIssueMetadata(3);
157
+ assert.deepEqual(result.linkedPullRequests, [69]);
158
+ assert.equal(result.linkedPullRequestsTruncated, true);
135
159
  });
136
160
 
137
161
  test('assignee mutation failures are not converted to success', async () => {