claude-code-session-manager 0.133.0 → 0.134.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 (93) hide show
  1. package/dist/assets/AgentLibrary-C9KFGJQq.js +2 -0
  2. package/dist/assets/{AppSettings-BHKM_AKh.js → AppSettings-CvVQ6ot5.js} +2 -2
  3. package/dist/assets/{Button-CmO1wmPw.js → Button-BHvploNk.js} +1 -1
  4. package/dist/assets/DocumentEditorPane-DaX4xag_.js +1 -0
  5. package/dist/assets/{Extensions-Boo21B3b.js → Extensions-DbRY-KEz.js} +2 -2
  6. package/dist/assets/{History-C4epd1hp.js → History-BE_mjM24.js} +2 -2
  7. package/dist/assets/{Library-CrgzRQzL.js → Library-I37dQ6pB.js} +1 -1
  8. package/dist/assets/{ListDetail-DA7y1DQ-.js → ListDetail-DJYMWYQd.js} +1 -1
  9. package/dist/assets/{Panel-D-WMBhKH.js → Panel-DP8eSKSs.js} +1 -1
  10. package/dist/assets/{ProjectClaudeConfig-CuUADpIu.js → ProjectClaudeConfig-Cw8lc3Qi.js} +5 -5
  11. package/dist/assets/{ProvenanceBadge-B7AsoRk6.js → ProvenanceBadge-DUwhsmdA.js} +1 -1
  12. package/dist/assets/Scheduler-B9D2gZqs.js +16 -0
  13. package/dist/assets/Settings-DSk7bn-1.js +2 -0
  14. package/dist/assets/{SkillReferenceGraph-DX4ZgvlY.js → SkillReferenceGraph-DtJcJJHR.js} +1 -1
  15. package/dist/assets/{Skills-DqKI37yi.js → Skills-BPZnSjsB.js} +10 -10
  16. package/dist/assets/{SourceChip-C974LROr.js → SourceChip-DUxulNOp.js} +1 -1
  17. package/dist/assets/{SystemPrompt-C502jIwO.js → SystemPrompt-BXAugVle.js} +1 -1
  18. package/dist/assets/{TiptapBody-DwNXN6Ki.js → TiptapBody-CDC1vrOo.js} +28 -28
  19. package/dist/assets/{Toggle-C2OsxnPK.js → Toggle-CrgM7OTR.js} +1 -1
  20. package/dist/assets/{ViewTabs-DBxKGbAK.js → ViewTabs-DLwaU9RB.js} +1 -1
  21. package/dist/assets/{VoiceButton-C680wpmX.js → VoiceButton-C4hIBxIP.js} +1 -1
  22. package/dist/assets/geist-sans-latin-300-normal-C3kkMBb6.woff2 +0 -0
  23. package/dist/assets/geist-sans-latin-400-normal-gapTbOY8.woff2 +0 -0
  24. package/dist/assets/geist-sans-latin-500-normal-uokXdC-Q.woff2 +0 -0
  25. package/dist/assets/geist-sans-latin-600-normal-DFOURf8L.woff2 +0 -0
  26. package/dist/assets/geist-sans-latin-700-normal-BmN9tIp5.woff2 +0 -0
  27. package/dist/assets/{historyTotals-Cz-VYPEc.js → historyTotals-itA00dXm.js} +1 -1
  28. package/dist/assets/ibm-plex-mono-latin-400-normal-DMJ8VG8y.woff2 +0 -0
  29. package/dist/assets/ibm-plex-mono-latin-500-normal-DSY6xOcd.woff2 +0 -0
  30. package/dist/assets/ibm-plex-mono-latin-600-normal-BgSNZQsw.woff2 +0 -0
  31. package/dist/assets/{index-CMwAikUb.css → index-Cjt8B7H9.css} +1 -1
  32. package/dist/assets/index-Cznhnxhq.js +3116 -0
  33. package/dist/assets/newsreader-latin-400-italic-CEihAR-f.woff2 +0 -0
  34. package/dist/assets/newsreader-latin-400-normal-BFBkh4jY.woff2 +0 -0
  35. package/dist/assets/newsreader-latin-500-normal-B66TYsaK.woff2 +0 -0
  36. package/dist/assets/newsreader-latin-600-normal-30OJ_TG_.woff2 +0 -0
  37. package/dist/assets/newsreader-latin-700-normal-rIgV_oaK.woff2 +0 -0
  38. package/dist/index.html +2 -5
  39. package/dist-web/app.css +1 -1
  40. package/dist-web/app.js +413 -408
  41. package/dist-web/index.html +0 -3
  42. package/package.json +4 -2
  43. package/scripts/README.md +1 -0
  44. package/scripts/scheduler-mcp-server.cjs +31 -0
  45. package/src/main/agentLibrary.cjs +27 -4
  46. package/src/main/build-info.json +4 -4
  47. package/src/main/chatRunner.cjs +9 -0
  48. package/src/main/config.cjs +22 -0
  49. package/src/main/crashDiagnostics.cjs +10 -2
  50. package/src/main/index.cjs +34 -25
  51. package/src/main/ipcSchemas.cjs +6 -0
  52. package/src/main/lib/agent-cli/agentCliEvents.cjs +8 -0
  53. package/src/main/lib/demo-video-kit/capture.cjs +4 -37
  54. package/src/main/lib/demo-video-kit/character.cjs +20 -2
  55. package/src/main/lib/demo-video-kit/checks.cjs +82 -1
  56. package/src/main/lib/demo-video-kit/frames.cjs +3 -28
  57. package/src/main/lib/demo-video-kit/playwrightLoader.cjs +67 -0
  58. package/src/main/lib/demo-video-kit/seedKit.cjs +2 -2
  59. package/src/main/lib/demo-video-kit/sound.cjs +5 -2
  60. package/src/main/lib/epic/epicMint.cjs +1 -3
  61. package/src/main/lib/epic/promptSessionsCreateEpic.cjs +37 -4
  62. package/src/main/lib/epic/restorableSessions.cjs +88 -0
  63. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +56 -1
  64. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +21 -3
  65. package/src/main/lib/feedback-remote/remoteAssets.cjs +25 -1
  66. package/src/main/lib/mcpToolCatalog.cjs +15 -0
  67. package/src/main/lib/persona-macro/agentPersonaSchema.cjs +10 -1
  68. package/src/main/lib/persona-macro/builtinMacros.cjs +3 -2
  69. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
  70. package/src/main/lib/prd/listPrdsSingleFlight.cjs +79 -0
  71. package/src/main/lib/prd/prdAgentType.cjs +17 -7
  72. package/src/main/lib/telemetry/crashTelemetry.cjs +10 -5
  73. package/src/main/lib/telemetry/telemetryBoot.cjs +77 -4
  74. package/src/main/lib/telemetry/telemetryClient.cjs +54 -9
  75. package/src/main/lib/telemetry/telemetryConsent.cjs +3 -0
  76. package/src/main/lib/telemetry/telemetryCounters.cjs +7 -2
  77. package/src/main/lib/telemetry/telemetrySettings.cjs +5 -0
  78. package/src/main/pty.cjs +2 -2
  79. package/src/main/scheduler/prdParser.cjs +1 -1
  80. package/src/main/scheduler.cjs +19 -3
  81. package/src/main/seedAgentPersonas.cjs +24 -0
  82. package/src/main/seedStatus.cjs +5 -2
  83. package/src/main/telemetryIpc.cjs +1 -5
  84. package/src/preload/api.d.ts +29 -14
  85. package/src/preload/apiSurface.json +7 -0
  86. package/src/preload/index.cjs +3 -1
  87. package/src/seed/agents/demo-video-builder.md +7 -2
  88. package/dist/assets/AgentLibrary-DOAG-mcG.js +0 -2
  89. package/dist/assets/DocumentEditorPane-8QMNrNRt.js +0 -1
  90. package/dist/assets/Scheduler-C86gRh51.js +0 -16
  91. package/dist/assets/Settings-B4Q9DwVS.js +0 -2
  92. package/dist/assets/index-Dh5geJe3.js +0 -3111
  93. package/src/main/lib/telemetry/telemetryBacklog.cjs +0 -607
@@ -1,607 +0,0 @@
1
- 'use strict';
2
-
3
- /**
4
- * telemetryBacklog.cjs — drains the PRE-EXISTING backlog of structured error
5
- * logs (`<project>/session-manager-operations/logs/errors-<date>.jsonl`,
6
- * written by opsErrorLog.cjs) into telemetryClient, and marks exactly what
7
- * was CONFIRMED delivered so nothing is ever sent twice and nothing is
8
- * silently lost.
9
- *
10
- * This is the "existing errors sent and marked done" half of the product
11
- * instruction telemetryBoot.cjs documents ("on installation of a new version
12
- * and loadup, existing errors are sent and marked done; new errors are
13
- * accumulated and periodically sent (daily)"). telemetryBoot/telemetryClient
14
- * own the daily-accumulate half; this module owns the backlog half. It does
15
- * NOT send anything itself — telemetryClient.reportError/logLine/flush are
16
- * the sole sender + the sole idempotency authority (recordId dedup,
17
- * telemetry-sent.json). This module is a SECOND, independent bookkeeper over
18
- * the same records (a byte-offset watermark), because a single writer can't
19
- * safely satisfy both "resume where we left off" (needs an optimistic,
20
- * fast-advancing offset) and "never lose a record to queue eviction" (needs
21
- * a conservative, delivery-confirmed offset) at once — see the two-phase
22
- * design below.
23
- *
24
- * TWO-PHASE WATERMARK. Per file, ~/.claude/session-manager/telemetry-
25
- * watermarks.json tracks:
26
- * - bytesEnqueued: how far we've read + handed lines to telemetryClient.
27
- * Advances the instant a line has been processed
28
- * (whether telemetryClient's queue accepted it, rejected
29
- * it as a duplicate, or dropped it via its own
30
- * dedup window) — malformed/duplicate/deduped lines must
31
- * never be able to wedge a file's forward progress, the
32
- * same principle opsErrorLog-adjacent lines document for
33
- * malformed JSON.
34
- * - bytesConfirmed: only advances for the CONTIGUOUS prefix of lines whose
35
- * recordId telemetryClient's flush() reports in its
36
- * `sent` array. A failed flush leaves this untouched.
37
- * - linesConfirmed / completedAt: bookkeeping for the retention-floor and
38
- * already-fully-delivered fast paths below.
39
- *
40
- * DETERMINISTIC recordId = sha256(`${projectHash}|${filename}|${byteOffset}`)
41
- * .slice(0, 16). Because it's a pure function of WHERE the line sits in the
42
- * file (never a random id, never file content), re-deriving it after a
43
- * watermark rewind reproduces the exact same id telemetryClient already
44
- * holds/held — so a rewind is harmless (the client's own recordId dedup
45
- * absorbs the resend) instead of duplicating records.
46
- *
47
- * BOOT RECONCILIATION (reconcileWatermarks, the anti-loss half): for any
48
- * file where bytesConfirmed < bytesEnqueued, re-derive the recordIds for the
49
- * bytes in that gap (cheap: recordId is a pure function of byte offset) and
50
- * ask telemetryClient whether each is still pending delivery or already in
51
- * its durable sent-set. Only when a record is in NEITHER (lost to queue
52
- * eviction, or a corrupt queue file) do we rewind bytesEnqueued back down to
53
- * bytesConfirmed so the next drain re-sends it.
54
- *
55
- * projectHash = sha256(normalizedProjectRoot).slice(0, 12) — same formula as
56
- * telemetryClient.cjs's internal hashCwd (kept as an independent literal
57
- * here, not a shared require, for the same reason opsErrorLog.cjs keeps its
58
- * own REDACT_KEY copy: this module must have no dependency on telemetry
59
- * client internals beyond its public ingest/egress contract). Keying the
60
- * watermark file by hash rather than raw path means the one on-disk artifact
61
- * this feature adds never itself stores a user's directory layout.
62
- *
63
- * Every entry point here is wrapped so it can never throw and never blocks
64
- * app startup — telemetry failing must stay completely invisible to the user.
65
- */
66
-
67
- const fs = require('node:fs');
68
- const fsp = require('node:fs/promises');
69
- const os = require('node:os');
70
- const path = require('node:path');
71
- const crypto = require('node:crypto');
72
-
73
- const config = require('../../config.cjs');
74
-
75
- const DEFAULT_LIMIT = 500;
76
- const RETENTION_DAYS = 30;
77
- const RETENTION_MS = RETENTION_DAYS * 24 * 60 * 60 * 1000;
78
- const FILE_DATE_RE = /^errors-(\d{4})-(\d{2})-(\d{2})\.jsonl$/;
79
- const NEWLINE = 0x0a;
80
-
81
- /** Module-singleton cache of the most recent drainBacklog() summary, for the Settings inspector. */
82
- let lastSummary = null;
83
-
84
- function lastRunSummary() {
85
- return lastSummary ? { ...lastSummary } : null;
86
- }
87
-
88
- let migrated = false;
89
- function watermarksPath() {
90
- const p = path.join(os.homedir(), '.claude', 'session-manager', 'telemetry-watermarks.json');
91
- if (!migrated) {
92
- migrated = true;
93
- config.migrateLegacyHomeFile(path.join(os.homedir(), '.config', 'session-manager', 'telemetry-watermarks.json'), p);
94
- }
95
- return p;
96
- }
97
-
98
- function resolveDeps(deps = {}) {
99
- return {
100
- sessionsStore: deps.sessionsStore || require('../../sessionsStore.cjs'),
101
- isEphemeralCwd: deps.isEphemeralCwd || require('../ephemeralCwd.cjs').isEphemeralCwd,
102
- resolveProjectContext: deps.resolveProjectContext || require('../projectRootResolve.cjs').resolveProjectContext,
103
- telemetryClient: deps.telemetryClient || require('./telemetryClient.cjs'),
104
- opsErrorLog: deps.opsErrorLog || require('./opsErrorLog.cjs'),
105
- config: deps.config || config,
106
- fs: deps.fs || fs,
107
- fsp: deps.fsp || fsp,
108
- };
109
- }
110
-
111
- function projectHashOf(normalizedCwd) {
112
- return crypto.createHash('sha256').update(String(normalizedCwd)).digest('hex').slice(0, 12);
113
- }
114
-
115
- function recordIdFor(projectHash, filename, byteOffset) {
116
- return crypto.createHash('sha256').update(`${projectHash}|${filename}|${byteOffset}`).digest('hex').slice(0, 16);
117
- }
118
-
119
- function watermarkKey(projectHash, filename) {
120
- return `${projectHash}/${filename}`;
121
- }
122
-
123
- // ─── watermark persistence ─────────────────────────────────────────────
124
-
125
- async function loadWatermarks(deps) {
126
- try {
127
- const raw = await deps.fsp.readFile(watermarksPath(), 'utf8');
128
- const data = JSON.parse(raw);
129
- if (data && typeof data === 'object' && !Array.isArray(data)) return data;
130
- return {};
131
- } catch {
132
- // Missing or corrupt watermarks file is treated as empty, never fatal —
133
- // worst case is a full (idempotent, deduped-by-recordId) re-drain.
134
- return {};
135
- }
136
- }
137
-
138
- async function saveWatermarks(deps, wm) {
139
- try {
140
- await deps.config.writeJson(watermarksPath(), wm);
141
- } catch {
142
- /* best-effort — a failed watermark write must never throw out of a boot path */
143
- }
144
- }
145
-
146
- function entryFor(wm, key) {
147
- const e = wm[key];
148
- if (e && typeof e === 'object') {
149
- return {
150
- bytesEnqueued: Number.isFinite(e.bytesEnqueued) ? e.bytesEnqueued : 0,
151
- bytesConfirmed: Number.isFinite(e.bytesConfirmed) ? e.bytesConfirmed : 0,
152
- linesConfirmed: Number.isFinite(e.linesConfirmed) ? e.linesConfirmed : 0,
153
- completedAt: typeof e.completedAt === 'string' ? e.completedAt : null,
154
- };
155
- }
156
- return { bytesEnqueued: 0, bytesConfirmed: 0, linesConfirmed: 0, completedAt: null };
157
- }
158
-
159
- // ─── project + file enumeration ────────────────────────────────────────
160
-
161
- /**
162
- * Known projects come from the same source of truth the renderer restores
163
- * tabs from (sessionsStore.cjs's ~/.claude/session-manager/tabs.json — TAB =
164
- * cwd = Main Project), deduped by normalized cwd, with ephemeral (worktree /
165
- * tmpdir) cwds excluded before normalization even runs, since a worktree cwd
166
- * would otherwise resolve back to its real project and be scanned twice
167
- * under two identities. A cwd that no longer exists on disk is skipped, not
168
- * thrown on.
169
- */
170
- async function enumerateProjectCwds(deps) {
171
- const cwds = [];
172
- const seen = new Set();
173
- let tabs = [];
174
- try {
175
- const loaded = await deps.sessionsStore.load();
176
- tabs = Array.isArray(loaded?.tabs) ? loaded.tabs : [];
177
- } catch {
178
- return cwds;
179
- }
180
- for (const tab of tabs) {
181
- const rawCwd = tab && typeof tab.cwd === 'string' ? tab.cwd : '';
182
- if (!rawCwd || !path.isAbsolute(rawCwd)) continue;
183
- if (deps.isEphemeralCwd(rawCwd)) continue;
184
- let normalized;
185
- try {
186
- normalized = deps.resolveProjectContext({ cwd: rawCwd }).cwd || rawCwd;
187
- } catch {
188
- normalized = rawCwd;
189
- }
190
- if (!normalized || deps.isEphemeralCwd(normalized)) continue;
191
- if (seen.has(normalized)) continue;
192
- let exists = false;
193
- try {
194
- exists = deps.fs.existsSync(normalized);
195
- } catch {
196
- exists = false;
197
- }
198
- if (!exists) continue;
199
- seen.add(normalized);
200
- cwds.push(normalized);
201
- }
202
- return cwds;
203
- }
204
-
205
- /** Oldest-first errors-YYYY-MM-DD.jsonl listing for one project's logs dir. */
206
- function listLogFiles(deps, cwd) {
207
- const dir = deps.opsErrorLog.logsDir(cwd);
208
- let names;
209
- try {
210
- names = deps.fs.readdirSync(dir);
211
- } catch {
212
- return [];
213
- }
214
- const files = [];
215
- for (const name of names) {
216
- const m = FILE_DATE_RE.exec(name);
217
- if (!m) continue;
218
- const dateMs = Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
219
- files.push({ name, dateMs, fullPath: path.join(dir, name) });
220
- }
221
- files.sort((a, b) => a.dateMs - b.dateMs);
222
- return files;
223
- }
224
-
225
- // ─── line parsing (byte-accurate, read-only) ───────────────────────────
226
-
227
- /**
228
- * Splits `buffer` into complete ('\n'-terminated) lines starting at
229
- * `fromByte`. A trailing partial line (no newline yet — an in-progress
230
- * write to today's file) is left unconsumed: neither counted nor advanced
231
- * past, so the next drain picks it up once it's complete. O(n) in the
232
- * scanned byte range.
233
- */
234
- function splitCompleteLines(buffer, fromByte) {
235
- const lines = [];
236
- let searchStart = fromByte;
237
- while (true) {
238
- const idx = buffer.indexOf(NEWLINE, searchStart);
239
- if (idx === -1) break;
240
- lines.push({
241
- text: buffer.toString('utf8', searchStart, idx),
242
- startByte: searchStart,
243
- endByte: idx + 1,
244
- });
245
- searchStart = idx + 1;
246
- }
247
- return lines;
248
- }
249
-
250
- function levelFor(parsed) {
251
- return parsed && parsed.level === 'warn' ? 'warn' : 'error';
252
- }
253
-
254
- async function reportLine(deps, { cwd, filename, recordId, parsed }) {
255
- const level = levelFor(parsed);
256
- const scope = (parsed && parsed.scope) || 'unknown';
257
- const tags = Array.isArray(parsed && parsed.tags) ? parsed.tags : [];
258
- const context = {
259
- scope,
260
- tags,
261
- cwd,
262
- tabId: parsed.tabId || null,
263
- epicId: parsed.epicId || null,
264
- backlogFile: filename,
265
- };
266
- if (level === 'warn') {
267
- return deps.telemetryClient.logLine({ recordId, level: 'warn', msg: `backlog:${scope}`, fields: context });
268
- }
269
- return deps.telemetryClient.reportError({ recordId, name: scope || 'backlogError', msg: `backlog:${scope}`, context });
270
- }
271
-
272
- // ─── drain ──────────────────────────────────────────────────────────────
273
-
274
- /**
275
- * drainBacklog({ now, limit, deps, reason }) — the main entry point.
276
- *
277
- * For every known, non-ephemeral project (oldest log file first within each
278
- * project), reads lines from the current bytesEnqueued watermark forward,
279
- * hands each to telemetryClient, then flushes once and advances
280
- * bytesConfirmed for the contiguous prefix of lines flush() reports as
281
- * `sent`. Bounded by `limit` lines total per call (default 500) so months of
282
- * backlog can't emit one enormous burst — the remainder is picked up by the
283
- * next call. Files older than the 30-day retention floor are stamped
284
- * completed WITHOUT ever being opened for read. Never throws.
285
- */
286
- async function drainBacklog({ now = Date.now(), limit = DEFAULT_LIMIT, deps: depsOverride, reason = 'boot' } = {}) {
287
- const deps = resolveDeps(depsOverride);
288
- const summary = {
289
- projectsScanned: 0,
290
- filesScanned: 0,
291
- linesEnqueued: 0,
292
- linesConfirmed: 0,
293
- linesSkipped: 0,
294
- filesCompleted: 0,
295
- watermarksRewound: 0,
296
- reason,
297
- };
298
-
299
- try {
300
- const reconcileSummary = await reconcileWatermarks({ now, deps: depsOverride });
301
- summary.watermarksRewound += reconcileSummary.watermarksRewound;
302
- } catch {
303
- /* reconciliation must never block a drain attempt */
304
- }
305
-
306
- let wm;
307
- try {
308
- wm = await loadWatermarks(deps);
309
- } catch {
310
- wm = {};
311
- }
312
-
313
- let budget = Number.isFinite(limit) && limit > 0 ? limit : DEFAULT_LIMIT;
314
- const cutoffMs = now - RETENTION_MS;
315
-
316
- let cwds = [];
317
- try {
318
- cwds = await enumerateProjectCwds(deps);
319
- } catch {
320
- cwds = [];
321
- }
322
-
323
- for (const cwd of cwds) {
324
- summary.projectsScanned += 1;
325
- const projectHash = projectHashOf(cwd);
326
- let files = [];
327
- try {
328
- files = listLogFiles(deps, cwd);
329
- } catch {
330
- files = [];
331
- }
332
-
333
- for (const file of files) {
334
- if (budget <= 0) break;
335
- const key = watermarkKey(projectHash, file.name);
336
- const entry = entryFor(wm, key);
337
-
338
- if (file.dateMs < cutoffMs) {
339
- // Retention floor: adoption never backfills ancient history, and the
340
- // file is never even stat'd to compute this.
341
- if (!entry.completedAt) {
342
- wm[key] = { ...entry, completedAt: new Date(now).toISOString() };
343
- summary.filesCompleted += 1;
344
- }
345
- continue;
346
- }
347
-
348
- let stat;
349
- try {
350
- stat = deps.fs.statSync(file.fullPath);
351
- } catch {
352
- continue; // file vanished under us — skip, don't throw
353
- }
354
- const size = stat.size;
355
-
356
- if (entry.completedAt && size === entry.bytesEnqueued) {
357
- // Fully confirmed and unchanged since — skipped without being
358
- // re-opened (only a cheap stat, never a content read).
359
- continue;
360
- }
361
-
362
- summary.filesScanned += 1;
363
-
364
- // Truncation/rotation safety: current size smaller than what we'd
365
- // already claimed to have enqueued means the file was truncated —
366
- // re-read from zero rather than seeking past EOF. A completed file
367
- // whose size has since changed (append past completion, or
368
- // truncation) is no longer "done" — it needs to be re-examined.
369
- let bytesEnqueued = entry.bytesEnqueued;
370
- let bytesConfirmed = entry.bytesConfirmed;
371
- if (size < bytesEnqueued) {
372
- bytesEnqueued = 0;
373
- bytesConfirmed = 0;
374
- }
375
-
376
- if (bytesConfirmed >= size && size > 0) {
377
- wm[key] = { ...entry, bytesEnqueued: size, bytesConfirmed: size, completedAt: new Date(now).toISOString() };
378
- summary.filesCompleted += 1;
379
- continue;
380
- }
381
-
382
- if (bytesEnqueued >= size) {
383
- // Nothing new since last drain.
384
- wm[key] = { ...entry, bytesEnqueued, bytesConfirmed, completedAt: null };
385
- continue;
386
- }
387
-
388
- let buffer;
389
- try {
390
- buffer = await deps.fsp.readFile(file.fullPath);
391
- } catch {
392
- continue;
393
- }
394
-
395
- const lines = splitCompleteLines(buffer, bytesEnqueued);
396
- const enqueuedThisFile = []; // { startByte, endByte, recordId }
397
- let cursor = bytesEnqueued;
398
-
399
- for (const line of lines) {
400
- if (budget <= 0) break;
401
- budget -= 1;
402
- cursor = line.endByte;
403
-
404
- let parsed = null;
405
- try {
406
- parsed = line.text.trim() ? JSON.parse(line.text) : null;
407
- } catch {
408
- parsed = null;
409
- }
410
- if (!parsed || typeof parsed !== 'object') {
411
- summary.linesSkipped += 1;
412
- continue;
413
- }
414
-
415
- const recordId = recordIdFor(projectHash, file.name, line.startByte);
416
- try {
417
- const result = await reportLine(deps, { cwd, filename: file.name, recordId, parsed });
418
- if (result && result.accepted) summary.linesEnqueued += 1;
419
- // Tracked for confirmation-prefix checking regardless of `accepted`
420
- // — a 'duplicate'/dedup rejection just means telemetryClient
421
- // already has (or already sent) this exact recordId, which the
422
- // sentIds check below verifies independently.
423
- enqueuedThisFile.push({ startByte: line.startByte, endByte: line.endByte, recordId });
424
- } catch {
425
- summary.linesSkipped += 1;
426
- }
427
- }
428
-
429
- bytesEnqueued = cursor;
430
- wm[key] = { ...entry, bytesEnqueued, bytesConfirmed, completedAt: null };
431
- await saveWatermarks(deps, wm);
432
-
433
- if (enqueuedThisFile.length > 0) {
434
- let flushResult = { sent: [], failed: [] };
435
- try {
436
- flushResult = await deps.telemetryClient.flush('manual');
437
- } catch {
438
- flushResult = { sent: [], failed: [] };
439
- }
440
- const sentIds = new Set(flushResult.sent || []);
441
-
442
- // Advance bytesConfirmed only across the CONTIGUOUS prefix (by byte
443
- // offset) of lines this round that were actually confirmed sent —
444
- // a gap (e.g. a later record's channel flushed but an earlier
445
- // record's channel didn't) must stop the advance right there.
446
- let confirmedThrough = bytesConfirmed;
447
- for (const rec of enqueuedThisFile) {
448
- if (rec.startByte !== confirmedThrough) break; // gap from a prior unconfirmed record
449
- if (!sentIds.has(rec.recordId)) break;
450
- confirmedThrough = rec.endByte;
451
- summary.linesConfirmed += 1;
452
- }
453
- bytesConfirmed = confirmedThrough;
454
-
455
- const finalEntry = { ...entry, bytesEnqueued, bytesConfirmed, completedAt: null };
456
- if (bytesConfirmed >= size) {
457
- finalEntry.completedAt = new Date(now).toISOString();
458
- summary.filesCompleted += 1;
459
- }
460
- wm[key] = finalEntry;
461
- await saveWatermarks(deps, wm);
462
- }
463
-
464
- // Yield between files so a large backlog never blocks the event loop.
465
- await new Promise((resolve) => setImmediate(resolve));
466
- }
467
- }
468
-
469
- lastSummary = { ...summary, ranAt: new Date(now).toISOString() };
470
- return summary;
471
- }
472
-
473
- // ─── boot reconciliation (anti-loss) ───────────────────────────────────
474
-
475
- /**
476
- * reconcileWatermarks({ now, deps }) — for any file whose watermark shows
477
- * bytesConfirmed < bytesEnqueued, re-derives the recordIds for the bytes in
478
- * that gap and checks whether telemetryClient still has each one pending, or
479
- * already recorded as sent. Only when a record is in NEITHER (queue
480
- * eviction, or a corrupt queue/sent file) is bytesEnqueued rewound back down
481
- * to bytesConfirmed so the next drainBacklog() call re-sends it. Never
482
- * throws.
483
- */
484
- async function reconcileWatermarks({ now = Date.now(), deps: depsOverride } = {}) {
485
- const deps = resolveDeps(depsOverride);
486
- const summary = { watermarksRewound: 0 };
487
-
488
- let wm;
489
- try {
490
- wm = await loadWatermarks(deps);
491
- } catch {
492
- return summary;
493
- }
494
-
495
- let sentIds = new Set();
496
- try {
497
- const raw = await deps.fsp.readFile(deps.telemetryClient.sentPath(), 'utf8');
498
- const data = JSON.parse(raw);
499
- if (data && Array.isArray(data.ids)) sentIds = new Set(data.ids);
500
- } catch {
501
- sentIds = new Set();
502
- }
503
-
504
- let cwds = [];
505
- try {
506
- cwds = await enumerateProjectCwds(deps);
507
- } catch {
508
- cwds = [];
509
- }
510
-
511
- const cwdByHash = new Map();
512
- for (const cwd of cwds) cwdByHash.set(projectHashOf(cwd), cwd);
513
-
514
- let changed = false;
515
- for (const key of Object.keys(wm)) {
516
- const slash = key.indexOf('/');
517
- if (slash === -1) continue;
518
- const projectHash = key.slice(0, slash);
519
- const filename = key.slice(slash + 1);
520
- const cwd = cwdByHash.get(projectHash);
521
- if (!cwd) continue; // project no longer known — leave watermark as-is
522
-
523
- const entry = entryFor(wm, key);
524
- if (entry.bytesConfirmed >= entry.bytesEnqueued) continue;
525
-
526
- const filePath = path.join(deps.opsErrorLog.logsDir(cwd), filename);
527
- let buffer;
528
- try {
529
- buffer = await deps.fsp.readFile(filePath);
530
- } catch {
531
- continue; // can't verify without the file — leave as-is rather than guess
532
- }
533
-
534
- const gapEnd = Math.min(entry.bytesEnqueued, buffer.length);
535
- const lines = splitCompleteLines(buffer.subarray(0, gapEnd), entry.bytesConfirmed);
536
- if (lines.length === 0) continue;
537
-
538
- let allAccountedFor = true;
539
- for (const line of lines) {
540
- const recordId = recordIdFor(projectHash, filename, line.startByte);
541
- let pending = false;
542
- try {
543
- pending = await deps.telemetryClient.isPending(recordId);
544
- } catch {
545
- pending = false;
546
- }
547
- if (pending || sentIds.has(recordId)) continue;
548
- allAccountedFor = false;
549
- break;
550
- }
551
-
552
- if (!allAccountedFor) {
553
- wm[key] = { ...entry, bytesEnqueued: entry.bytesConfirmed };
554
- summary.watermarksRewound += 1;
555
- changed = true;
556
- }
557
- }
558
-
559
- if (changed) await saveWatermarks(deps, wm);
560
- return summary;
561
- }
562
-
563
- // ─── boot wiring (the WHEN, mirroring telemetryBoot.cjs's own split) ────
564
-
565
- /**
566
- * bootDrain({ now, appVersion, deps }) — the call site index.cjs's
567
- * `ready-to-show` handler invokes: always drains once with reason 'boot',
568
- * and — the FIRST time this appVersion has ever been seen by the drainer
569
- * (tracked in the watermarks file's own `_meta.lastDrainVersion`, so this
570
- * module owns its own version-change bookkeeping rather than reaching into
571
- * telemetrySettings.json's strict, unrelated schema) — drains a second time
572
- * tagged reason 'version-change'. The second pass is cheap even when
573
- * nothing new exists to send: every file it would touch was already
574
- * advanced by the first pass in this same call, so it's a no-op scan.
575
- * Never throws.
576
- */
577
- async function bootDrain({ now = Date.now(), appVersion, deps: depsOverride } = {}) {
578
- const deps = resolveDeps(depsOverride);
579
- const summary = await drainBacklog({ now, deps: depsOverride, reason: 'boot' });
580
-
581
- try {
582
- const wm = await loadWatermarks(deps);
583
- const meta = (wm && typeof wm._meta === 'object' && wm._meta) || {};
584
- if (appVersion && meta.lastDrainVersion !== appVersion) {
585
- await drainBacklog({ now, deps: depsOverride, reason: 'version-change' });
586
- const wm2 = await loadWatermarks(deps);
587
- wm2._meta = { ...(wm2._meta && typeof wm2._meta === 'object' ? wm2._meta : {}), lastDrainVersion: appVersion };
588
- await saveWatermarks(deps, wm2);
589
- }
590
- } catch {
591
- /* version-change bookkeeping must never block the ordinary boot drain above */
592
- }
593
-
594
- return summary;
595
- }
596
-
597
- module.exports = {
598
- drainBacklog,
599
- reconcileWatermarks,
600
- bootDrain,
601
- watermarksPath,
602
- lastRunSummary,
603
- // exported for unit tests only
604
- _projectHashOf: projectHashOf,
605
- _recordIdFor: recordIdFor,
606
- _enumerateProjectCwds: enumerateProjectCwds,
607
- };