claude-mem-lite 6.35.0 → 6.35.2

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.
@@ -184,30 +184,40 @@ function markerNotRetracted(s) {
184
184
  * @returns {Set<number>} unique IDs referenced as `#NN` in assistant text
185
185
  */
186
186
  export function extractCitationsFromTranscript(transcriptPath, opts = {}) {
187
- const { mainOnly = false, includeDismissed = false } = opts;
188
187
  const ids = new Set();
189
- for (const entry of readTranscriptEntries(transcriptPath)) {
190
- // Claude Code transcript: one JSON per line with type='assistant' | 'user' | ...
191
- if (entry.type !== 'assistant' || !entry.message) continue;
192
- // Citation-decay loop scopes citation signal to main-thread text only —
193
- // subagent dispatches run their own session context the parent can't
194
- // reasonably be held accountable for. Default off preserves the broader
195
- // access_count-bump semantics of existing callers (P4 bumpCitationAccess).
196
- if (mainOnly && entry.isSidechain === true) continue;
197
- const content = entry.message.content;
198
- if (!Array.isArray(content)) continue;
199
- for (const block of content) {
200
- if (block.type !== 'text' || typeof block.text !== 'string') continue;
201
- CITATION_RE.lastIndex = 0;
202
- let m;
203
- while ((m = CITATION_RE.exec(block.text))) {
204
- const id = Number(m[1]);
205
- if (!(Number.isInteger(id) && id > 0 && id < 1e7)) continue;
206
- if (includeDismissed || !isDismissalAt(block.text, m.index + m[0].length)) ids.add(id);
207
- }
188
+ for (const entry of readTranscriptEntries(transcriptPath)) addCitationsOf(ids, entry, opts);
189
+ return ids;
190
+ }
191
+
192
+ /**
193
+ * extractCitationsFromTranscript's rule for ONE transcript record: add to `ids` the `#NN`
194
+ * ids it cites. The path scan and the Stop digest (lib/transcript-digest.mjs) both fold it.
195
+ *
196
+ * @param {Set<number>} ids
197
+ * @param {object} entry one parsed transcript record
198
+ * @param {{mainOnly?: boolean, includeDismissed?: boolean}} [opts]
199
+ */
200
+ export function addCitationsOf(ids, entry, opts = {}) {
201
+ const { mainOnly = false, includeDismissed = false } = opts;
202
+ // Claude Code transcript: one JSON per line with type='assistant' | 'user' | ...
203
+ if (entry.type !== 'assistant' || !entry.message) return;
204
+ // Citation-decay loop scopes citation signal to main-thread text only —
205
+ // subagent dispatches run their own session context the parent can't
206
+ // reasonably be held accountable for. Default off preserves the broader
207
+ // access_count-bump semantics of existing callers (P4 bumpCitationAccess).
208
+ if (mainOnly && entry.isSidechain === true) return;
209
+ const content = entry.message.content;
210
+ if (!Array.isArray(content)) return;
211
+ for (const block of content) {
212
+ if (block.type !== 'text' || typeof block.text !== 'string') continue;
213
+ CITATION_RE.lastIndex = 0;
214
+ let m;
215
+ while ((m = CITATION_RE.exec(block.text))) {
216
+ const id = Number(m[1]);
217
+ if (!(Number.isInteger(id) && id > 0 && id < 1e7)) continue;
218
+ if (includeDismissed || !isDismissalAt(block.text, m.index + m[0].length)) ids.add(id);
208
219
  }
209
220
  }
210
- return ids;
211
221
  }
212
222
 
213
223
  /**
@@ -319,38 +329,53 @@ export function classifyCitationContext(transcriptPath, opts = {}) {
319
329
  * Returns zeros if transcript is missing or empty.
320
330
  */
321
331
  export function computeCiteRecall(transcriptPath) {
322
- const injected = new Set();
323
- const cited = new Set();
332
+ const state = { injected: new Set(), cited: new Set() };
333
+ for (const entry of readTranscriptEntries(transcriptPath)) addCiteRecallOf(state, entry);
334
+ return citeRecallStats(state);
335
+ }
324
336
 
325
- for (const entry of readTranscriptEntries(transcriptPath)) {
326
- const target = entry.type === 'assistant' ? cited : injected;
327
- // Walk every text-bearing surface the transcript carries: top-level content,
328
- // nested message content (assistant/user blocks), and tool_result-style
329
- // entries that hide hook injections inside system-reminders.
330
- const surfaces = [];
331
- if (typeof entry.content === 'string') surfaces.push(entry.content);
332
- if (Array.isArray(entry.content)) surfaces.push(...entry.content);
333
- if (entry.message?.content) {
334
- if (typeof entry.message.content === 'string') surfaces.push(entry.message.content);
335
- else if (Array.isArray(entry.message.content)) surfaces.push(...entry.message.content);
337
+ /**
338
+ * computeCiteRecall's rule for ONE transcript record: `#NN` ids in assistant text go to
339
+ * `state.cited`, those anywhere else to `state.injected`.
340
+ *
341
+ * @param {{injected: Set<number>, cited: Set<number>}} state
342
+ * @param {object} entry one parsed transcript record
343
+ */
344
+ export function addCiteRecallOf(state, entry) {
345
+ const target = entry.type === 'assistant' ? state.cited : state.injected;
346
+ // Walk every text-bearing surface the transcript carries: top-level content,
347
+ // nested message content (assistant/user blocks), and tool_result-style
348
+ // entries that hide hook injections inside system-reminders.
349
+ const surfaces = [];
350
+ if (typeof entry.content === 'string') surfaces.push(entry.content);
351
+ if (Array.isArray(entry.content)) surfaces.push(...entry.content);
352
+ if (entry.message?.content) {
353
+ if (typeof entry.message.content === 'string') surfaces.push(entry.message.content);
354
+ else if (Array.isArray(entry.message.content)) surfaces.push(...entry.message.content);
355
+ }
356
+ for (const s of surfaces) {
357
+ let text = '';
358
+ if (typeof s === 'string') text = s;
359
+ else if (s && typeof s === 'object') {
360
+ if (typeof s.text === 'string') text = s.text;
361
+ else if (typeof s.content === 'string') text = s.content;
336
362
  }
337
- for (const s of surfaces) {
338
- let text = '';
339
- if (typeof s === 'string') text = s;
340
- else if (s && typeof s === 'object') {
341
- if (typeof s.text === 'string') text = s.text;
342
- else if (typeof s.content === 'string') text = s.content;
343
- }
344
- if (!text) continue;
345
- CITATION_RE.lastIndex = 0;
346
- let m;
347
- while ((m = CITATION_RE.exec(text))) {
348
- const id = Number(m[1]);
349
- if (Number.isInteger(id) && id > 0 && id < 1e7) target.add(id);
350
- }
363
+ if (!text) continue;
364
+ CITATION_RE.lastIndex = 0;
365
+ let m;
366
+ while ((m = CITATION_RE.exec(text))) {
367
+ const id = Number(m[1]);
368
+ if (Number.isInteger(id) && id > 0 && id < 1e7) target.add(id);
351
369
  }
352
370
  }
371
+ }
353
372
 
373
+ /**
374
+ * computeCiteRecall's result from its two sets.
375
+ * @param {{injected: Set<number>, cited: Set<number>}} state
376
+ * @returns {{injected: number, cited: number, recalled: number, ratio: number}}
377
+ */
378
+ export function citeRecallStats({ injected, cited }) {
354
379
  let recalled = 0;
355
380
  for (const id of injected) if (cited.has(id)) recalled++;
356
381
  const ratio = injected.size > 0 ? recalled / injected.size : 0;
@@ -378,24 +403,32 @@ export function computeCiteRecall(transcriptPath) {
378
403
  * @returns {Set<number>}
379
404
  */
380
405
  export function extractUserTypedIds(transcriptPath, opts = {}) {
381
- const { mainOnly = false } = opts;
382
406
  const ids = new Set();
383
- for (const entry of readTranscriptEntries(transcriptPath)) {
384
- if (entry.type !== 'user' || !entry.message) continue;
385
- if (mainOnly && entry.isSidechain === true) continue;
386
- const content = entry.message.content;
387
- const blocks =
388
- typeof content === 'string' ? [{ type: 'text', text: content }] : Array.isArray(content) ? content : [];
389
- for (const block of blocks) {
390
- if (block.type !== 'text' || typeof block.text !== 'string') continue;
391
- CITATION_RE.lastIndex = 0;
392
- let m;
393
- while ((m = CITATION_RE.exec(block.text))) addObsId(ids, m[1]);
394
- }
395
- }
407
+ for (const entry of readTranscriptEntries(transcriptPath)) addUserTypedIdsOf(ids, entry, opts);
396
408
  return ids;
397
409
  }
398
410
 
411
+ /**
412
+ * extractUserTypedIds's rule for ONE transcript record.
413
+ * @param {Set<number>} ids
414
+ * @param {object} entry one parsed transcript record
415
+ * @param {{mainOnly?: boolean}} [opts]
416
+ */
417
+ export function addUserTypedIdsOf(ids, entry, opts = {}) {
418
+ const { mainOnly = false } = opts;
419
+ if (entry.type !== 'user' || !entry.message) return;
420
+ if (mainOnly && entry.isSidechain === true) return;
421
+ const content = entry.message.content;
422
+ const blocks =
423
+ typeof content === 'string' ? [{ type: 'text', text: content }] : Array.isArray(content) ? content : [];
424
+ for (const block of blocks) {
425
+ if (block.type !== 'text' || typeof block.text !== 'string') continue;
426
+ CITATION_RE.lastIndex = 0;
427
+ let m;
428
+ while ((m = CITATION_RE.exec(block.text))) addObsId(ids, m[1]);
429
+ }
430
+ }
431
+
399
432
  /**
400
433
  * The set of ids this session actually put in front of the model, across ALL SEVEN faces.
401
434
  *
@@ -435,13 +468,44 @@ export function buildCitationRelevanceSet({
435
468
  sessionId = null,
436
469
  subagentInjected = [],
437
470
  } = {}) {
471
+ return citationRelevanceSetFrom({
472
+ attachmentInjected: extractAllInjected(transcriptPath),
473
+ userTyped: extractUserTypedIds(transcriptPath),
474
+ runtimeDir,
475
+ project,
476
+ sessionId,
477
+ subagentInjected,
478
+ });
479
+ }
480
+
481
+ /**
482
+ * buildCitationRelevanceSet from the two transcript reads it makes, already done: the
483
+ * Stop hook has them from its digest (lib/transcript-digest.mjs).
484
+ *
485
+ * @param {object} ctx
486
+ * @param {Iterable<number>} ctx.attachmentInjected extractAllInjected's ids (5 attachment faces)
487
+ * @param {Iterable<number>} ctx.userTyped extractUserTypedIds's ids
488
+ * @param {string} [ctx.runtimeDir]
489
+ * @param {string} [ctx.project]
490
+ * @param {string|null} [ctx.sessionId]
491
+ * @param {Iterable<number>} [ctx.subagentInjected]
492
+ * @returns {Set<number>}
493
+ */
494
+ export function citationRelevanceSetFrom({
495
+ attachmentInjected,
496
+ userTyped,
497
+ runtimeDir,
498
+ project,
499
+ sessionId = null,
500
+ subagentInjected = [],
501
+ }) {
438
502
  const out = new Set();
439
- for (const id of extractAllInjected(transcriptPath)) out.add(id); // 5 attachment faces
503
+ for (const id of attachmentInjected) out.add(id); // 5 attachment faces
440
504
  if (runtimeDir && project) {
441
505
  for (const id of extractInjectedFromKeyContext({ runtimeDir, project, sessionId })) out.add(id);
442
506
  }
443
507
  for (const id of subagentInjected) out.add(id);
444
- for (const id of extractUserTypedIds(transcriptPath)) out.add(id); // the user named it
508
+ for (const id of userTyped) out.add(id); // the user named it
445
509
  return out;
446
510
  }
447
511
 
@@ -632,7 +696,6 @@ function normalizeHookCommand(command) {
632
696
  * not enter the denominator, else it streak-demotes despite being used there.
633
697
  */
634
698
  function eachHookAttachment(transcriptPath, fn, opts = {}) {
635
- const { mainOnly = false } = opts;
636
699
  let prompt = null;
637
700
  for (const entry of readTranscriptEntries(transcriptPath)) {
638
701
  if (entry.type === 'user') {
@@ -640,23 +703,38 @@ function eachHookAttachment(transcriptPath, fn, opts = {}) {
640
703
  if (p !== null) prompt = p;
641
704
  continue;
642
705
  }
643
- if (entry.type !== 'attachment') continue;
644
- if (mainOnly && entry.isSidechain === true) continue;
645
- const att = entry.attachment;
646
- if (!att || att.type !== 'hook_success') continue;
647
- const stdout = att.stdout || '';
648
- if (!stdout) continue;
649
- // stdout is JSON wrapping additionalContext OR raw text (triggerErrorRecall
650
- // and the <memory-context> block write raw). Try JSON first, fall back to raw.
651
- let text = stdout;
652
- try {
653
- const parsed = JSON.parse(stdout);
654
- text = parsed?.hookSpecificOutput?.additionalContext || stdout;
655
- } catch {}
656
- fn({ command: normalizeHookCommand(att.command), text, prompt });
706
+ const att = hookAttachmentOf(entry, opts);
707
+ if (att) fn({ ...att, prompt });
657
708
  }
658
709
  }
659
710
 
711
+ /**
712
+ * The `hook_success` attachment ONE transcript record carries, as eachHookAttachment hands it
713
+ * on — `{command, text}` with the command quote-normalized and JSON additionalContext unwrapped
714
+ * — or null when the record is not one (or is a sidechain record under `mainOnly`).
715
+ *
716
+ * @param {object} entry one parsed transcript record
717
+ * @param {{mainOnly?: boolean}} [opts]
718
+ * @returns {{command: string, text: string}|null}
719
+ */
720
+ function hookAttachmentOf(entry, opts = {}) {
721
+ const { mainOnly = false } = opts;
722
+ if (entry.type !== 'attachment') return null;
723
+ if (mainOnly && entry.isSidechain === true) return null;
724
+ const att = entry.attachment;
725
+ if (!att || att.type !== 'hook_success') return null;
726
+ const stdout = att.stdout || '';
727
+ if (!stdout) return null;
728
+ // stdout is JSON wrapping additionalContext OR raw text (triggerErrorRecall
729
+ // and the <memory-context> block write raw). Try JSON first, fall back to raw.
730
+ let text = stdout;
731
+ try {
732
+ const parsed = JSON.parse(stdout);
733
+ text = parsed?.hookSpecificOutput?.additionalContext || stdout;
734
+ } catch {}
735
+ return { command: normalizeHookCommand(att.command), text };
736
+ }
737
+
660
738
  /**
661
739
  * The prompt a transcript `user` entry carries, as the UserPromptSubmit hook received it —
662
740
  * or null when the entry is not a typed main-thread prompt (a tool result, a sidechain
@@ -852,23 +930,37 @@ const ATTACHMENT_SURFACES = Object.keys(SURFACE_MATCHERS);
852
930
  * Always all four keys, always Sets (empty on missing/unreadable transcript).
853
931
  */
854
932
  export function extractInjectedBySurface(transcriptPath, opts = {}) {
933
+ const out = emptySurfaceSets();
934
+ for (const entry of readTranscriptEntries(transcriptPath)) addInjectedBySurfaceOf(out, entry, opts);
935
+ return out;
936
+ }
937
+
938
+ /** extractInjectedBySurface's accumulator before any record: one empty Set per attachment face. */
939
+ export function emptySurfaceSets() {
855
940
  const out = {};
856
941
  for (const face of ATTACHMENT_SURFACES) out[face] = new Set();
857
- eachHookAttachment(
858
- transcriptPath,
859
- (ctx) => {
860
- for (const face of ATTACHMENT_SURFACES) {
861
- const matcher = SURFACE_MATCHERS[face];
862
- if (!matcher.accepts(ctx)) continue;
863
- const target = out[face];
864
- matcher.collect(ctx.text, (raw) => addObsId(target, raw));
865
- }
866
- },
867
- opts,
868
- );
869
942
  return out;
870
943
  }
871
944
 
945
+ /**
946
+ * extractInjectedBySurface's rule for ONE transcript record. No matcher reads the prompt
947
+ * eachHookAttachment tracks, so a record is judged on its own.
948
+ *
949
+ * @param {Record<string, Set<number>>} out from emptySurfaceSets
950
+ * @param {object} entry one parsed transcript record
951
+ * @param {{mainOnly?: boolean}} [opts]
952
+ */
953
+ export function addInjectedBySurfaceOf(out, entry, opts = {}) {
954
+ const ctx = hookAttachmentOf(entry, opts);
955
+ if (!ctx) return;
956
+ for (const face of ATTACHMENT_SURFACES) {
957
+ const matcher = SURFACE_MATCHERS[face];
958
+ if (!matcher.accepts(ctx)) continue;
959
+ const target = out[face];
960
+ matcher.collect(ctx.text, (raw) => addObsId(target, raw));
961
+ }
962
+ }
963
+
872
964
  /**
873
965
  * Per-face count of how many DISTINCT hook attachments injected each id (D#193).
874
966
  *
@@ -1323,24 +1415,31 @@ const SUBAGENT_INJECT_ID_RE = new RegExp(`^\\s{0,4}#(${OBS_ID_DIGITS})\\s+—`);
1323
1415
  */
1324
1416
  export function extractInjectedFromSubagentPrompt(transcriptPath) {
1325
1417
  const ids = new Set();
1326
- for (const entry of readTranscriptEntries(transcriptPath)) {
1327
- if (entry.type !== 'user') continue;
1328
- const c = entry.message?.content;
1329
- const text =
1330
- typeof c === 'string'
1331
- ? c
1332
- : Array.isArray(c)
1333
- ? c.map((x) => (typeof x === 'string' ? x : x?.text || '')).join('\n')
1334
- : '';
1335
- if (!text || !SUBAGENT_INJECT_MARKER.test(text)) continue;
1336
- for (const bl of text.split('\n')) {
1337
- const m = SUBAGENT_INJECT_ID_RE.exec(bl);
1338
- if (m) addObsId(ids, m[1]);
1339
- }
1340
- }
1418
+ for (const entry of readTranscriptEntries(transcriptPath)) addSubagentPromptIdsOf(ids, entry);
1341
1419
  return ids;
1342
1420
  }
1343
1421
 
1422
+ /**
1423
+ * extractInjectedFromSubagentPrompt's rule for ONE transcript record.
1424
+ * @param {Set<number>} ids
1425
+ * @param {object} entry one parsed transcript record
1426
+ */
1427
+ export function addSubagentPromptIdsOf(ids, entry) {
1428
+ if (entry.type !== 'user') return;
1429
+ const c = entry.message?.content;
1430
+ const text =
1431
+ typeof c === 'string'
1432
+ ? c
1433
+ : Array.isArray(c)
1434
+ ? c.map((x) => (typeof x === 'string' ? x : x?.text || '')).join('\n')
1435
+ : '';
1436
+ if (!text || !SUBAGENT_INJECT_MARKER.test(text)) return;
1437
+ for (const bl of text.split('\n')) {
1438
+ const m = SUBAGENT_INJECT_ID_RE.exec(bl);
1439
+ if (m) addObsId(ids, m[1]);
1440
+ }
1441
+ }
1442
+
1344
1443
  /**
1345
1444
  * Locate the sidechain (subagent) transcripts belonging to ONE session, given
1346
1445
  * that session's main transcript path. Claude Code lays them out as
@@ -1410,20 +1509,33 @@ export function findSubagentTranscripts(transcriptPath) {
1410
1509
  * `cited` is always a subset of `injected`.
1411
1510
  */
1412
1511
  export function collectSubagentSurface(transcriptPath) {
1512
+ return subagentSurfaceFrom(
1513
+ findSubagentTranscripts(transcriptPath).map((p) => ({
1514
+ seen: extractInjectedFromSubagentPrompt(p),
1515
+ said: extractCitationsFromTranscript(p),
1516
+ })),
1517
+ );
1518
+ }
1519
+
1520
+ /**
1521
+ * collectSubagentSurface from its per-file reads, already done: for each sidechain file, the
1522
+ * ids its prompt was handed (`seen`, extractInjectedFromSubagentPrompt) and the ids it cited
1523
+ * (`said`, extractCitationsFromTranscript). The Stop hook has them from its digest.
1524
+ *
1525
+ * @param {Array<{seen: Set<number>, said: Set<number>}>} perFile
1526
+ * @returns {{injected: Set<number>, cited: Set<number>, files: number}}
1527
+ */
1528
+ export function subagentSurfaceFrom(perFile) {
1413
1529
  const injected = new Set();
1414
1530
  const cited = new Set();
1415
- let files = 0;
1416
- for (const p of findSubagentTranscripts(transcriptPath)) {
1417
- files++;
1531
+ for (const { seen, said } of perFile) {
1418
1532
  // Per-file intersection, not two unions: the pairing is the whole point.
1419
- const seen = extractInjectedFromSubagentPrompt(p);
1420
- const said = extractCitationsFromTranscript(p);
1421
1533
  for (const id of seen) {
1422
1534
  injected.add(id);
1423
1535
  if (said.has(id)) cited.add(id);
1424
1536
  }
1425
1537
  }
1426
- return { injected, cited, files };
1538
+ return { injected, cited, files: perFile.length };
1427
1539
  }
1428
1540
 
1429
1541
  export function computeThreadCiteRecall(transcriptPath) {
@@ -1523,15 +1635,25 @@ export function hasMainThreadAssistantText(transcriptPath) {
1523
1635
  // with the other seven scanners of the same file (audit P2-8).
1524
1636
  const entries = readTranscriptEntries(transcriptPath);
1525
1637
  for (let i = entries.length - 1; i >= 0; i--) {
1526
- const entry = entries[i];
1527
- if (entry.type !== 'assistant' || !entry.message) continue;
1528
- if (entry.isSidechain === true) continue;
1529
- const content = entry.message.content;
1530
- if (!Array.isArray(content)) continue;
1531
- for (const block of content) {
1532
- if (block.type !== 'text' || typeof block.text !== 'string') continue;
1533
- if (block.text.trim().length > 0) return true;
1534
- }
1638
+ if (isMainThreadAssistantText(entries[i])) return true;
1639
+ }
1640
+ return false;
1641
+ }
1642
+
1643
+ /**
1644
+ * hasMainThreadAssistantText's rule for ONE transcript record: a main-thread assistant
1645
+ * record with a non-blank text block.
1646
+ * @param {object} entry one parsed transcript record
1647
+ * @returns {boolean}
1648
+ */
1649
+ export function isMainThreadAssistantText(entry) {
1650
+ if (entry.type !== 'assistant' || !entry.message) return false;
1651
+ if (entry.isSidechain === true) return false;
1652
+ const content = entry.message.content;
1653
+ if (!Array.isArray(content)) return false;
1654
+ for (const block of content) {
1655
+ if (block.type !== 'text' || typeof block.text !== 'string') continue;
1656
+ if (block.text.trim().length > 0) return true;
1535
1657
  }
1536
1658
  return false;
1537
1659
  }
@@ -202,36 +202,50 @@ const MEM_SAVE_TOOL_NAMES = new Set([
202
202
  ]);
203
203
 
204
204
  export function countUnsavedBugfixShape(transcriptPath) {
205
- let nudged = 0;
206
- let saved = 0;
205
+ const state = { nudged: 0, saved: 0 };
206
+ for (const entry of readTranscriptEntries(transcriptPath)) addBugfixShapeOf(state, entry);
207
+ return bugfixShapeStats(state);
208
+ }
207
209
 
208
- for (const entry of readTranscriptEntries(transcriptPath)) {
209
- // Bugfix-shape hint emissions live in PostToolUse attachment.stdout.
210
- if (entry.type === 'attachment') {
211
- const stdout = entry.attachment?.stdout || '';
212
- if (stdout.includes(UNSAVED_BUGFIX_LITERAL)) nudged++;
213
- continue;
214
- }
210
+ /**
211
+ * countUnsavedBugfixShape's rule for ONE transcript record: count a hint emission into
212
+ * `state.nudged` and a lesson/bugfix save into `state.saved`.
213
+ * @param {{nudged: number, saved: number}} state
214
+ * @param {object} entry one parsed transcript record
215
+ */
216
+ export function addBugfixShapeOf(state, entry) {
217
+ // Bugfix-shape hint emissions live in PostToolUse attachment.stdout.
218
+ if (entry.type === 'attachment') {
219
+ const stdout = entry.attachment?.stdout || '';
220
+ if (stdout.includes(UNSAVED_BUGFIX_LITERAL)) state.nudged++;
221
+ return;
222
+ }
215
223
 
216
- // Save signals live in assistant tool_use blocks.
217
- if (entry.type === 'assistant' || entry.message?.role === 'assistant') {
218
- const content = entry.message?.content;
219
- if (!Array.isArray(content)) continue;
220
- for (const block of content) {
221
- if (block.type !== 'tool_use') continue;
222
- if (MEM_SAVE_TOOL_NAMES.has(block.name)) {
223
- const t = block.input?.type;
224
- if (t === 'bugfix' || t === 'lesson') saved++;
225
- continue;
226
- }
227
- if (block.name === 'Bash') {
228
- const cmd = block.input?.command || '';
229
- if (ACTIVITY_SAVE_LESSON_RE.test(cmd) || OBS_INSIGHT_SAVE_RE.test(cmd)) saved++;
230
- }
224
+ // Save signals live in assistant tool_use blocks.
225
+ if (entry.type === 'assistant' || entry.message?.role === 'assistant') {
226
+ const content = entry.message?.content;
227
+ if (!Array.isArray(content)) return;
228
+ for (const block of content) {
229
+ if (block.type !== 'tool_use') continue;
230
+ if (MEM_SAVE_TOOL_NAMES.has(block.name)) {
231
+ const t = block.input?.type;
232
+ if (t === 'bugfix' || t === 'lesson') state.saved++;
233
+ continue;
234
+ }
235
+ if (block.name === 'Bash') {
236
+ const cmd = block.input?.command || '';
237
+ if (ACTIVITY_SAVE_LESSON_RE.test(cmd) || OBS_INSIGHT_SAVE_RE.test(cmd)) state.saved++;
231
238
  }
232
239
  }
233
240
  }
241
+ }
234
242
 
243
+ /**
244
+ * countUnsavedBugfixShape's result from its two counts.
245
+ * @param {{nudged: number, saved: number}} state
246
+ * @returns {{nudged: number, saved: number, unsaved: number}}
247
+ */
248
+ export function bugfixShapeStats({ nudged, saved }) {
235
249
  return { nudged, saved, unsaved: Math.max(0, nudged - saved) };
236
250
  }
237
251
 
@@ -475,16 +489,23 @@ const CITE_BACK_ID_RE = citationIdRe();
475
489
 
476
490
  export function extractCiteBackSignals(transcriptPath) {
477
491
  const ids = new Set();
478
- for (const entry of readTranscriptEntries(transcriptPath)) {
479
- if (entry.type !== 'attachment') continue;
480
- const stdout = entry.attachment?.stdout || '';
481
- if (!stdout.includes(CITE_BACK_HINT_LEADER)) continue;
482
- CITE_BACK_ID_RE.lastIndex = 0;
483
- let m;
484
- while ((m = CITE_BACK_ID_RE.exec(stdout))) {
485
- const id = Number(m[1]);
486
- if (Number.isInteger(id) && id > 0 && id < 1e7) ids.add(id);
487
- }
488
- }
492
+ for (const entry of readTranscriptEntries(transcriptPath)) addCiteBackSignalsOf(ids, entry);
489
493
  return ids;
490
494
  }
495
+
496
+ /**
497
+ * extractCiteBackSignals's rule for ONE transcript record.
498
+ * @param {Set<number>} ids
499
+ * @param {object} entry one parsed transcript record
500
+ */
501
+ export function addCiteBackSignalsOf(ids, entry) {
502
+ if (entry.type !== 'attachment') return;
503
+ const stdout = entry.attachment?.stdout || '';
504
+ if (!stdout.includes(CITE_BACK_HINT_LEADER)) return;
505
+ CITE_BACK_ID_RE.lastIndex = 0;
506
+ let m;
507
+ while ((m = CITE_BACK_ID_RE.exec(stdout))) {
508
+ const id = Number(m[1]);
509
+ if (Number.isInteger(id) && id > 0 && id < 1e7) ids.add(id);
510
+ }
511
+ }