claude-code-session-manager 0.138.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 (91) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +339 -82
  3. package/dist/assets/{AppSettings-CgDhqrsU.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-CeDiyuNn.js → Panel-Csyd9HbD.js} +1 -1
  7. package/dist/assets/ProjectClaudeConfig-C-jlYpC_.js +26 -0
  8. package/dist/assets/{Scheduler-CkhTvG7C.js → Scheduler-NLs08fx7.js} +9 -9
  9. package/dist/assets/{SkillReferenceGraph-CFMK8NJh.js → SkillReferenceGraph-DcscPXAG.js} +1 -1
  10. package/dist/assets/Skills-BpGRKOcY.js +67 -0
  11. package/dist/assets/{TiptapBody-D1kTj-tn.js → TiptapBody-DSU3769X.js} +60 -54
  12. package/dist/assets/ViewTabs-C0PRZx4_.js +1 -0
  13. package/dist/assets/{VoiceButton-CZeyPM31.js → VoiceButton-D2rMurNg.js} +1 -1
  14. package/dist/assets/{historyTotals-B00l64Jw.js → historyTotals-TcIQs2sh.js} +1 -1
  15. package/dist/assets/{index-62tyjEQB.css → index-BCySPdtU.css} +1 -1
  16. package/dist/assets/{index-CgCxpunJ.js → index-C-d0DCre.js} +523 -515
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +469 -450
  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 +2 -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 +22 -2
  33. package/src/main/ipcSchemas.cjs +122 -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/epic/epicAdminRoutes.cjs +101 -0
  37. package/src/main/lib/epic/epicJobReceipt.cjs +87 -0
  38. package/src/main/lib/epic/epicOutsideRead.cjs +306 -0
  39. package/src/main/lib/epic/epicOutsideState.cjs +233 -0
  40. package/src/main/lib/epic/epicSettle.cjs +1 -1
  41. package/src/main/lib/epic/epicStateWatcher.cjs +157 -0
  42. package/src/main/lib/epic/externalRef.cjs +37 -0
  43. package/src/main/lib/epic/externalRefIndex.cjs +136 -0
  44. package/src/main/lib/epic/restorableSessions.cjs +151 -17
  45. package/src/main/lib/epic/transcriptUsage.cjs +197 -0
  46. package/src/main/lib/externalContract.cjs +111 -0
  47. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +121 -4
  48. package/src/main/lib/feedback-remote/crossProjectReply.cjs +83 -1
  49. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -6
  50. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +50 -8
  51. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +218 -4
  52. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +19 -3
  53. package/src/main/lib/feedback-remote/feedbackImages.cjs +171 -0
  54. package/src/main/lib/feedback-remote/localAdminHttp.cjs +11 -10
  55. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +120 -2
  56. package/src/main/lib/feedback-remote/needsYouAdminRoutes.cjs +133 -0
  57. package/src/main/lib/feedback-remote/needsYouIpc.cjs +50 -0
  58. package/src/main/lib/feedback-remote/needsYouStore.cjs +281 -0
  59. package/src/main/lib/historyRollup.cjs +32 -5
  60. package/src/main/lib/mcpToolCatalog.cjs +111 -14
  61. package/src/main/lib/persona-macro/agentAdminRoutes.cjs +121 -0
  62. package/src/main/lib/promptSessionSchema.cjs +4 -0
  63. package/src/main/lib/remoteTranscriptTail.cjs +32 -1
  64. package/src/main/lib/scheduler/schedulerPaths.cjs +9 -0
  65. package/src/main/lib/telemetry/auditEvents.cjs +176 -0
  66. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +45 -0
  67. package/src/main/loopEfficiencyHandlers.cjs +1 -1
  68. package/src/main/scheduler.cjs +29 -0
  69. package/src/main/templates/PRD_AUTHORING.md +1 -0
  70. package/src/main/transcripts.cjs +62 -7
  71. package/src/main/webRemote.cjs +122 -18
  72. package/src/preload/api.d.ts +71 -8
  73. package/src/preload/apiSurface.cjs +7 -0
  74. package/src/preload/apiSurface.json +408 -83
  75. package/src/preload/index.cjs +15 -3
  76. package/dist/assets/AgentLibrary-C1d_D7uQ.js +0 -2
  77. package/dist/assets/Button-Bk23rEnZ.js +0 -1
  78. package/dist/assets/DocumentEditorPane-BqY5Nq6W.js +0 -1
  79. package/dist/assets/Extensions-CXem-uwI.js +0 -2
  80. package/dist/assets/History-BwO3coo4.js +0 -2
  81. package/dist/assets/Library-BDV69fSe.js +0 -32
  82. package/dist/assets/ListDetail-CD-Fm6mh.js +0 -1
  83. package/dist/assets/ProjectClaudeConfig-NjdKdwe8.js +0 -25
  84. package/dist/assets/ProvenanceBadge-Bu8NmI_R.js +0 -1
  85. package/dist/assets/Settings-COT34hBF.js +0 -2
  86. package/dist/assets/Skills-BgexoUkQ.js +0 -29
  87. package/dist/assets/SourceChip-BXjcdeb1.js +0 -1
  88. package/dist/assets/SystemPrompt-CeeH3EeW.js +0 -1
  89. package/dist/assets/Toggle-CENi19iK.js +0 -1
  90. package/dist/assets/ViewTabs-DDBb0x96.js +0 -1
  91. package/dist/assets/claude-settings-schema-COigsajx.js +0 -3
@@ -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
  }
@@ -84,6 +84,31 @@ let _configCache = null;
84
84
  let _configCacheAt = 0;
85
85
  let _repairNeeded = false; // relay rejected the device token (invalid_token / 401): terminal until re-pair
86
86
  let _destroyed = false; // set at app shutdown to stop reconnect loops
87
+ let _frameAssembler = null; // inbound e2e:frame reassembly (lazy; reset with all clients)
88
+ let _frameSweepTimer = null;
89
+ const FRAME_SWEEP_MS = 30_000;
90
+
91
+ // Abilities this desktop advertises in event:remote:ready; web clients only send
92
+ // boxed e2e:frame sequences to desktops listing 'e2e-frames'.
93
+ const REMOTE_CAPABILITIES = Object.freeze(['e2e-frames', 'chat-images']);
94
+
95
+ function getFrameAssembler() {
96
+ if (!_frameAssembler) {
97
+ const { createFrameAssembler } = require('./lib/feedback-remote/remoteFrameAssembler.cjs');
98
+ _frameAssembler = createFrameAssembler();
99
+ }
100
+ return _frameAssembler;
101
+ }
102
+
103
+ function startFrameSweep() {
104
+ stopFrameSweep();
105
+ _frameSweepTimer = setInterval(() => { if (_frameAssembler) _frameAssembler.sweep(); }, FRAME_SWEEP_MS);
106
+ _frameSweepTimer.unref?.();
107
+ }
108
+
109
+ function stopFrameSweep() {
110
+ if (_frameSweepTimer) { clearInterval(_frameSweepTimer); _frameSweepTimer = null; }
111
+ }
87
112
 
88
113
  // E2E session state — reset on each new WS connection.
89
114
  // .state: 'idle' | 'pending_sas' | 'authenticated' | 'failed'
@@ -254,6 +279,7 @@ function resetE2e() {
254
279
 
255
280
  // Mark one client's session failed without touching any other client.
256
281
  function failClient(client) {
282
+ if (_frameAssembler) _frameAssembler.dropClient(client.key);
257
283
  client.e2e = makeState('failed');
258
284
  client.peerPubKey = null;
259
285
  client.deviceId = null;
@@ -383,6 +409,7 @@ function scheduleReconnect() {
383
409
  async function disconnect() {
384
410
  cancelReconnect();
385
411
  stopHeartbeat();
412
+ stopFrameSweep();
386
413
  resetE2e();
387
414
  if (_ws) {
388
415
  const ws = _ws;
@@ -453,6 +480,7 @@ async function connect() {
453
480
  _backoffMs = BACKOFF_INIT_MS;
454
481
  _missedPongs = 0;
455
482
  startHeartbeat();
483
+ startFrameSweep();
456
484
  // Update lastConnectedAt without exposing token
457
485
  invalidateConfigCache(); // a pin written since the last cached read must not be overwritten
458
486
  loadConfig().then(async (c) => {
@@ -479,6 +507,7 @@ async function connect() {
479
507
 
480
508
  ws.on('close', (code) => {
481
509
  stopHeartbeat();
510
+ stopFrameSweep();
482
511
  stopAllSessionWatches();
483
512
  resetE2e();
484
513
  if (_ws === ws) _ws = null;
@@ -561,6 +590,7 @@ function pruneSessionWatchers() {
561
590
  /** Tear down one client (its PTY streams + subscriptions) without touching others. */
562
591
  function teardownClient(key) {
563
592
  _lastRekeyMs.delete(key);
593
+ if (_frameAssembler) _frameAssembler.dropClient(key);
564
594
  const rec = _clients.teardown(key);
565
595
  pruneSessionWatchers();
566
596
  return rec;
@@ -568,6 +598,7 @@ function teardownClient(key) {
568
598
 
569
599
  /** Tear down every client — no client keeps a PTY stream or subscription afterwards. */
570
600
  function teardownAllClients() {
601
+ _frameAssembler = null; // drops every client's partial frames
571
602
  const n = _clients.teardownAll();
572
603
  pruneSessionWatchers();
573
604
  return n;
@@ -717,7 +748,7 @@ function stopAllSessionWatches() {
717
748
  function finalizeE2eAuthenticated(logMessage, client) {
718
749
  logs.writeLine({ scope: 'webRemote', level: 'info', message: logMessage });
719
750
  broadcastStatus();
720
- if (client && loadConfigSync().remoteEnabled) pushEventTo(client, 'event:remote:ready', { ts: Date.now() });
751
+ if (client && loadConfigSync().remoteEnabled) pushEventTo(client, 'event:remote:ready', { ts: Date.now(), capabilities: [...REMOTE_CAPABILITIES] });
721
752
  }
722
753
 
723
754
  // ─── Message handling & command dispatch ─────────────────────────────────────
@@ -897,6 +928,10 @@ async function handleMessage(raw, device) {
897
928
  } catch {
898
929
  return;
899
930
  }
931
+ if (inner && typeof inner === 'object' && inner.type === 'e2e:frame') {
932
+ await handleFrame(inner, device, client);
933
+ return;
934
+ }
900
935
  // Dispatch as if it arrived unencrypted
901
936
  await dispatchEnvelope(inner, device, client);
902
937
  return;
@@ -913,6 +948,31 @@ async function handleMessage(raw, device) {
913
948
  await dispatchEnvelope(envelope, device, client);
914
949
  }
915
950
 
951
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
952
+
953
+ /**
954
+ * One decrypted e2e:frame slice of a browser→desktop message too large for the relay's
955
+ * 256 KB cap. Only authenticated clients of an enabled remote are buffered; a completed
956
+ * message goes through the normal dispatchEnvelope gates.
957
+ */
958
+ async function handleFrame(inner, device, client) {
959
+ if (client.e2e.state !== 'authenticated') return;
960
+ if (!(await loadConfig()).remoteEnabled) {
961
+ if (_frameAssembler) _frameAssembler.dropClient(client.key); // kill switch: free any partial
962
+ return;
963
+ }
964
+ const payload = inner.payload;
965
+ const result = getFrameAssembler().accept(client.key, payload);
966
+ if (result.status === 'complete') {
967
+ await dispatchEnvelope(result.envelope, device, client);
968
+ return;
969
+ }
970
+ if (result.status !== 'refused') return;
971
+ const msgId = payload && typeof payload.msgId === 'string' && UUID_RE.test(payload.msgId) ? payload.msgId : undefined;
972
+ await auditLog(new Date().toISOString(), 'e2e:frame', device.deviceId, msgId, `refused:${result.reason}`, client);
973
+ if (msgId) respond(msgId, { error: 'rejected' }, undefined, client);
974
+ }
975
+
916
976
  const IPC_INVOKE_MAX_CALLS = 50;
917
977
  let _ipcDispatcher = null;
918
978
 
@@ -1269,33 +1329,75 @@ function getDispatchMap() {
1269
1329
  // client — in-process call, no admin HTTP hop needed since webRemote
1270
1330
  // already runs inside the Electron main process (PRD 753).
1271
1331
  'cmd:chat:send': async (payload) => {
1272
- const parsed = schemas.chatExternalSend.parse(payload);
1332
+ const result = schemas.remoteChatSend.safeParse(payload);
1333
+ if (!result.success) {
1334
+ const issues = result.error.issues;
1335
+ if (issues.length > 0 && issues.every((i) => i.path[0] === 'images')) {
1336
+ return { ok: false, disposition: 'refused', reason: 'attachment-invalid' };
1337
+ }
1338
+ throw result.error;
1339
+ }
1340
+ const parsed = result.data;
1273
1341
  const { readActiveIndex } = require('./lib/epic/epicMint.cjs');
1274
1342
  const data = await sessionsStore.load();
1275
1343
  const tabs = data?.tabs ?? [];
1276
- // Resolve the target in main: an open tab, or an ACTIVE Epic (by id or
1277
- // claudeSessionId) of an open project. Anything else is a structured refusal.
1278
1344
  const outcome = (r) => ({
1279
1345
  ok: r.disposition !== 'refused',
1280
1346
  disposition: r.disposition,
1281
1347
  ...(r.reason ? { reason: r.reason } : {}),
1282
1348
  });
1283
- if (tabs.some((t) => t.sessionId === parsed.tabId || t.id === parsed.tabId)) {
1284
- return outcome(await chatRunner.enqueueExternalPrompt(parsed.tabId, parsed.prompt));
1285
- }
1286
- for (const tab of tabs) {
1287
- const sessions = Object.values(readActiveIndex(tab.cwd)?.sessions ?? {});
1288
- const epic = sessions.find((e) => e && (e.id === parsed.tabId || e.claudeSessionId === parsed.tabId));
1289
- if (!epic) continue;
1290
- if (epic.status !== 'active' || !epic.claudeSessionId) {
1291
- return { ok: false, disposition: 'refused', reason: epic.status === 'proposed' ? 'proposed' : 'not-active' };
1349
+ // 1. Resolve the target BEFORE writing anything: an open tab, or an ACTIVE
1350
+ // Epic (by id or claudeSessionId) of an open project. Anything else is a
1351
+ // structured refusal.
1352
+ let target = null;
1353
+ const openTab = tabs.find((t) => t && (t.sessionId === parsed.tabId || t.id === parsed.tabId));
1354
+ if (openTab) {
1355
+ target = { id: parsed.tabId, extra: undefined, projectCwd: openTab.cwd };
1356
+ } else {
1357
+ for (const tab of tabs) {
1358
+ const sessions = Object.values(readActiveIndex(tab.cwd)?.sessions ?? {});
1359
+ const epic = sessions.find((e) => e && (e.id === parsed.tabId || e.claudeSessionId === parsed.tabId));
1360
+ if (!epic) continue;
1361
+ if (epic.status !== 'active' || !epic.claudeSessionId) {
1362
+ return { ok: false, disposition: 'refused', reason: epic.status === 'proposed' ? 'proposed' : 'not-active' };
1363
+ }
1364
+ target = {
1365
+ id: epic.id,
1366
+ extra: { sessionId: epic.claudeSessionId, cwd: epic.cwd || tab.cwd },
1367
+ projectCwd: tab.cwd,
1368
+ };
1369
+ break;
1292
1370
  }
1293
- return outcome(await chatRunner.enqueueExternalPrompt(epic.id, parsed.prompt, {
1294
- sessionId: epic.claudeSessionId,
1295
- cwd: epic.cwd || tab.cwd,
1296
- }));
1297
1371
  }
1298
- return { ok: false, disposition: 'refused', reason: 'unknown-target' };
1372
+ if (!target) return { ok: false, disposition: 'refused', reason: 'unknown-target' };
1373
+
1374
+ const enqueue = (prompt) => (target.extra
1375
+ ? chatRunner.enqueueExternalPrompt(target.id, prompt, target.extra)
1376
+ : chatRunner.enqueueExternalPrompt(target.id, prompt));
1377
+
1378
+ const images = parsed.images ?? [];
1379
+ if (images.length === 0) return outcome(await enqueue(parsed.prompt));
1380
+
1381
+ // 2. Save images under the owning open tab's project (never logged: no
1382
+ // image data or names reach the audit trail).
1383
+ const { saveChatImages, composeAttachedPrompt, removeSavedAttachments } = require('./lib/epic/epicAttachments.cjs');
1384
+ // projectCwd is an open tab's cwd: register it with the write boundary
1385
+ // (as promptSessionsIpc does) so the save never depends on a pty having spawned.
1386
+ require('./config.cjs').addAllowedRoot(validatePath(target.projectCwd));
1387
+ const saved = await saveChatImages({ projectCwd: target.projectCwd, images });
1388
+ if (!saved.ok) return { ok: false, disposition: 'refused', reason: 'attachment-invalid' };
1389
+
1390
+ // 3. Enqueue; only a definite refusal removes the files ('unconfirmed' may
1391
+ // still land, so its files stay).
1392
+ let r;
1393
+ try {
1394
+ r = await enqueue(composeAttachedPrompt(parsed.prompt, saved.paths));
1395
+ } catch (err) {
1396
+ await removeSavedAttachments(target.projectCwd, saved.paths);
1397
+ throw err;
1398
+ }
1399
+ if (r.disposition === 'refused') await removeSavedAttachments(target.projectCwd, saved.paths);
1400
+ return { ...outcome(r), attachments: saved.names };
1299
1401
  },
1300
1402
 
1301
1403
  'cmd:session:options': async () => {
@@ -1600,9 +1702,11 @@ function destroy() {
1600
1702
  _ws = null;
1601
1703
  }
1602
1704
  stopHeartbeat();
1705
+ stopFrameSweep();
1603
1706
  }
1604
1707
 
1605
1708
  module.exports = {
1709
+ REMOTE_CAPABILITIES,
1606
1710
  loadConfig,
1607
1711
  setIpcDispatcher,
1608
1712
  attachWindow,