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,281 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * needsYouStore.cjs — machine-level store of "Needs you" items: questions an
5
+ * outside app on this machine needs the owner to decide, so they can show in
6
+ * the Dashboard's Needs you list instead of one inbox per app.
7
+ *
8
+ * File: schedulerHome()/needs-you.json = { version: 1, items }.
9
+ * Writes are atomic (writeJsonAtomic) and serialized through one queue.
10
+ * A missing or corrupt file reads as empty; a corrupt file is set aside as
11
+ * `needs-you.json.corrupt-<ms>` at the next write. Answered or withdrawn items
12
+ * older than 14 days are dropped at the next write.
13
+ */
14
+
15
+ const fsp = require('node:fs/promises');
16
+ const { z } = require('zod');
17
+ const { writeJsonAtomic } = require('../util/atomicFs.cjs');
18
+ const { needsYouPath } = require('../scheduler/schedulerPaths.cjs');
19
+ const { normalizeExternalRef } = require('../epic/externalRef.cjs');
20
+
21
+ const STORE_VERSION = 1;
22
+ const MAX_OPEN_PER_APP = 10;
23
+ const MAX_OPEN_TOTAL = 50;
24
+ const RETENTION_MS = 14 * 24 * 60 * 60 * 1000;
25
+ const STATUSES = /** @type {const} */ (['open', 'answered', 'withdrawn']);
26
+
27
+ const AppSchema = z.string().regex(/^[A-Za-z0-9._-]{1,40}$/, 'app must be 1 to 40 letters, digits, . _ or -');
28
+
29
+ /** Runs a value through normalizeExternalRef; `required` refuses absent values. */
30
+ function refSchema(label, required) {
31
+ return z.unknown().transform((v, ctx) => {
32
+ if (required && (v === undefined || v === null)) {
33
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: `${label} is required.` });
34
+ return z.NEVER;
35
+ }
36
+ const r = normalizeExternalRef(v);
37
+ if (!r.ok) {
38
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: r.error.replace(/^externalRef/, label) });
39
+ return z.NEVER;
40
+ }
41
+ return r.value;
42
+ });
43
+ }
44
+
45
+ const TitleSchema = z.string().min(1).max(200).refine((s) => !/[\r\n]/.test(s), 'title must be one line');
46
+ const WhySchema = z.string().max(1000);
47
+ const LinkSchema = z.string().max(2000).regex(/^https?:\/\//, 'link must start with http:// or https://');
48
+ const OptionsSchema = z.array(z.string().min(1).max(80)).min(2).max(5)
49
+ .refine((opts) => new Set(opts).size === opts.length, 'options must be distinct');
50
+
51
+ const NeedsYouPostSchema = z.object({
52
+ app: AppSchema,
53
+ id: refSchema('id', true),
54
+ title: TitleSchema,
55
+ why: WhySchema.optional(),
56
+ link: LinkSchema.optional(),
57
+ options: OptionsSchema.optional(),
58
+ externalRef: refSchema('externalRef', false),
59
+ });
60
+
61
+ const KeySchema = z.object({ app: AppSchema, id: refSchema('id', true) });
62
+
63
+ const StoredItemSchema = z.object({
64
+ app: AppSchema,
65
+ id: z.string().min(1),
66
+ title: TitleSchema,
67
+ why: z.string(),
68
+ link: LinkSchema.nullable(),
69
+ options: OptionsSchema.nullable(),
70
+ externalRef: z.string().nullable(),
71
+ status: z.enum(STATUSES),
72
+ answer: z.string().nullable(),
73
+ createdAt: z.string(),
74
+ updatedAt: z.string(),
75
+ answeredAt: z.string().nullable(),
76
+ });
77
+
78
+ /** @typedef {z.infer<typeof StoredItemSchema>} NeedsYouItem */
79
+
80
+ // --- serialized writes ------------------------------------------------------
81
+
82
+ let writeChain = Promise.resolve();
83
+ /** @template T @param {() => Promise<T>} fn @returns {Promise<T>} */
84
+ function serialize(fn) {
85
+ const run = writeChain.then(fn, fn);
86
+ writeChain = run.then(() => undefined, () => undefined);
87
+ return run;
88
+ }
89
+
90
+ // --- read / write -----------------------------------------------------------
91
+
92
+ /** Returns { state: 'missing'|'corrupt'|'unreadable'|'ok', items }. Never throws. */
93
+ async function readStore(filePath) {
94
+ let text;
95
+ try {
96
+ text = await fsp.readFile(filePath, 'utf8');
97
+ } catch (err) {
98
+ if (err && err.code === 'ENOENT') return { state: 'missing', items: [] };
99
+ console.warn(`[needsYouStore] cannot read ${filePath}:`, err && err.message);
100
+ return { state: 'unreadable', items: [] };
101
+ }
102
+ let raw;
103
+ try {
104
+ raw = JSON.parse(text);
105
+ } catch {
106
+ return { state: 'corrupt', items: [] };
107
+ }
108
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return { state: 'corrupt', items: [] };
109
+ const list = Array.isArray(raw.items) ? raw.items : [];
110
+ const items = [];
111
+ const seen = new Set();
112
+ let dropped = 0;
113
+ for (const entry of list) {
114
+ const r = StoredItemSchema.safeParse(entry);
115
+ const key = r.success ? `${r.data.app}\u0000${r.data.id}` : '';
116
+ if (r.success && !seen.has(key)) {
117
+ seen.add(key);
118
+ items.push(r.data);
119
+ } else {
120
+ dropped++;
121
+ }
122
+ }
123
+ if (dropped > 0) console.warn(`[needsYouStore] dropped ${dropped} invalid item(s) from ${filePath}`);
124
+ return { state: 'ok', items };
125
+ }
126
+
127
+ /** Load for a write. MUST run inside serialize. Sets a corrupt file aside. */
128
+ async function loadForWrite(filePath) {
129
+ const cur = await readStore(filePath);
130
+ if (cur.state === 'unreadable') throw new Error(`needs-you store is unreadable: ${filePath}`);
131
+ if (cur.state === 'corrupt') {
132
+ const quarantine = `${filePath}.corrupt-${Date.now()}`;
133
+ await fsp.rename(filePath, quarantine);
134
+ console.warn(`[needsYouStore] ${filePath} is unparseable; preserved as ${quarantine}`);
135
+ }
136
+ return cur.items;
137
+ }
138
+
139
+ function prune(items, nowMs) {
140
+ return items.filter((it) => {
141
+ if (it.status === 'open') return true;
142
+ const closedAt = Date.parse(it.answeredAt || it.updatedAt);
143
+ return !(Number.isFinite(closedAt) && nowMs - closedAt > RETENTION_MS);
144
+ });
145
+ }
146
+
147
+ async function writeStore(filePath, items) {
148
+ await writeJsonAtomic(filePath, { version: STORE_VERSION, items: prune(items, Date.now()) });
149
+ }
150
+
151
+ function limitError(message) {
152
+ const err = /** @type {Error & { code: string }} */ (new Error(message));
153
+ err.code = 'NEEDS_YOU_LIMIT';
154
+ return err;
155
+ }
156
+
157
+ // --- public API ---------------------------------------------------------------
158
+
159
+ /**
160
+ * @param {{ app?: string, status?: string }} [filter]
161
+ * @returns {Promise<NeedsYouItem[]>}
162
+ */
163
+ async function listNeedsYou(filter = {}) {
164
+ const { app, status } = filter || {};
165
+ const { items } = await readStore(needsYouPath());
166
+ return items.filter((it) => (app === undefined || it.app === app) && (status === undefined || it.status === status));
167
+ }
168
+
169
+ /** The caller fields a post may set on an open item. */
170
+ function callerKey(item) {
171
+ return JSON.stringify([item.title, item.why, item.link, item.options, item.externalRef]);
172
+ }
173
+
174
+ /**
175
+ * Create an open item, or replace title/why/link/options/externalRef of an
176
+ * existing open item with the same app + id (a left-out field is cleared).
177
+ * A closed item is returned unchanged. `changed` is decided inside the write
178
+ * queue: true on create or when a stored field differs; an identical re-post
179
+ * writes nothing and keeps updatedAt.
180
+ * @param {unknown} input
181
+ * @returns {Promise<{ item: NeedsYouItem, created: boolean, changed: boolean }>}
182
+ */
183
+ async function postNeedsYou(input) {
184
+ const data = NeedsYouPostSchema.parse(input);
185
+ const filePath = needsYouPath();
186
+ return serialize(async () => {
187
+ const items = await loadForWrite(filePath);
188
+ const now = new Date().toISOString();
189
+ const existing = items.find((it) => it.app === data.app && it.id === data.id);
190
+ if (existing) {
191
+ if (existing.status !== 'open') return { item: existing, created: false, changed: false };
192
+ const before = callerKey(existing);
193
+ existing.title = data.title;
194
+ existing.why = data.why ?? '';
195
+ existing.link = data.link ?? null;
196
+ existing.options = data.options ?? null;
197
+ existing.externalRef = data.externalRef ?? null;
198
+ if (callerKey(existing) === before) return { item: existing, created: false, changed: false };
199
+ existing.updatedAt = now;
200
+ await writeStore(filePath, items);
201
+ return { item: existing, created: false, changed: true };
202
+ }
203
+ const open = items.filter((it) => it.status === 'open');
204
+ if (open.filter((it) => it.app === data.app).length >= MAX_OPEN_PER_APP) {
205
+ throw limitError(`${data.app} already has ${MAX_OPEN_PER_APP} open Needs you items.`);
206
+ }
207
+ if (open.length >= MAX_OPEN_TOTAL) {
208
+ throw limitError(`There are already ${MAX_OPEN_TOTAL} open Needs you items.`);
209
+ }
210
+ /** @type {NeedsYouItem} */
211
+ const item = {
212
+ app: data.app,
213
+ id: /** @type {string} */ (data.id),
214
+ title: data.title,
215
+ why: data.why ?? '',
216
+ link: data.link ?? null,
217
+ options: data.options ?? null,
218
+ externalRef: data.externalRef ?? null,
219
+ status: 'open',
220
+ answer: null,
221
+ createdAt: now,
222
+ updatedAt: now,
223
+ answeredAt: null,
224
+ };
225
+ items.push(item);
226
+ await writeStore(filePath, items);
227
+ return { item, created: true, changed: true };
228
+ });
229
+ }
230
+
231
+ /** Apply `mutate` to the open item app+id; returns it, or null when none / mutate refuses. */
232
+ async function updateOpen(app, id, mutate) {
233
+ const key = KeySchema.parse({ app, id });
234
+ const filePath = needsYouPath();
235
+ return serialize(async () => {
236
+ const items = await loadForWrite(filePath);
237
+ const item = items.find((it) => it.app === key.app && it.id === key.id);
238
+ if (!item || item.status !== 'open') return null;
239
+ const now = new Date().toISOString();
240
+ if (!mutate(item, now)) return null;
241
+ item.updatedAt = now;
242
+ await writeStore(filePath, items);
243
+ return item;
244
+ });
245
+ }
246
+
247
+ /**
248
+ * @param {{ app: string, id: string }} args
249
+ * @returns {Promise<NeedsYouItem | null>}
250
+ */
251
+ async function withdrawNeedsYou({ app, id }) {
252
+ return updateOpen(app, id, (item) => {
253
+ item.status = 'withdrawn';
254
+ return true;
255
+ });
256
+ }
257
+
258
+ /**
259
+ * @param {{ app: string, id: string, answer: string }} args
260
+ * @returns {Promise<NeedsYouItem | null>}
261
+ */
262
+ async function answerNeedsYou({ app, id, answer }) {
263
+ return updateOpen(app, id, (item, now) => {
264
+ if (!item.options || typeof answer !== 'string' || !item.options.includes(answer)) return false;
265
+ item.status = 'answered';
266
+ item.answer = answer;
267
+ item.answeredAt = now;
268
+ return true;
269
+ });
270
+ }
271
+
272
+ module.exports = {
273
+ NeedsYouPostSchema,
274
+ listNeedsYou,
275
+ postNeedsYou,
276
+ withdrawNeedsYou,
277
+ answerNeedsYou,
278
+ MAX_OPEN_PER_APP,
279
+ MAX_OPEN_TOTAL,
280
+ RETENTION_MS,
281
+ };
@@ -0,0 +1,113 @@
1
+ 'use strict'
2
+
3
+ // Inbound twin of remoteIpcDispatch.cjs's chunkFrames: rebuilds a browser→desktop
4
+ // message that arrived as several E2E-boxed `e2e:frame` envelopes (the bilko.run
5
+ // relay drops any socket message over 256 KB, so large uploads are split into
6
+ // ≤180 KB frames). Pure, per-client state with hard memory bounds — a buggy or
7
+ // hostile browser cannot exhaust desktop memory: bounded frames per message,
8
+ // bounded bytes per message, bounded concurrent messages per client, idle TTL.
9
+
10
+ const { joinFrames } = require('./remoteIpcDispatch.cjs')
11
+
12
+ const FRAME_LIMITS = Object.freeze({
13
+ maxMessageBytes: 25 * 1024 * 1024,
14
+ maxInflightPerClient: 2,
15
+ maxFrames: 200,
16
+ idleTtlMs: 60000,
17
+ })
18
+
19
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
20
+
21
+ function createFrameAssembler({
22
+ maxMessageBytes = FRAME_LIMITS.maxMessageBytes,
23
+ maxInflightPerClient = FRAME_LIMITS.maxInflightPerClient,
24
+ maxFrames = FRAME_LIMITS.maxFrames,
25
+ idleTtlMs = FRAME_LIMITS.idleTtlMs,
26
+ now = Date.now,
27
+ } = {}) {
28
+ /** @type {Map<string, Map<string, { total: number, frames: Map<number, string>, bytes: number, lastAt: number }>>} */
29
+ const clients = new Map()
30
+
31
+ function free(clientKey, msgId) {
32
+ const msgs = clients.get(clientKey)
33
+ if (!msgs) return
34
+ msgs.delete(msgId)
35
+ if (msgs.size === 0) clients.delete(clientKey)
36
+ }
37
+
38
+ function refuse(clientKey, msgId, reason) {
39
+ if (msgId !== undefined) free(clientKey, msgId)
40
+ return { status: 'refused', reason }
41
+ }
42
+
43
+ function sweep() {
44
+ const t = now()
45
+ for (const [clientKey, msgs] of clients) {
46
+ for (const [msgId, entry] of msgs) {
47
+ if (t - entry.lastAt > idleTtlMs) msgs.delete(msgId)
48
+ }
49
+ if (msgs.size === 0) clients.delete(clientKey)
50
+ }
51
+ }
52
+
53
+ function dropClient(clientKey) {
54
+ clients.delete(clientKey)
55
+ }
56
+
57
+ function accept(clientKey, payload) {
58
+ sweep()
59
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return refuse(clientKey, undefined, 'malformed')
60
+ const { msgId, seq, total, data } = payload
61
+ if (
62
+ typeof msgId !== 'string' || !UUID_RE.test(msgId) ||
63
+ !Number.isInteger(total) || total < 1 || total > maxFrames ||
64
+ !Number.isInteger(seq) || seq < 0 || seq >= total ||
65
+ typeof data !== 'string'
66
+ ) {
67
+ return refuse(clientKey, undefined, 'malformed')
68
+ }
69
+
70
+ let msgs = clients.get(clientKey)
71
+ let entry = msgs && msgs.get(msgId)
72
+ if (!entry) {
73
+ if (msgs && msgs.size >= maxInflightPerClient) return refuse(clientKey, undefined, 'too_many_inflight')
74
+ if (data.length > maxMessageBytes) return refuse(clientKey, undefined, 'too_large')
75
+ entry = { total, frames: new Map(), bytes: 0, lastAt: now() }
76
+ if (!msgs) {
77
+ msgs = new Map()
78
+ clients.set(clientKey, msgs)
79
+ }
80
+ msgs.set(msgId, entry)
81
+ } else {
82
+ if (entry.total !== total) return refuse(clientKey, msgId, 'total_mismatch')
83
+ if (entry.frames.has(seq)) return refuse(clientKey, msgId, 'duplicate_seq')
84
+ if (entry.bytes + data.length > maxMessageBytes) return refuse(clientKey, msgId, 'too_large')
85
+ }
86
+
87
+ entry.frames.set(seq, data)
88
+ entry.bytes += data.length
89
+ entry.lastAt = now()
90
+ if (entry.frames.size < entry.total) return { status: 'partial' }
91
+
92
+ free(clientKey, msgId)
93
+ const ordered = []
94
+ for (let i = 0; i < entry.total; i++) ordered.push({ seq: i, total: entry.total, data: entry.frames.get(i) })
95
+ let envelope
96
+ try {
97
+ envelope = joinFrames(ordered)
98
+ } catch {
99
+ return { status: 'refused', reason: 'bad_json' }
100
+ }
101
+ if (
102
+ !envelope || typeof envelope !== 'object' || Array.isArray(envelope) ||
103
+ typeof envelope.type !== 'string' || envelope.type.startsWith('e2e:')
104
+ ) {
105
+ return { status: 'refused', reason: 'bad_inner' }
106
+ }
107
+ return { status: 'complete', envelope }
108
+ }
109
+
110
+ return { accept, dropClient, sweep }
111
+ }
112
+
113
+ module.exports = { createFrameAssembler, FRAME_LIMITS }
@@ -15,9 +15,11 @@
15
15
  * toolCallCount, toolBreakdown, errorCount, sessionCount are populated;
16
16
  * token fields are 0. One per (date, projectDir).
17
17
  * - per-model line (modelId === a real model id): inputTokens,
18
- * outputTokens, cacheReadTokens, cacheCreationTokens are populated; the
19
- * rest are 0/empty. Cost is NOT stored — it's computed at read time from
20
- * MODEL_PRICING so a pricing fix retroactively corrects displayed cost.
18
+ * outputTokens, cacheReadTokens, cacheCreationTokens and (since v4)
19
+ * cacheCreation1hTokens — the 1-hour part of cacheCreationTokens — are
20
+ * populated; the rest are 0/empty. Cost is NOT stored — it's computed at
21
+ * read time from lib/claude/modelPricing.cjs so a pricing fix
22
+ * retroactively corrects displayed cost.
21
23
  * - finalized marker (projectDir === '', modelId === FINALIZED_MODEL_ID):
22
24
  * one per date, carries only `finalizedAt`. A date only counts as closed
23
25
  * (safe to trust the rollup with no live re-scan) once this exists.
@@ -35,11 +37,18 @@ const TOTALS_MODEL_ID = '';
35
37
  const FINALIZED_MODEL_ID = '__finalized__';
36
38
  const FINALIZED_PROJECT_ID = '';
37
39
  // Bumped when a bucket/finalized-marker line's shape changes in a way that
38
- // requires re-deriving it from transcripts (v1 → v2 added `activeMinutes`).
40
+ // requires re-deriving it from transcripts (v1 → v2 added `activeMinutes`;
41
+ // v2 → v3 counts each model call once — earlier versions over-counted calls,
42
+ // so a day still finalized at v<3 reads high; v3 → v4 records 1-hour cache
43
+ // writes as cacheCreation1hTokens on per-model lines).
39
44
  // isDateFinalized() gates on this so old-shape finalized days get re-scanned
40
45
  // by the existing finalizeClosedDays() budget/resume loop instead of a new
41
46
  // migration path.
42
- const ROLLUP_VERSION = 2;
47
+ const ROLLUP_VERSION = 4;
48
+ // The version that fixed the call over-count. A day finalized below it reads
49
+ // high and is reported as legacy; a day finalized at/above it but below
50
+ // ROLLUP_VERSION has correct counts and only lacks a newer field.
51
+ const OVERCOUNT_FIX_VERSION = 3;
43
52
 
44
53
  function rollupKey(date, projectDir, modelId) {
45
54
  return `${date}|${projectDir}|${modelId}`;
@@ -97,6 +106,22 @@ function isDateFinalized(mergedMap, date) {
97
106
  return (bucket.v ?? 1) >= ROLLUP_VERSION;
98
107
  }
99
108
 
109
+ /**
110
+ * Sorted dates whose finalized marker was written below OVERCOUNT_FIX_VERSION
111
+ * (no `v` counts as v1). These are days the finalize pass could not recount —
112
+ * typically because their transcripts are gone — so their stored numbers come
113
+ * from the over-counting scheme. A date with no marker is not legacy.
114
+ */
115
+ function legacyFinalizedDates(mergedMap) {
116
+ const dates = [];
117
+ for (const bucket of mergedMap.values()) {
118
+ if (bucket.projectDir !== FINALIZED_PROJECT_ID || bucket.modelId !== FINALIZED_MODEL_ID) continue;
119
+ if (!bucket.finalizedAt) continue;
120
+ if ((bucket.v ?? 1) < OVERCOUNT_FIX_VERSION) dates.push(bucket.date);
121
+ }
122
+ return dates.sort();
123
+ }
124
+
100
125
  /**
101
126
  * Append bucket entries (append-only) to the rollup file, then compact
102
127
  * (dedupe + rewrite) if the file has grown past COMPACT_THRESHOLD_BYTES.
@@ -138,10 +163,12 @@ module.exports = {
138
163
  FINALIZED_MODEL_ID,
139
164
  FINALIZED_PROJECT_ID,
140
165
  ROLLUP_VERSION,
166
+ OVERCOUNT_FIX_VERSION,
141
167
  rollupKey,
142
168
  mergeRollupLines,
143
169
  readRollup,
144
170
  isDateFinalized,
171
+ legacyFinalizedDates,
145
172
  appendRollupDays,
146
173
  compact,
147
174
  };