claude-code-session-manager 0.137.0 → 0.139.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 (101) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +339 -82
  3. package/dist/assets/{AppSettings-l7NTc0yu.js → AppSettings-CUfWY9vN.js} +2 -2
  4. package/dist/assets/History-DDnqaLyw.js +2 -0
  5. package/dist/assets/HomeClaudeConfig-CGD2Onjv.js +3 -0
  6. package/dist/assets/{Panel-BuInRmA0.js → Panel-Csyd9HbD.js} +1 -1
  7. package/dist/assets/ProjectClaudeConfig-C-jlYpC_.js +26 -0
  8. package/dist/assets/{Scheduler-B7sn2mUw.js → Scheduler-NLs08fx7.js} +9 -9
  9. package/dist/assets/{SkillReferenceGraph-DwV0Ueyc.js → SkillReferenceGraph-DcscPXAG.js} +1 -1
  10. package/dist/assets/Skills-BpGRKOcY.js +67 -0
  11. package/dist/assets/{TiptapBody-Bl8hDhhS.js → TiptapBody-DSU3769X.js} +60 -54
  12. package/dist/assets/ViewTabs-C0PRZx4_.js +1 -0
  13. package/dist/assets/{VoiceButton-DJx-jY4r.js → VoiceButton-D2rMurNg.js} +1 -1
  14. package/dist/assets/{historyTotals-Cgjm5q24.js → historyTotals-TcIQs2sh.js} +1 -1
  15. package/dist/assets/{index-62tyjEQB.css → index-BCySPdtU.css} +1 -1
  16. package/dist/assets/index-C-d0DCre.js +3124 -0
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +471 -452
  20. package/package.json +13 -5
  21. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  22. package/plugins/session-manager-dev/skills/builder/SKILL.md +12 -4
  23. package/plugins/session-manager-dev/skills/builder/scripts/publish-preflight.cjs +255 -0
  24. package/plugins/session-manager-dev/skills/develop/SKILL.md +12 -5
  25. package/scripts/README.md +1 -0
  26. package/scripts/scheduler-mcp-server.cjs +161 -18
  27. package/src/main/build-info.json +4 -4
  28. package/src/main/chatRunner.cjs +53 -2
  29. package/src/main/exchanges.cjs +70 -5
  30. package/src/main/historyAggregator.cjs +84 -58
  31. package/src/main/historyDashboard.cjs +18 -13
  32. package/src/main/index.cjs +35 -9
  33. package/src/main/ipcSchemas.cjs +133 -5
  34. package/src/main/lib/claude/effectiveModelInfo.cjs +2 -2
  35. package/src/main/lib/claude/modelPricing.cjs +148 -0
  36. package/src/main/lib/demo-video-kit/checks.cjs +16 -0
  37. package/src/main/lib/epic/epicAdminRoutes.cjs +101 -0
  38. package/src/main/lib/epic/epicAttachments.cjs +143 -0
  39. package/src/main/lib/epic/epicJobReceipt.cjs +87 -0
  40. package/src/main/lib/epic/epicMint.cjs +4 -0
  41. package/src/main/lib/epic/epicOutsideRead.cjs +306 -0
  42. package/src/main/lib/epic/epicOutsideState.cjs +233 -0
  43. package/src/main/lib/epic/epicSettle.cjs +1 -1
  44. package/src/main/lib/epic/epicStateWatcher.cjs +157 -0
  45. package/src/main/lib/epic/externalRef.cjs +37 -0
  46. package/src/main/lib/epic/externalRefIndex.cjs +136 -0
  47. package/src/main/lib/epic/restorableSessions.cjs +151 -17
  48. package/src/main/lib/epic/transcriptUsage.cjs +197 -0
  49. package/src/main/lib/externalContract.cjs +111 -0
  50. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +121 -4
  51. package/src/main/lib/feedback-remote/crossProjectReply.cjs +83 -1
  52. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -6
  53. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +50 -8
  54. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +218 -4
  55. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +19 -3
  56. package/src/main/lib/feedback-remote/feedbackImages.cjs +171 -0
  57. package/src/main/lib/feedback-remote/localAdminHttp.cjs +11 -10
  58. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +287 -1
  59. package/src/main/lib/feedback-remote/needsYouAdminRoutes.cjs +133 -0
  60. package/src/main/lib/feedback-remote/needsYouIpc.cjs +50 -0
  61. package/src/main/lib/feedback-remote/needsYouStore.cjs +281 -0
  62. package/src/main/lib/feedback-remote/remoteFrameAssembler.cjs +113 -0
  63. package/src/main/lib/historyRollup.cjs +32 -5
  64. package/src/main/lib/mcpToolCatalog.cjs +111 -14
  65. package/src/main/lib/persona-macro/agentAdminRoutes.cjs +121 -0
  66. package/src/main/lib/persona-macro/macroLibrary.cjs +7 -0
  67. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
  68. package/src/main/lib/process/bootStdioGuard.cjs +32 -0
  69. package/src/main/lib/process/stdioGuard.cjs +115 -0
  70. package/src/main/lib/promptSessionSchema.cjs +4 -0
  71. package/src/main/lib/remoteTranscriptTail.cjs +32 -1
  72. package/src/main/lib/scheduler/schedulerPaths.cjs +9 -0
  73. package/src/main/lib/telemetry/auditEvents.cjs +176 -0
  74. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +45 -0
  75. package/src/main/loopEfficiencyHandlers.cjs +1 -1
  76. package/src/main/scheduler.cjs +29 -0
  77. package/src/main/templates/PRD_AUTHORING.md +1 -0
  78. package/src/main/transcripts.cjs +62 -7
  79. package/src/main/webRemote.cjs +122 -18
  80. package/src/preload/api.d.ts +98 -9
  81. package/src/preload/apiSurface.cjs +7 -0
  82. package/src/preload/apiSurface.json +415 -83
  83. package/src/preload/index.cjs +17 -3
  84. package/src/seed/agents/demo-video-builder.md +10 -7
  85. package/dist/assets/AgentLibrary-DV0DTZDC.js +0 -2
  86. package/dist/assets/Button-Cmfkgjfa.js +0 -1
  87. package/dist/assets/DocumentEditorPane-MTljV-Uw.js +0 -1
  88. package/dist/assets/Extensions-Cc1Q_8id.js +0 -2
  89. package/dist/assets/History-CFo-1DHo.js +0 -2
  90. package/dist/assets/Library-C_ibFiOx.js +0 -32
  91. package/dist/assets/ListDetail-ByULG209.js +0 -1
  92. package/dist/assets/ProjectClaudeConfig-yqqVtHY7.js +0 -25
  93. package/dist/assets/ProvenanceBadge-CJvnQReI.js +0 -1
  94. package/dist/assets/Settings-DRRSJksU.js +0 -2
  95. package/dist/assets/Skills-DVYHA9gV.js +0 -29
  96. package/dist/assets/SourceChip-DfJ5_5rV.js +0 -1
  97. package/dist/assets/SystemPrompt-f11wGllK.js +0 -1
  98. package/dist/assets/Toggle-DaxeFDFp.js +0 -1
  99. package/dist/assets/ViewTabs-DRtgFKRw.js +0 -1
  100. package/dist/assets/claude-settings-schema-COigsajx.js +0 -3
  101. package/dist/assets/index-iQ6pdyuS.js +0 -3116
@@ -0,0 +1,115 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * stdioGuard.cjs — keep console writes to a dead stdout/stderr from becoming
5
+ * uncaughtExceptions.
6
+ *
7
+ * Incident: bin/cli.cjs spawns Electron with stdio ['inherit','inherit','pipe'],
8
+ * so a terminal launch hands the main process the terminal's tty as stdout.
9
+ * Once that terminal closes every write fails with EIO (tty) or EPIPE (pipe),
10
+ * and every console.log after the first became an uncaughtException
11
+ * "write EIO" — 6,603 telemetry reports from one Mac in 5 days (only ~3/min
12
+ * got through, thanks to telemetryClient's errorDedupAllows).
13
+ *
14
+ * Why Node's console does not save us: getStdout()/getStderr() set
15
+ * stream._destroy = dummyDestroy, which calls cb(err) then this._undestroy().
16
+ * On the FIRST failed write, console's write callback sees
17
+ * _writableState.errorEmitted === false and adds once('error', noop), so it is
18
+ * swallowed; emitErrorNT then sets errorEmitted = true. On the NEXT failed
19
+ * write the callback sees errorEmitted === true and adds no listener;
20
+ * dummyDestroy -> _undestroy resets errorEmitted to false and emitErrorNT
21
+ * emits 'error' with zero listeners -> uncaughtException. Reproduced on Node
22
+ * 22.22.1 and Electron 42.11.10 (Node 24.19.0): 10 console.log after the
23
+ * reader closed -> 9 uncaughtException; with any permanent 'error' listener
24
+ * on process.stdout -> 0.
25
+ *
26
+ * The fix: one permanent 'error' listener per stream. On a dead-stream code
27
+ * the stream's write becomes a no-op so nothing further is attempted. The
28
+ * log callback is injected (the file logger in production) — never console,
29
+ * which would recurse into the dead stream.
30
+ */
31
+
32
+ const DEAD_CODES = new Set(['EIO', 'EPIPE', 'ECONNRESET', 'ENXIO', 'EBADF']);
33
+
34
+ /** @type {WeakMap<object, { dead: boolean, loggedCodes: Set<string> }>} */
35
+ const state = new WeakMap();
36
+
37
+ function defaultStreams() {
38
+ return [{ name: 'stdout', stream: process.stdout }, { name: 'stderr', stream: process.stderr }];
39
+ }
40
+
41
+ function normalize(entry, i) {
42
+ if (!entry || typeof entry !== 'object') return null;
43
+ if (typeof entry.on === 'function') {
44
+ let name = `stream${i}`;
45
+ try {
46
+ if (entry === process.stdout) name = 'stdout';
47
+ else if (entry === process.stderr) name = 'stderr';
48
+ } catch { /* ignore */ }
49
+ return { name, stream: entry };
50
+ }
51
+ const s = entry.stream;
52
+ if (!s || typeof s !== 'object' || typeof s.on !== 'function') return null;
53
+ return { name: typeof entry.name === 'string' ? entry.name : `stream${i}`, stream: s };
54
+ }
55
+
56
+ function noopWrite(chunk, encoding, cb) {
57
+ const fn = typeof encoding === 'function' ? encoding : cb;
58
+ if (typeof fn === 'function') process.nextTick(fn);
59
+ return true;
60
+ }
61
+
62
+ function safeLog(log, info) {
63
+ if (typeof log !== 'function') return;
64
+ try { log(info); } catch { /* logging must never throw */ }
65
+ }
66
+
67
+ /**
68
+ * @param {{ streams?: Array<any>, log?: (info: { stream: string, code: string }) => void }} [opts]
69
+ * @returns {void}
70
+ */
71
+ function guardStdio({ streams, log } = {}) {
72
+ try {
73
+ const list = Array.isArray(streams) ? streams : defaultStreams();
74
+ list.forEach((entry, i) => {
75
+ try {
76
+ const n = normalize(entry, i);
77
+ if (!n || state.has(n.stream)) return;
78
+ const st = { dead: false, loggedCodes: new Set() };
79
+ state.set(n.stream, st);
80
+ n.stream.on('error', (err) => {
81
+ const code = String((err && err.code) || 'UNKNOWN');
82
+ if (DEAD_CODES.has(code)) {
83
+ if (st.dead) return;
84
+ st.dead = true;
85
+ try { n.stream.write = noopWrite; } catch { /* ignore */ }
86
+ safeLog(log, { stream: n.name, code });
87
+ return;
88
+ }
89
+ if (st.loggedCodes.has(code)) return;
90
+ st.loggedCodes.add(code);
91
+ safeLog(log, { stream: n.name, code });
92
+ });
93
+ } catch { /* never throw */ }
94
+ });
95
+ } catch { /* never throw */ }
96
+ }
97
+
98
+ /** @param {any} err */
99
+ function isDeadStdioWriteError(err) {
100
+ if (!err || typeof err !== 'object') return false;
101
+ return err.syscall === 'write' && DEAD_CODES.has(err.code);
102
+ }
103
+
104
+ /** @returns {(err: any) => boolean} true = report this uncaught error */
105
+ function createUncaughtReportFilter() {
106
+ let seenDead = false;
107
+ return (err) => {
108
+ if (!isDeadStdioWriteError(err)) return true;
109
+ if (seenDead) return false;
110
+ seenDead = true;
111
+ return true;
112
+ };
113
+ }
114
+
115
+ module.exports = { guardStdio, isDeadStdioWriteError, createUncaughtReportFilter };
@@ -45,6 +45,10 @@ const EpicSourceSchema = z.object({
45
45
  fromEpicId: z.string().optional(),
46
46
  // The macro that launched this Epic (new-epic-ui Epics only).
47
47
  macroId: z.string().optional(),
48
+ // An outside app's own id for this Epic. Any string here: the strict rule
49
+ // lives in epic/externalRef.cjs at entry points, since a stricter stored
50
+ // shape would make dropInvalidSessions drop a whole row.
51
+ externalRef: z.string().optional(),
48
52
  // Zod strips undeclared keys on the merge path; a stricter shape could make dropInvalidSessions (ipcSchemas.cjs) drop a whole row holding an older or malformed value.
49
53
  proposal: z.unknown().optional(),
50
54
  autoApprove: z.unknown().optional(),
@@ -28,10 +28,41 @@ function textOf(content) {
28
28
  .join('\n');
29
29
  }
30
30
 
31
- function cap(text, max) {
31
+ const ATTACHED_LINE = /^Attached: .+$/;
32
+
33
+ function capHead(text, max) {
32
34
  return text.length > max ? text.slice(0, max - 1) + '…' : text;
33
35
  }
34
36
 
37
+ /**
38
+ * Cap text at `max` chars. A trailing block of `Attached: <path>` lines (image
39
+ * sends append it) survives: only the body before it is cut, so the phone can
40
+ * still render attachment chips. Without such a block this is a plain head cap.
41
+ */
42
+ function cap(text, max) {
43
+ if (text.length <= max) return text;
44
+ const lines = text.split('\n');
45
+ let i = lines.length;
46
+ while (i > 0 && ATTACHED_LINE.test(lines[i - 1])) i--;
47
+ if (i === lines.length) return capHead(text, max);
48
+ const block = lines.slice(i);
49
+ const blockText = block.join('\n');
50
+ if (blockText.length <= max - 2) {
51
+ const body = lines.slice(0, i).join('\n').trimEnd();
52
+ const budget = max - 2 - blockText.length;
53
+ if (!body || budget < 1) return blockText;
54
+ return capHead(body, budget) + '\n\n' + blockText;
55
+ }
56
+ // Block alone overflows: whole lines from its start, no body.
57
+ let out = '';
58
+ for (const line of block) {
59
+ const next = out ? out + '\n' + line : line;
60
+ if (next.length > max) break;
61
+ out = next;
62
+ }
63
+ return out || capHead(block[0], max);
64
+ }
65
+
35
66
  function truncate(text) {
36
67
  return cap(text, MAX_TEXT_CHARS);
37
68
  }
@@ -107,6 +107,12 @@ function machineStatePath() { return assertNotLiveRoot(path.join(schedulerHome()
107
107
  function schedulerStatePath() { return assertNotLiveRoot(path.join(schedulerHome(), 'scheduler-state.json'), 'schedulerStatePath'); }
108
108
  function heartbeatPath() { return assertNotLiveRoot(path.join(schedulerHome(), 'scheduler-heartbeat.log'), 'heartbeatPath'); }
109
109
  function sessionSlotsConfigPath() { return assertNotLiveRoot(path.join(schedulerHome(), 'session-slots-config.json'), 'sessionSlotsConfigPath'); }
110
+ /** Machine-level (project cwd, externalRef) -> Epic id index (epic/externalRefIndex.cjs). */
111
+ function externalRefIndexPath() { return assertNotLiveRoot(path.join(schedulerHome(), 'external-refs.json'), 'externalRefIndexPath'); }
112
+ /** Machine-level "Needs you" items posted by outside apps (feedback-remote/needsYouStore.cjs). */
113
+ function needsYouPath() { return assertNotLiveRoot(path.join(schedulerHome(), 'needs-you.json'), 'needsYouPath'); }
114
+ /** Last-seen outside-facing state of every open Epic (epic/epicStateWatcher.cjs). */
115
+ function epicStateSnapshotPath() { return assertNotLiveRoot(path.join(schedulerHome(), 'epic-state-snapshot.json'), 'epicStateSnapshotPath'); }
110
116
  function watchdogLogsDir() { return assertNotLiveRoot(path.join(schedulerHome(), 'logs'), 'watchdogLogsDir'); }
111
117
  function restartRequestPath() { return assertNotLiveRoot(path.join(schedulerHome(), 'restart-request.json'), 'restartRequestPath'); }
112
118
  function restartingMarkerPath() { return assertNotLiveRoot(path.join(schedulerHome(), 'restarting.json'), 'restartingMarkerPath'); }
@@ -198,6 +204,9 @@ module.exports = {
198
204
  schedulerStatePath,
199
205
  heartbeatPath,
200
206
  sessionSlotsConfigPath,
207
+ externalRefIndexPath,
208
+ needsYouPath,
209
+ epicStateSnapshotPath,
201
210
  adminTokenPath,
202
211
  machineStateLogCwd,
203
212
  worktreeBase,
@@ -0,0 +1,176 @@
1
+ /**
2
+ * auditEvents.cjs — cursor reader over the audit log for outside apps.
3
+ *
4
+ * readEventsAfter({ after, kinds, limit, target }) → { events, next, more, gap }.
5
+ *
6
+ * Cursor = `<at of the last row handed out>~<count of rows with exactly that at
7
+ * already handed out>`. "Handed out" means scanned: next advances past every row
8
+ * this call looked at, matching or not, so rows sharing one timestamp are never
9
+ * skipped or repeated. `after` absent → no events, next = newest live row (start
10
+ * from now). `after === 'start'` → from the first row of the live file.
11
+ *
12
+ * The live file is read with readTail in a growing window (1 MB, doubling) until
13
+ * the window's first row is strictly before the cursor's at (so the whole group of
14
+ * rows sharing the cursor's at is visible) or the whole file is covered. Only when
15
+ * the cursor is at or before the live file's first row is the newest rotated
16
+ * archive (`audit-log-YYYY-MM.jsonl.gz`, same folder) unzipped in memory and its
17
+ * rows prepended — unless its compressed size exceeds MAX_ARCHIVE_GZ_BYTES (or the
18
+ * maxArchiveGzBytes option), in which case it is skipped and gap is true.
19
+ * gap = the cursor predates the oldest row still readable.
20
+ *
21
+ * Assumes rows are appended in non-decreasing `at` order (they are: appendAuditEvent
22
+ * stamps `now` at append time). Rows that fail to parse or lack a string `at` are skipped.
23
+ */
24
+ 'use strict';
25
+
26
+ const fs = require('node:fs');
27
+ const path = require('node:path');
28
+ const zlib = require('node:zlib');
29
+
30
+ const { auditLogPath, readTail } = require('./auditLog.cjs');
31
+
32
+ const OUTSIDE_EVENT_KINDS = Object.freeze(['epic_state_changed', 'job_transition', 'epic_cross_project_reply', 'needs_you_answered']);
33
+ const DEFAULT_KINDS = Object.freeze(['epic_state_changed']);
34
+ const DEFAULT_LIMIT = 100;
35
+ const MAX_LIMIT = 500;
36
+ const INITIAL_WINDOW = 1024 * 1024;
37
+ /** Largest compressed archive loadArchive will unzip in memory; a bigger one is skipped (gap true). */
38
+ const MAX_ARCHIVE_GZ_BYTES = 16 * 1024 * 1024;
39
+ const START = 'start';
40
+ const CURSOR_RE = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)~(\d+)$/;
41
+ const CURSOR_FORM = "expected '<ISO timestamp>~<count>' (e.g. 2026-11-01T00:00:00.000Z~1) or 'start'";
42
+ /** `code` of the Error parseCursor throws for a malformed cursor. */
43
+ const INVALID_AUDIT_CURSOR = 'INVALID_AUDIT_CURSOR';
44
+
45
+ /** @param {unknown} after */
46
+ function parseCursor(after) {
47
+ if (after === START) return { start: true, at: '', n: 0 };
48
+ const m = typeof after === 'string' ? CURSOR_RE.exec(after) : null;
49
+ if (!m) {
50
+ const err = /** @type {Error & { code: string }} */ (new Error(`invalid audit cursor ${JSON.stringify(after)}: ${CURSOR_FORM}`));
51
+ err.code = INVALID_AUDIT_CURSOR;
52
+ throw err;
53
+ }
54
+ return { start: false, at: m[1], n: Number(m[2]) };
55
+ }
56
+
57
+ /** @param {string[]} lines */
58
+ function parseRows(lines) {
59
+ const rows = [];
60
+ for (const line of lines) {
61
+ let r;
62
+ try { r = JSON.parse(line); } catch { continue; }
63
+ if (r && typeof r === 'object' && !Array.isArray(r) && typeof r.at === 'string') rows.push(r);
64
+ }
65
+ return rows;
66
+ }
67
+
68
+ function fileSize(target) {
69
+ try { return fs.statSync(target).size; } catch { return 0; }
70
+ }
71
+
72
+ /**
73
+ * Live rows, widening the tail window until its first row is strictly before
74
+ * `boundaryAt` (or the whole file is read). `boundaryAt === null` → whole file.
75
+ * @returns {{ rows: object[], whole: boolean }}
76
+ */
77
+ function loadLive(target, boundaryAt, initialWindow) {
78
+ let win = Math.max(1, initialWindow);
79
+ for (;;) {
80
+ const size = fileSize(target);
81
+ const whole = boundaryAt === null || win >= size;
82
+ const rows = parseRows(readTail(whole ? Math.max(size, 1) : win, target));
83
+ if (whole) return { rows, whole: true };
84
+ if (rows.length && rows[0].at < boundaryAt) return { rows, whole: false };
85
+ win *= 2;
86
+ }
87
+ }
88
+
89
+ /**
90
+ * Newest rotated archive's rows (in memory). rows = [] when none / unreadable;
91
+ * skipped = true when its compressed size is over `maxGzBytes` (never read).
92
+ * @returns {{ rows: object[], skipped: boolean }}
93
+ */
94
+ function loadArchive(target, maxGzBytes) {
95
+ const dir = path.dirname(target);
96
+ const base = path.basename(target, path.extname(target));
97
+ const re = new RegExp(`^${base.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}-\\d{4}-\\d{2}\\.jsonl\\.gz$`);
98
+ let names;
99
+ const none = { rows: [], skipped: false };
100
+ try { names = fs.readdirSync(dir).filter((f) => re.test(f)).sort(); } catch { return none; }
101
+ if (!names.length) return none;
102
+ const file = path.join(dir, names[names.length - 1]);
103
+ try {
104
+ if (fs.statSync(file).size > maxGzBytes) return { rows: [], skipped: true };
105
+ return { rows: parseRows(zlib.gunzipSync(fs.readFileSync(file)).toString('utf8').split('\n').filter(Boolean)), skipped: false };
106
+ } catch { return none; }
107
+ }
108
+
109
+ /** Annotate each row with its 1-based occurrence among rows sharing its `at`. */
110
+ function withOrdinals(rows) {
111
+ const out = [];
112
+ let prevAt = null;
113
+ let k = 0;
114
+ for (const r of rows) {
115
+ k = r.at === prevAt ? k + 1 : 1;
116
+ prevAt = r.at;
117
+ out.push({ row: r, ord: k });
118
+ }
119
+ return out;
120
+ }
121
+
122
+ const cursorOf = (at, n) => `${at}~${n}`;
123
+
124
+ /**
125
+ * @param {{ after?: string, kinds?: string[], limit?: number, target?: string, initialWindow?: number, maxArchiveGzBytes?: number }} [opts]
126
+ * @returns {{ events: object[], next: string, more: boolean, gap: boolean }}
127
+ */
128
+ function readEventsAfter({ after, kinds, limit, target, initialWindow, maxArchiveGzBytes } = {}) {
129
+ const file = target ?? auditLogPath();
130
+ const maxGz = Number.isFinite(maxArchiveGzBytes) && maxArchiveGzBytes >= 0 ? maxArchiveGzBytes : MAX_ARCHIVE_GZ_BYTES;
131
+ const win = Number.isFinite(initialWindow) && initialWindow > 0 ? initialWindow : INITIAL_WINDOW;
132
+ const kindSet = new Set(Array.isArray(kinds) && kinds.length ? kinds : DEFAULT_KINDS);
133
+ const lim = Number.isInteger(limit) && limit > 0 ? Math.min(limit, MAX_LIMIT) : DEFAULT_LIMIT;
134
+
135
+ if (after === undefined || after === null) {
136
+ const probe = parseRows(readTail(Math.min(win, 64 * 1024), file));
137
+ if (!probe.length && fileSize(file) === 0) return { events: [], next: START, more: false, gap: false };
138
+ const lastAt = probe.length ? probe[probe.length - 1].at : null;
139
+ const { rows } = loadLive(file, lastAt, win);
140
+ if (!rows.length) return { events: [], next: START, more: false, gap: false };
141
+ const ords = withOrdinals(rows);
142
+ const last = ords[ords.length - 1];
143
+ return { events: [], next: cursorOf(last.row.at, last.ord), more: false, gap: false };
144
+ }
145
+
146
+ const cur = parseCursor(after);
147
+ let gap = false;
148
+ let rows;
149
+ if (cur.start) {
150
+ rows = loadLive(file, null, win).rows;
151
+ } else {
152
+ const live = loadLive(file, cur.at, win);
153
+ rows = live.rows;
154
+ if (live.whole && (!rows.length || cur.at <= rows[0].at)) {
155
+ const archive = loadArchive(file, maxGz);
156
+ rows = archive.rows.concat(rows);
157
+ gap = archive.skipped || (rows.length > 0 && cur.at < rows[0].at);
158
+ }
159
+ }
160
+
161
+ const events = [];
162
+ let more = false;
163
+ let next = cur.start ? START : cursorOf(cur.at, cur.n);
164
+ for (const { row, ord } of withOrdinals(rows)) {
165
+ if (!cur.start && (row.at < cur.at || (row.at === cur.at && ord <= cur.n))) continue;
166
+ if (kindSet.has(row.kind)) {
167
+ if (events.length >= lim) { more = true; break; }
168
+ const { caller: _caller, ...rest } = row;
169
+ events.push(rest);
170
+ }
171
+ next = cursorOf(row.at, ord);
172
+ }
173
+ return { events, next, more, gap };
174
+ }
175
+
176
+ module.exports = { OUTSIDE_EVENT_KINDS, readEventsAfter, CURSOR_FORM, INVALID_AUDIT_CURSOR, MAX_ARCHIVE_GZ_BYTES };
@@ -0,0 +1,45 @@
1
+ /**
2
+ * eventsAdminRoutes.cjs — read-only admin HTTP route over auditEvents.cjs's
3
+ * cursor reader, so an outside script can ask for the events after its saved
4
+ * cursor instead of polling every Epic.
5
+ *
6
+ * GET /admin/events?after=<cursor|start>&kinds=<k1,k2>&limit=<1..500>
7
+ * → 200 { ok: true, events, next, more, gap }
8
+ * → 400 { ok: false, error: 'invalid query', details } for an unknown kind,
9
+ * an out-of-range limit, or a cursor readEventsAfter rejects.
10
+ *
11
+ * Writes no file and no audit row. Auth/loopback binding are the injected
12
+ * localAdminHttp.cjs transport's job (see index.cjs).
13
+ */
14
+ 'use strict';
15
+
16
+ const { schemas } = require('../../ipcSchemas.cjs');
17
+ const { sendJson } = require('../feedback-remote/localAdminHttp.cjs');
18
+ const { readEventsAfter, INVALID_AUDIT_CURSOR } = require('./auditEvents.cjs');
19
+
20
+ /** @param {{ registerRoute: Function }} adminHttp */
21
+ function registerAdminRoute(adminHttp) {
22
+ adminHttp.registerRoute('GET', '/admin/events', async (req, res, query) => {
23
+ let input;
24
+ try {
25
+ input = schemas.adminListEventsQuery.parse(Object.fromEntries(query ?? []));
26
+ } catch (e) {
27
+ sendJson(res, 400, { ok: false, error: 'invalid query', details: e?.issues ?? e?.message });
28
+ return;
29
+ }
30
+ let result;
31
+ try {
32
+ result = readEventsAfter({ after: input.after, kinds: input.kinds, limit: input.limit });
33
+ } catch (e) {
34
+ if (e instanceof Error && /** @type {Error & { code?: unknown }} */ (e).code === INVALID_AUDIT_CURSOR) {
35
+ sendJson(res, 400, { ok: false, error: 'invalid query', details: e.message });
36
+ return;
37
+ }
38
+ throw e;
39
+ }
40
+ const { events, next, more, gap } = result;
41
+ sendJson(res, 200, { ok: true, events, next, more, gap });
42
+ });
43
+ }
44
+
45
+ module.exports = { registerAdminRoute };
@@ -157,4 +157,4 @@ function registerLoopEfficiencyHandlers() {
157
157
  });
158
158
  }
159
159
 
160
- module.exports = { gatherLoopEfficiency, registerLoopEfficiencyHandlers, defaultUsage };
160
+ module.exports = { gatherLoopEfficiency, registerLoopEfficiencyHandlers, defaultUsage, runIdToMs };
@@ -1477,6 +1477,28 @@ function quarantinedCwdSet(state) {
1477
1477
  return new Set((state?.unreadableCwds ?? []).map((u) => u.cwd));
1478
1478
  }
1479
1479
 
1480
+ /**
1481
+ * Best-effort epic_state_changed emission for the tick (lib/epic/epicStateWatcher.cjs).
1482
+ * Watches every known project cwd except quarantined shards. Never rejects:
1483
+ * any failure is logged as a warning so it can never hold up dispatch.
1484
+ * SM_EPIC_STATE_WATCH_DISABLE=1 turns it off. `deps` is a test seam.
1485
+ * @param {any} state
1486
+ * @param {{ watch?: (o: { cwds: string[], jobs: any }) => Promise<unknown>, listCwds?: () => string[] }} [deps]
1487
+ * @returns {Promise<void>}
1488
+ */
1489
+ async function runEpicStateWatchForTick(state, deps = {}) {
1490
+ if (process.env.SM_EPIC_STATE_WATCH_DISABLE === '1') return;
1491
+ try {
1492
+ const watch = deps.watch ?? require('./lib/epic/epicStateWatcher.cjs').runEpicStateWatch;
1493
+ const listCwds = deps.listCwds ?? allProjectCwds;
1494
+ const quarantined = quarantinedCwdSet(state);
1495
+ const cwds = listCwds().filter((c) => !quarantined.has(c));
1496
+ await watch({ cwds, jobs: state?.jobs });
1497
+ } catch (e) {
1498
+ console.warn('[scheduler] epic state watch failed', /** @type {any} */ (e)?.message);
1499
+ }
1500
+ }
1501
+
1480
1502
  /**
1481
1503
  * Atomically mint a brand-new parallel-group NN for a PRD about to be
1482
1504
  * authored under the given project's own PRDs dir (falls back to
@@ -8184,6 +8206,12 @@ async function tickBody(gen, { bypassLoadGate, lastResort }) {
8184
8206
  reclaimTerminalJobOrphansThrottled(state).catch((e) => {
8185
8207
  console.warn('[scheduler] terminal job-worktree orphan reclaim failed', e?.message);
8186
8208
  });
8209
+ // Emit epic_state_changed audit rows for Epics whose outside-facing state
8210
+ // moved since the last tick. Best-effort and fire-and-forget: never awaited,
8211
+ // must never hold up dispatch.
8212
+ runEpicStateWatchForTick(state).catch((e) => {
8213
+ console.warn('[scheduler] epic state watch failed', e?.message);
8214
+ });
8187
8215
  // Session-Manager's machine-wide slot pool is the ONLY concurrency limit
8188
8216
  // the picker answers to (plus the memory gate below). The scheduler used
8189
8217
  // to also carry a private `concurrencyCap` of 3 — the exact per-consumer
@@ -12469,6 +12497,7 @@ module.exports = {
12469
12497
  pickForProject,
12470
12498
  reapDeadRunningJobs,
12471
12499
  runBranchSweep,
12500
+ runEpicStateWatchForTick,
12472
12501
  pollRecoveryClearSource,
12473
12502
  memoryLimitedBatchSize,
12474
12503
  availableForJobs,
@@ -223,6 +223,7 @@ Before queueing a new PRD, verify each of these:
223
223
  - [ ] **Every command bounded:** every test/build/deploy command is wrapped in `timeout` (typecheck/unit 300s, e2e 120s, `curl --max-time 15`).
224
224
  - [ ] **§2 No bonus work:** the AC list is the only source of work.
225
225
  - [ ] **§3 Verify, don't poll:** every deploy/migration step is followed by a test command that exits 1 on failure; the AC test command ran green once before you declare done.
226
+ - [ ] **Traceable criteria:** every criterion must be checkable after the run from the tree, a commit, or a read-only probe (registry, API, file); run-time steps such as printing probe output or a value seen mid-run belong in the run report, not in a criterion. Why: the 2026-11-21 release fix plan (3240) had process claims as criteria, and its validator could not verify them.
226
227
  - [ ] **§4 Bounded generators:** any search/seed loop has an explicit max and surfaces failure on exhaustion.
227
228
  - [ ] **§5 Frontmatter:** `title`, `cwd` (exists on this machine); `estimateMinutes` omitted (optional); `dependsOn` used for ordering, not `parallelGroup`.
228
229
  - [ ] **§6 Gate and files:** `gate` follows every rule in §6 (or is `["none"]` alone); `files` is 1–50 repo-relative paths, no overlap with a concurrent PRD.
@@ -473,11 +473,21 @@ const MAX_USAGE_FILE_BYTES = 64 * 1024 * 1024;
473
473
  /** Max distinct transcripts whose running totals stay cached. */
474
474
  const USAGE_CACHE_MAX = 200;
475
475
 
476
+ /** How many recent message ids a cache entry remembers for de-dup across tail reads. */
477
+ const USAGE_RECENT_IDS_MAX = 64;
478
+
476
479
  /**
477
- * LRU<filePath, { ino, size, mtimeMs, readOffset, usage }>. `readOffset` is the
478
- * byte just past the last complete (newline-terminated) line already summed, so
479
- * the next call only parses [readOffset, size). The full parse keeps no
480
- * de-dup state (every usage event is summed), so none is cached here.
480
+ * LRU<filePath, { ino, size, mtimeMs, readOffset, usage, recentIds, newestId }>. `readOffset`
481
+ * is the byte just past the last complete (newline-terminated) line already
482
+ * summed, so the next call only parses [readOffset, size). `recentIds` is an
483
+ * array of [message.id, { inputTokens, outputTokens }] (oldest first, at most
484
+ * USAGE_RECENT_IDS_MAX) — the values already counted for that id, so a message
485
+ * whose lines straddle two reads is still counted once. `newestId` is the
486
+ * message.id of the newest counted call (null if it had none), so a later line
487
+ * of that call can raise `usage.lastContext` while a late repeat of an older
488
+ * id cannot. `usage` = { inputTokens, outputTokens, lastContext, calls }:
489
+ * lastContext is input + cache-read + cache-creation tokens of the newest
490
+ * counted call (null before any), calls the number of counted calls.
481
491
  */
482
492
  const usageCache = new LRUCache(USAGE_CACHE_MAX);
483
493
 
@@ -510,6 +520,12 @@ async function usageForOne(filePath) {
510
520
  const start = canTail ? cached.readOffset : 0;
511
521
  let inputTokens = canTail ? cached.usage.inputTokens : 0;
512
522
  let outputTokens = canTail ? cached.usage.outputTokens : 0;
523
+ let calls = canTail ? cached.usage.calls : 0;
524
+ let lastContext = canTail ? cached.usage.lastContext : null;
525
+ // message.id of the newest counted call (null when that call had no id).
526
+ let newestId = canTail ? cached.newestId : null;
527
+ /** @type {Map<string, { inputTokens: number, outputTokens: number, context: number }>} */
528
+ const recent = new Map(canTail && cached.recentIds ? cached.recentIds : []);
513
529
  const want = stat.size - start;
514
530
  let buf = Buffer.alloc(0);
515
531
  if (want > 0) {
@@ -545,17 +561,56 @@ async function usageForOne(filePath) {
545
561
  for (const ev of events) {
546
562
  if (ev.kind !== 'usage') continue;
547
563
  const u = ev.data || {};
548
- inputTokens += u.input_tokens ?? u.inputTokens ?? 0;
549
- outputTokens += u.output_tokens ?? u.outputTokens ?? 0;
564
+ const inTok = u.input_tokens ?? u.inputTokens ?? 0;
565
+ const outTok = u.output_tokens ?? u.outputTokens ?? 0;
566
+ const ctx =
567
+ inTok +
568
+ (u.cache_read_input_tokens ?? u.cacheReadInputTokens ?? 0) +
569
+ (u.cache_creation_input_tokens ?? u.cacheCreationInputTokens ?? 0);
570
+ // One API message's usage is repeated on each of its transcript lines:
571
+ // count a message.id once, keeping the larger value of each field.
572
+ const id = obj?.message?.id;
573
+ if (typeof id !== 'string' || !id) {
574
+ inputTokens += inTok;
575
+ outputTokens += outTok;
576
+ calls += 1;
577
+ lastContext = ctx;
578
+ newestId = null;
579
+ continue;
580
+ }
581
+ const prev = recent.get(id);
582
+ if (prev) {
583
+ const nextIn = Math.max(prev.inputTokens, inTok);
584
+ const nextOut = Math.max(prev.outputTokens, outTok);
585
+ const nextCtx = Math.max(prev.context ?? 0, ctx);
586
+ inputTokens += nextIn - prev.inputTokens;
587
+ outputTokens += nextOut - prev.outputTokens;
588
+ // A later line of an older call never moves lastContext off the newest call.
589
+ if (id === newestId) lastContext = nextCtx;
590
+ recent.delete(id);
591
+ recent.set(id, { inputTokens: nextIn, outputTokens: nextOut, context: nextCtx });
592
+ } else {
593
+ inputTokens += inTok;
594
+ outputTokens += outTok;
595
+ calls += 1;
596
+ lastContext = ctx;
597
+ newestId = id;
598
+ recent.set(id, { inputTokens: inTok, outputTokens: outTok, context: ctx });
599
+ if (recent.size > USAGE_RECENT_IDS_MAX) {
600
+ recent.delete(recent.keys().next().value);
601
+ }
602
+ }
550
603
  }
551
604
  }
552
- const usage = { inputTokens, outputTokens };
605
+ const usage = { inputTokens, outputTokens, lastContext, calls };
553
606
  usageCache.set(filePath, {
554
607
  ino: stat.ino,
555
608
  size: stat.size,
556
609
  mtimeMs: stat.mtimeMs,
557
610
  readOffset: start + lastNl + 1,
558
611
  usage,
612
+ recentIds: [...recent],
613
+ newestId,
559
614
  });
560
615
  return usage;
561
616
  }