chompyy 0.4.7 → 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 (161) hide show
  1. package/README.md +40 -6
  2. package/dist/advice.js +2 -1
  3. package/dist/agentlimits.js +77 -0
  4. package/dist/agentusage.js +96 -0
  5. package/dist/appstate.js +72 -5
  6. package/dist/away.js +44 -5
  7. package/dist/blueprint.js +3 -7
  8. package/dist/board.js +4 -0
  9. package/dist/cli.js +328 -15
  10. package/dist/codexquota.js +106 -0
  11. package/dist/codexusage.js +10 -0
  12. package/dist/config.js +2 -0
  13. package/dist/context.js +30 -0
  14. package/dist/costs.js +1 -0
  15. package/dist/daytime.js +68 -0
  16. package/dist/demon.js +20 -0
  17. package/dist/didwork.js +46 -0
  18. package/dist/label.js +33 -0
  19. package/dist/learning.js +35 -0
  20. package/dist/menu.js +17 -0
  21. package/dist/nightcap.js +60 -0
  22. package/dist/nudge.js +47 -18
  23. package/dist/pacing.js +16 -1
  24. package/dist/questions.js +71 -0
  25. package/dist/recap.js +74 -0
  26. package/dist/receipt.js +48 -0
  27. package/dist/recipe.js +79 -0
  28. package/dist/send.js +46 -20
  29. package/dist/stamps.js +14 -0
  30. package/dist/taste.js +67 -7
  31. package/dist/triggers.js +5 -0
  32. package/dist/unkeep.js +220 -0
  33. package/dist/usage.js +21 -1
  34. package/dist/vendor/codeburn/antigravity.js +309 -0
  35. package/dist/vendor/codeburn/codex.js +429 -0
  36. package/dist/vendor/codeburn/copilot.js +292 -0
  37. package/dist/vendor/codeburn/gemini.js +195 -0
  38. package/dist/vendor/codeburn/grokbot.js +182 -0
  39. package/dist/vendor/codeburn/kimi.js +178 -0
  40. package/dist/vendor/codeburn/shims/chalk.js +14 -0
  41. package/dist/vendor/codeburn/shims/strip-ansi.js +6 -0
  42. package/dist/vendor/codeburn/src/act/backup.js +83 -0
  43. package/dist/vendor/codeburn/src/act/model-defaults.js +151 -0
  44. package/dist/vendor/codeburn/src/act/types.js +37 -0
  45. package/dist/vendor/codeburn/src/bash-utils.js +204 -0
  46. package/dist/vendor/codeburn/src/behavioral-weight.js +47 -0
  47. package/dist/vendor/codeburn/src/cache-dir.js +26 -0
  48. package/dist/vendor/codeburn/src/cache-refresh-lock.js +543 -0
  49. package/dist/vendor/codeburn/src/cache-sweep.js +67 -0
  50. package/dist/vendor/codeburn/src/classifier.js +209 -0
  51. package/dist/vendor/codeburn/src/claude-identity.js +223 -0
  52. package/dist/vendor/codeburn/src/codex-cache.js +377 -0
  53. package/dist/vendor/codeburn/src/codex-fork-replay.js +232 -0
  54. package/dist/vendor/codeburn/src/codex-jsonl-fields.js +99 -0
  55. package/dist/vendor/codeburn/src/codex-session-index.js +113 -0
  56. package/dist/vendor/codeburn/src/codex-throughput.js +544 -0
  57. package/dist/vendor/codeburn/src/compare-stats.js +405 -0
  58. package/dist/vendor/codeburn/src/config.js +145 -0
  59. package/dist/vendor/codeburn/src/content-utils.js +56 -0
  60. package/dist/vendor/codeburn/src/context-tree-codex.js +329 -0
  61. package/dist/vendor/codeburn/src/context-tree.js +664 -0
  62. package/dist/vendor/codeburn/src/copilot-aiu.js +16 -0
  63. package/dist/vendor/codeburn/src/currency.js +189 -0
  64. package/dist/vendor/codeburn/src/cursor-cache.js +238 -0
  65. package/dist/vendor/codeburn/src/cursor-import.js +402 -0
  66. package/dist/vendor/codeburn/src/cursor-sync.js +256 -0
  67. package/dist/vendor/codeburn/src/daily-cache.js +2036 -0
  68. package/dist/vendor/codeburn/src/data/litellm-snapshot.json +1 -0
  69. package/dist/vendor/codeburn/src/data/pricing-fallback.json +1 -0
  70. package/dist/vendor/codeburn/src/day-aggregator.js +327 -0
  71. package/dist/vendor/codeburn/src/editor-data-dir.js +11 -0
  72. package/dist/vendor/codeburn/src/fetch-utils.js +18 -0
  73. package/dist/vendor/codeburn/src/format.js +118 -0
  74. package/dist/vendor/codeburn/src/fs-utils.js +270 -0
  75. package/dist/vendor/codeburn/src/git-origin.js +334 -0
  76. package/dist/vendor/codeburn/src/granular-history.js +328 -0
  77. package/dist/vendor/codeburn/src/hermes-session-ledger.js +512 -0
  78. package/dist/vendor/codeburn/src/launcher-homes.js +142 -0
  79. package/dist/vendor/codeburn/src/live-sessions.js +358 -0
  80. package/dist/vendor/codeburn/src/math-utils.js +8 -0
  81. package/dist/vendor/codeburn/src/menubar-json.js +294 -0
  82. package/dist/vendor/codeburn/src/models.js +1879 -0
  83. package/dist/vendor/codeburn/src/optimize-one-hour-cache.js +92 -0
  84. package/dist/vendor/codeburn/src/optimize.js +4110 -0
  85. package/dist/vendor/codeburn/src/parse-workers.js +219 -0
  86. package/dist/vendor/codeburn/src/parser.js +6953 -0
  87. package/dist/vendor/codeburn/src/path-privacy.js +26 -0
  88. package/dist/vendor/codeburn/src/plans.js +135 -0
  89. package/dist/vendor/codeburn/src/pr-signals.js +132 -0
  90. package/dist/vendor/codeburn/src/project-filter-warnings.js +33 -0
  91. package/dist/vendor/codeburn/src/provider-issues.js +30 -0
  92. package/dist/vendor/codeburn/src/providers/amp.js +286 -0
  93. package/dist/vendor/codeburn/src/providers/antigravity.js +1731 -0
  94. package/dist/vendor/codeburn/src/providers/claude.js +551 -0
  95. package/dist/vendor/codeburn/src/providers/cline-cli.js +401 -0
  96. package/dist/vendor/codeburn/src/providers/cline.js +63 -0
  97. package/dist/vendor/codeburn/src/providers/codebuff.js +336 -0
  98. package/dist/vendor/codeburn/src/providers/codewhale.js +442 -0
  99. package/dist/vendor/codeburn/src/providers/codex.js +1720 -0
  100. package/dist/vendor/codeburn/src/providers/command-code.js +196 -0
  101. package/dist/vendor/codeburn/src/providers/copilot.js +3278 -0
  102. package/dist/vendor/codeburn/src/providers/crush.js +226 -0
  103. package/dist/vendor/codeburn/src/providers/cursor-agent.js +837 -0
  104. package/dist/vendor/codeburn/src/providers/cursor.js +1163 -0
  105. package/dist/vendor/codeburn/src/providers/devin.js +569 -0
  106. package/dist/vendor/codeburn/src/providers/droid.js +324 -0
  107. package/dist/vendor/codeburn/src/providers/dsh.js +690 -0
  108. package/dist/vendor/codeburn/src/providers/forge.js +245 -0
  109. package/dist/vendor/codeburn/src/providers/gemini.js +230 -0
  110. package/dist/vendor/codeburn/src/providers/goose.js +252 -0
  111. package/dist/vendor/codeburn/src/providers/grok.js +581 -0
  112. package/dist/vendor/codeburn/src/providers/grokbot.js +290 -0
  113. package/dist/vendor/codeburn/src/providers/hermes.js +771 -0
  114. package/dist/vendor/codeburn/src/providers/ibm-bob.js +53 -0
  115. package/dist/vendor/codeburn/src/providers/index.js +360 -0
  116. package/dist/vendor/codeburn/src/providers/kilo-code.js +50 -0
  117. package/dist/vendor/codeburn/src/providers/kimi.js +363 -0
  118. package/dist/vendor/codeburn/src/providers/kimicode.js +402 -0
  119. package/dist/vendor/codeburn/src/providers/kiro.js +1174 -0
  120. package/dist/vendor/codeburn/src/providers/lingtai-tui.js +372 -0
  121. package/dist/vendor/codeburn/src/providers/mistral-vibe-unified.js +236 -0
  122. package/dist/vendor/codeburn/src/providers/mistral-vibe.js +405 -0
  123. package/dist/vendor/codeburn/src/providers/mux.js +242 -0
  124. package/dist/vendor/codeburn/src/providers/open-design.js +217 -0
  125. package/dist/vendor/codeburn/src/providers/openclaude.js +309 -0
  126. package/dist/vendor/codeburn/src/providers/openclaw.js +442 -0
  127. package/dist/vendor/codeburn/src/providers/opencode-file-parser.js +131 -0
  128. package/dist/vendor/codeburn/src/providers/opencode.js +91 -0
  129. package/dist/vendor/codeburn/src/providers/pi.js +429 -0
  130. package/dist/vendor/codeburn/src/providers/quickdesk.js +491 -0
  131. package/dist/vendor/codeburn/src/providers/qwen.js +193 -0
  132. package/dist/vendor/codeburn/src/providers/session-message.js +118 -0
  133. package/dist/vendor/codeburn/src/providers/sqlite-session-parser.js +457 -0
  134. package/dist/vendor/codeburn/src/providers/types.js +5 -0
  135. package/dist/vendor/codeburn/src/providers/vercel-gateway.js +135 -0
  136. package/dist/vendor/codeburn/src/providers/vscode-cline-parser.js +212 -0
  137. package/dist/vendor/codeburn/src/providers/warp.js +575 -0
  138. package/dist/vendor/codeburn/src/providers/zcode.js +249 -0
  139. package/dist/vendor/codeburn/src/providers/zed.js +187 -0
  140. package/dist/vendor/codeburn/src/providers/zerostack.js +139 -0
  141. package/dist/vendor/codeburn/src/quota/antigravity.js +310 -0
  142. package/dist/vendor/codeburn/src/quota/claude.js +244 -0
  143. package/dist/vendor/codeburn/src/quota/cursor.js +301 -0
  144. package/dist/vendor/codeburn/src/quota/security.js +299 -0
  145. package/dist/vendor/codeburn/src/quota/types.js +1 -0
  146. package/dist/vendor/codeburn/src/scan-facts.js +99 -0
  147. package/dist/vendor/codeburn/src/session-cache.js +3040 -0
  148. package/dist/vendor/codeburn/src/session-count-label.js +14 -0
  149. package/dist/vendor/codeburn/src/session-output.js +139 -0
  150. package/dist/vendor/codeburn/src/session-population.js +30 -0
  151. package/dist/vendor/codeburn/src/sessions-report.js +1342 -0
  152. package/dist/vendor/codeburn/src/sqlite.js +528 -0
  153. package/dist/vendor/codeburn/src/sync/otlp.js +420 -0
  154. package/dist/vendor/codeburn/src/telemetry-snapshot.js +244 -0
  155. package/dist/vendor/codeburn/src/token-estimate.js +5 -0
  156. package/dist/vendor/codeburn/src/types.js +16 -0
  157. package/dist/vendor/codeburn/src/work-units.js +126 -0
  158. package/dist/vendor/codeburn/src/workflow-insights.js +228 -0
  159. package/dist/vendor/codeburn/src/wsl.js +198 -0
  160. package/dist/vendor/codeburn/src/yield.js +666 -0
  161. package/package.json +11 -3
@@ -0,0 +1,270 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ import { readFile, stat } from 'fs/promises';
3
+ import { readFileSync, statSync, createReadStream, openSync, readSync, closeSync } from 'fs';
4
+ import { pipeline } from 'stream';
5
+ import zlib from 'zlib';
6
+ // Hard cap well below V8's 512 MB string limit. Callers that need line-by-line
7
+ // processing should use readSessionLines(), which avoids materializing the
8
+ // whole file and can return large lines as Buffers.
9
+ export const MAX_SESSION_FILE_BYTES = 128 * 1024 * 1024;
10
+ export const LARGE_STREAM_LINE_BYTES = 32 * 1024;
11
+ // Line-by-line streaming has bounded memory (one line at a time) and is not
12
+ // constrained by V8's string limit, so it can safely handle multi-GB session
13
+ // files. Heavy Codex sessions routinely reach several GB (image-heavy compacted
14
+ // turns), so the cap is generous and exists only to guard against truly
15
+ // pathological inputs. When a file IS skipped, notice() surfaces it (always on,
16
+ // not verbose-gated) so a dropped session never silently understates usage.
17
+ export const MAX_STREAM_SESSION_FILE_BYTES = 4 * 1024 * 1024 * 1024;
18
+ function verbose() {
19
+ return process.env.CODEBURN_VERBOSE === '1';
20
+ }
21
+ function warn(msg) {
22
+ if (verbose())
23
+ process.stderr.write(`codeburn: ${msg}\n`);
24
+ }
25
+ // zstd is built into node:zlib from the 22.15 floor.
26
+ const MAX_ZSTD_HEAD_DECODED_BYTES = 64 * 1024 * 1024;
27
+ /** Reads a file's text, decompressing a `.zst` file on the fly. */
28
+ export function createTextReadStream(filePath, options) {
29
+ if (!filePath.endsWith('.zst'))
30
+ return createReadStream(filePath, options);
31
+ const raw = createReadStream(filePath, options);
32
+ // pipeline, not pipe: a read error has to fail the decoder too, or its
33
+ // consumer waits forever.
34
+ return pipeline(raw, zlib.createZstdDecompress(), () => { });
35
+ }
36
+ /** Up to `maxBytes` of a file's text from its start; for a `.zst` file only the compressed head is read. */
37
+ export function readTextHeadSync(filePath, maxBytes) {
38
+ const fd = openSync(filePath, 'r');
39
+ let head;
40
+ try {
41
+ const buf = Buffer.alloc(maxBytes);
42
+ head = buf.subarray(0, readSync(fd, buf, 0, maxBytes, 0));
43
+ }
44
+ finally {
45
+ closeSync(fd);
46
+ }
47
+ if (!filePath.endsWith('.zst') || head.length === 0)
48
+ return head;
49
+ // ZSTD_e_continue decodes a cut-off frame as far as it goes instead of
50
+ // rejecting it as truncated; a head that inflates past the cap is retried
51
+ // with less input.
52
+ for (;;) {
53
+ try {
54
+ return zlib.zstdDecompressSync(head, {
55
+ finishFlush: zlib.constants.ZSTD_e_continue,
56
+ maxOutputLength: MAX_ZSTD_HEAD_DECODED_BYTES,
57
+ }).subarray(0, maxBytes);
58
+ }
59
+ catch (err) {
60
+ if (err.code !== 'ERR_BUFFER_TOO_LARGE' || head.length < 2)
61
+ throw err;
62
+ head = head.subarray(0, head.length >> 1);
63
+ }
64
+ }
65
+ }
66
+ // Always surfaced (not verbose-gated): dropping an entire session file silently
67
+ // understates reported usage with no signal, so oversize skips use this.
68
+ function notice(msg) {
69
+ process.stderr.write(`codeburn: ${msg}\n`);
70
+ }
71
+ export async function readSessionFile(filePath, encoding = 'utf-8') {
72
+ let size;
73
+ try {
74
+ size = (await stat(filePath)).size;
75
+ }
76
+ catch (err) {
77
+ warn(`stat failed for ${filePath}: ${err.code ?? 'unknown'}`);
78
+ return null;
79
+ }
80
+ if (size > MAX_SESSION_FILE_BYTES) {
81
+ warn(`skipped oversize file ${filePath} (${size} bytes > cap ${MAX_SESSION_FILE_BYTES})`);
82
+ return null;
83
+ }
84
+ try {
85
+ return await readFile(filePath, encoding);
86
+ }
87
+ catch (err) {
88
+ warn(`read failed for ${filePath}: ${err.code ?? 'unknown'}`);
89
+ return null;
90
+ }
91
+ }
92
+ export function readSessionFileSync(filePath) {
93
+ let size;
94
+ try {
95
+ size = statSync(filePath).size;
96
+ }
97
+ catch (err) {
98
+ warn(`stat failed for ${filePath}: ${err.code ?? 'unknown'}`);
99
+ return null;
100
+ }
101
+ if (size > MAX_SESSION_FILE_BYTES) {
102
+ warn(`skipped oversize file ${filePath} (${size} bytes > cap ${MAX_SESSION_FILE_BYTES})`);
103
+ return null;
104
+ }
105
+ try {
106
+ return readFileSync(filePath, 'utf-8');
107
+ }
108
+ catch (err) {
109
+ warn(`read failed for ${filePath}: ${err.code ?? 'unknown'}`);
110
+ return null;
111
+ }
112
+ }
113
+ export async function* readSessionLines(filePath, shouldSkipHead, options = {}) {
114
+ let size;
115
+ try {
116
+ size = (await stat(filePath)).size;
117
+ }
118
+ catch (err) {
119
+ warn(`stat failed for ${filePath}: ${err.code ?? 'unknown'}`);
120
+ return;
121
+ }
122
+ const maxBytes = options.maxBytes ?? MAX_STREAM_SESSION_FILE_BYTES;
123
+ if (size > maxBytes) {
124
+ notice(`skipped oversize session ${filePath} (${size} bytes > cap ${maxBytes}); its usage is NOT counted`);
125
+ return;
126
+ }
127
+ const stream = createTextReadStream(filePath, options.startByteOffset !== undefined ? { start: options.startByteOffset } : undefined);
128
+ const SKIP_HEAD = 2048;
129
+ const largeLineThreshold = options.largeLineThresholdBytes ?? LARGE_STREAM_LINE_BYTES;
130
+ const formatLine = (buf, lineLen, head) => {
131
+ if (options.largeLineAsBuffer && lineLen > largeLineThreshold)
132
+ return buf;
133
+ return head !== undefined && lineLen <= SKIP_HEAD ? head : buf.toString('utf-8');
134
+ };
135
+ let parts = [];
136
+ let len = 0;
137
+ let skipping = false;
138
+ let headChecked = false;
139
+ let chunkBase = options.startByteOffset ?? 0;
140
+ const tracker = options.byteOffsetTracker;
141
+ try {
142
+ for await (const raw of stream) {
143
+ const chunk = raw;
144
+ let pos = 0;
145
+ while (pos < chunk.length) {
146
+ const nl = chunk.indexOf(0x0a, pos);
147
+ if (skipping) {
148
+ if (nl === -1) {
149
+ pos = chunk.length;
150
+ }
151
+ else {
152
+ if (tracker)
153
+ tracker.lastCompleteLineOffset = chunkBase + nl + 1;
154
+ skipping = false;
155
+ pos = nl + 1;
156
+ }
157
+ continue;
158
+ }
159
+ if (nl !== -1) {
160
+ if (pos < nl) {
161
+ parts.push(chunk.subarray(pos, nl));
162
+ len += nl - pos;
163
+ }
164
+ pos = nl + 1;
165
+ if (tracker)
166
+ tracker.lastCompleteLineOffset = chunkBase + pos;
167
+ if (len === 0) {
168
+ parts = [];
169
+ headChecked = false;
170
+ continue;
171
+ }
172
+ const buf = parts.length === 1 ? parts[0] : Buffer.concat(parts, len);
173
+ const lineLen = len;
174
+ parts = [];
175
+ len = 0;
176
+ headChecked = false;
177
+ if (shouldSkipHead) {
178
+ const head = lineLen > SKIP_HEAD
179
+ ? buf.subarray(0, SKIP_HEAD).toString('utf-8')
180
+ : buf.toString('utf-8');
181
+ if (shouldSkipHead(head))
182
+ continue;
183
+ yield formatLine(buf, lineLen, head);
184
+ }
185
+ else {
186
+ yield formatLine(buf, lineLen);
187
+ }
188
+ }
189
+ else {
190
+ const slice = chunk.subarray(pos);
191
+ parts.push(slice);
192
+ len += slice.length;
193
+ pos = chunk.length;
194
+ // Mid-line skip: once we have enough bytes to check the head,
195
+ // enter scanning mode — just look for \n without accumulating.
196
+ if (shouldSkipHead && !headChecked && len >= SKIP_HEAD) {
197
+ headChecked = true;
198
+ const headBuf = parts.length === 1
199
+ ? parts[0].subarray(0, SKIP_HEAD)
200
+ : Buffer.concat(parts, len).subarray(0, SKIP_HEAD);
201
+ if (shouldSkipHead(headBuf.toString('utf-8'))) {
202
+ skipping = true;
203
+ parts = [];
204
+ len = 0;
205
+ }
206
+ }
207
+ }
208
+ }
209
+ chunkBase += chunk.length;
210
+ }
211
+ if (!skipping && len > 0) {
212
+ if (tracker)
213
+ tracker.unterminatedLineEnd = chunkBase;
214
+ const buf = parts.length === 1 ? parts[0] : Buffer.concat(parts, len);
215
+ const lineLen = len;
216
+ if (shouldSkipHead) {
217
+ const head = lineLen > SKIP_HEAD
218
+ ? buf.subarray(0, SKIP_HEAD).toString('utf-8')
219
+ : buf.toString('utf-8');
220
+ if (!shouldSkipHead(head)) {
221
+ yield formatLine(buf, lineLen, head);
222
+ }
223
+ }
224
+ else {
225
+ yield formatLine(buf, lineLen);
226
+ }
227
+ }
228
+ }
229
+ catch (err) {
230
+ const code = err.code ?? 'unknown';
231
+ // A truncated .zst decodes up to the damage and would pass for a whole session.
232
+ if (filePath.endsWith('.zst'))
233
+ notice(`could not fully decompress ${filePath} (${code}); usage after the damaged part is NOT counted`);
234
+ else
235
+ warn(`stream read failed for ${filePath}: ${code}`);
236
+ }
237
+ finally {
238
+ stream.destroy();
239
+ }
240
+ }
241
+ /// Whether a line readSessionLines yielded may be folded, given what it parsed
242
+ /// into. A last line still missing its newline is folded only when it parsed
243
+ /// into an object or array, which no later bytes can extend into a different
244
+ /// valid line, and the tracker's resume offset then moves past it. A bare
245
+ /// scalar (`1` can still become `123`) is left to be re-read whole.
246
+ export function foldParsedLine(tracker, parsed) {
247
+ if (tracker.unterminatedLineEnd === undefined)
248
+ return true;
249
+ if (typeof parsed !== 'object' || parsed === null)
250
+ return false;
251
+ tracker.lastCompleteLineOffset = tracker.unterminatedLineEnd;
252
+ return true;
253
+ }
254
+ // Metadata syscalls (readdir/stat) issued one-at-a-time leave the OS idle
255
+ // between them: on a 21k-file corpus the discovery sweep spent most of its wall
256
+ // clock waiting rather than working. Results are returned in input order so
257
+ // callers keep their deterministic, order-sensitive downstream processing.
258
+ export const FS_SCAN_CONCURRENCY = 32;
259
+ export async function mapWithConcurrency(items, limit, worker) {
260
+ const out = new Array(items.length);
261
+ let idx = 0;
262
+ const run = async () => {
263
+ while (idx < items.length) {
264
+ const current = idx++;
265
+ out[current] = await worker(items[current], current);
266
+ }
267
+ };
268
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, run));
269
+ return out;
270
+ }
@@ -0,0 +1,334 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ import { existsSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
3
+ import { homedir, tmpdir } from 'node:os';
4
+ import { basename, dirname, isAbsolute, join, resolve, win32 } from 'node:path';
5
+ import { getCodeburnCacheDir } from './cache-dir.js';
6
+ import { normalizeProxyPath } from './models.js';
7
+ /// The `origin` remote of a checkout, read straight from .git/config. Two clones
8
+ /// or worktrees of the same repository share it, which is what lets surfaces
9
+ /// fold a dozen throwaway checkouts into one project.
10
+ export function parseGitConfigSection(config, section, key) {
11
+ const wanted = `[${section.toLowerCase()}]`;
12
+ let inSection = false;
13
+ for (const raw of config.split(/\r?\n/)) {
14
+ const line = raw.trim();
15
+ if (!line || line.startsWith('#') || line.startsWith(';'))
16
+ continue;
17
+ if (line.startsWith('[')) {
18
+ inSection = line.toLowerCase() === wanted;
19
+ continue;
20
+ }
21
+ if (!inSection)
22
+ continue;
23
+ const eq = line.indexOf('=');
24
+ if (eq < 0)
25
+ continue;
26
+ if (line.slice(0, eq).trim().toLowerCase() !== key.toLowerCase())
27
+ continue;
28
+ return line.slice(eq + 1).trim();
29
+ }
30
+ return null;
31
+ }
32
+ /** Comparable identity for a remote URL: `git@github.com:o/r.git` and
33
+ * `https://github.com/o/r` both become `github.com/o/r`. */
34
+ export function normalizeOriginUrl(url) {
35
+ return url
36
+ .trim()
37
+ .replace(/^[a-z+]+:\/\//i, '')
38
+ .replace(/^[^@/]+@/, '')
39
+ .replace(/:(?=[^/])/, '/')
40
+ .replace(/\/+$/, '')
41
+ .replace(/\.git$/i, '')
42
+ .toLowerCase();
43
+ }
44
+ function entryKind(path) {
45
+ try {
46
+ const st = statSync(path);
47
+ return st.isDirectory() ? 'dir' : st.isFile() ? 'file' : null;
48
+ }
49
+ catch {
50
+ return null;
51
+ }
52
+ }
53
+ function resolveGitCommonDir(gitDir) {
54
+ const marker = join(gitDir, 'commondir');
55
+ if (!existsSync(marker))
56
+ return gitDir;
57
+ const rel = readFileSync(marker, 'utf8').trim();
58
+ if (!rel)
59
+ return gitDir;
60
+ if (rel.startsWith('/') || /^[a-zA-Z]:[\\/]/.test(rel))
61
+ return rel;
62
+ return join(gitDir, rel);
63
+ }
64
+ // Memoized per repo root: every session in the same repo would otherwise
65
+ // re-read .git/config. Process-lifetime only, so a remote URL change needs a
66
+ // restart (a resident `serve` child included).
67
+ const originByRoot = new Map();
68
+ export function readGitOriginUrl(path) {
69
+ const memo = originByRoot.get(path);
70
+ if (memo !== undefined)
71
+ return memo;
72
+ const url = readGitOriginUrlUncached(path);
73
+ originByRoot.set(path, url);
74
+ return url;
75
+ }
76
+ /// A recorded working directory is usually inside the checkout, not at its root
77
+ /// (`<repo>/app`, `<repo>/src/lib`), so reading only `<path>/.git` found an
78
+ /// origin for a handful of the identities on a real machine and left every
79
+ /// other checkout of the same repository as its own picker row. Walk up to the
80
+ /// first ancestor with a .git and take its origin, or none: a local-only repo
81
+ /// nested in another one is its own project. Home is never the repo of a folder
82
+ /// below it, so a dotfiles repo there does not swallow every other folder.
83
+ function readGitOriginUrlUncached(path) {
84
+ const home = normalizeProxyPath(homedir());
85
+ let dir = path;
86
+ for (let depth = 0; depth < 64; depth++) {
87
+ if (dir !== path && normalizeProxyPath(dir) === home)
88
+ return null;
89
+ if (entryKind(join(dir, '.git')))
90
+ return originAt(dir);
91
+ const parent = dirname(dir);
92
+ if (parent === dir)
93
+ return null;
94
+ dir = parent;
95
+ }
96
+ return null;
97
+ }
98
+ function originAt(repoRoot) {
99
+ try {
100
+ let gitDir = join(repoRoot, '.git');
101
+ const kind = entryKind(gitDir);
102
+ if (kind === 'file') {
103
+ const match = readFileSync(gitDir, 'utf8').match(/^gitdir:\s*(.+?)\s*$/m);
104
+ if (!match?.[1])
105
+ return null;
106
+ gitDir = match[1].startsWith('/') || /^[a-zA-Z]:[\\/]/.test(match[1]) ? match[1] : join(repoRoot, match[1]);
107
+ }
108
+ else if (kind !== 'dir') {
109
+ return null;
110
+ }
111
+ for (const configPath of [join(gitDir, 'config'), join(resolveGitCommonDir(gitDir), 'config')]) {
112
+ if (!existsSync(configPath))
113
+ continue;
114
+ const url = parseGitConfigSection(readFileSync(configPath, 'utf8'), 'remote "origin"', 'url');
115
+ if (url)
116
+ return url;
117
+ }
118
+ return null;
119
+ }
120
+ catch {
121
+ return null;
122
+ }
123
+ }
124
+ // Agents delete their scratch clones, so the origin a folder had is kept in the
125
+ // cache dir: while the folder exists the filesystem answers (and overwrites the
126
+ // record, since scratch names get reused for other repos), once it is gone the
127
+ // record does.
128
+ const ORIGINS_FILE = 'git-origins.json';
129
+ const keyByPath = new Map();
130
+ let recorded = null;
131
+ const pending = new Map();
132
+ let exitHooked = false;
133
+ function readRecorded() {
134
+ try {
135
+ const parsed = JSON.parse(readFileSync(join(getCodeburnCacheDir(), ORIGINS_FILE), 'utf8'));
136
+ const paths = parsed?.paths;
137
+ if (!paths || typeof paths !== 'object')
138
+ return {};
139
+ return Object.fromEntries(Object.entries(paths).filter((e) => typeof e[1] === 'string'));
140
+ }
141
+ catch {
142
+ return {};
143
+ }
144
+ }
145
+ /** Normalized `origin` of the checkout containing `path`, or null when it has
146
+ * none. A path that no longer exists answers from what an earlier run saw. */
147
+ export function gitOriginKey(path) {
148
+ const memo = keyByPath.get(path);
149
+ if (memo !== undefined)
150
+ return memo;
151
+ recorded ??= readRecorded();
152
+ let key;
153
+ if (existsSync(path)) {
154
+ const url = readGitOriginUrl(path);
155
+ key = url ? normalizeOriginUrl(url) : null;
156
+ if ((Object.hasOwn(recorded, path) ? recorded[path] : null) !== key) {
157
+ if (key)
158
+ recorded[path] = key;
159
+ else
160
+ delete recorded[path];
161
+ checkoutsByParent = null;
162
+ folderNameMatch.clear();
163
+ // Lookups outside a parse (a filter over carried days) are kept too.
164
+ if (!exitHooked)
165
+ process.once('exit', saveGitOrigins);
166
+ exitHooked = true;
167
+ pending.set(path, key);
168
+ }
169
+ }
170
+ else {
171
+ key = Object.hasOwn(recorded, path) ? recorded[path] : null;
172
+ }
173
+ keyByPath.set(path, key);
174
+ return key;
175
+ }
176
+ /** A recorded project path as a native absolute path, or null. Codex strips
177
+ * the leading slash from its cwds, so a slash-bearing relative path is rooted. */
178
+ function nativeProjectPath(projectPath) {
179
+ const raw = (projectPath ?? '').trim().replace(/[\\/]+$/, '');
180
+ if (!raw)
181
+ return null;
182
+ if (isAbsolute(raw))
183
+ return raw;
184
+ if (process.platform === 'win32' || !raw.includes('/') || raw.startsWith('-'))
185
+ return null;
186
+ return `/${raw}`;
187
+ }
188
+ /** The origin of a recorded project path. */
189
+ export function projectOriginKey(projectPath) {
190
+ const path = nativeProjectPath(projectPath);
191
+ return path ? gitOriginKey(path) : null;
192
+ }
193
+ let checkoutsByParent = null;
194
+ const folderNameMatch = new Map();
195
+ /** Fallback for a DELETED folder that never had its origin recorded: when it is
196
+ * a sibling of a repository's checkout, named `<checkout>-<suffix>`
197
+ * or `<checkout>_<suffix>` in the same parent folder, it joins that
198
+ * repository; when several checkout names fit, the longest wins. Null while
199
+ * the folder exists (its own git data answers), when it has a real origin,
200
+ * and when the longest fitting names belong to two repositories. */
201
+ export function folderNameOriginKey(projectPath) {
202
+ const path = nativeProjectPath(projectPath);
203
+ if (!path)
204
+ return null;
205
+ const memo = folderNameMatch.get(path);
206
+ if (memo !== undefined)
207
+ return memo;
208
+ let match = null;
209
+ if (!existsSync(path) && !gitOriginKey(path)) {
210
+ if (!checkoutsByParent) {
211
+ checkoutsByParent = new Map();
212
+ for (const checkout of Object.keys(recorded ?? {})) {
213
+ const list = checkoutsByParent.get(dirname(checkout));
214
+ if (list)
215
+ list.push(checkout);
216
+ else
217
+ checkoutsByParent.set(dirname(checkout), [checkout]);
218
+ }
219
+ }
220
+ const name = basename(path);
221
+ let longest = 0;
222
+ let origins = new Set();
223
+ for (const checkout of checkoutsByParent.get(dirname(path)) ?? []) {
224
+ const base = basename(checkout);
225
+ if (base.length < longest || name.length <= base.length + 1 || !name.startsWith(base) || !'-_'.includes(name[base.length]))
226
+ continue;
227
+ const origin = gitOriginKey(checkout);
228
+ if (!origin)
229
+ continue;
230
+ if (base.length > longest) {
231
+ longest = base.length;
232
+ origins = new Set();
233
+ }
234
+ origins.add(origin);
235
+ }
236
+ if (origins.size === 1)
237
+ match = [...origins][0];
238
+ }
239
+ folderNameMatch.set(path, match);
240
+ return match;
241
+ }
242
+ /** The one list row (and filter pattern) for every folder under a temp root
243
+ * that is not a checkout of a known repository: agents' scratch folders,
244
+ * thousands of them, mostly deleted. */
245
+ export const TEMPORARY_PROJECTS = '@temp';
246
+ // macOS reaches /tmp and /var through /private, so both spellings fold to one.
247
+ function foldTempKey(path) {
248
+ const s = path.replace(/\\/g, '/').replace(/\/+$/, '').replace(/^\/private(?=\/(?:tmp|var)(?:\/|$))/, '');
249
+ return process.platform === 'win32' ? s.toLowerCase() : s;
250
+ }
251
+ let roots = null;
252
+ function tempRoots() {
253
+ roots ??= [...new Set([tmpdir(), '/tmp', '/var/folders'].map(foldTempKey))];
254
+ return roots;
255
+ }
256
+ export function isTemporaryProjectPath(projectPath) {
257
+ const path = nativeProjectPath(projectPath);
258
+ if (!path)
259
+ return false;
260
+ const key = foldTempKey(path);
261
+ return tempRoots().some(root => key === root || key.startsWith(`${root}/`));
262
+ }
263
+ /** Every repository an earlier parse saw a checkout of. */
264
+ export function knownOriginKeys() {
265
+ recorded ??= readRecorded();
266
+ return [...new Set(Object.values(recorded))];
267
+ }
268
+ /** A folder as `project link` stores it: absolute, with ~ expanded. */
269
+ export function projectLinkFolder(folder) {
270
+ const raw = folder.trim();
271
+ const path = raw === '~' || /^~[\\/]/.test(raw) ? homedir() + raw.slice(1) : raw;
272
+ return /^[a-zA-Z]:[\\/]/.test(path) ? win32.resolve(path) : resolve(path);
273
+ }
274
+ // Folders the user put in a repository (`codeburn project link`), longest
275
+ // first so a nested link wins. Never stamped into the day cache, so an unlink
276
+ // takes effect on the next report.
277
+ let projectLinks = [];
278
+ export function setProjectLinks(links) {
279
+ projectLinks = Object.entries(links && typeof links === 'object' ? links : {})
280
+ .filter((e) => typeof e[1] === 'string' && e[1] !== '')
281
+ .map(([folder, origin]) => [normalizeProxyPath(projectLinkFolder(folder)), origin])
282
+ .filter(([folder]) => folder !== '')
283
+ .sort((a, b) => b[0].length - a[0].length);
284
+ }
285
+ /** The repository a project link puts `projectPath` in. It beats the folder's
286
+ * own origin. Same path rule as proxy paths: per-OS case, folder boundary. */
287
+ export function linkedOriginKey(projectPath) {
288
+ if (!projectPath || projectLinks.length === 0)
289
+ return null;
290
+ const path = normalizeProxyPath(projectPath);
291
+ return projectLinks.find(([folder]) => path === folder || path.startsWith(`${folder}/`))?.[1] ?? null;
292
+ }
293
+ export function getProjectLinksConfigHash() {
294
+ return projectLinks.length ? JSON.stringify(projectLinks) : '';
295
+ }
296
+ /** "github.com/org/repo" -> "repo". */
297
+ export function originRepoName(originKey) {
298
+ return originKey.split('/').filter(Boolean).pop() ?? originKey;
299
+ }
300
+ /** Writes what this process learned, merged over what another one may have
301
+ * written meanwhile. Never fails the caller. */
302
+ export function saveGitOrigins() {
303
+ if (pending.size === 0)
304
+ return;
305
+ try {
306
+ const merged = readRecorded();
307
+ for (const [path, key] of pending) {
308
+ if (key)
309
+ merged[path] = key;
310
+ else
311
+ delete merged[path];
312
+ }
313
+ const target = join(getCodeburnCacheDir(), ORIGINS_FILE);
314
+ const tmp = `${target}.${process.pid}.tmp`;
315
+ writeFileSync(tmp, JSON.stringify({ version: 1, paths: merged }), { mode: 0o600 });
316
+ renameSync(tmp, target);
317
+ pending.clear();
318
+ }
319
+ catch {
320
+ // A missed save only means a later run learns it again while the folder exists.
321
+ }
322
+ }
323
+ export function __setTempRoots(paths) {
324
+ roots = paths && paths.map(foldTempKey);
325
+ }
326
+ export function __resetGitOriginCache() {
327
+ originByRoot.clear();
328
+ keyByPath.clear();
329
+ pending.clear();
330
+ recorded = null;
331
+ checkoutsByParent = null;
332
+ folderNameMatch.clear();
333
+ projectLinks = [];
334
+ }