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,607 @@
1
+ 'use strict';
2
+ // The two pieces of index coordination (S3), and nothing else: one init lock per project and one per-project sync
3
+ // lease, both shared by every session of this user on the machine (the temp folder is per user, so another account,
4
+ // another machine, a terminal or another tool is not seen).
5
+ //
6
+ // The init lock is a directory in the temp folder holding `owner.json`: an init that creates an index and a sync
7
+ // that updates one exclude each other, because CodeGraph's own `init` can hang for good when two start at the same
8
+ // instant. Clearing a stale lock happens under a second directory (`<lock>.takeover`), so only one session at a time
9
+ // can do it. The lease is a directory with `run/` (the session syncing), `req/` (one file per request waiting for a
10
+ // follow-up) and `gate/` (the short mutex the lease and the requests share); a request is only marked as served by a
11
+ // run that started after it and finished, so one that cannot be served is reported pending, never dropped and never
12
+ // reported as a sync of the caller.
13
+ //
14
+ // Every external seam is injected with a real default: `dir`, `isAlive`, `now`, `fs`. Nothing here spawns a child,
15
+ // so a lock is never held on behalf of a live process this module could not see.
16
+
17
+ const nodeFs = require('node:fs');
18
+ const { createHash, randomBytes } = require('node:crypto');
19
+ const os = require('node:os');
20
+ const path = require('node:path');
21
+
22
+ const { canonicalRoot } = require('./codegraph-paths.js');
23
+
24
+ /** The longest a `codegraph init` is allowed to run; a lock older than this cannot belong to a live one. */
25
+ const INIT_TIMEOUT_MS = 600_000;
26
+ /** The longest a `codegraph sync` is allowed to run; a lease older than this cannot belong to a live one. */
27
+ const SYNC_TIMEOUT_MS = 120_000;
28
+ /** The longest an init is allowed to run plus a minute: beyond that the lock is not trusted. */
29
+ const LOCK_MAX_AGE_MS = INIT_TIMEOUT_MS + 60_000;
30
+ /** One sync may run for its own two minutes; a lease older than this cannot belong to a sync still running. */
31
+ const SYNC_LEASE_MAX_AGE_MS = SYNC_TIMEOUT_MS + 60_000;
32
+ /** An empty lock directory this young is an owner about to write its record; older ones were abandoned. */
33
+ const UNWRITTEN_GRACE_MS = 10_000;
34
+ /** Clearing a stale lock takes milliseconds: a takeover guard older than this was left by a session that died. */
35
+ const TAKEOVER_GRACE_MS = 10_000;
36
+ /** Taking the gate takes milliseconds: one older than this was left by a session that died inside it. */
37
+ const GATE_GRACE_MS = 10_000;
38
+ /** How long a session waits for the gate before it gives up: there is no safe way to coordinate without it. */
39
+ const GATE_TIMEOUT_MS = 30_000;
40
+ /**
41
+ * How long a record whose adopted pid may be only the shell around the real init is trusted after that spawn. The
42
+ * shell can die while the init goes on, and the init announces itself in CodeGraph's own lock only a moment later.
43
+ */
44
+ const PROXY_TRUST_MS = 60_000;
45
+ const DEFAULT_POLL_MS = 50;
46
+ /** How long a session whose sync waits for the running one looks for its request to be served. */
47
+ const DEFAULT_REQUEST_WAIT_MS = SYNC_LEASE_MAX_AGE_MS + 60_000;
48
+
49
+ /** The `node:fs` surface these two pieces of state use, so a test can stand in for it. */
50
+ const FS_NAMES = ['existsSync', 'mkdirSync', 'readFileSync', 'readdirSync', 'renameSync', 'rmSync', 'statSync', 'writeFileSync'];
51
+
52
+ function fsOf(options) {
53
+ const fs = options && options.fs;
54
+ if (!fs) return nodeFs;
55
+ const merged = {};
56
+ for (const name of FS_NAMES) merged[name] = typeof fs[name] === 'function' ? fs[name] : nodeFs[name];
57
+ return merged;
58
+ }
59
+
60
+ function clockOf(options) {
61
+ return options && typeof options.now === 'function' ? options.now : Date.now;
62
+ }
63
+
64
+ function aliveOf(options) {
65
+ return options && typeof options.isAlive === 'function' ? options.isAlive : processExists;
66
+ }
67
+
68
+ function processExists(pid) {
69
+ try {
70
+ process.kill(pid, 0);
71
+ return true;
72
+ } catch (error) {
73
+ // EPERM: the process exists but belongs to someone else.
74
+ return Boolean(error) && error.code === 'EPERM';
75
+ }
76
+ }
77
+
78
+ function keyFor(project) {
79
+ return createHash('sha256').update(canonicalRoot(project)).digest('hex').slice(0, 16);
80
+ }
81
+
82
+ /** CodeGraph writes the pid of whatever writes the index here and removes the file when it ends, on failure too. */
83
+ const CODEGRAPH_LOCK = path.join('.codegraph', 'codegraph.lock');
84
+
85
+ /**
86
+ * Whether a CodeGraph process is writing the index of `project` right now, whoever started it (another session, the
87
+ * project daemon, a git hook, a terminal). CodeGraph holds `.codegraph/codegraph.lock` for every operation that
88
+ * writes the index (`init`, `sync`, a file index) and removes it when it ends; reads and queries never hold it. A pid
89
+ * that is not alive left the file behind. Any other error is a false: this never throws.
90
+ */
91
+ function codegraphWritingIndex(project, options) {
92
+ const fs = fsOf(options);
93
+ try {
94
+ const pid = Number.parseInt(fs.readFileSync(path.join(project, CODEGRAPH_LOCK), 'utf8').trim(), 10);
95
+ return Number.isInteger(pid) && pid > 0 && processExists(pid);
96
+ } catch {
97
+ return false;
98
+ }
99
+ }
100
+
101
+ // ---- The init lock ----
102
+
103
+ function lockPath(project, options) {
104
+ const base = options && typeof options.dir === 'string' ? options.dir : os.tmpdir();
105
+ return path.join(base, `pcs-init-${keyFor(project)}`);
106
+ }
107
+
108
+ function ownerIsValid(owner) {
109
+ return Number.isInteger(owner.pid)
110
+ && typeof owner.startedAt === 'number'
111
+ && typeof owner.token === 'string'
112
+ && (owner.initPid === undefined || Number.isInteger(owner.initPid))
113
+ && (owner.initPidAt === undefined || typeof owner.initPidAt === 'number')
114
+ && (owner.initProxy === undefined || typeof owner.initProxy === 'boolean')
115
+ && (owner.kind === undefined || owner.kind === 'init' || owner.kind === 'sync');
116
+ }
117
+
118
+ function readOwner(lock, options) {
119
+ const fs = fsOf(options);
120
+ try {
121
+ const owner = JSON.parse(fs.readFileSync(path.join(lock, 'owner.json'), 'utf8'));
122
+ return ownerIsValid(owner) ? owner : undefined;
123
+ } catch {
124
+ return undefined;
125
+ }
126
+ }
127
+
128
+ /** Whether the lock at `lock` still belongs to someone who is working. A missing lock is not held. */
129
+ function held(project, lock, options) {
130
+ const fs = fsOf(options);
131
+ const now = clockOf(options)();
132
+ const isAlive = aliveOf(options);
133
+ let directory;
134
+ try {
135
+ directory = fs.statSync(lock);
136
+ } catch {
137
+ return false;
138
+ }
139
+ const owner = readOwner(lock, options);
140
+ // No readable record: its owner is probably still writing it, unless it has been this way for a while.
141
+ if (owner === undefined) return now - directory.mtimeMs < UNWRITTEN_GRACE_MS;
142
+ if (now - owner.startedAt > LOCK_MAX_AGE_MS) return false;
143
+ if (isAlive(owner.pid)) return true;
144
+ if (owner.initPid !== undefined && isAlive(owner.initPid)) return true;
145
+ // The process writing the index itself, whatever pid this session spawned or adopted: on Windows the adopted pid
146
+ // is the shell, and a shell dies with the session that started it while the init goes on. That pid is another
147
+ // process, so it is judged with the real process table, not with a test hook.
148
+ if (codegraphWritingIndex(project, options)) return true;
149
+ // Right after the spawn CodeGraph has not written its lock yet; until then the record speaks for the init.
150
+ return owner.initProxy === true && owner.initPidAt !== undefined && now - owner.initPidAt < PROXY_TRUST_MS;
151
+ }
152
+
153
+ /** Replaces the owner record in one step, so a reader sees the old record or the new one, never none. */
154
+ function writeOwner(lock, owner, options) {
155
+ const fs = fsOf(options);
156
+ const draft = path.join(lock, `owner.${owner.token}.tmp`);
157
+ fs.writeFileSync(draft, JSON.stringify(owner));
158
+ fs.renameSync(draft, path.join(lock, 'owner.json'));
159
+ }
160
+
161
+ /**
162
+ * Clears the stale lock at `lock`; true when the caller may try to take it again. Only the session holding the
163
+ * takeover guard gets this far, and it checks again under the guard: another session may have taken the lock over
164
+ * since this one judged it stale.
165
+ */
166
+ function clearStale(project, lock, options, token) {
167
+ const fs = fsOf(options);
168
+ const guard = `${lock}.takeover`;
169
+ try {
170
+ fs.mkdirSync(guard);
171
+ } catch {
172
+ // Someone else is taking it over right now, or died doing it: then the next session gets its turn.
173
+ try {
174
+ if (clockOf(options)() - fs.statSync(guard).mtimeMs > TAKEOVER_GRACE_MS) fs.rmSync(guard, { recursive: true, force: true });
175
+ } catch {
176
+ // Already gone.
177
+ }
178
+ return false;
179
+ }
180
+ try {
181
+ if (held(project, lock, options)) return false;
182
+ const judged = (readOwner(lock, options) || {}).token;
183
+ const aside = `${lock}.stale-${token}`;
184
+ try {
185
+ fs.renameSync(lock, aside);
186
+ } catch {
187
+ return true; // Its owner removed it meanwhile.
188
+ }
189
+ if ((readOwner(aside, options) || {}).token !== judged) {
190
+ // Not the lock judged stale: its owner left and another session took it in between. Give it back.
191
+ try {
192
+ fs.renameSync(aside, lock);
193
+ } catch {
194
+ // The lock is taken again; the moved one is lost either way.
195
+ }
196
+ return false;
197
+ }
198
+ try {
199
+ fs.rmSync(aside, { recursive: true, force: true });
200
+ } catch {
201
+ // Leftovers are harmless.
202
+ }
203
+ return true;
204
+ } finally {
205
+ try {
206
+ fs.rmSync(guard, { recursive: true, force: true });
207
+ } catch {
208
+ // A guard left behind expires.
209
+ }
210
+ }
211
+ }
212
+
213
+ /**
214
+ * Takes the init lock of `project`, for an `init` (the default) or a `sync`. Never throws: when the temp folder
215
+ * cannot be used the session goes on as if it had the lock, which is how it behaved before locks existed.
216
+ */
217
+ function tryAcquireInitLock(project, options = {}, kind = 'init') {
218
+ const fs = fsOf(options);
219
+ const lock = lockPath(project, options);
220
+ const mine = { pid: process.pid, startedAt: clockOf(options)(), token: randomBytes(8).toString('hex'), kind };
221
+ const adopt = (pid, adoptOptions = {}) => {
222
+ if ((readOwner(lock, options) || {}).token !== mine.token) return;
223
+ mine.initPid = pid;
224
+ mine.initPidAt = clockOf(options)();
225
+ mine.initProxy = adoptOptions.proxy === true;
226
+ try {
227
+ writeOwner(lock, mine, options);
228
+ } catch {
229
+ // The lock still holds while this session lives.
230
+ }
231
+ };
232
+ const release = () => {
233
+ // Only remove what is still ours: after a takeover the lock belongs to someone else.
234
+ const owner = readOwner(lock, options);
235
+ if (owner && owner.token === mine.token) fs.rmSync(lock, { recursive: true, force: true });
236
+ };
237
+ for (let attempt = 0; attempt < 2; attempt += 1) {
238
+ try {
239
+ fs.mkdirSync(lock);
240
+ writeOwner(lock, mine, options);
241
+ return { status: 'acquired', adopt, release };
242
+ } catch (error) {
243
+ if (!error || error.code !== 'EEXIST') return { status: 'acquired', adopt: () => {}, release: () => {} };
244
+ }
245
+ if (held(project, lock, options)) return { status: 'busy' };
246
+ if (typeof options.onStale === 'function') {
247
+ try {
248
+ options.onStale();
249
+ } catch {
250
+ // A test hook that throws must not break the lock.
251
+ }
252
+ }
253
+ if (!clearStale(project, lock, options, mine.token)) return { status: 'busy' };
254
+ }
255
+ return { status: 'busy' };
256
+ }
257
+
258
+ /** Whether the init lock of `project` is held right now: a session is writing the index, or CodeGraph still is. */
259
+ function isInitLocked(project, options = {}) {
260
+ try {
261
+ return held(project, lockPath(project, options), options);
262
+ } catch {
263
+ return false;
264
+ }
265
+ }
266
+
267
+ /** Whether an init (as opposed to a sync) is running on `project` right now. Reads only. */
268
+ function isInitRunning(project, options = {}) {
269
+ try {
270
+ const lock = lockPath(project, options);
271
+ if (!held(project, lock, options)) return false;
272
+ // A record that cannot be read yet is someone writing it: counting it as an init only costs a prefetch.
273
+ return (readOwner(lock, options) || {}).kind !== 'sync';
274
+ } catch {
275
+ return false;
276
+ }
277
+ }
278
+
279
+ /** The lock as a caller injects it: one index writer at a time per project. */
280
+ const realInitLock = {
281
+ acquire: (project, options) => tryAcquireInitLock(project, {}, options && options.kind),
282
+ isHeld: (project) => isInitLocked(project),
283
+ isInitRunning: (project) => isInitRunning(project),
284
+ };
285
+
286
+ // ---- The per-project sync lease ----
287
+
288
+ function stateDir(project, options) {
289
+ const base = options && typeof options.dir === 'string' ? options.dir : os.tmpdir();
290
+ return path.join(base, `pcs-sync-${keyFor(project)}`);
291
+ }
292
+
293
+ const leasePath = (state) => path.join(state, 'run');
294
+ const requestsPath = (state) => path.join(state, 'req');
295
+ const gatePath = (state) => path.join(state, 'gate');
296
+
297
+ function leaseIsValid(lease) {
298
+ return Number.isInteger(lease.pid)
299
+ && typeof lease.startedAt === 'number'
300
+ && typeof lease.token === 'string'
301
+ && (lease.cliPid === undefined || Number.isInteger(lease.cliPid))
302
+ && (lease.cliPidAt === undefined || typeof lease.cliPidAt === 'number')
303
+ && (lease.cliProxy === undefined || typeof lease.cliProxy === 'boolean');
304
+ }
305
+
306
+ function readLease(state, options) {
307
+ const fs = fsOf(options);
308
+ try {
309
+ const lease = JSON.parse(fs.readFileSync(path.join(leasePath(state), 'owner.json'), 'utf8'));
310
+ return leaseIsValid(lease) ? lease : undefined;
311
+ } catch {
312
+ return undefined;
313
+ }
314
+ }
315
+
316
+ /** Replaces the record in one step, so a reader sees the old record or the new one, never none. */
317
+ function writeLeaseRecord(state, lease, options) {
318
+ const fs = fsOf(options);
319
+ const draft = path.join(leasePath(state), `owner.${lease.token}.tmp`);
320
+ fs.writeFileSync(draft, JSON.stringify(lease));
321
+ fs.renameSync(draft, path.join(leasePath(state), 'owner.json'));
322
+ }
323
+
324
+ function takeLease(state, lease, options) {
325
+ const fs = fsOf(options);
326
+ fs.mkdirSync(leasePath(state));
327
+ writeLeaseRecord(state, lease, options);
328
+ }
329
+
330
+ /** Whether the command this session started is still writing the index after the session itself is gone. */
331
+ function cliHeld(project, lease, now, options) {
332
+ if (lease.cliPid === undefined || lease.cliPidAt === undefined) return false;
333
+ // A sync of this package cannot last longer than its own timeout: an older record cannot name a live one.
334
+ if (now - lease.cliPidAt > SYNC_LEASE_MAX_AGE_MS) return false;
335
+ if (aliveOf(options)(lease.cliPid)) return true;
336
+ if (lease.cliProxy !== true) return false;
337
+ // On Windows the spawned shell can die while the command goes on. CodeGraph's own writer lock then names the
338
+ // process that really writes the index; until that appears the record speaks for the command it just started.
339
+ const busy = options && typeof options.codegraphBusy === 'function' ? options.codegraphBusy : codegraphWritingIndex;
340
+ if (busy(project)) return true;
341
+ return now - lease.cliPidAt < PROXY_TRUST_MS;
342
+ }
343
+
344
+ /** Whether the lease at `state` belongs to a sync of this project that is still going on. */
345
+ function leaseHeld(state, project, options) {
346
+ const fs = fsOf(options);
347
+ const now = clockOf(options)();
348
+ let directory;
349
+ try {
350
+ directory = fs.statSync(leasePath(state));
351
+ } catch {
352
+ return false;
353
+ }
354
+ const lease = readLease(state, options);
355
+ // No readable record: its owner is probably still writing it, unless it has been this way for a while.
356
+ if (lease === undefined) return now - directory.mtimeMs < UNWRITTEN_GRACE_MS;
357
+ if (now - lease.startedAt <= SYNC_LEASE_MAX_AGE_MS && aliveOf(options)(lease.pid)) return true;
358
+ return cliHeld(project, lease, now, options);
359
+ }
360
+
361
+ /**
362
+ * Restamps this session's record before each run. A run is bounded by its own timeout, so a session that is alive
363
+ * and following up on requests never looks like one that is gone.
364
+ */
365
+ function refreshLease(state, token, options) {
366
+ const lease = readLease(state, options);
367
+ if (lease === undefined || lease.token !== token) return;
368
+ try {
369
+ writeLeaseRecord(state, { pid: process.pid, startedAt: clockOf(options)(), token }, options);
370
+ } catch {
371
+ // The record it had is still there.
372
+ }
373
+ }
374
+
375
+ /** Records the command this session just started, so the lease keeps speaking for it after the session dies. */
376
+ function adoptCli(state, token, pid, spawn, options) {
377
+ const lease = readLease(state, options);
378
+ if (lease === undefined || lease.token !== token) return;
379
+ try {
380
+ writeLeaseRecord(state, { ...lease, cliPid: pid, cliPidAt: clockOf(options)(), cliProxy: Boolean(spawn) && spawn.proxy === true }, options);
381
+ } catch {
382
+ // The session itself still holds the lease; this only covers its death.
383
+ }
384
+ }
385
+
386
+ /** Forgets the command once the run it belonged to came back. */
387
+ function clearCli(state, token, options) {
388
+ const lease = readLease(state, options);
389
+ if (lease === undefined || lease.token !== token) return;
390
+ try {
391
+ writeLeaseRecord(state, { pid: lease.pid, startedAt: lease.startedAt, token: lease.token }, options);
392
+ } catch {
393
+ // The record it had is still there.
394
+ }
395
+ }
396
+
397
+ /**
398
+ * Removes the lease only while the record on disk proves it is still `token`'s. A record that cannot be read is not
399
+ * proof of ownership: another session may be replacing it, or be inside the `mkdir run/` → `owner.json` window of its
400
+ * own takeover, so the folder is left alone. Only a record-less lease older than `UNWRITTEN_GRACE_MS` was abandoned by
401
+ * a session that died, and that one is removed so an interrupted session never wedges the project.
402
+ */
403
+ function releaseLease(state, token, options) {
404
+ const fs = fsOf(options);
405
+ const lease = readLease(state, options);
406
+ if (lease === undefined) {
407
+ let directory;
408
+ try {
409
+ directory = fs.statSync(leasePath(state));
410
+ } catch {
411
+ return; // Nothing to release.
412
+ }
413
+ if (clockOf(options)() - directory.mtimeMs < UNWRITTEN_GRACE_MS) return;
414
+ } else if (lease.token !== token) {
415
+ return; // After a takeover the lease belongs to someone else.
416
+ }
417
+ try {
418
+ fs.rmSync(leasePath(state), { recursive: true, force: true });
419
+ } catch {
420
+ // Leftovers expire.
421
+ }
422
+ }
423
+
424
+ function pendingRequests(state, options) {
425
+ try {
426
+ return fsOf(options).readdirSync(requestsPath(state));
427
+ } catch {
428
+ return [];
429
+ }
430
+ }
431
+
432
+ /** The gate could not be taken (or the state could not hold it), so nothing may be assumed about the coordination. */
433
+ const GATE_UNAVAILABLE = Symbol('gate-unavailable');
434
+
435
+ function pause(ms) {
436
+ return new Promise((resolve) => setTimeout(resolve, ms));
437
+ }
438
+
439
+ /** Runs `action` holding the short per-project mutex that the lease and the pending requests share. */
440
+ async function withGate(state, options, action) {
441
+ const fs = fsOf(options);
442
+ const gate = gatePath(state);
443
+ const deadline = Date.now() + GATE_TIMEOUT_MS;
444
+ for (;;) {
445
+ try {
446
+ fs.mkdirSync(gate);
447
+ break;
448
+ } catch (error) {
449
+ // Anything but a gate another session holds means there is no usable state to coordinate through.
450
+ if (!error || error.code !== 'EEXIST') return GATE_UNAVAILABLE;
451
+ }
452
+ try {
453
+ if (clockOf(options)() - fs.statSync(gate).mtimeMs > GATE_GRACE_MS) {
454
+ fs.rmSync(gate, { recursive: true, force: true });
455
+ continue;
456
+ }
457
+ } catch {
458
+ continue; // It is gone already.
459
+ }
460
+ if (Date.now() > deadline) return GATE_UNAVAILABLE;
461
+ await pause(options && Number.isFinite(options.pollMs) ? options.pollMs : DEFAULT_POLL_MS);
462
+ }
463
+ try {
464
+ return action();
465
+ } finally {
466
+ try {
467
+ fs.rmSync(gate, { recursive: true, force: true });
468
+ } catch {
469
+ // A dead session's gate expires.
470
+ }
471
+ }
472
+ }
473
+
474
+ /**
475
+ * Takes the lease of `state` for this session: now, or after clearing one left by a sync that is really gone.
476
+ * Nothing is cleared unless the gate was taken for real and the lease still looks dead under it, so a live lease is
477
+ * never removed; `unavailable` means the state could not be used at all and no sync may start (fail closed).
478
+ */
479
+ async function claimLease(state, project, token, options) {
480
+ const fs = fsOf(options);
481
+ for (;;) {
482
+ try {
483
+ takeLease(state, { pid: process.pid, startedAt: clockOf(options)(), token }, options);
484
+ return 'acquired';
485
+ } catch (error) {
486
+ if (!error || error.code !== 'EEXIST') return 'unavailable';
487
+ }
488
+ if (leaseHeld(state, project, options)) return 'busy';
489
+ const cleared = await withGate(state, options, () => {
490
+ // Judged again under the gate: another session may have taken the lease since this one looked.
491
+ if (leaseHeld(state, project, options)) return false;
492
+ try {
493
+ fs.rmSync(leasePath(state), { recursive: true, force: true });
494
+ } catch {
495
+ // The owner removed it.
496
+ }
497
+ return true;
498
+ });
499
+ if (cleared === GATE_UNAVAILABLE) return 'unavailable';
500
+ if (cleared === false) return 'busy';
501
+ }
502
+ }
503
+
504
+ /**
505
+ * One extension-started sync per project at a time, and one follow-up per burst of requests that arrived while a run
506
+ * was in progress. The requests of a run are deleted only after it came back, so a runner that dies inside it leaves
507
+ * every pending request for the next session, and the lease is released under the gate only once nothing is pending.
508
+ */
509
+ class FileSyncCoordinator {
510
+ constructor(options = {}) {
511
+ this.options = options || {};
512
+ }
513
+
514
+ async request(project, attempt) {
515
+ const options = this.options;
516
+ const fs = fsOf(options);
517
+ const state = stateDir(project, options);
518
+ const token = randomBytes(8).toString('hex');
519
+ const marker = path.join(requestsPath(state), token);
520
+ try {
521
+ fs.mkdirSync(requestsPath(state), { recursive: true });
522
+ // The request is recorded before the lease is looked at, and stays there until a run that started after it
523
+ // has finished. A session killed mid-sync loses nothing: its demand is still on disk for the next one.
524
+ fs.writeFileSync(marker, '');
525
+ } catch {
526
+ // Fail closed: without this state the package cannot tell whether another session is already syncing.
527
+ return { status: 'unavailable' };
528
+ }
529
+ const deadline = Date.now() + (Number.isFinite(options.requestWaitMs) ? options.requestWaitMs : DEFAULT_REQUEST_WAIT_MS);
530
+ for (;;) {
531
+ // A missing marker means the run that took it has finished: the demand was served, not merely picked up.
532
+ if (!fs.existsSync(marker)) return { status: 'coalesced' };
533
+ if (Date.now() >= deadline) return { status: 'queued' };
534
+ const claimed = await claimLease(state, project, token, options);
535
+ if (claimed === 'unavailable') return { status: 'unavailable' };
536
+ if (claimed === 'acquired') {
537
+ const result = await this.runAsRunner(state, token, attempt);
538
+ if (result.status === 'unavailable') return { status: 'unavailable' };
539
+ if (result.status === 'ran') return { status: 'ran', ok: result.ok };
540
+ // The index is locked by an init: give the lease back and wait for it like every other request.
541
+ await withGate(state, options, () => releaseLease(state, token, options));
542
+ }
543
+ await pause(Number.isFinite(options.pollMs) ? options.pollMs : DEFAULT_POLL_MS);
544
+ }
545
+ }
546
+
547
+ /** Runs the sync once for the requests already waiting, then once more per burst that arrived meanwhile. */
548
+ async runAsRunner(state, token, attempt) {
549
+ const options = this.options;
550
+ try {
551
+ for (;;) {
552
+ const served = await withGate(state, options, () => {
553
+ refreshLease(state, token, options);
554
+ return pendingRequests(state, options);
555
+ });
556
+ if (served === GATE_UNAVAILABLE) return { status: 'unavailable' };
557
+ const result = await attempt((pid, spawn) => adoptCli(state, token, pid, spawn, options));
558
+ if (!result.ran) return { status: 'busy' };
559
+ const more = await withGate(state, options, () => {
560
+ clearCli(state, token, options);
561
+ for (const request of served) {
562
+ try {
563
+ fsOf(options).rmSync(path.join(requestsPath(state), request), { force: true });
564
+ } catch {
565
+ // Gone already.
566
+ }
567
+ }
568
+ if (pendingRequests(state, options).length > 0) return true;
569
+ releaseLease(state, token, options);
570
+ return false;
571
+ });
572
+ if (more === GATE_UNAVAILABLE) {
573
+ // The run happened, but its demand could not be marked as served: the next sync serves it again.
574
+ return { status: 'ran', ok: result.ok };
575
+ }
576
+ if (more !== true) return { status: 'ran', ok: result.ok };
577
+ }
578
+ } finally {
579
+ // A throwing sync still lets the next session in; a lease already released or taken over is left alone.
580
+ releaseLease(state, token, options);
581
+ }
582
+ }
583
+ }
584
+
585
+ /** The real coordinator: one per process is enough, the state is on disk. */
586
+ function syncLease(options = {}) {
587
+ return new FileSyncCoordinator(options);
588
+ }
589
+
590
+ const realSyncLease = syncLease();
591
+
592
+ module.exports = {
593
+ INIT_TIMEOUT_MS,
594
+ SYNC_TIMEOUT_MS,
595
+ LOCK_MAX_AGE_MS,
596
+ SYNC_LEASE_MAX_AGE_MS,
597
+ UNWRITTEN_GRACE_MS,
598
+ PROXY_TRUST_MS,
599
+ DEFAULT_REQUEST_WAIT_MS,
600
+ codegraphWritingIndex,
601
+ tryAcquireInitLock,
602
+ isInitLocked,
603
+ isInitRunning,
604
+ realInitLock,
605
+ syncLease,
606
+ realSyncLease,
607
+ };