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
@@ -0,0 +1,246 @@
1
+ 'use strict';
2
+ // The daemon a checkout already has: resolved from CodeGraph's own registry, one checkout at a time, and asked
3
+ // over its own socket. Nothing here starts, configures or stops a daemon, and nothing here trusts the MCP
4
+ // configuration: a registered MCP server says nothing about whether a daemon is reachable. The registry is only
5
+ // ever read, and only this checkout's records are considered — a worktree is its own root, so its parent's
6
+ // daemon is never its own.
7
+
8
+ const net = require('node:net');
9
+ const nodeFs = require('node:fs');
10
+ const { homedir } = require('node:os');
11
+ const { join } = require('node:path');
12
+ const { canonicalRoot } = require('./codegraph-paths.js');
13
+
14
+ /** The hello line a CodeGraph daemon sends carries `protocol`; this is the only one spoken here. */
15
+ const DAEMON_PROTOCOL = 1;
16
+ /** An explore answer is tens of kilobytes; anything near this size is not one worth keeping in memory. */
17
+ const MAX_REPLY_CHARS = 1_000_000;
18
+ /** A daemon sends its hello line as soon as it accepts; one silent this long is hung, and the next one gets the rest of the budget. */
19
+ const DAEMON_HELLO_TIMEOUT_MS = 2_000;
20
+ /** CodeGraph answers an explore without a project with this plain text, not with an error. */
21
+ const NO_PROJECT_TEXT = 'No CodeGraph project is loaded';
22
+
23
+ const PIPE_PREFIX = '\\\\.\\pipe\\';
24
+
25
+ /**
26
+ * The same project can be spelled with another letter case or a trailing separator, and on Windows as a mapped
27
+ * drive (Y:\...) or as the UNC path behind it (\\server\share\...). One canonical form for every root comparison.
28
+ */
29
+ const normalizeRoot = (path) => canonicalRoot(path);
30
+
31
+ const DEFAULT_REGISTRY = () => join(homedir(), '.codegraph', 'daemons');
32
+
33
+ /** Every seam with its real default: a registry directory, fs, platform, the liveness check, the socket and the clock. */
34
+ function seams(options = {}) {
35
+ return {
36
+ registryDir: options.registryDir ?? DEFAULT_REGISTRY(),
37
+ fs: { ...nodeFs, ...(options.fs ?? {}) },
38
+ platform: options.platform ?? process.platform,
39
+ alive: options.alive ?? processAlive,
40
+ connect: options.connect ?? ((socketPath) => net.createConnection(socketPath)),
41
+ now: options.now ?? Date.now,
42
+ };
43
+ }
44
+
45
+ /** Whether a process with this pid exists; signal 0 only checks. EPERM means it exists under another user. */
46
+ function processAlive(pid) {
47
+ try {
48
+ process.kill(pid, 0);
49
+ return true;
50
+ } catch (error) {
51
+ return error?.code === 'EPERM';
52
+ }
53
+ }
54
+
55
+ /**
56
+ * Whether a daemon socket is still there. A Windows named pipe is not a file: listing the pipe directory shows the
57
+ * live ones without connecting to them, and a listing that fails counts as present rather than risk missing a live
58
+ * daemon. Every other socket path is a socket file, which existsSync checks.
59
+ */
60
+ function socketPresent(socketPath, seam) {
61
+ if (seam.platform !== 'win32' || !socketPath.toLowerCase().startsWith(PIPE_PREFIX)) return seam.fs.existsSync(socketPath);
62
+ const name = socketPath.slice(PIPE_PREFIX.length).toLowerCase();
63
+ try {
64
+ return seam.fs.readdirSync(PIPE_PREFIX).some((entry) => entry.toLowerCase() === name);
65
+ } catch {
66
+ return true;
67
+ }
68
+ }
69
+
70
+ /** A record whose process runs and whose socket is still there: only that one is a daemon to reuse. */
71
+ function isLive(entry, seam) {
72
+ return entry.pid !== undefined && seam.alive(entry.pid) && socketPresent(entry.socketPath, seam);
73
+ }
74
+
75
+ /** Daemons registered for `root` in any spelling, newest first. Reads the registry only; starts nothing. */
76
+ function daemonsFor(root, seam) {
77
+ let files;
78
+ try {
79
+ files = seam.fs.readdirSync(seam.registryDir).filter((file) => file.endsWith('.json'));
80
+ } catch {
81
+ return [];
82
+ }
83
+ const wanted = normalizeRoot(root);
84
+ const found = [];
85
+ for (const file of files) {
86
+ try {
87
+ const entry = JSON.parse(seam.fs.readFileSync(join(seam.registryDir, file), 'utf8'));
88
+ if (typeof entry.root !== 'string' || typeof entry.socketPath !== 'string') continue;
89
+ if (normalizeRoot(entry.root) !== wanted) continue;
90
+ found.push({
91
+ root: entry.root,
92
+ socketPath: entry.socketPath,
93
+ startedAt: typeof entry.startedAt === 'number' ? entry.startedAt : 0,
94
+ pid: typeof entry.pid === 'number' ? entry.pid : undefined,
95
+ });
96
+ } catch {
97
+ /* a damaged record is not a daemon */
98
+ }
99
+ }
100
+ return found.sort((a, b) => b.startedAt - a.startedAt);
101
+ }
102
+
103
+ /**
104
+ * The newest registered daemon of exactly `root` whose process runs and whose socket is still there. A worktree or
105
+ * child checkout is its own root: nothing registered for another checkout is ever returned here. This reads the
106
+ * registry only — it never starts, connects to or stops anything, and it is not affected by MCP server
107
+ * configuration, which says nothing about whether a daemon is reachable.
108
+ */
109
+ function liveDaemon(root, options = {}) {
110
+ const seam = seams(options);
111
+ const daemon = daemonsFor(root, seam).find((entry) => isLive(entry, seam));
112
+ if (daemon === undefined) return undefined;
113
+ return { root: daemon.root, socketPath: daemon.socketPath, ...(daemon.pid === undefined ? {} : { pid: daemon.pid }) };
114
+ }
115
+
116
+ /**
117
+ * What the daemon state of this checkout is: a live one, only records whose daemon is gone, or none. The answer
118
+ * comes from the registry of this root alone, never from an MCP server entry.
119
+ */
120
+ function daemonStatus(root, options = {}) {
121
+ const seam = seams(options);
122
+ const daemons = daemonsFor(root, seam);
123
+ if (daemons.length === 0) return 'none';
124
+ return daemons.some((entry) => isLive(entry, seam)) ? 'live' : 'dead';
125
+ }
126
+
127
+ /**
128
+ * How the newest daemon of this project spells its root, or undefined when none is registered. Passing that
129
+ * spelling to codegraph keeps it on the same daemon: CodeGraph keys daemons by the path it was given.
130
+ */
131
+ function registeredRoot(root, options = {}) {
132
+ const seam = seams(options);
133
+ // Dead records stay in the registry (CodeGraph owns those files), but they never win: a record is alive only
134
+ // while its process runs and its socket is still there, so a reused pid cannot make a stale spelling win.
135
+ const daemons = daemonsFor(root, seam);
136
+ return (daemons.find((entry) => isLive(entry, seam)) ?? daemons[0])?.root;
137
+ }
138
+
139
+ /** The path to hand to the codegraph CLI for this project: the registered spelling when there is one. */
140
+ function projectArgument(root, options = {}) {
141
+ return registeredRoot(root, options) ?? root;
142
+ }
143
+
144
+ /** A socket that accepted but never said hello: the next one gets the rest of the budget. */
145
+ async function ask(socketPath, query, timeoutMs, seam) {
146
+ return new Promise((resolveResult) => {
147
+ let settled = false;
148
+ let socket;
149
+ const finish = (result) => {
150
+ if (settled) return;
151
+ settled = true;
152
+ clearTimeout(deadlineTimer);
153
+ clearTimeout(helloTimer);
154
+ try { socket?.destroy(); } catch { /* already gone */ }
155
+ resolveResult(result);
156
+ };
157
+ try {
158
+ socket = seam.connect(socketPath);
159
+ } catch {
160
+ resolveResult({ status: 'unavailable' });
161
+ return;
162
+ }
163
+ const budget = Math.max(1, timeoutMs);
164
+ const deadlineTimer = setTimeout(() => finish({ status: 'timeout' }), budget);
165
+ // Only the hello line waits on this timer; the rest of the conversation keeps the whole budget.
166
+ const helloTimer = setTimeout(() => finish({ status: 'silent' }), Math.max(1, Math.min(DAEMON_HELLO_TIMEOUT_MS, budget)));
167
+ const send = (message) => socket.write(`${JSON.stringify(message)}\n`);
168
+ let buffer = '';
169
+ let stage = 'hello';
170
+ socket.setEncoding('utf8');
171
+ socket.on('error', () => finish({ status: 'unavailable' }));
172
+ socket.on('close', () => finish({ status: 'unavailable' }));
173
+ socket.on('data', (chunk) => {
174
+ buffer += chunk;
175
+ if (buffer.length > MAX_REPLY_CHARS) return finish({ status: 'unavailable' });
176
+ let newline;
177
+ while ((newline = buffer.indexOf('\n')) >= 0) {
178
+ const line = buffer.slice(0, newline).trim();
179
+ buffer = buffer.slice(newline + 1);
180
+ if (line.length === 0) continue;
181
+ let message;
182
+ try { message = JSON.parse(line); } catch { return finish({ status: 'unavailable' }); }
183
+ if (stage === 'hello') {
184
+ if (typeof message.codegraph !== 'string' || message.protocol !== DAEMON_PROTOCOL) return finish({ status: 'unavailable' });
185
+ clearTimeout(helloTimer);
186
+ stage = 'initialize';
187
+ send({
188
+ jsonrpc: '2.0',
189
+ id: 1,
190
+ method: 'initialize',
191
+ params: { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'odd-worktree-codegraph', version: '0' } },
192
+ });
193
+ } else if (stage === 'initialize' && message.id === 1) {
194
+ if (message.error !== undefined) return finish({ status: 'unavailable' });
195
+ stage = 'explore';
196
+ send({ jsonrpc: '2.0', method: 'notifications/initialized' });
197
+ send({ jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'codegraph_explore', arguments: { query } } });
198
+ } else if (stage === 'explore' && message.id === 2) {
199
+ // CodeGraph reports a crashed query worker with isError and a text, not with a JSON-RPC error.
200
+ const text = message.result?.content?.[0]?.text;
201
+ const failed = message.error !== undefined || message.result?.isError === true;
202
+ if (failed || typeof text !== 'string' || text.startsWith(NO_PROJECT_TEXT)) return finish({ status: 'unavailable' });
203
+ return finish({ status: 'ok', text });
204
+ }
205
+ }
206
+ });
207
+ });
208
+ }
209
+
210
+ /**
211
+ * Runs `codegraph_explore` through the daemon already serving `root`, the same text the CLI prints but without a
212
+ * process of its own. It only reads the daemon registry and connects: it never starts a daemon, and never throws.
213
+ */
214
+ async function exploreViaDaemon(root, query, timeoutMs, options = {}) {
215
+ const seam = seams(options);
216
+ try {
217
+ const deadline = seam.now() + timeoutMs;
218
+ let silent = false;
219
+ const sockets = daemonsFor(root, seam).map((entry) => entry.socketPath);
220
+ for (const socketPath of sockets) {
221
+ const result = await ask(socketPath, query, deadline - seam.now(), seam);
222
+ if (result.status === 'silent') {
223
+ silent = true;
224
+ continue;
225
+ }
226
+ if (result.status !== 'unavailable') return result;
227
+ }
228
+ // A silent daemon is there but hung: warming another one would not make this query faster.
229
+ return silent ? { status: 'timeout' } : { status: 'unavailable' };
230
+ } catch {
231
+ return { status: 'unavailable' };
232
+ }
233
+ }
234
+
235
+ module.exports = {
236
+ DAEMON_PROTOCOL,
237
+ DAEMON_HELLO_TIMEOUT_MS,
238
+ MAX_REPLY_CHARS,
239
+ NO_PROJECT_TEXT,
240
+ normalizeRoot,
241
+ daemonStatus,
242
+ liveDaemon,
243
+ registeredRoot,
244
+ projectArgument,
245
+ exploreViaDaemon,
246
+ };
@@ -0,0 +1,182 @@
1
+ 'use strict';
2
+ // S9: freshness without a daemon. After a successful `edit` or `write`, ask for one background sync of the checkout the edited
3
+ // file lives in (its git toplevel, read once per directory), debounced per checkout, on the same coordination every other index
4
+ // write uses. It never runs while a live daemon watches that checkout (the daemon's watcher already syncs it), never in a
5
+ // read-only role, never without the CLI or without an index, and a sync asked for while one runs becomes exactly one more when
6
+ // it ends. Git, the index check, the daemon check, the sync and the timers are all injected; nothing here throws into the host.
7
+ //
8
+ // S2: the window is also observable. A search that would read the index while a window writes it joins that window with
9
+ // `whenIdle` (bounded) instead of racing it, and `inFlight` answers synchronously whether there is anything to join, so a
10
+ // caller with nothing in flight adds no latency at all. Joining never starts a sync.
11
+
12
+ const { execFile } = require('node:child_process');
13
+ const nodeFs = require('node:fs');
14
+ const nodePath = require('node:path');
15
+
16
+ const EDIT_TOOLS = new Set(['edit', 'write']);
17
+ const DEBOUNCE_MS = 2000;
18
+ const GIT_TIMEOUT_MS = 5000;
19
+
20
+ /** The git toplevel of a directory through one fixed-argv child, awaited; undefined when it is not a checkout. */
21
+ function gitToplevel(dir) {
22
+ return new Promise((resolve) => {
23
+ try {
24
+ execFile('git', ['-C', dir, 'rev-parse', '--show-toplevel'], { timeout: GIT_TIMEOUT_MS, windowsHide: true }, (error, stdout) => {
25
+ const top = error ? '' : String(stdout).trim();
26
+ resolve(top.length > 0 ? top : undefined);
27
+ });
28
+ } catch {
29
+ resolve(undefined);
30
+ }
31
+ });
32
+ }
33
+
34
+ function editedPath(event, cwd) {
35
+ const input = event && typeof event.input === 'object' && event.input !== null ? event.input : {};
36
+ const raw = typeof input.path === 'string' ? input.path : typeof input.file_path === 'string' ? input.file_path : '';
37
+ if (raw.length === 0) return undefined;
38
+ return nodePath.isAbsolute(raw) ? raw : nodePath.resolve(cwd || process.cwd(), raw);
39
+ }
40
+
41
+ function createEditSync(deps = {}) {
42
+ const available = deps.available || (() => true);
43
+ const toplevel = deps.toplevel || gitToplevel;
44
+ const hasIndex = deps.hasIndex || ((root) => nodeFs.existsSync(nodePath.join(root, '.codegraph')));
45
+ const daemonLive = deps.daemonLive || (() => false);
46
+ const setTimer = deps.setTimer || ((fn, ms) => {
47
+ const timer = setTimeout(fn, ms);
48
+ if (timer && typeof timer.unref === 'function') timer.unref();
49
+ return timer;
50
+ });
51
+ const clearTimer = deps.clearTimer || ((timer) => clearTimeout(timer));
52
+ const debounceMs = deps.debounceMs === undefined ? DEBOUNCE_MS : deps.debounceMs;
53
+
54
+ const roots = new Map(); // directory -> toplevel | null
55
+ const windows = new Map(); // root -> { timer, running, pending, queued, waiters }
56
+
57
+ /** Whether this root has a sync running, one owed, or (only while running) a re-run asked for. */
58
+ function inFlightState(state) {
59
+ return state.running === true || state.pending === true || state.queued === true;
60
+ }
61
+
62
+ /** Answers every joined caller at once: the window reached a quiet point, was disposed, or ran out its budget. */
63
+ function settle(state, reason) {
64
+ for (const waiter of state.waiters.splice(0)) {
65
+ if (waiter.timer !== undefined) clearTimer(waiter.timer);
66
+ waiter.resolve(reason);
67
+ }
68
+ }
69
+
70
+ async function rootOf(dir) {
71
+ if (roots.has(dir)) return roots.get(dir);
72
+ let top;
73
+ try {
74
+ top = await toplevel(dir);
75
+ } catch {
76
+ top = undefined;
77
+ }
78
+ const root = typeof top === 'string' && top.length > 0 ? top : null;
79
+ roots.set(dir, root);
80
+ return root;
81
+ }
82
+
83
+ async function runWindow(root) {
84
+ const state = windows.get(root);
85
+ if (!state) return;
86
+ state.timer = undefined;
87
+ if (state.running) {
88
+ state.pending = true;
89
+ return;
90
+ }
91
+ state.running = true;
92
+ state.queued = false;
93
+ try {
94
+ await deps.sync(root);
95
+ } catch {
96
+ // A failed background sync is never worth bothering the session.
97
+ } finally {
98
+ state.running = false;
99
+ }
100
+ if (state.pending) {
101
+ state.pending = false;
102
+ // Owed from here until the window this re-arms runs: a caller that joined waits for that one too.
103
+ state.queued = true;
104
+ schedule(root);
105
+ }
106
+ if (!inFlightState(state)) settle(state, 'done');
107
+ }
108
+
109
+ function schedule(root) {
110
+ let state = windows.get(root);
111
+ if (!state) {
112
+ state = { timer: undefined, running: false, pending: false, queued: false, waiters: [] };
113
+ windows.set(root, state);
114
+ }
115
+ if (state.running) {
116
+ state.pending = true;
117
+ return;
118
+ }
119
+ if (state.timer !== undefined) clearTimer(state.timer);
120
+ state.timer = setTimer(() => runWindow(root), debounceMs);
121
+ }
122
+
123
+ return {
124
+ /** The host's `tool_result` event. Resolves once the window is scheduled, never after the sync. */
125
+ async onToolResult(event, ctx) {
126
+ try {
127
+ if (!event || event.isError === true || !EDIT_TOOLS.has(event.toolName)) return;
128
+ if (deps.role === 'read-only') return;
129
+ if (!available()) return;
130
+ const file = editedPath(event, (ctx && ctx.cwd) || deps.cwd);
131
+ if (file === undefined) return;
132
+ const root = await rootOf(nodePath.dirname(file));
133
+ if (root === null) return;
134
+ if (!hasIndex(root)) return;
135
+ if (daemonLive(root)) return;
136
+ schedule(root);
137
+ } catch {
138
+ // The host never sees a failure of this hook.
139
+ }
140
+ },
141
+ /**
142
+ * Whether this root has a sync running or one owed right now. Synchronous on purpose: the caller that finds
143
+ * nothing to join declines to wait at all. A window that is only debounced is scheduled, not in flight.
144
+ */
145
+ inFlight(root) {
146
+ const state = windows.get(root);
147
+ return state !== undefined && inFlightState(state);
148
+ },
149
+ /**
150
+ * Settles with `'done'` when the running sync and the one follow-up it owes have finished, `'idle'` at once
151
+ * when nothing is in flight (or the budget is not a positive number), `'budget'` when the budget ran out first,
152
+ * and `'disposed'` when shutdown ended the wait. Never rejects, never starts a sync.
153
+ */
154
+ whenIdle(root, budgetMs) {
155
+ const state = windows.get(root);
156
+ if (state === undefined || !inFlightState(state)) return Promise.resolve('idle');
157
+ if (typeof budgetMs !== 'number' || !Number.isFinite(budgetMs) || budgetMs <= 0) return Promise.resolve('budget');
158
+ return new Promise((resolve) => {
159
+ const waiter = { resolve, timer: undefined };
160
+ waiter.timer = setTimer(() => {
161
+ waiter.timer = undefined;
162
+ const at = state.waiters.indexOf(waiter);
163
+ if (at !== -1) state.waiters.splice(at, 1);
164
+ resolve('budget');
165
+ }, budgetMs);
166
+ state.waiters.push(waiter);
167
+ });
168
+ },
169
+ /** Clears every pending window (session shutdown), and releases whoever joined one instead of leaving it waiting. */
170
+ dispose() {
171
+ for (const state of windows.values()) {
172
+ if (state.timer !== undefined) clearTimer(state.timer);
173
+ state.timer = undefined;
174
+ state.pending = false;
175
+ state.queued = false;
176
+ settle(state, 'disposed');
177
+ }
178
+ },
179
+ };
180
+ }
181
+
182
+ module.exports = { createEditSync, gitToplevel, DEBOUNCE_MS };