pi-odd-worktree 2.1.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/README.md +54 -319
  2. package/extensions/odd-worktree-tools.ts +4145 -2529
  3. package/lib/bash-activity.js +1164 -0
  4. package/lib/bash-design.js +684 -0
  5. package/lib/bash-destructive.js +559 -0
  6. package/lib/bash-frame.js +205 -0
  7. package/lib/card-content.js +23 -0
  8. package/lib/card-style.js +175 -0
  9. package/lib/checkout-facts.js +30 -70
  10. package/lib/codegraph-card-preview.js +628 -0
  11. package/lib/codegraph-card.js +515 -0
  12. package/lib/codegraph-compaction.js +76 -0
  13. package/lib/codegraph-daemon.js +246 -0
  14. package/lib/codegraph-edit-sync.js +182 -0
  15. package/lib/codegraph-guard-target.js +337 -0
  16. package/lib/codegraph-guard.js +211 -0
  17. package/lib/codegraph-index.js +1020 -0
  18. package/lib/codegraph-lock.js +607 -0
  19. package/lib/codegraph-mcp-config.js +134 -0
  20. package/lib/codegraph-mcp.js +123 -0
  21. package/lib/codegraph-paths.js +69 -0
  22. package/lib/codegraph-prompt/explore.md +11 -0
  23. package/lib/codegraph-prompt/fix.md +6 -0
  24. package/lib/codegraph-prompt/generic.md +8 -0
  25. package/lib/codegraph-prompt/judge.md +9 -0
  26. package/lib/codegraph-prompt/orchestrator.md +17 -0
  27. package/lib/codegraph-prompt/verify.md +10 -0
  28. package/lib/codegraph-prompt/worker.md +7 -0
  29. package/lib/codegraph-role.js +55 -0
  30. package/lib/codegraph-rules.js +146 -0
  31. package/lib/codegraph-session.js +303 -383
  32. package/lib/codegraph-warmup.js +139 -0
  33. package/lib/file-card-markdown.js +141 -0
  34. package/lib/file-card-resolver.js +245 -0
  35. package/lib/file-card.js +659 -0
  36. package/lib/files-index.js +387 -0
  37. package/lib/files-insert.js +81 -0
  38. package/lib/files-orders.js +326 -0
  39. package/lib/files-picker-view.js +1416 -0
  40. package/lib/files-preview.js +338 -0
  41. package/lib/files-scope-detail.js +171 -0
  42. package/lib/files-scope-view.js +507 -0
  43. package/lib/gh-issues.js +308 -14
  44. package/lib/issue-preview.js +26 -7
  45. package/lib/issues-bash-mutation.js +206 -0
  46. package/lib/issues-cache-store.js +261 -0
  47. package/lib/issues-section.js +710 -0
  48. package/lib/issues-view.js +649 -52
  49. package/lib/odd-prompt/odd-worktrees.md +21 -0
  50. package/lib/odd-worktrees-prompt.js +10 -28
  51. package/lib/related-issues-cache.js +210 -0
  52. package/lib/shell-card.js +825 -0
  53. package/lib/skill-odd-card.js +183 -0
  54. package/lib/tui-paint.js +4 -5
  55. package/lib/warp-create-panel.js +538 -250
  56. package/lib/warp-create-picker.js +56 -9
  57. package/lib/warp-delete-confirm.js +19 -28
  58. package/lib/warp-selector-view.js +160 -82
  59. package/lib/which-command.js +90 -0
  60. package/lib/worktree-card.js +267 -897
  61. package/lib/worktree-cards.js +383 -0
  62. package/lib/worktree-create.js +287 -0
  63. package/lib/worktree-git.js +3 -3
  64. package/lib/worktree-guard.js +548 -0
  65. package/lib/worktree-hooks.js +421 -712
  66. package/lib/worktree-list.js +120 -0
  67. package/lib/worktree-registry.js +162 -879
  68. package/lib/{worktree-close-herdr.js → worktree-remove.js} +9 -11
  69. package/lib/worktree-setup-runner.js +376 -0
  70. package/lib/worktree-setup.js +140 -0
  71. package/lib/worktree-warp-busy.js +462 -85
  72. package/lib/worktree-warp-sessions.js +1 -2
  73. package/package.json +2 -2
  74. package/tools/bash-activity.test.js +1419 -0
  75. package/tools/bash-design.test.js +1091 -0
  76. package/tools/bash-destructive.test.js +139 -0
  77. package/tools/card-content.test.js +44 -0
  78. package/tools/card-style.test.js +298 -0
  79. package/tools/codegraph-card-preview.test.js +254 -0
  80. package/tools/codegraph-card.test.js +1080 -0
  81. package/tools/codegraph-compaction.test.js +378 -0
  82. package/tools/codegraph-daemon.test.js +248 -0
  83. package/tools/codegraph-edit-sync.test.js +295 -0
  84. package/tools/codegraph-guard-target.test.js +174 -0
  85. package/tools/codegraph-guard.test.js +238 -0
  86. package/tools/codegraph-index.test.js +1948 -0
  87. package/tools/codegraph-lock.test.js +932 -0
  88. package/tools/codegraph-mcp-config.test.js +181 -0
  89. package/tools/codegraph-mcp.test.js +194 -0
  90. package/tools/codegraph-paths.test.js +44 -0
  91. package/tools/codegraph-role.test.js +30 -0
  92. package/tools/codegraph-rules.test.js +250 -0
  93. package/tools/codegraph-session.test.js +660 -391
  94. package/tools/codegraph-warmup.test.js +316 -0
  95. package/tools/commands.test.js +510 -31
  96. package/tools/file-card-markdown.test.js +188 -0
  97. package/tools/file-card.test.js +1289 -0
  98. package/tools/files-bridge.test.js +575 -0
  99. package/tools/files-command.test.js +610 -0
  100. package/tools/files-index.test.js +473 -0
  101. package/tools/files-insert.test.js +139 -0
  102. package/tools/files-orders.test.js +597 -0
  103. package/tools/files-picker-view.test.js +1871 -0
  104. package/tools/files-preview.test.js +452 -0
  105. package/tools/files-scope-detail.test.js +264 -0
  106. package/tools/files-scope-view.test.js +614 -0
  107. package/tools/fixtures/card-codegraph-outputs.js +110 -0
  108. package/tools/fixtures/codegraph-cli-stub.js +16 -0
  109. package/tools/fixtures/codegraph-init-process.js +28 -0
  110. package/tools/fixtures/codegraph-lock-worker.js +117 -0
  111. package/tools/fixtures/daemon-fake.js +98 -0
  112. package/tools/fixtures/daemon-mcp-server.js +39 -0
  113. package/tools/fixtures/daemon-warmup-worker.js +12 -0
  114. package/tools/fixtures/load-extension.js +136 -3
  115. package/tools/gh-issues-feedback.test.js +31 -7
  116. package/tools/gh-issues.test.js +391 -1
  117. package/tools/issue-preview.test.js +44 -7
  118. package/tools/issues-bash-mutation.test.js +101 -0
  119. package/tools/issues-cache-store.test.js +222 -0
  120. package/tools/issues-command.test.js +1512 -66
  121. package/tools/issues-open-guard.test.js +1096 -0
  122. package/tools/issues-section.test.js +4195 -0
  123. package/tools/issues-seed-query-regression.test.js +67 -0
  124. package/tools/issues-view.test.js +1489 -60
  125. package/tools/odd-worktrees-prompt.test.js +98 -65
  126. package/tools/package-surface.test.js +431 -36
  127. package/tools/related-issues-cache.test.js +324 -0
  128. package/tools/shell-card.test.js +834 -0
  129. package/tools/skill-odd-card.test.js +200 -0
  130. package/tools/t5-session-identity.test.js +44 -22
  131. package/tools/warp-busy-guard.test.js +2565 -309
  132. package/tools/warp-create-panel.test.js +499 -74
  133. package/tools/warp-create-picker.test.js +101 -5
  134. package/tools/warp-delete-confirm.test.js +49 -15
  135. package/tools/warp-empty-session.test.js +0 -1
  136. package/tools/warp-fallback-regression.test.js +533 -0
  137. package/tools/warp-selector-view.test.js +460 -196
  138. package/tools/which-command.test.js +126 -0
  139. package/tools/worktree-card.test.js +551 -0
  140. package/tools/worktree-cards.test.js +845 -0
  141. package/tools/worktree-changes.test.js +4 -5
  142. package/tools/worktree-create.test.js +489 -0
  143. package/tools/worktree-guard.test.js +823 -0
  144. package/tools/worktree-hooks.test.js +905 -0
  145. package/tools/worktree-list.test.js +170 -0
  146. package/tools/worktree-registry.test.js +89 -230
  147. package/tools/worktree-remove-async.test.js +318 -0
  148. package/tools/worktree-setup-runner.test.js +276 -0
  149. package/tools/worktree-setup.test.js +140 -0
  150. package/tools/worktree-tools.test.js +419 -199
  151. package/lib/codegraph-commands.js +0 -165
  152. package/lib/odd-prompt/odd-worktrees.with-codegraph.md +0 -19
  153. package/lib/odd-prompt/odd-worktrees.without-codegraph.md +0 -15
  154. package/lib/worktree-model-result.js +0 -291
  155. package/tools/codegraph-commands.test.js +0 -371
  156. package/tools/herdr-free-create.test.js +0 -161
  157. package/tools/worktree-close-herdr-async.test.js +0 -204
  158. package/tools/worktree-odd-migration.test.js +0 -224
  159. package/tools/worktree-registry-cache.test.js +0 -163
  160. package/tools/worktree-registry-odd.test.js +0 -231
@@ -1,438 +1,358 @@
1
1
  'use strict';
2
- // Session-scoped CodeGraph freshness for the worktree tools (S1-S6/S8/S9).
2
+ // The one place that wires CodeGraph into a session. The extension calls `registerCodegraph(pi)` once and everything else
3
+ // lives here, so the extension itself stays a single line:
3
4
  //
4
- // Two questions, one gate. `hasCodegraph` answers "is the CLI present" once per
5
- // process and caches it (S3), with `CODEGRAPH_FORCE=1` as the only escape (S4).
6
- // `resolveProjectRoot` answers "which checkout does this file belong to" from
7
- // `git -C <dir> rev-parse --show-toplevel`, cached per directory (S1).
5
+ // - session start (a primary session): ensure the global MCP entry once per process, then create-or-sync the session's index
6
+ // and warm its daemon, in the background and never awaited by the host;
7
+ // - compaction: one background sync of an existing index, never an init;
8
+ // - a successful native `codegraph init`: one coordinated sync, and its honest outcome appended to the tool's own result;
9
+ // - a successful `edit` or `write`: a debounced sync of the edited file's checkout;
10
+ // - before a CodeGraph search: a bounded join of the index work this process already has in flight for that checkout
11
+ // (never a new one, and nothing at all when nothing is in flight);
12
+ // - a search or read call into another checkout, or into the session's own one: one reminder appended to
13
+ // that call's result (never a block, never a separate message), forgotten on a compaction and a new session;
14
+ // - the CodeGraph tool card, through the host's renderer hook;
15
+ // - shutdown: every pending window is cleared.
8
16
  //
9
- // `scheduleSync` is the fire-and-forget entry the extension calls from
10
- // `tool_result`. It never throws and never blocks: the decision object is the
11
- // only synchronous return, and the sync itself is detached, unref'd and never
12
- // awaited (S1). Per resolved root there is ONE debounce timer and one
13
- // `{running, pending}` pair, so a burst of edits collapses and an edit during a
14
- // run starts exactly ONE more afterwards (S2). Across processes an exclusive
15
- // `<root>/.codegraph/pi-sync.lock` guards the run: a held foreign lock is
16
- // skipped (never queued) with one bounded deferred retry, and a lock whose pid
17
- // is dead or whose age passes the TTL is taken over (S2/S8). A root without
18
- // `.codegraph/` is skipped (S6) and a root whose CodeGraph daemon is alive is
19
- // skipped too, because that daemon's watcher already syncs the tree (S5). The
20
- // process-wide switch `/codegraph-hook` flips is `setHookEnabled` below: off
21
- // answers `hook-off` before any probe, read or lock, so nothing is spawned (S9).
22
- //
23
- // Every external effect is injectable through `deps` — `execFile`, `spawn`,
24
- // `exists`, `readFile`, `now`, `setTimeout`/`clearTimeout`, `isAlive`,
25
- // `binaryExists` — so tests never start a real child process or touch the
26
- // network.
27
-
28
- const fs = require('node:fs');
29
- const path = require('node:path');
30
- const { spawn, execFileSync } = require('node:child_process');
31
-
32
- const DEBOUNCE_MS = 2000;
33
- const RETRY_DELAY_MS = 5000;
34
- const LOCK_TTL_MS = 5 * 60 * 1000;
35
- const RUN_TIMEOUT_MS = 2 * 60 * 1000;
36
- const GIT_TIMEOUT_MS = 10000;
37
- const LOCK_FILE = 'pi-sync.lock';
38
- const DAEMON_PID_FILE = 'daemon.pid';
39
- const CODEGRAPH_BIN = 'codegraph';
40
-
41
- // One answer per process (S3): never re-probe, never re-read PATH.
42
- let gateAnswer = null;
43
- // The process-wide sync switch (S9). `null` follows the environment: enabled
44
- // unless `CODEGRAPH_HOOK=0`, which is the persistent way to start it disabled.
45
- let hookEnabled = null;
46
- // One cache per directory (S1), including the null answers.
47
- const rootCache = new Map();
48
- // One scheduler state per resolved root (S2).
49
- const syncStates = new Map();
50
- let idleWaiters = [];
51
-
52
- // --- injectable defaults -------------------------------------------------
53
-
54
- function defaultBinaryExists(file) {
55
- try {
56
- fs.accessSync(file, fs.constants.X_OK);
57
- return true;
58
- } catch {
59
- return false;
60
- }
61
- }
62
-
63
- function defaultExecFile(bin, args, opts = {}) {
64
- return execFileSync(bin, args, {
65
- encoding: 'utf8',
66
- timeout: opts.timeoutMs,
67
- windowsHide: true,
68
- });
17
+ // All of it applies only when the `codegraph` CLI is installed (probed once per process): without it nothing is registered.
18
+ // No handler throws into the host, and every collaborator is injectable.
19
+
20
+ const nodeOs = require('node:os');
21
+ const nodePath = require('node:path');
22
+
23
+ const index = require('./codegraph-index.js');
24
+ const { createCodegraphCardResolver } = require('./codegraph-card.js');
25
+ const { compactionSync } = require('./codegraph-compaction.js');
26
+ const { createEditSync } = require('./codegraph-edit-sync.js');
27
+ const { createCodegraphGuard } = require('./codegraph-guard.js');
28
+ const { liveDaemon } = require('./codegraph-daemon.js');
29
+ const { ensureCodegraphServer } = require('./codegraph-mcp-config.js');
30
+ const { sessionIndexRole } = require('./codegraph-role.js');
31
+ const { warmUpDaemon } = require('./codegraph-warmup.js');
32
+
33
+ const MCP_FILE = 'mcp.json';
34
+
35
+ // S2: how long a search may wait for the index write already in flight before it runs against the index as it is.
36
+ const JOIN_BUDGET_MS = 5000;
37
+ const JOIN_BUDGET_ENV = 'ODD_WORKTREE_CODEGRAPH_JOIN_MS';
38
+ const MCP_CODEGRAPH_PREFIX = 'mcp__codegraph__';
39
+ const SEARCH_OPERATIONS = new Set(['query', 'explore']);
40
+
41
+ /** The agent directory the host reads its MCP configuration from: its own override, else `~/.pi/agent`. */
42
+ function agentDirOf(env) {
43
+ const named = env && env.PI_CODING_AGENT_DIR;
44
+ return typeof named === 'string' && named.length > 0 ? named : nodePath.join(nodeOs.homedir(), '.pi', 'agent');
69
45
  }
70
46
 
71
- function defaultSpawn(bin, args, opts) {
72
- return spawn(bin, args, opts);
73
- }
74
-
75
- function defaultReadFile(file) {
76
- return fs.readFileSync(file, 'utf8');
77
- }
78
-
79
- function defaultIsAlive(pid) {
80
- if (!Number.isInteger(pid) || pid <= 0) return false;
81
- try {
82
- process.kill(pid, 0);
83
- return true;
84
- } catch (err) {
85
- // A pid owned by someone else is alive but not signalable.
86
- return Boolean(err && err.code === 'EPERM');
87
- }
88
- }
89
-
90
- function timers(deps) {
91
- return {
92
- setTimeout: typeof deps.setTimeout === 'function' ? deps.setTimeout : setTimeout,
93
- clearTimeout: typeof deps.clearTimeout === 'function' ? deps.clearTimeout : clearTimeout,
47
+ function notifier(ctx) {
48
+ return (notice) => {
49
+ try {
50
+ if (notice && ctx && ctx.ui && typeof ctx.ui.notify === 'function') ctx.ui.notify(notice.text, notice.level);
51
+ } catch {
52
+ // Telling the user is never worth failing the session.
53
+ }
94
54
  };
95
55
  }
96
56
 
97
- function pick(deps, name, fallback) {
98
- return typeof deps[name] === 'function' ? deps[name] : fallback;
99
- }
100
-
101
- // --- session gate (S3/S4) ------------------------------------------------
102
-
103
- function probeOnPath(bin, env, deps) {
104
- const exists = pick(deps, 'binaryExists', defaultBinaryExists);
105
- const rawPath = (env && (env.PATH || env.Path)) || '';
106
- for (const dir of String(rawPath).split(path.delimiter)) {
107
- if (dir.length === 0) continue;
108
- if (exists(path.join(dir, bin))) return true;
57
+ /** What the user is told about the MCP entry; an unchanged entry says nothing. */
58
+ function mcpNotice(result) {
59
+ if (!result) return undefined;
60
+ if (result.status === 'added' || result.status === 'fixed') {
61
+ return {
62
+ text: `CodeGraph MCP entry ${result.status === 'added' ? 'added to' : 'fixed in'} ${MCP_FILE}: reload Pi for the MCP tool to appear`,
63
+ level: 'info',
64
+ };
65
+ }
66
+ if (result.status === 'invalid' || result.status === 'unreadable' || result.status === 'failed') {
67
+ return { text: `could not check the CodeGraph entry of ${MCP_FILE} (${result.status}); the file was left untouched`, level: 'warning' };
109
68
  }
110
- return false;
69
+ return undefined;
111
70
  }
112
71
 
113
- // The session gate. `CODEGRAPH_FORCE=1` answers present without probing, so a
114
- // CLI installed mid-session does not need a restart; every other answer is
115
- // probed once and then frozen for the life of the process.
116
- function hasCodegraph(env, deps = {}) {
117
- const effectiveEnv = env || process.env;
118
- if (effectiveEnv.CODEGRAPH_FORCE === '1') return true;
119
- if (gateAnswer === null) gateAnswer = probeOnPath(CODEGRAPH_BIN, effectiveEnv, deps || {});
120
- return gateAnswer;
72
+ function sessionCwd(event, ctx) {
73
+ if (ctx && typeof ctx.cwd === 'string' && ctx.cwd.length > 0) return ctx.cwd;
74
+ if (event && typeof event.cwd === 'string' && event.cwd.length > 0) return event.cwd;
75
+ return process.cwd();
121
76
  }
122
77
 
123
- function resetCodegraphGate() {
124
- gateAnswer = null;
78
+ /**
79
+ * S2: whether this tool call is a CodeGraph search — the native tool's `query`/`explore`, or any tool the CodeGraph
80
+ * MCP server exposes. Read from the event alone: the decision is made before the tool runs, from what it will do.
81
+ */
82
+ function isCodegraphSearch(event) {
83
+ const name = event && typeof event.toolName === 'string' ? event.toolName : '';
84
+ if (name.length === 0) return false;
85
+ if (name.startsWith(MCP_CODEGRAPH_PREFIX)) return true;
86
+ if (name !== index.NATIVE_CODEGRAPH_TOOL) return false;
87
+ const input = event.input && typeof event.input === 'object' && event.input !== null ? event.input : {};
88
+ return SEARCH_OPERATIONS.has(input.operation);
125
89
  }
126
90
 
127
- // --- sync hook switch (S9) ----------------------------------------------
128
-
129
- // The switch is process-wide and in memory only: nothing is written to user
130
- // configuration. `on`/`off` from the command set it explicitly; no argument
131
- // toggles whatever it currently reads.
132
- function isHookEnabled(env) {
133
- if (hookEnabled !== null) return hookEnabled;
134
- return (env || process.env).CODEGRAPH_HOOK !== '0';
91
+ /** The join budget in ms: five seconds by default, a positive override from the environment, and 0 to never join. */
92
+ function joinBudgetMs(env) {
93
+ const raw = env && env[JOIN_BUDGET_ENV];
94
+ if (raw === undefined || raw === null || String(raw).trim().length === 0) return JOIN_BUDGET_MS;
95
+ const parsed = Number(String(raw).trim());
96
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : JOIN_BUDGET_MS;
135
97
  }
136
98
 
137
- function setHookEnabled(enabled) {
138
- hookEnabled = enabled !== false;
99
+ /**
100
+ * The first text part of a result keeps the tool's own words; the hook's line is a part of its own after them.
101
+ * Everything else the result carried — its structured content above all — rides along unchanged, so the result is
102
+ * kept whole.
103
+ */
104
+ function withNotice(event, text) {
105
+ const content = Array.isArray(event.content) ? event.content : [];
106
+ const patch = { content: [...content, { type: 'text', text }] };
107
+ if (event && event.structuredContent !== undefined) patch.structuredContent = event.structuredContent;
108
+ return patch;
139
109
  }
140
110
 
141
- // --- project root (S1) --------------------------------------------------
111
+ function registerCodegraph(pi, deps = {}) {
112
+ const env = deps.env || process.env;
113
+ const impl = {
114
+ ensureCodegraphServer,
115
+ prepareProject: index.prepareProject,
116
+ compactionSync,
117
+ syncAfterNativeInit: index.syncAfterNativeInit,
118
+ createEditSync,
119
+ createCodegraphGuard,
120
+ warmUpDaemon,
121
+ createCodegraphCardResolver,
122
+ ...(deps.impl || {}),
123
+ };
124
+ if (typeof pi?.on !== 'function') return { registered: false };
125
+ if (!index.cliAvailable({ hasBinary: deps.hasBinary })) return { registered: false };
126
+
127
+ const child = env.GENTLE_PI_AGENTS_CHILD === '1';
128
+ const role = sessionIndexRole(env);
129
+ const registryDir = deps.registryDir;
130
+ // S6: the card's cwd seam reads the session this wiring belongs to; unknown until
131
+ // the host names it at session_start, and then the segment is shown, not guessed.
132
+ let sessionDir;
133
+ let mcpChecked = false;
134
+ // S2: the index writes this process already asked for, per checkout. Registering one here is what lets a
135
+ // search join it; nothing in this map starts work of its own.
136
+ const indexWork = new Map(); // checkout root -> Set of promises this process started
137
+ const delay = typeof deps.delay === 'function' ? deps.delay : (ms) => new Promise((resolve) => {
138
+ const timer = setTimeout(resolve, ms);
139
+ if (timer && typeof timer.unref === 'function') timer.unref();
140
+ });
142
141
 
143
- function resolveProjectRoot(dir, deps = {}) {
144
- if (typeof dir !== 'string' || dir.length === 0) return null;
145
- const key = path.resolve(dir);
146
- if (rootCache.has(key)) return rootCache.get(key);
147
- const execFile = pick(deps, 'execFile', defaultExecFile);
148
- let root = null;
142
+ // The CodeGraph card goes through the host's renderer hook, looked up when it is used: an older host without it draws
143
+ // nothing of ours and loses nothing. No tool, command or execution is registered by it.
149
144
  try {
150
- const out = execFile('git', ['-C', key, 'rev-parse', '--show-toplevel'], { timeoutMs: GIT_TIMEOUT_MS });
151
- const text = typeof out === 'string' ? out : out && typeof out.stdout === 'string' ? out.stdout : '';
152
- const trimmed = text.trim();
153
- if (trimmed.length > 0) root = trimmed;
145
+ impl.createCodegraphCardResolver({
146
+ metrics: deps.metrics || (() => null),
147
+ cwd: () => sessionDir,
148
+ registerToolRenderer: (resolver) => (typeof pi.registerToolRenderer === 'function' ? pi.registerToolRenderer(resolver) : undefined),
149
+ });
154
150
  } catch {
155
- root = null;
151
+ // The card is cosmetic.
156
152
  }
157
- rootCache.set(key, root);
158
- return root;
159
- }
160
153
 
161
- // --- lock (S2/S8) -------------------------------------------------------
154
+ // The two reminders own their own state: a compaction, a `/warp` and a new session are its facts to keep.
155
+ const guards = impl.createCodegraphGuard({ env, argv: deps.argv, toplevel: deps.toplevel, isDirectory: deps.isDirectory });
162
156
 
163
- function writeLock(lockPath, pid, now) {
164
- let fd;
165
- try {
166
- fd = fs.openSync(lockPath, 'wx');
167
- } catch (err) {
168
- if (err && err.code === 'EEXIST') return false;
169
- throw err;
170
- }
171
- try {
172
- fs.writeSync(fd, JSON.stringify({ pid, startedAt: now }));
173
- } finally {
174
- fs.closeSync(fd);
175
- }
176
- return true;
177
- }
178
-
179
- // `{ok:true}` when this process owns the lock; `{ok:false}` when a live foreign
180
- // lock holds it. A lock whose content is unreadable, whose pid is dead or whose
181
- // age passes the TTL is stale and is taken over. Two processes racing on the
182
- // takeover cannot both win: the second `wx` create loses.
183
- function acquireLock(lockPath, deps) {
184
- const now = typeof deps.now === 'function' ? deps.now() : Date.now();
185
- const pid = Number.isInteger(deps.pid) ? deps.pid : process.pid;
186
- const ttl = typeof deps.lockTtlMs === 'number' ? deps.lockTtlMs : LOCK_TTL_MS;
187
- const readFile = pick(deps, 'readFile', defaultReadFile);
188
- const isAlive = pick(deps, 'isAlive', defaultIsAlive);
189
-
190
- if (writeLock(lockPath, pid, now)) return { ok: true };
191
-
192
- let held = null;
193
- try {
194
- held = JSON.parse(readFile(lockPath));
195
- } catch {
196
- held = null;
197
- }
198
- const heldPid = held && Number.parseInt(held.pid, 10);
199
- const heldAt = held && Number(held.startedAt);
200
- const stale = !held
201
- || !Number.isInteger(heldPid) || heldPid <= 0
202
- || !Number.isFinite(heldAt) || (now - heldAt) > ttl
203
- || !isAlive(heldPid);
204
- if (!stale) return { ok: false };
157
+ const editSync = impl.createEditSync({
158
+ role,
159
+ available: () => true,
160
+ daemonLive: (root) => liveDaemon(root, { registryDir }) !== undefined,
161
+ sync: (root) => index.requestCoordinatedSync({ project: root, run: deps.run }),
162
+ });
205
163
 
206
- try {
207
- fs.unlinkSync(lockPath);
208
- } catch {
209
- // Another process already took the stale lock over; the create below
210
- // decides who wins.
164
+ /**
165
+ * Runs index work this process asks for and keeps it visible under its checkout, so a search can join it.
166
+ * The caller gets the very same promise, rejection and all; the copy kept here is always settled-and-forgotten,
167
+ * so it can never be an unhandled rejection or a leak.
168
+ */
169
+ function trackIndexWork(root, start) {
170
+ const work = Promise.resolve().then(start);
171
+ let pending = indexWork.get(root);
172
+ if (pending === undefined) {
173
+ pending = new Set();
174
+ indexWork.set(root, pending);
175
+ }
176
+ pending.add(work);
177
+ const forget = () => {
178
+ const live = indexWork.get(root);
179
+ if (live === undefined) return;
180
+ live.delete(work);
181
+ if (live.size === 0) indexWork.delete(root);
182
+ };
183
+ work.then(forget, forget);
184
+ return work;
211
185
  }
212
- return writeLock(lockPath, pid, now) ? { ok: true } : { ok: false };
213
- }
214
186
 
215
- function releaseLock(lockPath) {
216
- try {
217
- fs.unlinkSync(lockPath);
218
- } catch {
219
- // Already gone (a takeover) or never created: nothing to release.
187
+ /**
188
+ * S2: what a search may join, or `undefined` when there is nothing — which is the synchronous answer that keeps
189
+ * an idle checkout at zero latency. Only work already asked for is joined: our own preparations and post-init
190
+ * syncs, and the edit sync's running window. Nothing here starts one.
191
+ */
192
+ function joinInFlightWork(root, budgetMs) {
193
+ const waiting = [];
194
+ const pending = indexWork.get(root);
195
+ if (pending !== undefined) {
196
+ for (const work of pending) waiting.push(Promise.resolve(work).then(() => undefined, () => undefined));
197
+ }
198
+ try {
199
+ if (editSync && typeof editSync.inFlight === 'function' && editSync.inFlight(root) === true) {
200
+ const idle = typeof editSync.whenIdle === 'function' ? editSync.whenIdle(root, budgetMs) : undefined;
201
+ if (idle !== undefined && idle !== null) waiting.push(Promise.resolve(idle).then(() => undefined, () => undefined));
202
+ }
203
+ } catch {
204
+ // A window that cannot report itself is simply not joined.
205
+ }
206
+ if (waiting.length === 0) return undefined;
207
+ return Promise.all(waiting).then(() => undefined, () => undefined);
220
208
  }
221
- }
222
-
223
- // --- one background run -------------------------------------------------
224
209
 
225
- // Resolves when the child is launched AND finished (its `close`/`error`), so the
226
- // in-process `running` flag covers the whole sync while the caller never waits
227
- // for it. The lock is held for the same span: a parallel Pi session skips
228
- // instead of racing another sync on the same checkout.
229
- function runSync(root, deps) {
230
- const lockPath = path.join(root, '.codegraph', LOCK_FILE);
231
- let lock;
232
- try {
233
- lock = acquireLock(lockPath, deps);
234
- } catch {
235
- return Promise.resolve('lock-error');
236
- }
237
- if (!lock.ok) return Promise.resolve('locked');
210
+ const joinIndexWork = typeof deps.joinIndexWork === 'function' ? deps.joinIndexWork : joinInFlightWork;
238
211
 
239
- return new Promise((resolve) => {
240
- let child;
212
+ /** The wait a search gets: bounded by the budget and never rejecting, whatever the joined work or the seam does. */
213
+ function boundedWait(work, budgetMs) {
214
+ const settled = Promise.resolve(work).then(() => undefined, () => undefined);
215
+ let expiry;
241
216
  try {
242
- child = pick(deps, 'spawn', defaultSpawn)(CODEGRAPH_BIN, ['sync', root], {
243
- cwd: root,
244
- detached: true,
245
- stdio: 'ignore',
246
- env: deps.env || process.env,
247
- });
217
+ expiry = Promise.resolve(delay(budgetMs)).then(() => undefined, () => undefined);
248
218
  } catch {
249
- releaseLock(lockPath);
250
- resolve('spawn-failed');
251
- return;
219
+ // A timer seam that cannot arm its timer must never remove the cap: the wait answers as expired instead, so the
220
+ // tool runs at once rather than awaiting joined work that may never settle.
221
+ expiry = Promise.resolve();
252
222
  }
253
- if (child && typeof child.unref === 'function') {
254
- try {
255
- child.unref();
256
- } catch {
257
- // An unref failure never changes the outcome.
223
+ return Promise.race([settled, expiry]);
224
+ }
225
+
226
+ async function startSession(event, ctx) {
227
+ const notify = notifier(ctx);
228
+ try {
229
+ if (!child && !mcpChecked) {
230
+ mcpChecked = true;
231
+ notify(mcpNotice(await impl.ensureCodegraphServer({ agentDir: agentDirOf(env) })));
258
232
  }
233
+ } catch {
234
+ // The MCP entry is never worth stopping the index.
259
235
  }
260
- let settled = false;
261
- const timeoutMs = typeof deps.runTimeoutMs === 'number' ? deps.runTimeoutMs : RUN_TIMEOUT_MS;
262
- let watchdog = null;
263
- const done = () => {
264
- if (settled) return;
265
- settled = true;
266
- if (watchdog !== null) clearTimeout(watchdog);
267
- releaseLock(lockPath);
268
- resolve('spawned');
269
- };
270
- // A sync that hangs keeps the lock and the root's `running` flag, which would
271
- // wedge that checkout for the rest of the session. Bound it: one SIGTERM, then
272
- // settle regardless, so the state and the lock come back.
273
- const t = timers(deps);
274
- watchdog = t.setTimeout(() => {
275
- watchdog = null;
276
- if (child && typeof child.kill === 'function') {
277
- try { child.kill('SIGTERM'); } catch { /* best effort */ }
278
- }
279
- done();
280
- }, timeoutMs);
281
- if (watchdog && typeof watchdog.unref === 'function') watchdog.unref();
282
- if (!child || typeof child.once !== 'function') {
283
- // No event surface (a minimal double): the launch itself is the end.
284
- done();
285
- return;
236
+ try {
237
+ const cwd = sessionCwd(event, ctx);
238
+ // Never awaited by the host, and joined by a search that arrives while it runs.
239
+ const result = await trackIndexWork(cwd, () => impl.prepareProject({
240
+ cwd,
241
+ env,
242
+ role,
243
+ reason: event && event.reason,
244
+ hasBinary: deps.hasBinary,
245
+ onStart: (action) => notify({ text: index.indexStartNotice(action), level: 'info' }),
246
+ onIndexed: (indexed) => notify(index.indexOutcomeNotice(indexed, cwd)),
247
+ warm: (root) => impl.warmUpDaemon(root, undefined, { registryDir, background: true }),
248
+ }));
249
+ if (result && (result.warm === 'ok' || result.warm === 'failed')) notify(index.warmOutcomeNotice(result.warm, cwd));
250
+ } catch {
251
+ // The index preparation never breaks a session.
286
252
  }
287
- child.once('close', done);
288
- child.once('error', done);
289
- });
290
- }
291
-
292
- function isQuiescent() {
293
- for (const state of syncStates.values()) {
294
- if (state.running || state.timer !== null || state.retryTimer !== null) return false;
295
253
  }
296
- return true;
297
- }
298
254
 
299
- function settleIdleWaiters() {
300
- if (idleWaiters.length === 0 || !isQuiescent()) return;
301
- const waiters = idleWaiters;
302
- idleWaiters = [];
303
- for (const resolve of waiters) resolve();
304
- }
305
-
306
- function beginRun(root, state, deps) {
307
- state.running = true;
308
- void runSync(root, deps).then((outcome) => {
309
- state.running = false;
310
- if (outcome === 'locked' && !state.retried) {
311
- // One bounded retry: the last edit before a foreign sync still lands,
312
- // and a lock that stays held never becomes a busy loop.
313
- state.retried = true;
314
- const delay = typeof deps.retryDelayMs === 'number' ? deps.retryDelayMs : RETRY_DELAY_MS;
315
- state.retryTimer = timers(deps).setTimeout(() => {
316
- state.retryTimer = null;
317
- beginRun(root, state, deps);
318
- }, delay);
319
- return;
255
+ pi.on('session_start', (event, ctx) => {
256
+ try {
257
+ // The card names the explored checkout against the session's own directory.
258
+ sessionDir = sessionCwd(event, ctx);
259
+ } catch {
260
+ // An unknown cwd only means the explicit projectPath is shown.
320
261
  }
321
- if (outcome !== 'locked') state.retried = false;
322
- if (state.pending) {
323
- state.pending = false;
324
- state.retried = false;
325
- beginRun(root, state, deps);
326
- return;
262
+ try {
263
+ // A new, resumed or forked session is a new session; a `/reload` keeps this one and what it was told.
264
+ if (!event || event.reason !== 'reload') guards.onNewSession();
265
+ } catch {
266
+ // Forgetting a reminder never breaks a session.
327
267
  }
328
- settleIdleWaiters();
329
- }).catch(() => {
330
- state.running = false;
331
- state.pending = false;
332
- settleIdleWaiters();
268
+ // Never awaited: the host's own startup does not wait for an index.
269
+ void startSession(event, ctx);
333
270
  });
334
- }
335
271
 
336
- // CodeGraph 1.6 writes `{pid, version, socketPath, startedAt}` to daemon.pid and
337
- // tolerates a bare decimal from older versions, so read both shapes.
338
- function daemonPidOf(text) {
339
- const raw = String(text || '').trim();
340
- if (raw.startsWith('{')) {
272
+ // S2: the pre-execution hook. Pi awaits this answer and BLOCKS the tool when the hook throws
273
+ // (docs/extensions.md:3253), so it answers `undefined` for every other tool and whenever nothing is in flight,
274
+ // and the promise it does answer with is budget-capped and never rejects. It never starts a sync, init or seed.
275
+ pi.on('tool_call', (event, ctx) => {
341
276
  try {
342
- const info = JSON.parse(raw);
343
- const pid = Number(info && info.pid);
344
- return Number.isInteger(pid) && pid > 0 ? pid : null;
277
+ if (!isCodegraphSearch(event)) return undefined;
278
+ const budgetMs = joinBudgetMs(env);
279
+ if (!(budgetMs > 0)) return undefined;
280
+ const work = joinIndexWork(sessionCwd(event, ctx), budgetMs);
281
+ if (work === undefined || work === null) return undefined;
282
+ return boundedWait(work, budgetMs);
345
283
  } catch {
346
- return null;
284
+ // Waiting for the index is never worth blocking a search.
285
+ return undefined;
347
286
  }
348
- }
349
- const pid = Number.parseInt(raw, 10);
350
- return Number.isInteger(pid) && pid > 0 ? pid : null;
351
- }
352
-
353
- function daemonAlive(codegraphDir, deps) {
354
- const readFile = pick(deps, 'readFile', defaultReadFile);
355
- const isAlive = pick(deps, 'isAlive', defaultIsAlive);
356
- let text;
357
- try {
358
- text = readFile(path.join(codegraphDir, DAEMON_PID_FILE));
359
- } catch {
360
- return false;
361
- }
362
- const pid = daemonPidOf(text);
363
- return pid !== null && isAlive(pid);
364
- }
365
-
366
- // --- entry point --------------------------------------------------------
287
+ });
367
288
 
368
- // The extension's fire-and-forget entry (S1). Never throws, never waits:
369
- // `{scheduled, reason}` describes what was decided, and settled work is
370
- // observable through `whenIdle()`.
371
- function scheduleSync(filePath, deps = {}) {
372
- const effectiveDeps = deps || {};
373
- try {
374
- if (typeof filePath !== 'string' || filePath.length === 0) return { scheduled: false, reason: 'no-path' };
375
- const env = effectiveDeps.env || process.env;
376
- // The user's switch wins over everything below: off means no root read, no
377
- // daemon read, no lock and no child.
378
- if (!isHookEnabled(env)) return { scheduled: false, reason: 'hook-off' };
379
- if (!hasCodegraph(env, effectiveDeps)) return { scheduled: false, reason: 'no-codegraph' };
380
- const root = resolveProjectRoot(path.dirname(path.resolve(filePath)), effectiveDeps);
381
- if (root === null) return { scheduled: false, reason: 'no-root' };
289
+ pi.on('session_compact', (event, ctx) => {
290
+ try {
291
+ guards.onCompacted();
292
+ } catch {
293
+ // Forgetting a reminder never breaks a session.
294
+ }
295
+ // S2: the compaction's sync is tracked exactly like the session-start preparation and the post-init sync, so a
296
+ // search arriving while it runs joins it. The host is still handed nothing: the work runs off its path.
297
+ const cwd = sessionCwd(event, ctx);
298
+ void trackIndexWork(cwd, () => impl.compactionSync({ cwd, env, role, hasBinary: deps.hasBinary })).catch(() => {});
299
+ });
382
300
 
383
- const codegraphDir = path.join(root, '.codegraph');
384
- const exists = pick(effectiveDeps, 'exists', fs.existsSync);
385
- if (!exists(codegraphDir)) return { scheduled: false, reason: 'no-index' };
386
- if (daemonAlive(codegraphDir, effectiveDeps)) return { scheduled: false, reason: 'daemon' };
301
+ // The session's tools reach the guards from the ONE source that has them: the prompt options of
302
+ // `before_agent_start`. Nothing here touches the prompt itself.
303
+ pi.on('before_agent_start', (event) => {
304
+ try {
305
+ guards.observeTools(event && event.systemPromptOptions && event.systemPromptOptions.selectedTools);
306
+ } catch {
307
+ // Recording the tools never breaks a prompt.
308
+ }
309
+ });
387
310
 
388
- let state = syncStates.get(root);
389
- if (state === undefined) {
390
- state = { timer: null, retryTimer: null, running: false, pending: false, retried: false };
391
- syncStates.set(root, state);
311
+ pi.on('tool_result', async (event, ctx) => {
312
+ try {
313
+ void Promise.resolve(editSync.onToolResult(event, ctx)).catch(() => {});
314
+ } catch {
315
+ // The edit sync never fails a tool result.
392
316
  }
393
- if (state.running) {
394
- state.pending = true;
395
- return { scheduled: true, reason: 'queued' };
317
+ const extras = [];
318
+ const appendNotice = (notice) => {
319
+ if (typeof notice === 'string' && notice.length > 0) extras.push(notice);
320
+ };
321
+ try {
322
+ const decision = index.initHookDecision(event, role);
323
+ if (decision === 'skip-read-only') {
324
+ appendNotice(index.postInitSyncNotice('skipped-read-only'));
325
+ } else if (decision === 'sync') {
326
+ // An init aimed at another checkout is that checkout's own business, not this session's index.
327
+ if (!(event.input && (typeof event.input.worktree === 'string' || typeof event.input.path === 'string'))) {
328
+ const cwd = sessionCwd(event, ctx);
329
+ const outcome = await trackIndexWork(cwd, () => impl.syncAfterNativeInit({ cwd, env, role }));
330
+ // S4: a completed sync appends nothing; only one that did not complete earns a line.
331
+ appendNotice(index.postInitSyncNotice(outcome));
332
+ }
333
+ }
334
+ } catch {
335
+ // The post-init line never fails a tool result.
396
336
  }
397
- const t = timers(effectiveDeps);
398
- if (state.timer !== null) t.clearTimeout(state.timer);
399
- state.retried = false;
400
- const delay = typeof effectiveDeps.debounceMs === 'number' ? effectiveDeps.debounceMs : DEBOUNCE_MS;
401
- state.timer = t.setTimeout(() => {
402
- state.timer = null;
403
- beginRun(root, state, effectiveDeps);
404
- }, delay);
405
- return { scheduled: true, reason: 'scheduled' };
406
- } catch {
407
- return { scheduled: false, reason: 'error' };
408
- }
409
- }
337
+ try {
338
+ // The reminders cite the CodeGraph rule, so they go quiet with it: ODD_WORKTREE_PROMPT=0 suppresses both.
339
+ const reminder = env.ODD_WORKTREE_PROMPT === '0' ? undefined : await guards.onToolResult(event, ctx);
340
+ if (reminder) extras.push(reminder);
341
+ } catch {
342
+ // The reminder never fails a tool result.
343
+ }
344
+ return extras.length === 0 ? undefined : withNotice(event, extras.join('\n\n'));
345
+ });
410
346
 
411
- // Resolves when no root has a timer, a retry or a run in flight, so a test can
412
- // await settled work without sleeping.
413
- function whenIdle() {
414
- if (isQuiescent()) return Promise.resolve();
415
- return new Promise((resolve) => { idleWaiters.push(resolve); });
416
- }
347
+ pi.on('session_shutdown', () => {
348
+ try {
349
+ editSync.dispose();
350
+ } catch {
351
+ // Shutdown never fails on a timer.
352
+ }
353
+ });
417
354
 
418
- // Test-only full reset: the gate, the hook switch, both caches and the waiters.
419
- function resetCodegraphSession() {
420
- gateAnswer = null;
421
- hookEnabled = null;
422
- rootCache.clear();
423
- syncStates.clear();
424
- const waiters = idleWaiters;
425
- idleWaiters = [];
426
- for (const resolve of waiters) resolve();
355
+ return { registered: true };
427
356
  }
428
357
 
429
- module.exports = {
430
- hasCodegraph,
431
- isHookEnabled,
432
- setHookEnabled,
433
- resetCodegraphGate,
434
- resetCodegraphSession,
435
- resolveProjectRoot,
436
- scheduleSync,
437
- whenIdle,
438
- };
358
+ module.exports = { registerCodegraph, agentDirOf, mcpNotice };