chompyy 0.5.0 → 0.6.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 (154) hide show
  1. package/README.md +11 -0
  2. package/dist/agentlimits.js +77 -0
  3. package/dist/agentusage.js +96 -0
  4. package/dist/appstate.js +63 -3
  5. package/dist/away.js +44 -5
  6. package/dist/blueprint.js +3 -7
  7. package/dist/board.js +1 -0
  8. package/dist/cli.js +263 -5
  9. package/dist/codexquota.js +106 -0
  10. package/dist/codexusage.js +10 -0
  11. package/dist/config.js +2 -0
  12. package/dist/context.js +30 -0
  13. package/dist/costs.js +1 -0
  14. package/dist/demon.js +20 -0
  15. package/dist/label.js +33 -0
  16. package/dist/menu.js +17 -0
  17. package/dist/nightcap.js +60 -0
  18. package/dist/nudge.js +47 -18
  19. package/dist/pacing.js +16 -1
  20. package/dist/questions.js +71 -0
  21. package/dist/recap.js +74 -0
  22. package/dist/receipt.js +48 -0
  23. package/dist/recipe.js +79 -0
  24. package/dist/stamps.js +14 -0
  25. package/dist/triggers.js +5 -0
  26. package/dist/usage.js +21 -1
  27. package/dist/vendor/codeburn/antigravity.js +309 -0
  28. package/dist/vendor/codeburn/codex.js +429 -0
  29. package/dist/vendor/codeburn/copilot.js +292 -0
  30. package/dist/vendor/codeburn/gemini.js +195 -0
  31. package/dist/vendor/codeburn/grokbot.js +182 -0
  32. package/dist/vendor/codeburn/kimi.js +178 -0
  33. package/dist/vendor/codeburn/shims/chalk.js +14 -0
  34. package/dist/vendor/codeburn/shims/strip-ansi.js +6 -0
  35. package/dist/vendor/codeburn/src/act/backup.js +83 -0
  36. package/dist/vendor/codeburn/src/act/model-defaults.js +151 -0
  37. package/dist/vendor/codeburn/src/act/types.js +37 -0
  38. package/dist/vendor/codeburn/src/bash-utils.js +204 -0
  39. package/dist/vendor/codeburn/src/behavioral-weight.js +47 -0
  40. package/dist/vendor/codeburn/src/cache-dir.js +26 -0
  41. package/dist/vendor/codeburn/src/cache-refresh-lock.js +543 -0
  42. package/dist/vendor/codeburn/src/cache-sweep.js +67 -0
  43. package/dist/vendor/codeburn/src/classifier.js +209 -0
  44. package/dist/vendor/codeburn/src/claude-identity.js +223 -0
  45. package/dist/vendor/codeburn/src/codex-cache.js +377 -0
  46. package/dist/vendor/codeburn/src/codex-fork-replay.js +232 -0
  47. package/dist/vendor/codeburn/src/codex-jsonl-fields.js +99 -0
  48. package/dist/vendor/codeburn/src/codex-session-index.js +113 -0
  49. package/dist/vendor/codeburn/src/codex-throughput.js +544 -0
  50. package/dist/vendor/codeburn/src/compare-stats.js +405 -0
  51. package/dist/vendor/codeburn/src/config.js +145 -0
  52. package/dist/vendor/codeburn/src/content-utils.js +56 -0
  53. package/dist/vendor/codeburn/src/context-tree-codex.js +329 -0
  54. package/dist/vendor/codeburn/src/context-tree.js +664 -0
  55. package/dist/vendor/codeburn/src/copilot-aiu.js +16 -0
  56. package/dist/vendor/codeburn/src/currency.js +189 -0
  57. package/dist/vendor/codeburn/src/cursor-cache.js +238 -0
  58. package/dist/vendor/codeburn/src/cursor-import.js +402 -0
  59. package/dist/vendor/codeburn/src/cursor-sync.js +256 -0
  60. package/dist/vendor/codeburn/src/daily-cache.js +2036 -0
  61. package/dist/vendor/codeburn/src/data/litellm-snapshot.json +1 -0
  62. package/dist/vendor/codeburn/src/data/pricing-fallback.json +1 -0
  63. package/dist/vendor/codeburn/src/day-aggregator.js +327 -0
  64. package/dist/vendor/codeburn/src/editor-data-dir.js +11 -0
  65. package/dist/vendor/codeburn/src/fetch-utils.js +18 -0
  66. package/dist/vendor/codeburn/src/format.js +118 -0
  67. package/dist/vendor/codeburn/src/fs-utils.js +270 -0
  68. package/dist/vendor/codeburn/src/git-origin.js +334 -0
  69. package/dist/vendor/codeburn/src/granular-history.js +328 -0
  70. package/dist/vendor/codeburn/src/hermes-session-ledger.js +512 -0
  71. package/dist/vendor/codeburn/src/launcher-homes.js +142 -0
  72. package/dist/vendor/codeburn/src/live-sessions.js +358 -0
  73. package/dist/vendor/codeburn/src/math-utils.js +8 -0
  74. package/dist/vendor/codeburn/src/menubar-json.js +294 -0
  75. package/dist/vendor/codeburn/src/models.js +1879 -0
  76. package/dist/vendor/codeburn/src/optimize-one-hour-cache.js +92 -0
  77. package/dist/vendor/codeburn/src/optimize.js +4110 -0
  78. package/dist/vendor/codeburn/src/parse-workers.js +219 -0
  79. package/dist/vendor/codeburn/src/parser.js +6953 -0
  80. package/dist/vendor/codeburn/src/path-privacy.js +26 -0
  81. package/dist/vendor/codeburn/src/plans.js +135 -0
  82. package/dist/vendor/codeburn/src/pr-signals.js +132 -0
  83. package/dist/vendor/codeburn/src/project-filter-warnings.js +33 -0
  84. package/dist/vendor/codeburn/src/provider-issues.js +30 -0
  85. package/dist/vendor/codeburn/src/providers/amp.js +286 -0
  86. package/dist/vendor/codeburn/src/providers/antigravity.js +1731 -0
  87. package/dist/vendor/codeburn/src/providers/claude.js +551 -0
  88. package/dist/vendor/codeburn/src/providers/cline-cli.js +401 -0
  89. package/dist/vendor/codeburn/src/providers/cline.js +63 -0
  90. package/dist/vendor/codeburn/src/providers/codebuff.js +336 -0
  91. package/dist/vendor/codeburn/src/providers/codewhale.js +442 -0
  92. package/dist/vendor/codeburn/src/providers/codex.js +1720 -0
  93. package/dist/vendor/codeburn/src/providers/command-code.js +196 -0
  94. package/dist/vendor/codeburn/src/providers/copilot.js +3278 -0
  95. package/dist/vendor/codeburn/src/providers/crush.js +226 -0
  96. package/dist/vendor/codeburn/src/providers/cursor-agent.js +837 -0
  97. package/dist/vendor/codeburn/src/providers/cursor.js +1163 -0
  98. package/dist/vendor/codeburn/src/providers/devin.js +569 -0
  99. package/dist/vendor/codeburn/src/providers/droid.js +324 -0
  100. package/dist/vendor/codeburn/src/providers/dsh.js +690 -0
  101. package/dist/vendor/codeburn/src/providers/forge.js +245 -0
  102. package/dist/vendor/codeburn/src/providers/gemini.js +230 -0
  103. package/dist/vendor/codeburn/src/providers/goose.js +252 -0
  104. package/dist/vendor/codeburn/src/providers/grok.js +581 -0
  105. package/dist/vendor/codeburn/src/providers/grokbot.js +290 -0
  106. package/dist/vendor/codeburn/src/providers/hermes.js +771 -0
  107. package/dist/vendor/codeburn/src/providers/ibm-bob.js +53 -0
  108. package/dist/vendor/codeburn/src/providers/index.js +360 -0
  109. package/dist/vendor/codeburn/src/providers/kilo-code.js +50 -0
  110. package/dist/vendor/codeburn/src/providers/kimi.js +363 -0
  111. package/dist/vendor/codeburn/src/providers/kimicode.js +402 -0
  112. package/dist/vendor/codeburn/src/providers/kiro.js +1174 -0
  113. package/dist/vendor/codeburn/src/providers/lingtai-tui.js +372 -0
  114. package/dist/vendor/codeburn/src/providers/mistral-vibe-unified.js +236 -0
  115. package/dist/vendor/codeburn/src/providers/mistral-vibe.js +405 -0
  116. package/dist/vendor/codeburn/src/providers/mux.js +242 -0
  117. package/dist/vendor/codeburn/src/providers/open-design.js +217 -0
  118. package/dist/vendor/codeburn/src/providers/openclaude.js +309 -0
  119. package/dist/vendor/codeburn/src/providers/openclaw.js +442 -0
  120. package/dist/vendor/codeburn/src/providers/opencode-file-parser.js +131 -0
  121. package/dist/vendor/codeburn/src/providers/opencode.js +91 -0
  122. package/dist/vendor/codeburn/src/providers/pi.js +429 -0
  123. package/dist/vendor/codeburn/src/providers/quickdesk.js +491 -0
  124. package/dist/vendor/codeburn/src/providers/qwen.js +193 -0
  125. package/dist/vendor/codeburn/src/providers/session-message.js +118 -0
  126. package/dist/vendor/codeburn/src/providers/sqlite-session-parser.js +457 -0
  127. package/dist/vendor/codeburn/src/providers/types.js +5 -0
  128. package/dist/vendor/codeburn/src/providers/vercel-gateway.js +135 -0
  129. package/dist/vendor/codeburn/src/providers/vscode-cline-parser.js +212 -0
  130. package/dist/vendor/codeburn/src/providers/warp.js +575 -0
  131. package/dist/vendor/codeburn/src/providers/zcode.js +249 -0
  132. package/dist/vendor/codeburn/src/providers/zed.js +187 -0
  133. package/dist/vendor/codeburn/src/providers/zerostack.js +139 -0
  134. package/dist/vendor/codeburn/src/quota/antigravity.js +310 -0
  135. package/dist/vendor/codeburn/src/quota/claude.js +244 -0
  136. package/dist/vendor/codeburn/src/quota/cursor.js +301 -0
  137. package/dist/vendor/codeburn/src/quota/security.js +299 -0
  138. package/dist/vendor/codeburn/src/quota/types.js +1 -0
  139. package/dist/vendor/codeburn/src/scan-facts.js +99 -0
  140. package/dist/vendor/codeburn/src/session-cache.js +3040 -0
  141. package/dist/vendor/codeburn/src/session-count-label.js +14 -0
  142. package/dist/vendor/codeburn/src/session-output.js +139 -0
  143. package/dist/vendor/codeburn/src/session-population.js +30 -0
  144. package/dist/vendor/codeburn/src/sessions-report.js +1342 -0
  145. package/dist/vendor/codeburn/src/sqlite.js +528 -0
  146. package/dist/vendor/codeburn/src/sync/otlp.js +420 -0
  147. package/dist/vendor/codeburn/src/telemetry-snapshot.js +244 -0
  148. package/dist/vendor/codeburn/src/token-estimate.js +5 -0
  149. package/dist/vendor/codeburn/src/types.js +16 -0
  150. package/dist/vendor/codeburn/src/work-units.js +126 -0
  151. package/dist/vendor/codeburn/src/workflow-insights.js +228 -0
  152. package/dist/vendor/codeburn/src/wsl.js +198 -0
  153. package/dist/vendor/codeburn/src/yield.js +666 -0
  154. package/package.json +1 -1
@@ -0,0 +1,47 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ // Behavioral weight — the single definition of which served calls count as
3
+ // requests. A copilot shutdown rollup, synthesized residual, or store row
4
+ // paired with its per-turn call (`supplementaryAccounting`, assigned at serve
5
+ // time) carries real tokens and cost but is not a distinct behavioral
6
+ // request. Hermes observation-time deltas persist the same flag. Every
7
+ // user-visible calls/turns counter weighs calls through these helpers so no
8
+ // surface can disagree with the session summaries or the sealed daily
9
+ // history. Token and cost sums intentionally keep every call —
10
+ // supplementary accounting must never be filtered out, only weightless.
11
+ /** True when the call is a real request; false for supplementary accounting (weight 0). */
12
+ export function isBehavioralCall(call) {
13
+ return !call.supplementaryAccounting;
14
+ }
15
+ /// How many requests one served call stands for. Normally 1. A provider that
16
+ /// only publishes DAILY AGGREGATES (Vercel AI Gateway's /v1/report, one row per
17
+ /// day+model carrying `request_count`) has no per-request record to yield, so
18
+ /// its single call carries the count instead — synthesizing N empty calls would
19
+ /// fabricate rows in every session drill-down and scale with the user's traffic.
20
+ /// Cost and tokens stay on the one call, so only request counters move.
21
+ export function behavioralCallWeight(call) {
22
+ if (call.supplementaryAccounting)
23
+ return 0;
24
+ const count = call.requestCount;
25
+ return count != null && Number.isFinite(count) && count > 0 ? Math.floor(count) : 1;
26
+ }
27
+ /** Number of real requests among a turn's calls. */
28
+ export function behavioralCallCount(calls) {
29
+ let n = 0;
30
+ for (const call of calls)
31
+ n += behavioralCallWeight(call);
32
+ return n;
33
+ }
34
+ /** True when the turn holds at least one behavioral call — supplementary-only turns add no turn/edit weight. */
35
+ export function isBehavioralTurn(turn) {
36
+ if (turn.projectContinuation)
37
+ return false;
38
+ return turn.assistantCalls.some(call => !call.supplementaryAccounting);
39
+ }
40
+ /** Number of behavioral turns (weightless accounting containers excluded). */
41
+ export function behavioralTurnCount(turns) {
42
+ let n = 0;
43
+ for (const turn of turns)
44
+ if (isBehavioralTurn(turn))
45
+ n++;
46
+ return n;
47
+ }
@@ -0,0 +1,26 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ import { readFile } from 'fs/promises';
3
+ import { homedir } from 'os';
4
+ import { join } from 'path';
5
+ /**
6
+ * Resolve CodeBurn's shared cache directory at call time.
7
+ *
8
+ * Reading the environment on every call matters for embedded consumers and
9
+ * tests that change CODEBURN_CACHE_DIR after importing the CLI modules.
10
+ */
11
+ export function getCodeburnCacheDir() {
12
+ const override = process.env['CODEBURN_CACHE_DIR'];
13
+ return override?.trim() ? override : join(homedir(), '.cache', 'codeburn');
14
+ }
15
+ /** Providers CodeBurn no longer reads. Their session cache sections and daily
16
+ * history slices are dropped on load, so a removed tool leaves nothing behind. */
17
+ export const RETIRED_PROVIDER_NAMES = new Set(['roo-code']);
18
+ export async function readExistingTextFile(path) {
19
+ try {
20
+ return { status: 'ok', text: await readFile(path, 'utf-8') };
21
+ }
22
+ catch (err) {
23
+ const code = err && typeof err === 'object' && 'code' in err ? err.code : undefined;
24
+ return { status: code === 'ENOENT' ? 'absent' : 'unreadable' };
25
+ }
26
+ }
@@ -0,0 +1,543 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ import { createHash, randomBytes } from 'crypto';
3
+ import { existsSync, readFileSync, unlinkSync } from 'fs';
4
+ import { mkdir, open, readFile, rename, stat, unlink, utimes, writeFile } from 'fs/promises';
5
+ import { join } from 'path';
6
+ import { getCodeburnCacheDir } from './cache-dir.js';
7
+ const LOCK_FILE = 'session-refresh.lock';
8
+ const DEFAULT_HEARTBEAT_MS = 10_000;
9
+ const DEFAULT_STALE_MS = 90_000;
10
+ // A waiter that gives up before the stale gate opens can NEVER recover an
11
+ // abandoned lock, so an abandoned lock livelocks every later process: each one
12
+ // burns its whole wait, times out, serves read-only, and the leftover survives
13
+ // (#1117). The default is therefore derived from staleMs rather than fixed, so
14
+ // the two can never drift back out of order. The common abandoned case does not
15
+ // wait this long anyway - a dead holder's pid is detected on the first poll.
16
+ const DEFAULT_WAIT_MARGIN_MS = 30_000;
17
+ const DEFAULT_POLL_MS = 100;
18
+ const WINDOWS_RETRIES = 3;
19
+ const defaultClock = {
20
+ monotonicNow: () => Number(process.hrtime.bigint()) / 1_000_000,
21
+ wallNow: () => Date.now(),
22
+ };
23
+ function delay(ms) {
24
+ return new Promise(resolve => { setTimeout(resolve, ms); });
25
+ }
26
+ // Mirrors session-cache.ts's hydrating.lock probe. Our own pid never counts as a
27
+ // foreign holder. EPERM means the pid exists but belongs to another user - still
28
+ // alive. Windows supports signal 0 as an existence test the same way.
29
+ //
30
+ // A false "alive" (the holder died and an unrelated process inherited its pid)
31
+ // only delays recovery to the age gate. A false "dead" would be the dangerous
32
+ // direction, and needs the lock file to have been written by a process on
33
+ // another host - i.e. a cache dir on a network share, which nothing supports.
34
+ function pidLooksAlive(pid) {
35
+ if (!Number.isInteger(pid) || pid <= 0 || pid === process.pid)
36
+ return false;
37
+ try {
38
+ process.kill(pid, 0);
39
+ return true;
40
+ }
41
+ catch (err) {
42
+ return err.code === 'EPERM';
43
+ }
44
+ }
45
+ // Paths of locks this process currently owns, for the signal handler. The
46
+ // in-process single-flight is per lock path, so independent cache transactions
47
+ // may legitimately hold different locks at the same time.
48
+ const ownedLockPaths = new Set();
49
+ // Synchronous variant for the signal path: a handler can't await, so read +
50
+ // unlink synchronously. Only unlinks a lock we actually own.
51
+ function removeOurLockSync() {
52
+ for (const lockPath of [...ownedLockPaths]) {
53
+ try {
54
+ const parsed = JSON.parse(readFileSync(lockPath, 'utf-8'));
55
+ if (parsed?.pid === process.pid)
56
+ unlinkSync(lockPath);
57
+ }
58
+ catch { /* best-effort; nothing to clean or already gone */ }
59
+ }
60
+ }
61
+ /** Release every warm-refresh lock owned by this process before a caller uses
62
+ * `process.exit()`. Signal handlers already cover SIGINT/SIGTERM; the TUI's q
63
+ * path exits directly after restoring the terminal and needs the same cleanup. */
64
+ export function releaseOwnedRefreshLocksForExit() {
65
+ removeOurLockSync();
66
+ }
67
+ // Arm once, only while we hold the lock: on a catchable termination (Ctrl-C, or
68
+ // the menubar/desktop watchdog's SIGTERM) clean our lock before dying so a
69
+ // killed refresh leaves no leftover. SIGKILL can't be caught, so that path still
70
+ // relies on the waiter's dead-pid takeover. process.once + re-raise preserves
71
+ // the default exit and any other listener. Mirrors session-cache.ts.
72
+ let signalCleanupArmed = false;
73
+ function armSignalCleanup() {
74
+ if (signalCleanupArmed)
75
+ return;
76
+ signalCleanupArmed = true;
77
+ for (const sig of ['SIGINT', 'SIGTERM']) {
78
+ process.once(sig, () => {
79
+ removeOurLockSync();
80
+ process.kill(process.pid, sig);
81
+ });
82
+ }
83
+ }
84
+ function isBusyError(err) {
85
+ const code = err?.code;
86
+ return code === 'EPERM' || code === 'EBUSY';
87
+ }
88
+ function isExistsError(err) {
89
+ return err?.code === 'EEXIST';
90
+ }
91
+ function isMissingError(err) {
92
+ return err?.code === 'ENOENT';
93
+ }
94
+ async function retryWindowsMutation(operation, sleep) {
95
+ for (let attempt = 0; attempt < WINDOWS_RETRIES; attempt++) {
96
+ try {
97
+ await operation();
98
+ return true;
99
+ }
100
+ catch (err) {
101
+ if (isMissingError(err))
102
+ return true;
103
+ if (!isBusyError(err) || attempt === WINDOWS_RETRIES - 1)
104
+ return false;
105
+ await sleep(10 * (attempt + 1));
106
+ }
107
+ }
108
+ return false;
109
+ }
110
+ // The directory entry becomes visible before the awaited body write, so the
111
+ // file is briefly observable at zero bytes. Deliberately left as is: a corrupt
112
+ // body is only ever recovered once its mtime is older than staleMs, and this
113
+ // window is milliseconds wide on a file whose mtime is by definition now, so
114
+ // no observer can reach the age gate through it. Closing it would mean
115
+ // link()ing a temp file into place, which is not portable to filesystems
116
+ // without hard links.
117
+ async function createExclusive(path, body) {
118
+ try {
119
+ const handle = await open(path, 'wx', 0o600);
120
+ try {
121
+ await handle.writeFile(body, { encoding: 'utf-8' });
122
+ }
123
+ finally {
124
+ await handle.close();
125
+ }
126
+ return 'created';
127
+ }
128
+ catch (err) {
129
+ return isExistsError(err) ? 'exists' : 'unavailable';
130
+ }
131
+ }
132
+ async function observe(path) {
133
+ // Exclusive create exposes the directory entry just before its small body is
134
+ // written, and heartbeats of OLDER codeburn versions sharing this cache dir
135
+ // still rewrite the body in place (truncating it briefly); this version's
136
+ // heartbeat replaces atomically. Treat that bounded transition as
137
+ // contention, not broken infrastructure.
138
+ let sawChange = false;
139
+ let corrupt = null;
140
+ for (let attempt = 0; attempt < 3; attempt++) {
141
+ try {
142
+ const before = await stat(path);
143
+ const raw = await readFile(path, 'utf-8');
144
+ const after = await stat(path);
145
+ if (before.mtimeMs !== after.mtimeMs || before.size !== after.size) {
146
+ sawChange = true;
147
+ await delay(1);
148
+ continue;
149
+ }
150
+ const digest = createHash('sha1').update(raw).digest('hex');
151
+ // A body that is valid JSON of the wrong shape is corrupt like any other,
152
+ // including one written by a future version with a different record
153
+ // shape. That is safe precisely because staleness is never waived: a
154
+ // foreign version's LIVE lock keeps its mtime fresh through its own
155
+ // heartbeat, so it is never taken — both versions just degrade to the
156
+ // read-only path. Only an abandoned one is recovered, and a lock record
157
+ // is per-run state with nothing in it worth preserving.
158
+ let parsed;
159
+ try {
160
+ parsed = JSON.parse(raw);
161
+ }
162
+ catch {
163
+ parsed = undefined;
164
+ }
165
+ if (parsed && typeof parsed.pid === 'number' && typeof parsed.token === 'string' && typeof parsed.at === 'number') {
166
+ return { record: { pid: parsed.pid, token: parsed.token, at: parsed.at }, mtimeMs: after.mtimeMs, digest };
167
+ }
168
+ // Keep the most recent corrupt read. It is not evidence of stability on
169
+ // its own: tryTakeover re-observes under the guard and compares with
170
+ // sameObservation before acting, so stability is proven there, not here.
171
+ corrupt = { record: null, mtimeMs: after.mtimeMs, digest };
172
+ }
173
+ catch (err) {
174
+ if (isMissingError(err))
175
+ return 'missing';
176
+ const code = err?.code;
177
+ if (code === 'EACCES' || code === 'EPERM')
178
+ return 'unavailable';
179
+ }
180
+ await delay(1);
181
+ }
182
+ // Contention outranks corruption: a body seen mid-rewrite is a live owner's,
183
+ // and the caller must poll rather than treat it as recoverable.
184
+ if (sawChange)
185
+ return 'changing';
186
+ return corrupt ?? 'unavailable';
187
+ }
188
+ function sameObservation(a, b) {
189
+ // A corrupt body and an owned one are never "the same observation", even
190
+ // though `a.record?.token === b.record?.token` cannot tell them apart once
191
+ // both sides are corrupt. Compare that boundary explicitly, then require the
192
+ // bytes themselves to match, so "unchanged" survives a coarse mtime.
193
+ if ((a.record === null) !== (b.record === null))
194
+ return false;
195
+ return a.record?.token === b.record?.token && a.mtimeMs === b.mtimeMs && a.digest === b.digest;
196
+ }
197
+ const singleFlightTails = new Map();
198
+ async function enterSingleFlight(lockPath) {
199
+ const previous = singleFlightTails.get(lockPath) ?? Promise.resolve();
200
+ let leave;
201
+ const current = new Promise(resolve => { leave = resolve; });
202
+ singleFlightTails.set(lockPath, current);
203
+ await previous;
204
+ return () => {
205
+ leave();
206
+ if (singleFlightTails.get(lockPath) === current)
207
+ singleFlightTails.delete(lockPath);
208
+ };
209
+ }
210
+ /**
211
+ * Strict gate for the warm session-cache read/reconcile/parse/save transaction.
212
+ * Lock ordering, when the daily-cache follow-up lands, is daily → session.
213
+ */
214
+ export async function acquireCacheRefreshLock(options = {}) {
215
+ const cacheDir = options.cacheDir ?? getCodeburnCacheDir();
216
+ const lockFile = options.lockFile ?? LOCK_FILE;
217
+ // Never allow a caller-controlled path to escape cacheDir or collide with
218
+ // the takeover suffix. All current callers use fixed names or a hex digest.
219
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,200}$/.test(lockFile) || lockFile.endsWith('.takeover')) {
220
+ return { outcome: 'unavailable' };
221
+ }
222
+ const lockPath = join(cacheDir, lockFile);
223
+ const takeoverPath = join(cacheDir, `${lockFile}.takeover`);
224
+ const leaveSingleFlight = await enterSingleFlight(lockPath);
225
+ let ownsSingleFlight = true;
226
+ const leave = () => {
227
+ if (!ownsSingleFlight)
228
+ return;
229
+ ownsSingleFlight = false;
230
+ leaveSingleFlight();
231
+ };
232
+ const clock = options.clock ?? defaultClock;
233
+ const heartbeatMs = options.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;
234
+ const staleMs = options.staleMs ?? DEFAULT_STALE_MS;
235
+ const waitMs = options.waitMs ?? staleMs + DEFAULT_WAIT_MARGIN_MS;
236
+ const pollMs = options.pollMs ?? DEFAULT_POLL_MS;
237
+ const sleep = options.sleep ?? delay;
238
+ const token = randomBytes(16).toString('hex');
239
+ const body = () => JSON.stringify({ pid: process.pid, token, at: clock.wallNow() });
240
+ // In-process serializer for every operation that takes the takeover guard on
241
+ // behalf of THIS owner (heartbeat tick, publication fence). Without it the
242
+ // fence can observe its own heartbeat's guard file and read "guard held" as
243
+ // "displaced", aborting a legitimate publication — fail-safe but it throws
244
+ // away the parse the lock exists to protect. Cross-process semantics are
245
+ // untouched: the guard file still arbitrates between processes.
246
+ let ownerOpTail = Promise.resolve();
247
+ const serializeOwnerOp = (fn) => {
248
+ const next = ownerOpTail.then(fn);
249
+ ownerOpTail = next.catch(() => undefined);
250
+ return next;
251
+ };
252
+ // An abandoned lock is one whose heartbeat has FROZEN - mtime stops advancing
253
+ // the moment the holder dies or is displaced, and a live holder rewrites it
254
+ // every heartbeatMs - OR whose recorded holder pid is gone. The pid check is
255
+ // what turns a SIGKILLed holder from a full staleMs stall into a one-poll
256
+ // recovery; the age check still covers every holder we cannot probe (a corrupt
257
+ // body, a future version's record shape, a holder on another host).
258
+ //
259
+ // A LIVE holder is never abandoned by either clause, which is the whole safety
260
+ // argument: its heartbeat keeps the mtime inside staleMs and its pid answers
261
+ // signal 0. Our own pid is treated as alive so a leaked in-process handle is
262
+ // never stolen from either. Callers re-observe under the takeover guard and
263
+ // require the bytes to be unchanged before acting on this.
264
+ const abandoned = (observation) => {
265
+ if (Math.max(0, clock.wallNow() - observation.mtimeMs) > staleMs)
266
+ return true;
267
+ const pid = observation.record?.pid;
268
+ return pid !== undefined && pid !== process.pid && !pidLooksAlive(pid);
269
+ };
270
+ const acquireTakeoverGuard = async () => {
271
+ const created = await createExclusive(takeoverPath, body());
272
+ if (created !== 'exists')
273
+ return created;
274
+ const staleGuard = await observe(takeoverPath);
275
+ if (staleGuard === 'missing')
276
+ return createExclusive(takeoverPath, body());
277
+ if (staleGuard === 'changing')
278
+ return 'exists';
279
+ if (staleGuard === 'unavailable')
280
+ return 'unavailable';
281
+ // Same abandonment test as the primary lock: a holder killed while it held
282
+ // the guard would otherwise block every takeover for a full staleMs and
283
+ // defeat the dead-pid fast path on the lock itself.
284
+ if (!abandoned(staleGuard))
285
+ return 'exists';
286
+ const reverified = await observe(takeoverPath);
287
+ if (reverified === 'missing')
288
+ return createExclusive(takeoverPath, body());
289
+ if (reverified === 'changing')
290
+ return 'exists';
291
+ if (reverified === 'unavailable')
292
+ return 'unavailable';
293
+ if (!sameObservation(staleGuard, reverified))
294
+ return 'exists';
295
+ if (!await retryWindowsMutation(() => unlink(takeoverPath), sleep))
296
+ return 'unavailable';
297
+ return createExclusive(takeoverPath, body());
298
+ };
299
+ const removeIfOwned = async () => {
300
+ // A contender holds the takeover guard only for milliseconds at a time;
301
+ // retry briefly rather than abandoning our lock to 90s stale-timeout,
302
+ // which would stall every waiting process for that long.
303
+ let guard = 'exists';
304
+ for (let attempt = 0; attempt < 20 && guard !== 'created'; attempt++) {
305
+ guard = await acquireTakeoverGuard();
306
+ if (guard === 'unavailable')
307
+ return false;
308
+ if (guard !== 'created')
309
+ await sleep(pollMs);
310
+ }
311
+ if (guard !== 'created')
312
+ return false;
313
+ try {
314
+ const current = await observe(lockPath);
315
+ if (current === 'missing')
316
+ return true;
317
+ if (current === 'changing')
318
+ return false;
319
+ if (current === 'unavailable')
320
+ return false;
321
+ if (current.record?.token !== token)
322
+ return true;
323
+ return retryWindowsMutation(() => unlink(lockPath), sleep);
324
+ }
325
+ finally {
326
+ await retryWindowsMutation(() => unlink(takeoverPath), sleep);
327
+ }
328
+ };
329
+ const verifyStillOwner = () => serializeOwnerOp(async () => {
330
+ const guard = await acquireTakeoverGuard();
331
+ if (guard !== 'created')
332
+ return false;
333
+ try {
334
+ const current = await observe(lockPath);
335
+ return current !== 'missing' && current !== 'changing' && current !== 'unavailable' && current.record?.token === token;
336
+ }
337
+ finally {
338
+ await retryWindowsMutation(() => unlink(takeoverPath), sleep);
339
+ }
340
+ });
341
+ const makeHandle = () => {
342
+ let released = false;
343
+ let heartbeatRunning = false;
344
+ ownedLockPaths.add(lockPath);
345
+ armSignalCleanup();
346
+ // One tick at a time, counted from when it is queued, not when it runs:
347
+ // an interval that fires faster than a tick completes would otherwise
348
+ // pile ticks up in the serializer, and the fence waits behind all of them.
349
+ const heartbeat = setInterval(() => {
350
+ if (released || heartbeatRunning)
351
+ return;
352
+ heartbeatRunning = true;
353
+ void serializeOwnerOp(async () => {
354
+ if (released) {
355
+ heartbeatRunning = false;
356
+ return;
357
+ }
358
+ const guard = await acquireTakeoverGuard();
359
+ if (guard !== 'created') {
360
+ heartbeatRunning = false;
361
+ return;
362
+ }
363
+ try {
364
+ const current = await observe(lockPath);
365
+ if (current === 'missing' || current === 'changing' || current === 'unavailable')
366
+ return;
367
+ // A corrupt body is NOT ours to rewrite, even though no parseable
368
+ // token contradicts us. Holding the takeover guard excludes the other
369
+ // guard-takers, but NOT createExclusive, which publishes a directory
370
+ // entry before its body — so an unparseable body may be a successor's
371
+ // lock a millisecond from being written, or a foreign version's whose
372
+ // record shape we cannot read. Stamping our token over it made this
373
+ // process an owner again after it had been legitimately replaced:
374
+ // verifyStillOwner then answered true for a displaced writer, and
375
+ // release()'s removeIfOwned deleted the live successor's lock.
376
+ //
377
+ // So a body we cannot prove is ours ends our ownership. The mtime
378
+ // stops advancing, the fence refuses to publish (the parse is
379
+ // discarded, which is the fail-safe direction), and a successor
380
+ // recovers the lock one staleMs later through the age gate. Losing a
381
+ // parse is the correct price for never having two owners.
382
+ if (current.record === null || current.record.token !== token)
383
+ return;
384
+ // Atomic replace: a truncate-in-place rewrite here exposed every
385
+ // reader to an empty or partial body for the width of the write
386
+ // (#904). rename() swaps the directory entry whole, so a reader sees
387
+ // either the previous body or the next one, never a torn one. The
388
+ // temp name is deterministic per lock: there is one owner at a time,
389
+ // so a crash's leftover is simply overwritten by the next tick.
390
+ const nextPath = lockPath + '.hb-next';
391
+ await writeFile(nextPath, body(), { encoding: 'utf-8', mode: 0o600 });
392
+ try {
393
+ await rename(nextPath, lockPath);
394
+ }
395
+ catch (err) {
396
+ // Windows can refuse the replace while an unrelated open handle
397
+ // lingers. Skipping the tick is safe: the mtime simply does not
398
+ // advance this round, and staleMs is nine heartbeats wide.
399
+ await unlink(nextPath).catch(() => { });
400
+ if (!isBusyError(err))
401
+ throw err;
402
+ return;
403
+ }
404
+ const now = new Date(clock.wallNow());
405
+ await utimes(lockPath, now, now);
406
+ }
407
+ catch { /* verify/release will turn displacement or I/O failure into a closed gate */ }
408
+ finally {
409
+ await retryWindowsMutation(() => unlink(takeoverPath), sleep);
410
+ heartbeatRunning = false;
411
+ }
412
+ });
413
+ }, heartbeatMs);
414
+ heartbeat.unref();
415
+ return {
416
+ token,
417
+ verifyStillOwner,
418
+ release: async () => {
419
+ if (released)
420
+ return;
421
+ released = true;
422
+ clearInterval(heartbeat);
423
+ try {
424
+ while (heartbeatRunning)
425
+ await sleep(1);
426
+ await removeIfOwned();
427
+ }
428
+ finally {
429
+ ownedLockPaths.delete(lockPath);
430
+ leave();
431
+ }
432
+ },
433
+ };
434
+ };
435
+ const tryCreateOwner = async () => {
436
+ const result = await createExclusive(lockPath, body());
437
+ if (result === 'created')
438
+ return { outcome: 'acquired', handle: makeHandle() };
439
+ if (result === 'unavailable')
440
+ return { outcome: 'unavailable' };
441
+ return null;
442
+ };
443
+ const tryTakeover = async (stale) => {
444
+ const guard = await acquireTakeoverGuard();
445
+ if (guard === 'unavailable')
446
+ return { outcome: 'unavailable' };
447
+ if (guard === 'exists')
448
+ return null;
449
+ try {
450
+ const current = await observe(lockPath);
451
+ if (current === 'unavailable')
452
+ return { outcome: 'unavailable' };
453
+ if (current === 'changing')
454
+ return null;
455
+ if (current === 'missing' || !sameObservation(stale, current))
456
+ return null;
457
+ if (!abandoned(current))
458
+ return null;
459
+ if (!await retryWindowsMutation(() => unlink(lockPath), sleep))
460
+ return { outcome: 'unavailable' };
461
+ // Publish the successor while the takeover guard is still canonical.
462
+ // Otherwise a waiter can observe neither file and misclassify the narrow
463
+ // unlink/create gap as a clean completion by the stale owner.
464
+ const successor = await createExclusive(lockPath, body());
465
+ if (successor === 'created')
466
+ return { outcome: 'acquired', handle: makeHandle() };
467
+ if (successor === 'unavailable')
468
+ return { outcome: 'unavailable' };
469
+ return null;
470
+ }
471
+ finally {
472
+ // Never override the try-block's outcome from here: returning
473
+ // 'unavailable' after 'acquired' would abandon a live heartbeating
474
+ // handle that then blocks every other process until this one exits.
475
+ // A guard file we fail to remove reads as contention to others and is
476
+ // replaced once stale.
477
+ await retryWindowsMutation(() => unlink(takeoverPath), sleep);
478
+ }
479
+ };
480
+ try {
481
+ if (!existsSync(cacheDir))
482
+ await mkdir(cacheDir, { recursive: true });
483
+ const immediate = await tryCreateOwner();
484
+ if (immediate) {
485
+ if (immediate.outcome !== 'acquired')
486
+ leave();
487
+ return immediate;
488
+ }
489
+ const deadline = clock.monotonicNow() + waitMs;
490
+ while (clock.monotonicNow() < deadline) {
491
+ const observation = await observe(lockPath);
492
+ if (observation === 'unavailable') {
493
+ leave();
494
+ return { outcome: 'unavailable' };
495
+ }
496
+ if (observation === 'changing') {
497
+ await sleep(pollMs);
498
+ continue;
499
+ }
500
+ if (observation === 'missing') {
501
+ // A stale taker removes the primary while holding the guard, then
502
+ // exclusively creates its successor. Do not misreport that narrow gap
503
+ // as a clean completion by the previous owner.
504
+ const guard = await observe(takeoverPath);
505
+ if (guard === 'unavailable') {
506
+ leave();
507
+ return { outcome: 'unavailable' };
508
+ }
509
+ if (guard === 'changing') {
510
+ await sleep(pollMs);
511
+ continue;
512
+ }
513
+ if (guard === 'missing') {
514
+ leave();
515
+ return { outcome: 'completed-by-other' };
516
+ }
517
+ await sleep(pollMs);
518
+ continue;
519
+ }
520
+ // A corrupt observation takes this path unchanged. Staleness is never
521
+ // waived for it: an abandoned corrupt lock is older than staleMs and is
522
+ // recovered here, while a corrupt body younger than that is waited out
523
+ // and left alone, because it may belong to a live owner whose heartbeat
524
+ // will repair it. Worst case we time out and serve the prior snapshot
525
+ // read-only for one staleMs window instead of freezing forever.
526
+ if (abandoned(observation)) {
527
+ const takeover = await tryTakeover(observation);
528
+ if (takeover) {
529
+ if (takeover.outcome !== 'acquired')
530
+ leave();
531
+ return takeover;
532
+ }
533
+ }
534
+ await sleep(pollMs);
535
+ }
536
+ leave();
537
+ return { outcome: 'timed-out' };
538
+ }
539
+ catch {
540
+ leave();
541
+ return { outcome: 'unavailable' };
542
+ }
543
+ }