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,528 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ import { createRequire } from 'node:module';
3
+ import { spawn, spawnSync } from 'node:child_process';
4
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, renameSync, statSync, unlinkSync, utimesSync } from 'node:fs';
5
+ import { createHash, randomBytes } from 'node:crypto';
6
+ import { homedir } from 'node:os';
7
+ import { join, sep } from 'node:path';
8
+ import { pathToFileURL } from 'node:url';
9
+ import { getCodeburnCacheDir } from './cache-dir.js';
10
+ /// Thin SQLite read-only wrapper over Node's built-in `node:sqlite` module (stable in
11
+ /// Node 24, experimental in Node 22 / 23). Replaces the earlier `better-sqlite3` binding
12
+ /// so the dependency graph no longer pulls in the deprecated `prebuild-install` package
13
+ /// (issue #75). Works across Cursor and OpenCode session DBs, both of which we only read.
14
+ const requireForSqlite = createRequire(import.meta.url);
15
+ let DatabaseSync = null;
16
+ let loadAttempted = false;
17
+ let loadError = null;
18
+ const textDecoder = new TextDecoder('utf-8', { fatal: false });
19
+ /// Safely decode a BLOB column (Uint8Array) to a UTF-8 string. Node's
20
+ /// node:sqlite crashes with a V8 CHECK abort when a TEXT column contains
21
+ /// invalid UTF-8 (common in Cursor chat blobs with truncated multi-byte
22
+ /// chars). By selecting those columns as `CAST(... AS BLOB)` in SQL, we
23
+ /// get a Uint8Array here and decode it in JS where bad bytes become the
24
+ /// U+FFFD replacement character instead of aborting the process.
25
+ export function blobToText(value) {
26
+ if (value == null)
27
+ return '';
28
+ if (typeof value === 'string')
29
+ return value;
30
+ return textDecoder.decode(value);
31
+ }
32
+ /// Lazily imports `node:sqlite`. On Node 22/23 it emits an ExperimentalWarning the first
33
+ /// time the module is loaded; we silence that specific warning once so dashboards aren't
34
+ /// preceded by a scary stderr line every run. Any other warnings (including future
35
+ /// non-SQLite ones) are left untouched.
36
+ function loadDriver() {
37
+ if (loadAttempted)
38
+ return DatabaseSync !== null;
39
+ loadAttempted = true;
40
+ const origEmit = process.emit.bind(process);
41
+ let restored = false;
42
+ const restore = () => {
43
+ if (restored)
44
+ return;
45
+ restored = true;
46
+ process.emit = origEmit;
47
+ };
48
+ // Node's `process.emit` signature is overloaded; we intercept the 'warning' channel
49
+ // only and proxy everything else through unchanged. The `any` cast avoids chasing the
50
+ // overload union which isn't worth its verbosity for a single-purpose shim.
51
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
52
+ process.emit = function patchedEmit(event, ...args) {
53
+ if (event === 'warning') {
54
+ const warning = args[0];
55
+ if (warning?.name === 'ExperimentalWarning' &&
56
+ typeof warning.message === 'string' &&
57
+ /SQLite/i.test(warning.message)) {
58
+ return false;
59
+ }
60
+ }
61
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
62
+ return origEmit.call(this, event, ...args);
63
+ };
64
+ try {
65
+ const mod = requireForSqlite('node:sqlite');
66
+ DatabaseSync = mod.DatabaseSync;
67
+ return true;
68
+ }
69
+ catch (err) {
70
+ const message = err instanceof Error ? err.message : String(err);
71
+ loadError =
72
+ 'SQLite-based providers (Cursor, OpenCode) need Node 22+ with the node:sqlite module.\n' +
73
+ `Current Node: ${process.version}.\n` +
74
+ 'Upgrade Node (https://nodejs.org) and run codeburn again.\n' +
75
+ `(underlying error: ${message})`;
76
+ return false;
77
+ }
78
+ finally {
79
+ process.nextTick(restore);
80
+ }
81
+ }
82
+ export function isSqliteAvailable() {
83
+ return loadDriver();
84
+ }
85
+ export function getSqliteLoadError() {
86
+ return loadError ?? 'SQLite driver not available';
87
+ }
88
+ export function isSqliteBusyError(err) {
89
+ const e = err;
90
+ const code = typeof e?.code === 'string' ? e.code : '';
91
+ const errcode = typeof e?.errcode === 'number' ? e.errcode : null;
92
+ const message = [
93
+ typeof e?.message === 'string' ? e.message : '',
94
+ typeof e?.errstr === 'string' ? e.errstr : '',
95
+ ].join(' ');
96
+ return (errcode === 5 ||
97
+ errcode === 6 ||
98
+ code === 'SQLITE_BUSY' ||
99
+ code === 'SQLITE_LOCKED' ||
100
+ /\bSQLITE_(BUSY|LOCKED)\b|database (?:is |table is )?locked/i.test(message));
101
+ }
102
+ /// SQLite reports SQLITE_READONLY_DIRECTORY as ERR_SQLITE_ERROR with an extended
103
+ /// result code on the Node 22 builds CodeBurn supports. Keep the base-code check
104
+ /// so this also covers SQLITE_READONLY and its other extended variants, while
105
+ /// leaving ENOENT/SQLITE_CANTOPEN distinguishable to callers.
106
+ export function isSqliteReadonlyError(err) {
107
+ const e = err;
108
+ const code = typeof e?.code === 'string' ? e.code : '';
109
+ const errcode = typeof e?.errcode === 'number' ? e.errcode : null;
110
+ const message = [
111
+ typeof e?.message === 'string' ? e.message : '',
112
+ typeof e?.errstr === 'string' ? e.errstr : '',
113
+ ].join(' ');
114
+ return ((errcode !== null && (errcode & 0xff) === 8) ||
115
+ /SQLITE_READONLY|attempt to write a readonly database|readonly database|read-only database/i.test(`${code} ${message}`));
116
+ }
117
+ /// A read-only parent reports SQLITE_READONLY_DIRECTORY when it must create the
118
+ /// sidecars from scratch, but SQLITE_CANTOPEN when a `-wal` is present and the
119
+ /// `-shm` it needs to index it is not. openReadonlyCache re-throws the original
120
+ /// error when the database itself is missing, which is the other CANTOPEN.
121
+ function isSqliteSidecarError(err) {
122
+ if (isSqliteReadonlyError(err))
123
+ return true;
124
+ const errcode = err?.errcode;
125
+ return typeof errcode === 'number' && (errcode & 0xff) === 14;
126
+ }
127
+ let uriFilenamesSupported = null;
128
+ /// node:sqlite only enables SQLITE_OPEN_URI from Node 22.15 on (measured: 22.13
129
+ /// and 22.14 fail, 22.15 and later work). Below that a `file:...` location is
130
+ /// taken literally and fails as CANTOPEN, so the immutable open is not attempted
131
+ /// there. The probe is an in-memory URI rather than a version comparison: it
132
+ /// answers the question directly and touches no filesystem either way.
133
+ export function sqliteSupportsUriFilenames() {
134
+ if (uriFilenamesSupported !== null)
135
+ return uriFilenamesSupported;
136
+ uriFilenamesSupported = false;
137
+ const Driver = loadDriver() ? DatabaseSync : null;
138
+ if (Driver !== null) {
139
+ try {
140
+ new Driver('file:codeburn-uri-probe?mode=memory', { readOnly: true }).close();
141
+ uriFilenamesSupported = true;
142
+ }
143
+ catch {
144
+ // An older build: locations are plain paths, and the copy fallback covers
145
+ // exactly the case the immutable open would have.
146
+ }
147
+ }
148
+ return uriFilenamesSupported;
149
+ }
150
+ /// A superseded copy is dropped once it has gone this long without being used.
151
+ /// The delay is what keeps a concurrent reader of the previous copy from having
152
+ /// its file yanked out from under it.
153
+ const CACHE_ENTRY_MAX_AGE_MS = 24 * 60 * 60 * 1000;
154
+ const warnedDatabases = new Set();
155
+ /// One notice per source path per run: a provider may discover many sessions
156
+ /// from the same database, and the first notice already says what happened.
157
+ function warnSqliteOnce(path, message) {
158
+ if (warnedDatabases.has(path))
159
+ return;
160
+ warnedDatabases.add(path);
161
+ process.stderr.write(message);
162
+ }
163
+ /// A read-only SQLite connection can still need sidecar files.
164
+ export function warnSqliteReadonlyOnce(path) {
165
+ warnSqliteOnce(path, `codeburn: SQLite database ${path} is in a read-only directory and needs sidecar files; using a cache copy when necessary. ` +
166
+ 'The original database is not modified.\n');
167
+ }
168
+ function errorCode(err) {
169
+ if (typeof err !== 'object' || err === null || !('code' in err))
170
+ return undefined;
171
+ const code = err.code;
172
+ return typeof code === 'string' ? code : undefined;
173
+ }
174
+ function describeError(err) {
175
+ return err instanceof Error ? err.message : String(err);
176
+ }
177
+ /// This deliberately mirrors fingerprintSqliteFile/fingerprintFile in
178
+ /// session-cache.ts. openDatabase is synchronous, so the fallback uses the
179
+ /// synchronous fs APIs only after the direct open has already failed; the
180
+ /// ordinary successful open remains probe-free.
181
+ function fingerprintDatabase(path) {
182
+ const main = statSync(path);
183
+ let wal = null;
184
+ try {
185
+ wal = statSync(path + '-wal');
186
+ }
187
+ catch (err) {
188
+ if (errorCode(err) !== 'ENOENT')
189
+ throw err;
190
+ }
191
+ return {
192
+ dev: main.dev,
193
+ ino: main.ino,
194
+ mtimeMs: wal ? Math.max(main.mtimeMs, wal.mtimeMs) : main.mtimeMs,
195
+ sizeBytes: main.size + (wal?.size ?? 0),
196
+ walBytes: wal?.size ?? 0,
197
+ };
198
+ }
199
+ function sameFingerprint(a, b) {
200
+ return (a.dev === b.dev &&
201
+ a.ino === b.ino &&
202
+ a.mtimeMs === b.mtimeMs &&
203
+ a.sizeBytes === b.sizeBytes &&
204
+ a.walBytes === b.walBytes);
205
+ }
206
+ function unlinkQuietly(path) {
207
+ try {
208
+ unlinkSync(path);
209
+ }
210
+ catch {
211
+ // Already gone, or still held open by another CodeBurn on Windows. Either
212
+ // way the next run's eviction pass gets another chance at it.
213
+ }
214
+ }
215
+ function copyOptionalFile(sourcePath, destinationPath) {
216
+ try {
217
+ copyFileSync(sourcePath, destinationPath);
218
+ return true;
219
+ }
220
+ catch (err) {
221
+ if (errorCode(err) === 'ENOENT')
222
+ return false;
223
+ throw err;
224
+ }
225
+ }
226
+ function sourceKeyOf(sourcePath) {
227
+ return createHash('sha256').update(sourcePath, 'utf8').digest('hex').slice(0, 32);
228
+ }
229
+ /// The copy is named after the source it came from AND the fingerprint it was
230
+ /// taken at, so a refresh publishes a new file rather than overwriting one that
231
+ /// another process may still have open.
232
+ function cacheEntryName(sourceKey, fingerprint) {
233
+ const parts = `${fingerprint.dev}:${fingerprint.ino}:${fingerprint.mtimeMs}:${fingerprint.sizeBytes}:${fingerprint.walBytes}`;
234
+ return `${sourceKey}.${createHash('sha256').update(parts).digest('hex').slice(0, 16)}.db`;
235
+ }
236
+ function dropCopy(cacheDir, name) {
237
+ unlinkQuietly(join(cacheDir, name));
238
+ unlinkQuietly(join(cacheDir, name + '-wal'));
239
+ unlinkQuietly(join(cacheDir, name + '-shm'));
240
+ }
241
+ /// Superseded copies are cleaned up here rather than by overwriting them: keep
242
+ /// the one in use plus at most one predecessor, and drop anything untouched for
243
+ /// a day, which is also what a source path that no longer exists looks like.
244
+ /// Reuse touches the copy, so its mtime is last-use rather than copy time.
245
+ function evictSupersededCopies(cacheDir, sourceKey, keepName) {
246
+ let names;
247
+ try {
248
+ names = readdirSync(cacheDir);
249
+ }
250
+ catch {
251
+ return;
252
+ }
253
+ const now = Date.now();
254
+ const superseded = [];
255
+ for (const name of names) {
256
+ if (!name.endsWith('.db') || name === keepName)
257
+ continue;
258
+ let mtimeMs;
259
+ try {
260
+ mtimeMs = statSync(join(cacheDir, name)).mtimeMs;
261
+ }
262
+ catch {
263
+ continue;
264
+ }
265
+ if (name.startsWith(`${sourceKey}.`))
266
+ superseded.push({ name, mtimeMs });
267
+ else if (now - mtimeMs > CACHE_ENTRY_MAX_AGE_MS)
268
+ dropCopy(cacheDir, name);
269
+ }
270
+ superseded.sort((a, b) => b.mtimeMs - a.mtimeMs);
271
+ for (const [index, entry] of superseded.entries()) {
272
+ if (index > 0 || now - entry.mtimeMs > CACHE_ENTRY_MAX_AGE_MS)
273
+ dropCopy(cacheDir, entry.name);
274
+ }
275
+ }
276
+ /// A concurrent CodeBurn may have published the same copy first. The name is
277
+ /// the fingerprint, so the content is identical by construction and losing that
278
+ /// race is not an error.
279
+ function publish(tempPath, finalPath) {
280
+ try {
281
+ renameSync(tempPath, finalPath);
282
+ }
283
+ catch (err) {
284
+ if (!existsSync(finalPath))
285
+ throw err;
286
+ }
287
+ }
288
+ function readOnlyCachePath(sourcePath, fingerprint) {
289
+ const cacheDir = join(getCodeburnCacheDir(), 'sqlite-ro');
290
+ mkdirSync(cacheDir, { recursive: true, mode: 0o700 });
291
+ const sourceKey = sourceKeyOf(sourcePath);
292
+ const name = cacheEntryName(sourceKey, fingerprint);
293
+ const cachePath = join(cacheDir, name);
294
+ if (existsSync(cachePath)) {
295
+ const now = new Date();
296
+ try {
297
+ utimesSync(cachePath, now, now);
298
+ }
299
+ catch {
300
+ // mtime is only the eviction clock; a copy we cannot touch still reads.
301
+ }
302
+ evictSupersededCopies(cacheDir, sourceKey, name);
303
+ return cachePath;
304
+ }
305
+ const tempBase = `${cachePath}.tmp-${process.pid}-${randomBytes(8).toString('hex')}`;
306
+ const tempWal = tempBase + '-wal';
307
+ try {
308
+ copyFileSync(sourcePath, tempBase);
309
+ const copiedWal = copyOptionalFile(sourcePath + '-wal', tempWal);
310
+ // Do not publish a cache made from a moving database. A live WAL writer will
311
+ // normally make the direct open succeed once its sidecars exist; this check
312
+ // covers the narrow race where the source changes during the copy fallback.
313
+ if (!sameFingerprint(fingerprintDatabase(sourcePath), fingerprint)) {
314
+ throw new Error('SQLite database changed while preparing its read-only cache copy');
315
+ }
316
+ // The -wal goes first: a reader that can see the database must never find it
317
+ // without the sidecar holding its most recent rows.
318
+ if (copiedWal)
319
+ publish(tempWal, cachePath + '-wal');
320
+ publish(tempBase, cachePath);
321
+ evictSupersededCopies(cacheDir, sourceKey, name);
322
+ return cachePath;
323
+ }
324
+ finally {
325
+ unlinkQuietly(tempBase);
326
+ unlinkQuietly(tempWal);
327
+ }
328
+ }
329
+ function openReadonlyCache(path, originalError) {
330
+ const Driver = DatabaseSync;
331
+ if (Driver === null)
332
+ throw new Error(getSqliteLoadError());
333
+ let fingerprint;
334
+ try {
335
+ fingerprint = fingerprintDatabase(path);
336
+ }
337
+ catch {
338
+ // Preserve the original SQLite error when the source disappeared or became
339
+ // inaccessible between the failed query and the fallback probe.
340
+ throw originalError;
341
+ }
342
+ // An absent or empty -wal holds no frames, so there is nothing to go stale and
343
+ // nothing worth copying: immutable lets SQLite skip the -shm it cannot create
344
+ // and read the source in place.
345
+ if (fingerprint.walBytes === 0 && sqliteSupportsUriFilenames()) {
346
+ try {
347
+ return new Driver(`${pathToFileURL(path).href}?immutable=1`, { readOnly: true });
348
+ }
349
+ catch {
350
+ // Understood but refused: the copy covers it.
351
+ }
352
+ }
353
+ let cachedPath;
354
+ try {
355
+ cachedPath = readOnlyCachePath(path, fingerprint);
356
+ }
357
+ catch (err) {
358
+ warnSqliteOnce(path, `codeburn: SQLite database ${path} is in a read-only directory and its cache copy could not be written ` +
359
+ `(${describeError(err)}); skipping this database.\n`);
360
+ throw originalError;
361
+ }
362
+ return new Driver(cachedPath, { readOnly: true });
363
+ }
364
+ /// macOS keeps `~/Library/Group Containers` behind Full Disk Access. When the
365
+ /// process running codeburn has no consent and cannot show the prompt, open()
366
+ /// on a database in there never returns: the whole run wedges before printing
367
+ /// anything, and so does the resident `serve` child. fs.accessSync/openSync
368
+ /// block the same way, so the only safe probe is a child we can kill.
369
+ const GROUP_CONTAINERS_PREFIX = join(homedir(), 'Library', 'Group Containers') + sep;
370
+ const TCC_PROBE = "try{require('node:fs').closeSync(require('node:fs').openSync(process.argv[1],'r'))}catch(e){process.exit(e.code==='ENOENT'?2:1)}";
371
+ const TCC_PROBE_TIMEOUT_MS = 3000;
372
+ /// Short enough that granting access recovers on the next `serve` refresh,
373
+ /// long enough that a resident process does not fork per request.
374
+ const TCC_PROBE_CACHE_MS = 60_000;
375
+ const tccProbeCache = new Map();
376
+ const tccProbeRefreshing = new Set();
377
+ let warnedTccBlocked = false;
378
+ export function isBlockedDatabaseError(err) {
379
+ return typeof err === 'object' && err !== null && 'codeburnBlocked' in err;
380
+ }
381
+ /// Turn one probe outcome into a verdict. A timeout kill (SIGKILL) is a real
382
+ /// hang: never open the file wherever it lives. A spawn that never ran (the
383
+ /// child could not start, e.g. execPath missing) taught us nothing about the
384
+ /// file, so fail CLOSED for Group Container paths - opening one with no consent
385
+ /// wedges the whole process - and open elsewhere, where a spawn failure is not
386
+ /// the file's fault. Otherwise 0 is readable, 2 is missing (let the real open
387
+ /// report that), any other exit means do not touch it.
388
+ function classifyProbe(result, isGroupContainer) {
389
+ if (result.signal === 'SIGKILL')
390
+ return true;
391
+ if (result.error)
392
+ return isGroupContainer;
393
+ return result.status !== 0 && result.status !== 2;
394
+ }
395
+ /// Re-probe a stale entry off the request path. spawnSync would freeze the
396
+ /// single-threaded serve queue for up to the timeout on every stale read; the
397
+ /// async spawn refreshes the cache without blocking the caller, which keeps
398
+ /// serving on the last known verdict until it lands.
399
+ function refreshProbeAsync(key, path, script, execPath, isGroupContainer) {
400
+ if (tccProbeRefreshing.has(key))
401
+ return;
402
+ tccProbeRefreshing.add(key);
403
+ const settle = (result) => {
404
+ tccProbeRefreshing.delete(key);
405
+ tccProbeCache.set(key, { blocked: classifyProbe(result, isGroupContainer), at: Date.now() });
406
+ };
407
+ let child;
408
+ try {
409
+ child = spawn(execPath, ['-e', script, path], {
410
+ stdio: 'ignore',
411
+ // process.execPath is Electron's binary in the desktop app; without this
412
+ // it would launch a second app window instead of running the script.
413
+ env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
414
+ });
415
+ }
416
+ catch (error) {
417
+ settle({ signal: null, error, status: null });
418
+ return;
419
+ }
420
+ const timer = setTimeout(() => {
421
+ child.kill('SIGKILL');
422
+ settle({ signal: 'SIGKILL', status: null });
423
+ }, TCC_PROBE_TIMEOUT_MS);
424
+ timer.unref?.();
425
+ child.once('error', (error) => { clearTimeout(timer); settle({ signal: null, error, status: null }); });
426
+ child.once('exit', (status, signal) => { clearTimeout(timer); settle({ signal, status }); });
427
+ }
428
+ /// `script` and `execPath` are only ever overridden by tests, which cannot make
429
+ /// a real open() hang on demand nor break the spawn itself.
430
+ export function probeDatabaseBlocked(path, script = TCC_PROBE, execPath = process.execPath) {
431
+ const now = Date.now();
432
+ const key = `${script}\u0000${path}`;
433
+ const isGroupContainer = path.startsWith(GROUP_CONTAINERS_PREFIX);
434
+ const cached = tccProbeCache.get(key);
435
+ if (cached) {
436
+ // Stale: refresh in the background so granting FDA later recovers, but never
437
+ // block this (possibly serve) request on spawnSync; answer with the last
438
+ // known verdict until the async re-probe lands.
439
+ if (now - cached.at >= TCC_PROBE_CACHE_MS)
440
+ refreshProbeAsync(key, path, script, execPath, isGroupContainer);
441
+ return cached.blocked;
442
+ }
443
+ // Cold: no cached verdict yet. A one-shot CLI run has no later request to wait
444
+ // for an async probe, so answer authoritatively now with a single spawnSync.
445
+ // serve warms this cache off the request path when it arms its root watchers.
446
+ const probe = spawnSync(execPath, ['-e', script, path], {
447
+ timeout: TCC_PROBE_TIMEOUT_MS,
448
+ killSignal: 'SIGKILL',
449
+ stdio: 'ignore',
450
+ // process.execPath is Electron's binary in the desktop app; without this it
451
+ // would launch a second app window instead of running the script.
452
+ env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
453
+ });
454
+ const blocked = classifyProbe(probe, isGroupContainer);
455
+ tccProbeCache.set(key, { blocked, at: now });
456
+ return blocked;
457
+ }
458
+ /// True for a Group Container path this process must not open: kqueue-backed
459
+ /// fs.watch hangs on it exactly like DatabaseSync does.
460
+ export function isPathBlocked(path, script = TCC_PROBE) {
461
+ return path.startsWith(GROUP_CONTAINERS_PREFIX) && probeDatabaseBlocked(path, script);
462
+ }
463
+ export function assertDatabaseReadable(path, script = TCC_PROBE) {
464
+ if (!isPathBlocked(path, script))
465
+ return;
466
+ if (!warnedTccBlocked) {
467
+ warnedTccBlocked = true;
468
+ process.stderr.write("codeburn: skipped warp: macOS blocked access to Warp's database; grant Full Disk Access to the app " +
469
+ 'running codeburn (System Settings > Privacy & Security) and retry\n');
470
+ }
471
+ throw Object.assign(new Error(`macOS blocked access to ${path}`), { codeburnBlocked: true });
472
+ }
473
+ export function openDatabase(path) {
474
+ if (!loadDriver() || DatabaseSync === null) {
475
+ throw new Error(getSqliteLoadError());
476
+ }
477
+ assertDatabaseReadable(path);
478
+ let db;
479
+ let fallbackUsed = false;
480
+ try {
481
+ db = new DatabaseSync(path, { readOnly: true });
482
+ }
483
+ catch (err) {
484
+ if (!isSqliteSidecarError(err))
485
+ throw err;
486
+ fallbackUsed = true;
487
+ db = openReadonlyCache(path, err);
488
+ warnSqliteReadonlyOnce(path);
489
+ }
490
+ try {
491
+ db.exec?.('PRAGMA busy_timeout = 1000');
492
+ }
493
+ catch {
494
+ // Best effort. Some Node sqlite builds may not expose exec on DatabaseSync.
495
+ }
496
+ return {
497
+ query(sql, params = []) {
498
+ try {
499
+ return db.prepare(sql).all(...params);
500
+ }
501
+ catch (err) {
502
+ if (!isSqliteSidecarError(err))
503
+ throw err;
504
+ if (fallbackUsed)
505
+ throw err;
506
+ fallbackUsed = true;
507
+ try {
508
+ db.close();
509
+ }
510
+ catch {
511
+ // The failed connection may already have been closed by node:sqlite.
512
+ }
513
+ db = openReadonlyCache(path, err);
514
+ warnSqliteReadonlyOnce(path);
515
+ try {
516
+ db.exec?.('PRAGMA busy_timeout = 1000');
517
+ }
518
+ catch {
519
+ // Best effort, matching the direct-open path above.
520
+ }
521
+ return db.prepare(sql).all(...params);
522
+ }
523
+ },
524
+ close() {
525
+ db.close();
526
+ },
527
+ };
528
+ }