@jjh32456/longlive 1.8.12 → 2.0.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 (83) hide show
  1. package/CHANGELOG.md +232 -202
  2. package/QUICKSTART.md +10 -11
  3. package/README.en.md +13 -4
  4. package/README.md +42 -11
  5. package/SPEC.md +3 -3
  6. package/build-info.json +231 -121
  7. package/cordis.patch.yml +32 -1
  8. package/docs/ARCHITECTURE.md +1 -1
  9. package/docs/AUTO-RECALL.md +1 -1
  10. package/docs/CONFIG.md +41 -9
  11. package/docs/FAQ.md +7 -7
  12. package/docs/FEATURES.md +6 -6
  13. package/docs/OPERATIONS.md +1 -1
  14. package/docs/PANEL-INTEGRATION.md +1 -1
  15. package/docs/PRIVACY.md +5 -5
  16. package/docs/QUICKSTART.md +3 -3
  17. package/docs/README.en.md +4 -2
  18. package/docs/TROUBLESHOOTING.md +4 -4
  19. package/package.json +6 -3
  20. package/runbook.md +3 -3
  21. package/scripts/migrate-200.mjs +8 -0
  22. package/scripts/migrate-lifecycle.mjs +2 -2
  23. package/src/answer/claim-guard.mjs +234 -0
  24. package/src/backup.js +165 -1
  25. package/src/config.js +18 -7
  26. package/src/features.js +128 -5
  27. package/src/handoff/index.js +133 -0
  28. package/src/handoff/model.js +48 -0
  29. package/src/identity/handover.js +203 -15
  30. package/src/identity/inject-position.js +3 -1
  31. package/src/memory/a1-migration.js +72 -6
  32. package/src/memory/archive-cold-state.mjs +794 -0
  33. package/src/memory/archive-staging.mjs +305 -0
  34. package/src/memory/archive.mjs +415 -0
  35. package/src/memory/capture-host.js +71 -2
  36. package/src/memory/capture.js +45 -6
  37. package/src/memory/catchup.mjs +534 -0
  38. package/src/memory/conclusion-distill.js +51 -2
  39. package/src/memory/conclusion-drafts.js +7 -3
  40. package/src/memory/conflicts.js +915 -2
  41. package/src/memory/consolidate.js +20 -1
  42. package/src/memory/forget-v2.js +272 -2
  43. package/src/memory/forget.js +20 -1
  44. package/src/memory/frames-activation.js +3 -1
  45. package/src/memory/fts-query.js +2 -2
  46. package/src/memory/index.js +80 -7
  47. package/src/memory/land.mjs +743 -0
  48. package/src/memory/lifecycle.js +128 -0
  49. package/src/memory/maintenance.js +386 -22
  50. package/src/memory/memory-health.mjs +607 -0
  51. package/src/memory/migrate-200.js +1681 -0
  52. package/src/memory/migrate-lifecycle.js +3 -3
  53. package/src/memory/procedure-candidate.mjs +377 -0
  54. package/src/memory/procedure.js +20 -1
  55. package/src/memory/prospective-memory.mjs +362 -0
  56. package/src/memory/recall-feedback.mjs +406 -0
  57. package/src/memory/recall-v2.js +13 -1
  58. package/src/memory/recall.js +102 -1
  59. package/src/memory/reinforce.js +138 -2
  60. package/src/memory/retention.js +34 -0
  61. package/src/memory/turn-budget.mjs +290 -0
  62. package/src/memory/wake-bridge.mjs +2999 -0
  63. package/src/memory/working-frame.js +271 -8
  64. package/src/metrics/classify.mjs +3 -1
  65. package/src/recall/archive-config.mjs +130 -0
  66. package/src/recall/archive-fallback.mjs +174 -19
  67. package/src/recall/archive-search.mjs +3 -0
  68. package/src/recall/archive-state.mjs +588 -0
  69. package/src/recall/brain.mjs +501 -0
  70. package/src/recall/current-line.mjs +110 -0
  71. package/src/recall/edges.js +21 -2
  72. package/src/recall/explain.mjs +10 -0
  73. package/src/recall/gate-log.mjs +280 -0
  74. package/src/recall/gate-metrics.mjs +191 -0
  75. package/src/recall/index.js +322 -21
  76. package/src/recall/inject-order.mjs +3 -1
  77. package/src/recall/recall-core.mjs +47 -2
  78. package/src/recall/turn-budget-inject.mjs +154 -0
  79. package/src/retention/cold-gate.mjs +146 -0
  80. package/src/retention/config.js +58 -1
  81. package/src/retention/index.js +193 -35
  82. package/src/router/design-headings.json +10 -10
  83. package/src/tools.js +122 -6
@@ -13,6 +13,7 @@ import path from 'node:path';
13
13
  import crypto from 'node:crypto';
14
14
 
15
15
  import { memoryRootFromConfig, resolveInside, relativePath, memoryError } from './paths.js';
16
+ import { withWriteEvidence as landWithWriteEvidence, UNIMPLEMENTED_CODE as LAND_UNIMPLEMENTED_CODE } from './land.mjs';
16
17
  import {
17
18
  parseFrontmatter, dayString, isoStamp, isDayString,
18
19
  } from './frontmatter.js';
@@ -608,7 +609,7 @@ export function resolveConsolidationProposal(args = {}, config = {}) {
608
609
  * every proposal of the newest scanned day is resolved, a new
609
610
  * `lastConsolidated`. No card is ever edited.
610
611
  */
611
- export function memoryConsolidate(args = {}, config = {}) {
612
+ function memoryConsolidateLegacy(args = {}, config = {}) {
612
613
  if (args.apply === true) {
613
614
  throw memoryError('E_READ_ONLY', 'memory_consolidate 只出提案,不支持 apply — 请人工决定后再改卡');
614
615
  }
@@ -813,3 +814,21 @@ export function memoryConsolidate(args = {}, config = {}) {
813
814
  export {
814
815
  contentTokens, buildCardIndex, cosineScore, coverageScore, pickQuote, pickClaim, paragraphUnits,
815
816
  };
817
+
818
+ /**
819
+ * M12/M13/M15 出口委托:land.mjs(落盘门,批次 B)。
820
+ * land 未实现时如实回退旧路径(不双写、不静默吞错);land 实现后同一入口自动切到新路径。
821
+ */
822
+ function landDoubleRoute(name, legacy) {
823
+ try {
824
+ return landWithWriteEvidence(name, legacy);
825
+ } catch (error) {
826
+ if (error?.code === LAND_UNIMPLEMENTED_CODE) return legacy();
827
+ throw error;
828
+ }
829
+ }
830
+
831
+ /** 工具入口:memory_consolidate。委托 land 落盘门(未实现时回退旧路径)。 */
832
+ export function memoryConsolidate(args = {}, config = {}) {
833
+ return landDoubleRoute('memory_consolidate', () => memoryConsolidateLegacy(args, config));
834
+ }
@@ -15,9 +15,11 @@ import path from 'node:path';
15
15
 
16
16
  import { appendAuditRecord, resolveAuditKey, verifyAuditChain } from './audit-records.js';
17
17
  import { memoryForget, DECAY_RULES } from './forget.js';
18
+ import { daysBetween, dayString, isDayString, parseFrontmatter } from './frontmatter.js';
18
19
  import { memoryError, memoryRootFromConfig, relativePath, resolveInside } from './paths.js';
19
20
  import { isProtectedPath } from './retention.js';
20
21
  import { readCardAnchors } from './card-anchors.js';
22
+ import { appendGateLog } from '../recall/gate-log.mjs';
21
23
  import {
22
24
  appendAudit, ensureDir, epochsDir, sha256File, tombstonesPath, writeFileAtomic,
23
25
  } from './state.js';
@@ -37,9 +39,277 @@ export function isPureNoisePath(relPath) {
37
39
  return PURE_NOISE_PATTERNS.some((pattern) => pattern.test(rel));
38
40
  }
39
41
 
40
- /** Read-only proposal (delegates to forget.js dry-run). */
42
+ /**
43
+ * 选择性遗忘评分(D13 唯一公式源):score = salience*2 + strength + 30/(30+ageDays)。
44
+ *
45
+ * 原始分、全程不四舍五入;参数缺失/非法返回 null(绝不返回 0 冒充有效分)。
46
+ * 阈值 7.50 的比较一律用本函数原始返回值,展示层才允许 toFixed(2)。
47
+ */
48
+ export function score({ salience, strength, ageDays } = {}) {
49
+ const s = Number(salience);
50
+ const t = Number(strength);
51
+ const a = Number(ageDays);
52
+ if (!Number.isFinite(s) || !Number.isFinite(t) || !Number.isFinite(a) || a < 0) return null;
53
+ return s * 2 + t + 30 / (30 + a);
54
+ }
55
+
56
+ /** 计划 §4② 术语里的别名;两个名字指向同一实现。 */
57
+ export const forgetScore = score;
58
+
59
+ export const FORGET_SUGGESTIONS_REL = '.longlive/hardgate/forget-suggestions.jsonl';
60
+ export const FORGET_SUGGESTIONS_SCHEMA = 'hardgate-forget-suggestions/v1';
61
+ export const SCORE_THRESHOLD = 7.5;
62
+ export const SUGGESTION_MAX_ITEMS = 200;
63
+ export const SUGGESTION_RETENTION_DAYS = 90;
64
+ export const SUGGESTION_AGE_DAYS_MIN = 30;
65
+ export const SUGGESTION_SALIENCE_BELOW = 4;
66
+ export const SUGGESTION_GATE_EVENT = 'hg.d13.fail';
67
+
68
+ const DAY_MS = 24 * 60 * 60 * 1000;
69
+
70
+ function gateFail(root, code, message, extra = {}) {
71
+ try {
72
+ appendGateLog(root, {
73
+ gate: SUGGESTION_GATE_EVENT,
74
+ decision: 'fail',
75
+ reason: code,
76
+ evidence: [String(message), ...(Array.isArray(extra.evidence) ? extra.evidence : [])],
77
+ });
78
+ } catch {
79
+ // 门日志本身失败不能再把主流程拖垮;返回码仍是 fail-closed。
80
+ }
81
+ }
82
+
83
+ function suggestionFilePath(root) {
84
+ return path.join(root, FORGET_SUGGESTIONS_REL);
85
+ }
86
+
87
+ function readSuggestionRows(root) {
88
+ let text = '';
89
+ try {
90
+ text = fs.readFileSync(suggestionFilePath(root), 'utf8');
91
+ } catch {
92
+ return [];
93
+ }
94
+ const rows = [];
95
+ for (const line of text.split(/\r?\n/)) {
96
+ const trimmed = line.trim();
97
+ if (trimmed === '') continue;
98
+ try {
99
+ const row = JSON.parse(trimmed);
100
+ if (row && typeof row.rel === 'string') rows.push(row);
101
+ } catch {
102
+ // 坏行丢弃,不当建议使用
103
+ }
104
+ }
105
+ return rows;
106
+ }
107
+
108
+ function pruneSuggestionRows(rows, atMs) {
109
+ const cutoff = atMs - SUGGESTION_RETENTION_DAYS * DAY_MS;
110
+ const kept = rows.filter((row) => {
111
+ const stamp = Date.parse(String(row.suggestedAt ?? ''));
112
+ return Number.isFinite(stamp) && stamp >= cutoff;
113
+ });
114
+ kept.sort((left, right) => {
115
+ const l = Date.parse(String(left.suggestedAt ?? '')) || 0;
116
+ const r = Date.parse(String(right.suggestedAt ?? '')) || 0;
117
+ if (l !== r) return l - r;
118
+ return String(left.rel).localeCompare(String(right.rel));
119
+ });
120
+ return kept.slice(-SUGGESTION_MAX_ITEMS);
121
+ }
122
+
123
+ function writeSuggestionRows(root, rows, at) {
124
+ const file = suggestionFilePath(root);
125
+ const pruned = pruneSuggestionRows(rows, at.getTime());
126
+ const content = pruned.map((row) => JSON.stringify(row)).join('\n') + (pruned.length > 0 ? '\n' : '');
127
+ ensureDir(root, path.dirname(file));
128
+ writeFileAtomic(root, file, content, { now: at });
129
+ return { rows: pruned, file, rel: FORGET_SUGGESTIONS_REL };
130
+ }
131
+
132
+ function listTopicCards(root) {
133
+ const topics = path.join(root, 'topics');
134
+ const found = [];
135
+ const walk = (dir) => {
136
+ let entries = [];
137
+ try {
138
+ entries = fs.readdirSync(dir, { withFileTypes: true });
139
+ } catch {
140
+ return;
141
+ }
142
+ for (const entry of entries) {
143
+ const abs = path.join(dir, entry.name);
144
+ if (entry.isDirectory()) {
145
+ if (entry.name === 'archive') continue;
146
+ walk(abs);
147
+ continue;
148
+ }
149
+ if (!entry.isFile() || !entry.name.endsWith('.md')) continue;
150
+ found.push(abs);
151
+ }
152
+ };
153
+ walk(topics);
154
+ found.sort((left, right) => left.localeCompare(right));
155
+ return found.map((abs) => ({ abs, rel: relativePath(root, abs).replace(/\\/g, '/') }));
156
+ }
157
+
158
+ function cardMeta(abs) {
159
+ const text = fs.readFileSync(abs, 'utf8');
160
+ const parsed = parseFrontmatter(text);
161
+ const fields = parsed.fields ?? {};
162
+ return {
163
+ fields,
164
+ status: typeof fields.status === 'string' ? fields.status : 'active',
165
+ salience: Number(fields.salience),
166
+ strength: Number(fields.strength),
167
+ lastUsed: fields.last_used,
168
+ missingMeta: !Number.isFinite(Number(fields.salience))
169
+ || !Number.isFinite(Number(fields.strength))
170
+ || !isDayString(fields.last_used),
171
+ };
172
+ }
173
+
174
+ /**
175
+ * 选择性遗忘建议(D13)。
176
+ *
177
+ * 计划 §4② 口径:autoApply:false(默认)——只写 forget-suggestions.jsonl
178
+ * (≤200 条 / 90 天),绝不自动标 historical;人工确认后只走既有 memory_forget。
179
+ * 显式传 autoApply:true 视为越权,fail-closed 抛 E_HG_D13_AUTOAPPLY_UNSUPPORTED。
180
+ *
181
+ * 判据:score<7.50(原始分不四舍五入)∧ salience<4 ∧ ageDays>30 ∧ 非 missing_meta;
182
+ * salience≥5(immune5)与 status=locked 永不进建议队列。
183
+ */
41
184
  export function proposeForget(args = {}, config = {}) {
42
- return memoryForget({ ...args, confirm: undefined }, config);
185
+ const requestedAutoApply = args.autoApply !== undefined ? args.autoApply : config.autoApply;
186
+ if (requestedAutoApply !== undefined && requestedAutoApply !== false) {
187
+ let root = null;
188
+ try {
189
+ root = memoryRootFromConfig(config);
190
+ } catch {
191
+ root = null;
192
+ }
193
+ if (root) gateFail(root, 'E_HG_D13_AUTOAPPLY_UNSUPPORTED', '计划 §4② 只允许 autoApply:false');
194
+ throw memoryError(
195
+ 'E_HG_D13_AUTOAPPLY_UNSUPPORTED',
196
+ '计划 v3.6.4 §4②:遗忘只写建议队列(autoApply:false),人工确认后才标 historical',
197
+ );
198
+ }
199
+
200
+ const base = memoryForget({ ...args, confirm: undefined, autoApply: undefined }, config);
201
+ const root = memoryRootFromConfig(config);
202
+ const at = config.now instanceof Date
203
+ ? config.now
204
+ : new Date(config.now ?? args.now ?? Date.now());
205
+ const todayDay = isDayString(config.today) ? config.today : dayString(at);
206
+
207
+ let cards;
208
+ try {
209
+ if (typeof args.path === 'string' && args.path.trim() !== '') {
210
+ const abs = resolveInside(root, args.path);
211
+ cards = [{ abs, rel: relativePath(root, abs).replace(/\\/g, '/') }];
212
+ } else {
213
+ cards = listTopicCards(root);
214
+ }
215
+ } catch (error) {
216
+ gateFail(root, 'E_HG_D13_SCAN_FAILED', String(error?.message ?? error));
217
+ throw memoryError('E_HG_D13_SCAN_FAILED', `扫描卡片失败:${error?.message ?? error}`);
218
+ }
219
+
220
+ let missingMeta = 0;
221
+ let immune = 0;
222
+ let skipped = 0;
223
+ const candidates = [];
224
+ for (const card of cards) {
225
+ let meta;
226
+ try {
227
+ meta = cardMeta(card.abs);
228
+ } catch {
229
+ missingMeta += 1;
230
+ continue;
231
+ }
232
+ if (meta.missingMeta) {
233
+ missingMeta += 1;
234
+ continue;
235
+ }
236
+ if (meta.status === 'locked' || meta.salience >= DECAY_RULES.immuneSalience) {
237
+ immune += 1;
238
+ continue;
239
+ }
240
+ const usedMs = Date.parse(String(meta.lastUsed));
241
+ if (!Number.isFinite(usedMs)) {
242
+ missingMeta += 1;
243
+ continue;
244
+ }
245
+ // 与夹具/计划同口径:ageDays 是到 now 的小数天(last_used 按 UTC 零点解析)。
246
+ const ageDays = Math.max(0, (at.getTime() - usedMs) / DAY_MS);
247
+ if (ageDays == null) {
248
+ missingMeta += 1;
249
+ continue;
250
+ }
251
+ const value = score({ salience: meta.salience, strength: meta.strength, ageDays });
252
+ if (value == null) {
253
+ missingMeta += 1;
254
+ continue;
255
+ }
256
+ if (!(value < SCORE_THRESHOLD && meta.salience < SUGGESTION_SALIENCE_BELOW && ageDays > SUGGESTION_AGE_DAYS_MIN)) {
257
+ skipped += 1;
258
+ continue;
259
+ }
260
+ candidates.push({
261
+ schema: FORGET_SUGGESTIONS_SCHEMA,
262
+ rel: card.rel,
263
+ score: value,
264
+ threshold: SCORE_THRESHOLD,
265
+ salience: meta.salience,
266
+ strength: meta.strength,
267
+ ageDays,
268
+ missing_meta: false,
269
+ suggestedAt: at.toISOString(),
270
+ status: 'open',
271
+ autoApplied: false,
272
+ });
273
+ }
274
+
275
+ let queue = null;
276
+ try {
277
+ const existing = readSuggestionRows(root);
278
+ const openRels = new Set(existing.filter((row) => row.status !== 'closed').map((row) => String(row.rel)));
279
+ const added = candidates.filter((row) => !openRels.has(row.rel));
280
+ if (added.length > 0) {
281
+ queue = writeSuggestionRows(root, [...existing, ...added], at);
282
+ } else if (existing.length > 0) {
283
+ queue = writeSuggestionRows(root, existing, at);
284
+ } else {
285
+ queue = { rows: [], file: suggestionFilePath(root), rel: FORGET_SUGGESTIONS_REL };
286
+ }
287
+ } catch (error) {
288
+ gateFail(root, 'E_HG_D13_SUGGEST_FAILED', String(error?.message ?? error));
289
+ throw memoryError('E_HG_D13_SUGGEST_FAILED', `写 forget-suggestions 失败:${error?.message ?? error}`);
290
+ }
291
+
292
+ return {
293
+ ...base,
294
+ autoApply: false,
295
+ scoreThreshold: SCORE_THRESHOLD,
296
+ scanned: cards.length,
297
+ missingMeta,
298
+ immune,
299
+ skipped,
300
+ suggestions: (queue?.rows ?? []).map((row) => row.rel),
301
+ queued: candidates.length,
302
+ suggestionsFile: FORGET_SUGGESTIONS_REL,
303
+ suggestionsRel: queue?.rel ?? FORGET_SUGGESTIONS_REL,
304
+ };
305
+ }
306
+
307
+ /** 只读:给面板/维护链查建议队列(含 90 天窗口裁剪口径)。 */
308
+ export function readForgetSuggestions(config = {}) {
309
+ const root = memoryRootFromConfig(config);
310
+ const at = config.now instanceof Date ? config.now : new Date(config.now ?? Date.now());
311
+ const rows = pruneSuggestionRows(readSuggestionRows(root), at.getTime());
312
+ return { ok: true, schema: FORGET_SUGGESTIONS_SCHEMA, rows, file: FORGET_SUGGESTIONS_REL, count: rows.length };
43
313
  }
44
314
 
45
315
  function sha256Hex(text) {
@@ -23,6 +23,7 @@ import path from 'node:path';
23
23
  import { appendAuditRecord, resolveAuditKey } from './audit-records.js';
24
24
  import { isProtectedPath } from './retention.js';
25
25
  import { memoryRootFromConfig, resolveInside, relativePath, memoryError } from './paths.js';
26
+ import { withWriteEvidence as landWithWriteEvidence, UNIMPLEMENTED_CODE as LAND_UNIMPLEMENTED_CODE } from './land.mjs';
26
27
  import {
27
28
  dayString, daysBetween, isoStamp, isDayString,
28
29
  } from './frontmatter.js';
@@ -241,7 +242,7 @@ export function forgetStatus(args = {}, config = {}) {
241
242
  };
242
243
  }
243
244
 
244
- export function memoryForget(args = {}, config = {}) {
245
+ function memoryForgetLegacy(args = {}, config = {}) {
245
246
  if (args.status === true) return forgetStatus({}, config);
246
247
  const root = memoryRootFromConfig(config);
247
248
  const now = config.now instanceof Date ? config.now : new Date();
@@ -510,3 +511,21 @@ export function memoryForget(args = {}, config = {}) {
510
511
  `每卡先备份(${moved.length} 份),墓碑共 ${tombstoneLines} 行(三问齐全),audit 记 1 行,脚手架 ${created.join('/') || '已存在'};未删除任何文件`,
511
512
  };
512
513
  }
514
+
515
+ /**
516
+ * M12/M13/M15 出口委托:land.mjs(落盘门,批次 B)。
517
+ * land 未实现时如实回退旧路径(不双写、不静默吞错);land 实现后同一入口自动切到新路径。
518
+ */
519
+ function landDoubleRoute(name, legacy) {
520
+ try {
521
+ return landWithWriteEvidence(name, legacy);
522
+ } catch (error) {
523
+ if (error?.code === LAND_UNIMPLEMENTED_CODE) return legacy();
524
+ throw error;
525
+ }
526
+ }
527
+
528
+ /** 工具入口:memory_forget。委托 land 落盘门(未实现时回退旧路径)。 */
529
+ export function memoryForget(args = {}, config = {}) {
530
+ return landDoubleRoute('memory_forget', () => memoryForgetLegacy(args, config));
531
+ }
@@ -61,7 +61,9 @@ function recallMessage(text) {
61
61
  return {
62
62
  role: 'user',
63
63
  source: { kind: 'auto' },
64
- content: [{ type: 'text', text: `${AUTO_TEXT_MARK} ${text}` }],
64
+ // 2.0.0 生产块头是 `【自动想起 · recallId=…】`;探针必须用真实生产形状,
65
+ // 否则会掩盖 inject-position/working-frame 对生产块头的识别回归。
66
+ content: [{ type: 'text', text: `${AUTO_TEXT_MARK} · recallId=probe】 ${text}` }],
65
67
  };
66
68
  }
67
69
 
@@ -66,8 +66,8 @@ export function cjkBigrams(run) {
66
66
  // ---------------------------------------------------------------------------
67
67
  // S8:长 CJK run 不再整段丢弃。
68
68
  //
69
- // 旧实现只保留长度 2–12 的**整段** run;一段包含主题词的长句(例如「简介我准备
70
- // 放我朋友那五问你现在根据那五问回答」)长度 >12 就被整体扔掉,留下的是标点切
69
+ // 旧实现只保留长度 2–12 的**整段** run;一段包含主题词的长句(例如「整理一下五问
70
+ // 清单然后按这五问逐条回答」)长度 >12 就被整体扔掉,留下的是标点切
71
71
  // 开的短片段 → auto 卡 / 事件 terms 没有主题词。
72
72
  //
73
73
  // 新实现(仍然无词典、无外部依赖):
@@ -33,6 +33,10 @@ export const RAW_DIRS = ['raw', 'topics/raw'];
33
33
  export const RAW_INDEX_POLICY = 'excluded-by-default';
34
34
  export const RAW_OPT_IN_FIELD = 'index';
35
35
 
36
+ /** 正文上限(按 Unicode 码点):召回面只带这么多正文,超长标 bodyTruncated。 */
37
+ export const CARD_BODY_MAX = 1200;
38
+ export const CARD_BODY_HIDDEN = '<hidden>';
39
+
36
40
  /**
37
41
  * Raw source material is deliberately NOT part of the generated card table:
38
42
  * it is evidence/archive, and indexing every transcript would make INDEX.md a
@@ -96,31 +100,100 @@ function firstSummaryLine(body) {
96
100
  return '(空)';
97
101
  }
98
102
 
99
- function readCard(root, abs) {
103
+ function truthyFlag(value) {
104
+ return value === true || value === 'true' || value === 'yes' || value === 1;
105
+ }
106
+
107
+ function relFromAbs(abs, root) {
108
+ if (root) return relativePath(root, abs);
109
+ const parts = String(abs).split(/[\\/]/u);
110
+ const anchors = ['topics', 'journal', 'procedures', 'flow', 'handover'];
111
+ for (let index = parts.length - 1; index >= 0; index -= 1) {
112
+ if (anchors.includes(parts[index])) return parts.slice(index).join('/');
113
+ }
114
+ return path.basename(abs);
115
+ }
116
+
117
+ /**
118
+ * Resolve the four supported call shapes:
119
+ * readCard(root, abs) / readCard(abs, {memoryRoot}) / readCard(abs) /
120
+ * readCard({memoryRoot, path})
121
+ * The shape matters for the recall surface (C 召回面) — legacy callers and the
122
+ * d3 fixture both pass a mix, so all four are accepted.
123
+ */
124
+ function resolveReadCardArgs(first, second) {
125
+ const asPath = (value) => (typeof value === 'string' && value.trim() !== '' ? path.resolve(value) : null);
126
+ let root = null;
127
+ let abs = null;
128
+ if (first && typeof first === 'object') {
129
+ root = asPath(first.memoryRoot);
130
+ abs = asPath(first.path ?? first.abs ?? first.rel);
131
+ } else if (second && typeof second === 'object') {
132
+ root = asPath(second.memoryRoot);
133
+ abs = asPath(first);
134
+ } else if (typeof first === 'string' && typeof second === 'string' && path.isAbsolute(second)) {
135
+ root = asPath(first);
136
+ abs = asPath(second);
137
+ } else {
138
+ abs = asPath(first);
139
+ root = asPath(second);
140
+ }
141
+ return { root, abs };
142
+ }
143
+
144
+ /**
145
+ * 读一张卡:frontmatter + 正文。正文按 C 召回面口径带 body(≤1,200 码点,
146
+ * 超长 bodyTruncated:true,另给 bodyChars);local_only / 隐私卡正文与摘要一律
147
+ * 替成 <hidden>,不许把私密正文带进索引或召回。
148
+ */
149
+ export function readCard(first, second) {
150
+ const { root, abs } = resolveReadCardArgs(first, second);
151
+ if (!abs) throw memoryError('E_CARD_PATH', 'readCard 需要一个卡片路径');
100
152
  const text = fs.readFileSync(abs, 'utf8');
101
153
  const parsed = parseFrontmatter(text);
102
- const rel = relativePath(root, abs);
154
+ const rel = relFromAbs(abs, root);
103
155
  const title = collapse(parsed.fields.title || firstHeading(parsed.body) || path.basename(abs, '.md')) || '(无题)';
156
+ const rawBody = String(parsed.body ?? '').trim();
157
+ const localOnly = truthyFlag(parsed.fields.local_only) || truthyFlag(parsed.extras?.local_only);
158
+ const bodyChars = Array.from(rawBody).length;
159
+ let body = rawBody;
160
+ let bodyTruncated = false;
161
+ if (localOnly) {
162
+ body = CARD_BODY_HIDDEN;
163
+ } else if (bodyChars > CARD_BODY_MAX) {
164
+ body = Array.from(rawBody).slice(0, CARD_BODY_MAX).join('');
165
+ bodyTruncated = true;
166
+ }
104
167
  return {
105
168
  abs,
106
169
  rel,
107
170
  title,
108
- summary: firstSummaryLine(parsed.body),
171
+ summary: localOnly ? CARD_BODY_HIDDEN : firstSummaryLine(parsed.body),
109
172
  legacy: parsed.legacy,
110
173
  fields: parsed.fields,
111
174
  extras: parsed.extras ?? {},
175
+ body,
176
+ bodyChars: localOnly ? 0 : Array.from(body).length,
177
+ bodyTruncated,
178
+ auto: rel.replace(/\\/g, '/').startsWith('topics/auto/'),
112
179
  };
113
180
  }
114
181
 
115
- /** All cards under `topics/` and `journal/`, sorted for a stable index. */
182
+ function shouldSkipScanRel(rel) {
183
+ const normalized = rel.replace(/\\/g, '/');
184
+ if (normalized === 'topics/archive' || normalized.startsWith('topics/archive/')) return true;
185
+ if (normalized === 'journal/archive' || normalized.startsWith('journal/archive/')) return true;
186
+ if (normalized.includes('/archive/')) return true;
187
+ return false;
188
+ }
189
+
190
+ /** All cards under `topics/` (incl. `topics/auto/`) and `journal/`, archive excluded. */
116
191
  export function scanCards(root) {
117
192
  const cards = [];
118
193
  for (const dir of SCAN_DIRS) {
119
194
  for (const abs of listMarkdownFiles(root, dir)) {
120
195
  const rel = relativePath(root, abs);
121
- // A1 v2: auto-* staging is deliberately outside the recall surface until
122
- // a human/dream review promotes it to a regular topic card.
123
- if (rel.startsWith('topics/auto/')) continue;
196
+ if (shouldSkipScanRel(rel)) continue;
124
197
  cards.push(readCard(root, abs));
125
198
  }
126
199
  }