claude-mem-lite 6.34.0 → 6.35.1

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.
@@ -9,7 +9,7 @@
9
9
  "plugins": [
10
10
  {
11
11
  "name": "claude-mem-lite",
12
- "version": "6.34.0",
12
+ "version": "6.35.1",
13
13
  "source": "./",
14
14
  "homepage": "https://github.com/sdsrss/claude-mem-lite",
15
15
  "description": "Persistent long-term memory for Claude Code via MCP — captures coding decisions, bugfixes, and context across sessions. FTS5 BM25 keyword search with episode batching. Single SQLite DB, no external services. A lighter, lower-cost alternative to claude-mem (episode batching + a smaller model; cost savings are an internal estimate, not a measured benchmark)."
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem-lite",
3
- "version": "6.34.0",
3
+ "version": "6.35.1",
4
4
  "description": "Persistent long-term memory for Claude Code via MCP — captures coding decisions, bugfixes, and context across sessions. FTS5 BM25 keyword search with episode batching. Single SQLite DB, no external services. A lighter, lower-cost alternative to claude-mem (episode batching + a smaller model; cost savings are an internal estimate, not a measured benchmark).",
5
5
  "author": {
6
6
  "name": "sdsrss"
package/README.md CHANGED
@@ -239,6 +239,19 @@ rm -rf ~/claude-mem-lite/ # unhidden data dir from before the first release (n
239
239
  repos/ # Shallow-cloned source repos
240
240
  ```
241
241
 
242
+ ## Upgrading to 6.35.0
243
+
244
+ **The Last Session line names the session's main outcome more often; nothing to run, and the
245
+ schema version stays 49.** To go back, pin `claude-mem-lite@6.34.0`.
246
+
247
+ - **The session summary prompt's rule for the session's replies asks the model to order the work
248
+ it lists as completed by importance**, so the Last Session line SessionStart shows, cut to 120
249
+ characters, starts with the session's main finished outcome more often. The Completed field is
250
+ longer than before.
251
+ - **`uninstall --purge` no longer says `Done!` when `~/.claude-mem-lite` is a symbolic link.** The
252
+ purge then removes nothing and names the link.
253
+ - See CHANGELOG.md.
254
+
242
255
  ## Upgrading to 6.34.0
243
256
 
244
257
  **The session summary reads every turn's last reply; nothing to run, and the schema version stays
@@ -957,7 +970,7 @@ Each observation includes type, title, narrative, concepts, facts, importance (1
957
970
  # git clone install:
958
971
  node install.mjs install # Install and configure
959
972
  node install.mjs uninstall # Remove (keep data)
960
- node install.mjs uninstall --purge # Remove and delete all data
973
+ node install.mjs uninstall --purge # Remove and delete the data (see Uninstall)
961
974
  node install.mjs status # Show current status
962
975
  node cli.mjs doctor # Diagnose issues (cli.mjs, not install.mjs — see note)
963
976
  node cli.mjs repair # Recover a broken install from the latest signed release
@@ -1058,13 +1071,15 @@ After it finishes, `~/.claude-mem-lite/` is back in sync with the latest release
1058
1071
  # git clone:
1059
1072
  cd claude-mem-lite
1060
1073
  node install.mjs uninstall # Keeps ~/.claude-mem-lite/ data
1061
- node install.mjs uninstall --purge # Deletes ~/.claude-mem-lite/ and all data
1074
+ node install.mjs uninstall --purge # Deletes ~/.claude-mem-lite/ and its data
1062
1075
 
1063
1076
  # npx:
1064
1077
  npx claude-mem-lite uninstall
1065
1078
  npx claude-mem-lite uninstall --purge
1066
1079
  ```
1067
1080
 
1081
+ When `~/.claude-mem-lite` is a symbolic link, `--purge` removes nothing and names the link.
1082
+
1068
1083
  Data in `~/.claude-mem-lite/` is preserved by default. Delete manually if needed:
1069
1084
  ```bash
1070
1085
  rm -rf ~/.claude-mem-lite/
package/README.zh-CN.md CHANGED
@@ -201,6 +201,14 @@ rm -rf ~/claude-mem-lite/ # 首个发布版之前的非隐藏目录(不是
201
201
  repos/ # 浅克隆的源代码仓库
202
202
  ```
203
203
 
204
+ ## 升级到 6.35.0
205
+
206
+ **Last Session 那一行更常写出会话最重要的结果;不用执行任何操作,schema 版本仍是 49。** 想退回,请固定 `claude-mem-lite@6.34.0`。
207
+
208
+ - **会话摘要提示里讲会话回复的那条规则,要求模型按重要性排列 completed 里的完成事项**,所以 SessionStart 显示的、截到 120 字符的 Last Session 那一行,更常以会话最重要的完成结果开头。Completed 字段比以前长。
209
+ - **`~/.claude-mem-lite` 是符号链接时,`uninstall --purge` 不再打印 `Done!`。** 这时 purge 什么都不删,并说明是哪个链接。
210
+ - 详见 CHANGELOG.md。
211
+
204
212
  ## 升级到 6.34.0
205
213
 
206
214
  **会话摘要会读每一轮的最后回复;不用执行任何操作,schema 版本仍是 49。** 想退回,请固定 `claude-mem-lite@6.33.0`,并删掉数据目录里的 `runtime/turn-replies-*.json`:6.33.0 不读它们。
@@ -738,7 +746,7 @@ Episode 缓冲区 -> 刷新为 JSON -> claude -p --model haiku -> 结构化观
738
746
  # git clone 安装:
739
747
  node install.mjs install # 安装并配置
740
748
  node install.mjs uninstall # 移除(保留数据)
741
- node install.mjs uninstall --purge # 移除并删除所有数据
749
+ node install.mjs uninstall --purge # 移除并删除数据(见「卸载」)
742
750
  node install.mjs status # 显示当前状态
743
751
  node cli.mjs doctor # 诊断问题(用 cli.mjs 而非 install.mjs,见下方说明)
744
752
  node cli.mjs repair # 从最新签名发布恢复损坏的安装
@@ -804,13 +812,15 @@ T=$(mktemp -d) && U=$(curl -sL https://api.github.com/repos/sdsrss/claude-mem-li
804
812
  # git clone:
805
813
  cd claude-mem-lite
806
814
  node install.mjs uninstall # 保留 ~/.claude-mem-lite/ 数据
807
- node install.mjs uninstall --purge # 删除 ~/.claude-mem-lite/ 及所有数据
815
+ node install.mjs uninstall --purge # 删除 ~/.claude-mem-lite/ 及其数据
808
816
 
809
817
  # npx:
810
818
  npx claude-mem-lite uninstall
811
819
  npx claude-mem-lite uninstall --purge
812
820
  ```
813
821
 
822
+ `~/.claude-mem-lite` 是符号链接时,`--purge` 什么都不删,并说明是哪个链接。
823
+
814
824
  数据默认保留在 `~/.claude-mem-lite/` 中。如需删除:
815
825
  ```bash
816
826
  rm -rf ~/.claude-mem-lite/
package/hook-llm.mjs CHANGED
@@ -26,7 +26,7 @@ import {
26
26
  import { acquireLLMSlot, releaseLLMSlot, LLM_SEM_TIMEOUT } from './hook-semaphore.mjs';
27
27
  import { BG_LLM_TIMEOUT_MS } from './haiku-client.mjs';
28
28
  import { scrubRecord, scrubFilePaths } from './lib/scrub-record.mjs';
29
- import { mergeModelSummary, summarySuperseded } from './lib/fast-summary.mjs';
29
+ import { mergeModelSummary, modelSummaryFields, summarySuperseded } from './lib/fast-summary.mjs';
30
30
  import { recordMetric } from './lib/metrics.mjs';
31
31
  import { readTurnReplies } from './lib/turn-replies.mjs';
32
32
  import { DB_DIR } from './schema.mjs';
@@ -1754,6 +1754,16 @@ export const SUMMARY_TURN_TAIL = 300;
1754
1754
  export const SUMMARY_TURNS_FIRST = 4;
1755
1755
  export const SUMMARY_TURNS_LAST = 8;
1756
1756
 
1757
+ /**
1758
+ * D26 (D#845) — the last sentence of both reply rules: `completed` ordered by importance, so the
1759
+ * Last Session line SessionStart cuts to 120 characters starts with the session's main finished
1760
+ * outcome. That line left it out in 23 of 60 calls without this sentence and 11 of 60 with it;
1761
+ * no other count rose by more than 1 (docs/audits/20261112-d26-reading.md). The prompt without
1762
+ * a reply does not carry it.
1763
+ */
1764
+ export const SUMMARY_COMPLETED_ORDER =
1765
+ "Order completed by importance: begin with the session's most important finished outcome, the one a person picking this work up next most needs to know (such as a release published, a deploy live, a fix merged or a measurement's verdict), then list every other finished item. This changes only the order: keep every item and detail you would otherwise include, and an item's state is still the one given by the latest reply that mentions it.";
1766
+
1757
1767
  /**
1758
1768
  * The final reply as the summary prompt carries it: scrubbed whole first, so a secret
1759
1769
  * straddling a cut is never half-kept, then cut to head + tail with the omitted length named.
@@ -1813,8 +1823,9 @@ export function mergeSummaryRows(observations, events) {
1813
1823
  * The session summary prompt. `observations` are {type, title, narrative} newest first,
1814
1824
  * `userPrompts` the raw prompt texts in order; both are cut here. `finalReply`, when given, is
1815
1825
  * the session's last assistant message (D19): it goes into the user part behind the same input
1816
- * guard, and the system part says the outcome it reports wins. Without one the prompt is the
1817
- * one shipped before D19, byte for byte. `turnReplies` (D22), each turn's last reply oldest
1826
+ * guard, and the system part says the outcome it reports wins and that completed is ordered by
1827
+ * importance (SUMMARY_COMPLETED_ORDER, D26). Without one the prompt is the one shipped before D19,
1828
+ * byte for byte. `turnReplies` (D22), each turn's last reply oldest
1818
1829
  * first, replaces the final reply when it holds two or more turns with text (its last one IS
1819
1830
  * the final reply); with fewer the prompt is the D19 one.
1820
1831
  */
@@ -1838,10 +1849,10 @@ lessons: Only genuinely non-obvious insights (debugging discoveries, gotchas, ar
1838
1849
  key_decisions: Only decisions with lasting impact (library choices, architecture, data model). Include reasoning. Empty array if none.${
1839
1850
  turns
1840
1851
  ? `
1841
- Replies: the user message ends with the assistant's last reply of each turn, oldest first; the last one is the session's final reply. These are the assistant's own account of the outcome. completed lists the main work the replies report as done in every turn, not only the last. Work a reply reports as done (tests passed, saved, committed, fixed) is completed — never list it in remaining_items or next_steps. An item's state is the one given by the latest reply that mentions it. What is still unfinished, failed or left for later belongs in remaining_items.`
1852
+ Replies: the user message ends with the assistant's last reply of each turn, oldest first; the last one is the session's final reply. These are the assistant's own account of the outcome. completed lists the main work the replies report as done in every turn, not only the last. Work a reply reports as done (tests passed, saved, committed, fixed) is completed — never list it in remaining_items or next_steps. An item's state is the one given by the latest reply that mentions it. What is still unfinished, failed or left for later belongs in remaining_items. ${SUMMARY_COMPLETED_ORDER}`
1842
1853
  : reply
1843
1854
  ? `
1844
- Final reply: the user message ends with the session's final reply, the assistant's own account of the outcome. Work it reports as done (tests passed, saved, committed, fixed) is completed — never list it in remaining_items or next_steps. What it reports as unfinished, failed or left for later belongs in remaining_items.`
1855
+ Final reply: the user message ends with the session's final reply, the assistant's own account of the outcome. Work it reports as done (tests passed, saved, committed, fixed) is completed — never list it in remaining_items or next_steps. What it reports as unfinished, failed or left for later belongs in remaining_items. ${SUMMARY_COMPLETED_ORDER}`
1845
1856
  : ''
1846
1857
  }`;
1847
1858
  const user = `Project: ${project}${promptCtx}
@@ -1953,65 +1964,17 @@ export async function handleLLMSummary() {
1953
1964
  releaseLLMSlot();
1954
1965
  }
1955
1966
 
1956
- // Coerce a prose field to a string before scrub/bind. Haiku sometimes returns a LIST for
1957
- // completed/next_steps/remaining_items; binding a non-string straight to SQL throws
1958
- // ("Too many parameter values") out of this try/finally and drops the WHOLE summary incl.
1959
- // lessons + key_decisions. Join array items; non-strings → ''. (lessons/key_decisions are
1960
- // JSON.stringify'd separately below.)
1961
- const asText = (v) =>
1962
- Array.isArray(v)
1963
- ? v.filter((x) => typeof x === 'string' && x.trim()).join('; ')
1964
- : typeof v === 'string'
1965
- ? v
1966
- : '';
1967
-
1968
- // Persist when ANY meaningful field is present — not just `request`. Gating on `request`
1969
- // alone dropped the whole INSERT/UPDATE (losing the session's highest-value fields:
1970
- // lessons + key_decisions) whenever Haiku returned an empty request string but a rich
1971
- // `{completed, lessons, key_decisions}` — a common degraded shape. Downstream tolerates an
1972
- // empty request: INSERT writes '' and the UPDATE keeps the row's own request (or an older row's)
1973
- // when the reply's is empty. Use asText in the gate so a non-string / empty-array field can't falsely
1974
- // trigger it.
1975
- // Items are kept only when they are non-empty strings. Array.isArray alone stored a reply of
1976
- // [123, null, {…}, "real lesson"] as-is, and SessionStart then injected
1977
- // "Lessons: 123; ; [object Object]", pushing the real lesson out of its 3-item window.
1978
- const textItems = (v) =>
1979
- Array.isArray(v) ? v.filter((x) => typeof x === 'string' && x.trim()).map((x) => x.trim()) : [];
1980
- const lessons = llmParsed ? textItems(llmParsed.lessons) : [];
1981
- const keyDecisions = llmParsed ? textItems(llmParsed.key_decisions) : [];
1982
- const hasSummaryContent =
1983
- llmParsed &&
1984
- (asText(llmParsed.request) ||
1985
- asText(llmParsed.completed) ||
1986
- asText(llmParsed.remaining_items) ||
1987
- asText(llmParsed.next_steps) ||
1988
- lessons.length > 0 ||
1989
- keyDecisions.length > 0);
1990
- if (hasSummaryContent) {
1967
+ // The reply's fields, coerced and scrubbed (lib/fast-summary.mjs), or null with nothing to
1968
+ // write.
1969
+ const safe = modelSummaryFields(llmParsed);
1970
+ if (safe) {
1991
1971
  const now = new Date();
1992
- const lessonsJson = lessons.length > 0 ? JSON.stringify(lessons) : null;
1993
- const decisionsJson = keyDecisions.length > 0 ? JSON.stringify(keyDecisions) : null;
1994
-
1995
1972
  // Upgrade the session's summary row instead of creating another. This worker runs after
1996
1973
  // EVERY Stop (one per assistant turn) and again from SessionStart's /clear path; selecting
1997
1974
  // only a `notes = 'fast'` row found nothing once the first run had upgraded it, and each
1998
1975
  // later turn INSERTed (one live session: 37 rows in 65 minutes). mergeModelSummary lands
1999
1976
  // on the session's newest row and keeps a report's Done / Not done over the model's
2000
1977
  // (lib/fast-summary.mjs).
2001
- //
2002
- // Scrub LLM-output text fields at the write boundary. lessons / key_decisions are
2003
- // JSON.stringify(array<string>); scrubSecrets uses opaque placeholders that preserve
2004
- // JSON structure, so the JSON string is scrubbed whole.
2005
- const safe = scrubRecord('session_summaries', {
2006
- request: asText(llmParsed.request),
2007
- investigated: asText(llmParsed.investigated),
2008
- learned: asText(llmParsed.learned),
2009
- completed: asText(llmParsed.completed),
2010
- next_steps: asText(llmParsed.next_steps),
2011
- remaining_items: asText(llmParsed.remaining_items),
2012
- lessons: lessonsJson,
2013
- key_decisions: decisionsJson,
2014
- });
2015
1978
  if (mergeModelSummary(db, { sessionId, project, fields: safe, now, spawnEpoch })) {
2016
1979
  outcome('written');
2017
1980
  } else {
package/hook.mjs CHANGED
@@ -164,19 +164,17 @@ import {
164
164
  } from './lib/maintain-core.mjs';
165
165
  import { snapshotDb } from './lib/db-backup.mjs';
166
166
  import {
167
- extractCitationsFromTranscript,
168
- extractInjectedBySurface,
169
- buildCitationRelevanceSet,
167
+ citationRelevanceSetFrom,
170
168
  unionSurfaces,
171
169
  extractInjectedFromKeyContext,
172
170
  bumpCitationAccess,
173
- computeCiteRecall,
171
+ citeRecallStats,
174
172
  applyCitationDecay,
175
173
  recordCitationFunnel,
176
174
  recordCitationSurfaces,
177
- collectSubagentSurface,
178
- hasMainThreadAssistantText,
175
+ subagentSurfaceFrom,
179
176
  } from './lib/citation-tracker.mjs';
177
+ import { digestTranscript, DIGEST_FILE_PREFIX } from './lib/transcript-digest.mjs';
180
178
  import { resolveEdgeAttribution, readPreRecallFileEdges } from './lib/edge-attribution.mjs';
181
179
  import { extractTailAssistantText, extractStructuredSummary } from './lib/summary-extractor.mjs';
182
180
  import { recordTurnReply, TURN_REPLIES_PREFIX } from './lib/turn-replies.mjs';
@@ -211,11 +209,10 @@ import {
211
209
  } from './hook-handoff.mjs';
212
210
  import {
213
211
  loadCiteBackForEpisode,
214
- extractCiteBackSignals,
215
212
  buildUnsavedBugfixHint,
216
213
  claimBugfixNudge,
217
214
  BUGFIX_NUDGE_MARKER_PREFIX,
218
- countUnsavedBugfixShape,
215
+ bugfixShapeStats,
219
216
  buildCiteRecallNudge as libBuildCiteRecallNudge,
220
217
  nextCiteStreakState,
221
218
  } from './lib/cite-back-hint.mjs';
@@ -1279,21 +1276,26 @@ async function readStopHookInput() {
1279
1276
  return { ccSessionId, transcriptPath, lastAssistantMessage };
1280
1277
  }
1281
1278
 
1279
+ /**
1280
+ * This turn's final reply: the host's `last_assistant_message` when it sends one, else the
1281
+ * transcript's last assistant text, read backwards from the end of the file. A forward parse of
1282
+ * the whole file took 1.6 s on a 475 MB transcript, on every turn (issue #53). Claude Code
1283
+ * 2.1.322 omits the field only when its last assistant message carries no text.
1284
+ */
1285
+ function stopFinalReply({ transcriptPath, lastAssistantMessage }) {
1286
+ if (lastAssistantMessage !== null) return lastAssistantMessage;
1287
+ return transcriptPath ? extractTailAssistantText(transcriptPath) : null;
1288
+ }
1289
+
1282
1290
  /**
1283
1291
  * D#825 — record this turn's final reply under this Stop's memory session and its current prompt
1284
- * number, for the summary worker (lib/turn-replies.mjs). The host's `last_assistant_message`
1285
- * when it sends one; from a host that does not, the transcript's last assistant text, the reply
1292
+ * number, for the summary worker (lib/turn-replies.mjs). The reply is stopFinalReply's, the one
1286
1293
  * the Stop baseline reads. A turn answering a task notice stores no prompt, so its reply lands
1287
1294
  * on the prompt before it and replaces that reply: a turn's last reply wins. Never throws.
1288
1295
  */
1289
1296
  function recordStopTurnReply(db, { sessionId, transcriptPath, lastAssistantMessage }) {
1290
1297
  try {
1291
- const reply =
1292
- lastAssistantMessage !== null
1293
- ? lastAssistantMessage
1294
- : transcriptPath
1295
- ? extractTailAssistantText(transcriptPath)
1296
- : null;
1298
+ const reply = stopFinalReply({ transcriptPath, lastAssistantMessage });
1297
1299
  if (!reply || !reply.trim()) return;
1298
1300
  const n =
1299
1301
  db
@@ -1423,7 +1425,7 @@ function markSessionCompletedAndSaveHandoff(
1423
1425
  }
1424
1426
 
1425
1427
  /** Fast summary baseline — ensures a summary exists even if the background LLM fails. */
1426
- function writeFastSummaryBaseline(db, { sessionId, project, transcriptPath }) {
1428
+ function writeFastSummaryBaseline(db, { sessionId, project, transcriptPath, lastAssistantMessage }) {
1427
1429
  // Stop fires once per assistant TURN and the mem session survives it (R10-P1-1), so this
1428
1430
  // runs on every turn of a session. The first turn with anything to say INSERTs the row
1429
1431
  // (T4-P2-B's guard: never a second row); every later turn REFRESHES that row from its tail's
@@ -1439,8 +1441,7 @@ function writeFastSummaryBaseline(db, { sessionId, project, transcriptPath }) {
1439
1441
  // CLAUDE.md §10 mandates Done/Not done/Failed/Uncertain markers, so the
1440
1442
  // tail is deterministically parseable without Haiku. Prior baseline left
1441
1443
  // remaining_items=='' for every session whose Haiku pass failed (≈66%
1442
- // in prod data), losing the user-visible "Not done" list. handleStop calls this
1443
- // AFTER trackCitationsAtStop so the parse is the one it left memoized.
1444
+ // in prod data), losing the user-visible "Not done" list.
1444
1445
  let structuredCompleted = '';
1445
1446
  let structuredNotDone = '';
1446
1447
  let structuredNotes = '';
@@ -1448,7 +1449,7 @@ function writeFastSummaryBaseline(db, { sessionId, project, transcriptPath }) {
1448
1449
  // (D#121, lib/fast-summary.mjs writeStopSummary).
1449
1450
  let tail = null;
1450
1451
  try {
1451
- tail = transcriptPath ? extractTailAssistantText(transcriptPath) : null;
1452
+ tail = stopFinalReply({ transcriptPath, lastAssistantMessage });
1452
1453
  if (tail) {
1453
1454
  const s = extractStructuredSummary(tail);
1454
1455
  structuredCompleted = s.done;
@@ -1488,23 +1489,26 @@ function trackCitationsAtStop(db, { sessionId, project, ccSessionId, transcriptP
1488
1489
  // applyCitationDecay checks separately.
1489
1490
  try {
1490
1491
  if (transcriptPath && !process.env.CLAUDE_MEM_NO_CITATION_TRACK) {
1492
+ // Issue #53: every question below is answered from the digest, which parses only the
1493
+ // bytes appended since the previous Stop (lib/transcript-digest.mjs). Each of them used
1494
+ // to parse the whole transcript: one shared parse per Stop within lib/transcript-scan.mjs's
1495
+ // heap budget (256 MB at most), one parse per question above it. Each answer is copied
1496
+ // where the code below used to get a fresh Set and may add to it.
1497
+ const digest = digestTranscript(transcriptPath, { runtimeDir: RUNTIME_DIR });
1498
+ if (!digest.complete) {
1499
+ // A transcript first seen larger than one Stop's read budget is caught up over several
1500
+ // Stops. Writing from part of it would bank verdicts the rest contradicts — an id cited
1501
+ // later in the unread part would be decided uncited — so this Stop writes nothing.
1502
+ debugLog('DEBUG', 'handleStop', 'citations: transcript digest still catching up; nothing written');
1503
+ return;
1504
+ }
1505
+ const d = digest.main;
1491
1506
  // D#152/D#177: the `subagent` face, collected ONCE, up front, and used twice —
1492
1507
  // by the decay block below (only under CLAUDE_MEM_SUBAGENT_DECAY) and by its own
1493
- // metering call at the tail. It used to be collected at the tail only, with a
1494
- // comment saying the position was load-bearing because lib/transcript-scan.mjs
1495
- // memoizes ONE file and reading the sidechains evicts the parent. That constraint
1496
- // is real but it is not "last" — it is "not BETWEEN two parent scans". Running it
1497
- // FIRST parses the sidechains before anything has memoized the parent, so the
1498
- // parent is then parsed once and stays memoized for every scanner after it:
1499
- // still one parent parse per Stop, the property the tail comment was protecting.
1500
- let sub = { injected: new Set(), cited: new Set(), files: 0 };
1501
- try {
1502
- sub = collectSubagentSurface(transcriptPath);
1503
- } catch (e) {
1504
- debugCatch(e, 'handleStop-subagent-collect');
1505
- }
1508
+ // metering call at the tail.
1509
+ const sub = subagentSurfaceFrom(digest.subagents);
1506
1510
 
1507
- const ids = extractCitationsFromTranscript(transcriptPath);
1511
+ const ids = new Set(d.cited);
1508
1512
  if (ids.size > 0) {
1509
1513
  // Gate the access-count channel on relevance (audit FLOW-2 / D#179). The cited
1510
1514
  // set is every `#NN` in this session's assistant text and cannot tell a
@@ -1512,8 +1516,9 @@ function trackCitationsAtStop(db, { sessionId, project, ccSessionId, transcriptP
1512
1516
  // session names dozens of ids in prose, and access_count > 3 promotes a row a
1513
1517
  // tier via boostAccessed. The population to credit — all seven faces, and why
1514
1518
  // extractAllInjected alone is the wrong five — lives in the builder.
1515
- const relevant = buildCitationRelevanceSet({
1516
- transcriptPath,
1519
+ const relevant = citationRelevanceSetFrom({
1520
+ attachmentInjected: unionSurfaces(d.injected),
1521
+ userTyped: d.userTyped,
1517
1522
  runtimeDir: RUNTIME_DIR,
1518
1523
  project,
1519
1524
  sessionId: ccSessionId,
@@ -1531,11 +1536,9 @@ function trackCitationsAtStop(db, { sessionId, project, ccSessionId, transcriptP
1531
1536
  );
1532
1537
  }
1533
1538
 
1534
- // v32 citation-decay: tighter feedback loop on top of P4. Re-scan
1535
- // transcript with main-thread filter, extract injected IDs from BOTH
1536
- // surfaces (PTR + UserPromptSubmit <memory-context>) via extractAllInjected,
1537
- // then mutate importance/streak per applyCitationDecay's contract.
1538
- // Cheap (file still in OS cache).
1539
+ // v32 citation-decay: tighter feedback loop on top of P4. The main-thread
1540
+ // injected ids from every attachment face (PTR + UserPromptSubmit
1541
+ // <memory-context> + …), then mutate the streaks per applyCitationDecay's contract.
1539
1542
  //
1540
1543
  // v34.x: pre-v34 this only saw pre-tool-recall injections, leaving the
1541
1544
  // UPS surface (highest-volume — all decision-type FTS hits) starved.
@@ -1552,13 +1555,13 @@ function trackCitationsAtStop(db, { sessionId, project, ccSessionId, transcriptP
1552
1555
  // survives to citation_surface_log below so "which face earns its
1553
1556
  // budget" becomes answerable. Before this, every face was merged
1554
1557
  // before anything was recorded and no lever had a target.
1555
- const injectedBySurface = extractInjectedBySurface(transcriptPath, { mainOnly: true });
1558
+ const injectedBySurface = d.injectedMain;
1556
1559
  const injected = unionSurfaces(injectedBySurface);
1557
1560
  // P5 ①: cite-back signals — observations whose warned file the agent
1558
1561
  // edited this session. Union into injected so they're resolved (they
1559
1562
  // were injected via pre-tool-recall) and, below, into cited so the
1560
1563
  // edit promotes them even without a literal #NN in text.
1561
- const citeBackIds = extractCiteBackSignals(transcriptPath);
1564
+ const citeBackIds = d.citeBack;
1562
1565
  for (const id of citeBackIds) injected.add(id);
1563
1566
  // D#124, promotion-only (v3.66.1): the SessionStart Key Context block
1564
1567
  // leaves no hook attachment, so its ids come from the per-session
@@ -1595,14 +1598,14 @@ function trackCitationsAtStop(db, { sessionId, project, ccSessionId, transcriptP
1595
1598
  // contract is "NEXT time you produce user-facing text," so a
1596
1599
  // session with zero main-thread text gets a free pass — the
1597
1600
  // next Stop in the same session will re-evaluate.
1598
- if (!hasMainThreadAssistantText(transcriptPath)) {
1601
+ if (!d.mainText.seen) {
1599
1602
  debugLog(
1600
1603
  'DEBUG',
1601
1604
  'handleStop',
1602
1605
  `citation-decay: skipped (no main-thread assistant text yet, injected=${injected.size})`,
1603
1606
  );
1604
1607
  } else {
1605
- const citedMain = extractCitationsFromTranscript(transcriptPath, { mainOnly: true });
1608
+ const citedMain = new Set(d.citedMain);
1606
1609
  for (const id of citeBackIds) citedMain.add(id);
1607
1610
  // D#177: admit the `subagent` face to the decay loop. It cannot ride the
1608
1611
  // normal path because its injection lands in a dispatched agent's PROMPT
@@ -1731,15 +1734,9 @@ function trackCitationsAtStop(db, { sessionId, project, ccSessionId, transcriptP
1731
1734
  }
1732
1735
 
1733
1736
  // Persist cite-recall ratio for the next SessionStart to surface as
1734
- // feedback. This block re-scans the transcript rather than threading the
1735
- // count through `extractCitationsFromTranscript`, so the bump path stays
1736
- // unchanged — and since P2-8 every scanner in it shares ONE parse via
1737
- // lib/transcript-scan.mjs, so "scan again" costs an array iteration, not a
1738
- // re-read. (The old wording, "cheap; the file is already in OS cache", was
1739
- // arguing the pre-memo case: the OS cache saved the read, never the parse,
1740
- // which was ~all of the cost.)
1737
+ // feedback.
1741
1738
  try {
1742
- const stats = computeCiteRecall(transcriptPath);
1739
+ const stats = citeRecallStats(d.citeRecall);
1743
1740
  // D#19: the RATIO GATE's own denominator, alongside the wide one. `stats` counts
1744
1741
  // every `#NN`-shaped token in non-assistant text — tool_result bodies, file
1745
1742
  // contents, CLI output, pasted reports — which is the right caliber for "what has
@@ -1747,24 +1744,19 @@ function trackCitationsAtStop(db, { sessionId, project, ccSessionId, transcriptP
1747
1744
  // (measured 11.2x inflation, R11-B-P2-2). Both are persisted; buildCiteRecallNudge
1748
1745
  // gates on this pair and falls back to the wide one for older payloads.
1749
1746
  //
1750
- // Cost is an array iteration, not a parse: this block runs after the decay loop's
1751
- // own extractInjectedBySurface on the same path, and lib/transcript-scan.mjs memoizes
1752
- // the parse. mainOnly mirrors the decay loop — an id injected only inside a subagent
1747
+ // mainOnly mirrors the decay loop — an id injected only inside a subagent
1753
1748
  // would otherwise enter the denominator while its citation lands in another
1754
1749
  // transcript, scoring a miss the main thread never had a chance to avoid.
1755
1750
  let gate = { gateInjected: null, gateRecalled: null, gateRatio: null };
1756
1751
  try {
1757
- const gateInjectedIds = unionSurfaces(extractInjectedBySurface(transcriptPath, { mainOnly: true }));
1752
+ const gateInjectedIds = unionSurfaces(d.injectedMain);
1758
1753
  // The nudge asks whether the agent ANSWERED what the hooks showed it, so a
1759
1754
  // `#NN n/a — <reason>` still counts. Since D#98 the default directive asks for no
1760
1755
  // reply on a lesson that did not apply, so that silence now reads as a miss here and
1761
1756
  // the gate fires more (projected 78/95 → up to 87/95 qualifying sessions,
1762
1757
  // docs/audits/20260927-d98-dismissal-baseline.md). Left as is: the gate already fired
1763
1758
  // on most sessions and self-silences after 3; D#111's readout re-measures it.
1764
- const gateCited = extractCitationsFromTranscript(transcriptPath, {
1765
- mainOnly: true,
1766
- includeDismissed: true,
1767
- });
1759
+ const gateCited = d.citedMainAnswered;
1768
1760
  let hit = 0;
1769
1761
  for (const id of gateInjectedIds) if (gateCited.has(id)) hit++;
1770
1762
  gate = {
@@ -1779,9 +1771,8 @@ function trackCitationsAtStop(db, { sessionId, project, ccSessionId, transcriptP
1779
1771
  }
1780
1772
  // B2 (v2.83.1): also persist the bugfix-shape nudge/save delta so
1781
1773
  // the next SessionStart can surface "N unsaved bugfix-shape edits"
1782
- // alongside cite-recall. Same scan target (transcript already in OS
1783
- // cache); same persistence file; one extra line in buildCiteRecallNudge.
1784
- const bugfixStats = countUnsavedBugfixShape(transcriptPath);
1774
+ // alongside cite-recall. Same persistence file; one extra line in buildCiteRecallNudge.
1775
+ const bugfixStats = bugfixShapeStats(d.bugfixShape);
1785
1776
  const dest = citeRecallPathFor(RUNTIME_DIR, project);
1786
1777
  // Carry the consecutive-low-cite streak forward so the SessionStart
1787
1778
  // nag can self-silence after the project has ignored it N times.
@@ -1812,11 +1803,11 @@ function trackCitationsAtStop(db, { sessionId, project, ccSessionId, transcriptP
1812
1803
  `,
1813
1804
  )
1814
1805
  .all(sessionId);
1815
- const d = detectUnpersistedDecision({
1806
+ const u = detectUnpersistedDecision({
1816
1807
  prompts: promptRows.map((r) => r.prompt_text),
1817
- transcriptPath,
1808
+ persistenceCount: d.persistence.count,
1818
1809
  });
1819
- if (d.fire) decisionSignal = d.signal;
1810
+ if (u.fire) decisionSignal = u.signal;
1820
1811
  } catch (e) {
1821
1812
  debugCatch(e, 'handleStop-persist-reminder');
1822
1813
  }
@@ -1853,25 +1844,14 @@ function trackCitationsAtStop(db, { sessionId, project, ccSessionId, transcriptP
1853
1844
  // promotion all keep the un-widened set. `CLAUDE_MEM_SUBAGENT_DECAY=0` returns
1854
1845
  // the face to metering-only.
1855
1846
  //
1856
- // The "placed LAST" note below is now historical: `collectSubagentSurface` runs
1857
- // at the HEAD of this block (the decay loop needs its result), and `sub` here is
1858
- // that same object rather than a second call. The parse-count property the note
1859
- // defends is unchanged — see the comment at the collection site.
1860
- // earlier, this block costs ONE extra parse of the parent — the memo
1861
- // re-caches on the first re-read, so it is one, not one per later
1862
- // scanner — and breaks the "one parse per Stop" property the block
1863
- // above documents. Measured by instrumenting the parse: 1 parent parse
1864
- // at this position, 2 when relocated earlier. ~25ms on the largest
1865
- // real transcript here (5.4MB), matching lib/transcript-scan.mjs's
1866
- // own header figure.
1847
+ // `sub` is the one collected at the head of this block (the decay loop needs it too).
1867
1848
  // The text floor is re-checked rather than inherited — same reason as
1868
1849
  // every other face: a tool-only Stop must not bank a verdict, and it
1869
1850
  // must not enter the funnel's session denominator either.
1870
1851
  try {
1871
- if (hasMainThreadAssistantText(transcriptPath)) {
1872
- // `sub` is the one collected at the top of this block — a second
1873
- // collectSubagentSurface call here would re-parse every sidechain file and,
1874
- // worse, could disagree with the set the decay loop above just scored.
1852
+ if (d.mainText.seen) {
1853
+ // `sub` is the one collected at the top of this block, so this records the set
1854
+ // the decay loop above just scored.
1875
1855
  if (sub.injected.size > 0) {
1876
1856
  recordCitationSurfaces(
1877
1857
  db,
@@ -1920,11 +1900,8 @@ async function handleStop() {
1920
1900
  if (db) {
1921
1901
  try {
1922
1902
  markSessionCompletedAndSaveHandoff(db, { sessionId, project, ccSessionId, episodeSnapshot, stopEpoch });
1923
- // Citations first: they read the subagent transcripts before the parent, so the parent is
1924
- // parsed once and stays memoized (D#152). The summary reads the parent's tail on every
1925
- // turn; run before them, it parsed the parent a second time in any session with subagents.
1926
1903
  trackCitationsAtStop(db, { sessionId, project, ccSessionId, transcriptPath });
1927
- writeFastSummaryBaseline(db, { sessionId, project, transcriptPath });
1904
+ writeFastSummaryBaseline(db, { sessionId, project, transcriptPath, lastAssistantMessage });
1928
1905
  } catch (e) {
1929
1906
  // Another process held the write lock past HOOK_DB_DEADLINE_MS: this turn's handoff,
1930
1907
  // citations and baseline are lost either way. The summary worker below does not run under
@@ -2017,7 +1994,8 @@ function gcStalePreRecallCooldowns() {
2017
1994
  name.startsWith('.claude-mem-keyctx-') || // D#123 Key Context marker — same per-session growth, same 24h GC
2018
1995
  name.startsWith(BUGFIX_NUDGE_MARKER_PREFIX) || // §9-B once-per-session nudge claim — same shape
2019
1996
  name.startsWith(RECALL_SHOWN_PREFIX) || // injection budget C1/C3 per-thread marker — same shape
2020
- name.startsWith(TURN_REPLIES_PREFIX); // D#825 per-session turn replies; its workers read it within minutes
1997
+ name.startsWith(TURN_REPLIES_PREFIX) || // D#825 per-session turn replies; its workers read it within minutes
1998
+ name.startsWith(DIGEST_FILE_PREFIX); // issue #53 per-transcript Stop digest; a later Stop re-reads from byte 0
2021
1999
  if (!isCooldown && !isInjectedMarker) continue;
2022
2000
  try {
2023
2001
  const p = join(RUNTIME_DIR, name);
package/install.mjs CHANGED
@@ -1973,10 +1973,47 @@ async function uninstall() {
1973
1973
  let purgeIncomplete = false; // reported, and not followed by "Done!" and exit 0
1974
1974
  if (flags.has('--purge')) {
1975
1975
  const homeDir = join(homedir(), '.claude-mem-lite');
1976
- // Always remove the homedir code/install dir (guarded to the canonical path).
1977
- if (existsSync(DATA_DIR) && DATA_DIR === homeDir) {
1978
- rmSync(DATA_DIR, { recursive: true, force: true });
1979
- ok('Data purged (~/.claude-mem-lite/)');
1976
+ // D#829: with ~/.claude-mem-lite a link, rmSync took the link alone and the run said
1977
+ // "Data purged" and "Done!" with the store left behind it. The target may be a directory the
1978
+ // user chose, and it holds the code too, so nothing is removed through the link. Nothing is
1979
+ // removed at all: removing the link first and leaving the rest to the relocated purge ended in
1980
+ // "Done!" with the store left when CLAUDE_MEM_DIR named the target by another spelling
1981
+ // (`<link>/`), and telling that spelling apart needs resolved paths, whose failures were read
1982
+ // as "the target is gone" (D#811 reviews r1 F1, r2 R2-1). One lstat decides; the link stays as
1983
+ // the record of where the store is.
1984
+ let homeIsLink = false;
1985
+ try {
1986
+ homeIsLink = lstatSync(DATA_DIR).isSymbolicLink();
1987
+ } catch {
1988
+ /* absent, or not lstat-able: existsSync below decides, as before */
1989
+ }
1990
+ if (homeIsLink) {
1991
+ let to = '';
1992
+ try {
1993
+ to = ` to ${readlinkSync(DATA_DIR)}`;
1994
+ } catch {
1995
+ /* raced away */
1996
+ }
1997
+ warn(
1998
+ `~/.claude-mem-lite is a link${to}. --purge does not delete through a link, so it removed nothing` +
1999
+ (MEM_DATA_DIR !== homeDir ? ` (CLAUDE_MEM_DIR ${MEM_DATA_DIR} included).` : '.'),
2000
+ );
2001
+ purgeIncomplete = true;
2002
+ } else if (existsSync(DATA_DIR) && DATA_DIR === homeDir) {
2003
+ // Always remove the homedir code/install dir (guarded to the canonical path). An entry it
2004
+ // may not remove threw out of here uncaught, and the relocated purge below never ran (D#815).
2005
+ try {
2006
+ rmSync(DATA_DIR, { recursive: true, force: true });
2007
+ // D#835 (D#829 review r2 X1): with another process deleting files in it, rmSync returned
2008
+ // normally and the directory, store included, was still there (7 of 12 runs on Node 26).
2009
+ if (existsSync(DATA_DIR)) {
2010
+ warn('Could not remove ~/.claude-mem-lite: it was still there when the removal returned.');
2011
+ purgeIncomplete = true;
2012
+ } else ok('Data purged (~/.claude-mem-lite/)');
2013
+ } catch (e) {
2014
+ warn(`Could not remove ~/.claude-mem-lite (${e.code || e.message}).`);
2015
+ purgeIncomplete = true;
2016
+ }
1980
2017
  } else if (existsSync(DATA_DIR)) {
1981
2018
  fail('DATA_DIR path mismatch, refusing to purge for safety: ' + DATA_DIR);
1982
2019
  }
@@ -1984,8 +2021,8 @@ async function uninstall() {
1984
2021
  // claude-mem-lite.db), so a mistyped CLAUDE_MEM_DIR is never touched. Even then only what
1985
2022
  // claude-mem-lite writes there goes: the directory may be one the user keeps other files in,
1986
2023
  // and removing it whole took those too (R32 E2E install F1, P0). It is removed only once
1987
- // nothing else is left in it.
1988
- if (MEM_DATA_DIR !== homeDir) {
2024
+ // nothing else is left in it. Not when ~/.claude-mem-lite is a link (above).
2025
+ if (MEM_DATA_DIR !== homeDir && !homeIsLink) {
1989
2026
  // Not existsSync: it is false on EACCES too, so a store it could not look for was reported
1990
2027
  // absent, then "Done!" (R32 depth-2 review M1).
1991
2028
  let storeLookup = null;
@@ -5104,7 +5141,7 @@ Usage:
5104
5141
  node install.mjs install Install (copy files to ~/.claude-mem-lite/)
5105
5142
  node install.mjs install --dev Install dev mode (symlinks to dev dir)
5106
5143
  node install.mjs uninstall Remove (keep data)
5107
- node install.mjs uninstall --purge Remove and delete all data
5144
+ node install.mjs uninstall --purge Remove and delete the data
5108
5145
  node install.mjs status Show current status (use --json for structured output)
5109
5146
  node install.mjs doctor Diagnose issues (use --json for structured output)
5110
5147
  node install.mjs cleanup Remove stale temp/staging files (use --dry-run to preview)