@jjh32456/longlive 0.0.0-stage → 1.8.12

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 (309) hide show
  1. package/CHANGELOG.md +205 -0
  2. package/LICENSE +21 -0
  3. package/QUICKSTART.md +363 -0
  4. package/README.en.md +55 -0
  5. package/README.md +225 -2
  6. package/SPEC.md +211 -0
  7. package/build-info.json +1555 -0
  8. package/cordis.patch.yml +177 -0
  9. package/docs/A1-MIGRATION.md +75 -0
  10. package/docs/ANSWER-GUARD.md +92 -0
  11. package/docs/ARCHITECTURE.md +128 -0
  12. package/docs/AUTO-RECALL-WIRING.md +115 -0
  13. package/docs/AUTO-RECALL.md +237 -0
  14. package/docs/CONCEPTS.md +143 -0
  15. package/docs/CONFIG.md +807 -0
  16. package/docs/ERRORS.md +271 -0
  17. package/docs/FAQ.md +186 -0
  18. package/docs/FEATURES.md +579 -0
  19. package/docs/INDEX-FRESHNESS.md +21 -0
  20. package/docs/METRICS.md +244 -0
  21. package/docs/MIGRATION-1.6.0.md +220 -0
  22. package/docs/OPERATIONS.md +439 -0
  23. package/docs/PANEL-INTEGRATION.md +190 -0
  24. package/docs/PRIVACY.md +88 -0
  25. package/docs/QUICKSTART.md +155 -0
  26. package/docs/RAW-INDEX-POLICY.md +7 -0
  27. package/docs/README.en.md +46 -0
  28. package/docs/RESIDENT-WATCHER.md +90 -0
  29. package/docs/SESSION-WATCH.md +214 -0
  30. package/docs/TOOLS.md +184 -0
  31. package/docs/TROUBLESHOOTING.md +329 -0
  32. package/icon.svg +11 -0
  33. package/lib/client.js +436 -0
  34. package/locale/en.json +6 -0
  35. package/locale/zh.json +6 -0
  36. package/package.json +160 -4
  37. package/runbook.md +343 -0
  38. package/scripts/archive-digest-build.mjs +668 -0
  39. package/scripts/auto-truncate-run.ps1 +752 -0
  40. package/scripts/backfill-auto-cards.mjs +98 -0
  41. package/scripts/edges-build.mjs +1003 -0
  42. package/scripts/index-maintain.mjs +39 -0
  43. package/scripts/index-reconcile.mjs +49 -0
  44. package/scripts/index-status.mjs +28 -0
  45. package/scripts/install-resident-watcher.ps1 +15 -0
  46. package/scripts/install-session-watch.ps1 +332 -0
  47. package/scripts/install-surgery-task.ps1 +174 -0
  48. package/scripts/lib/auto-truncate-run.ps1 +512 -0
  49. package/scripts/lib/session-watch-fixture.mjs +207 -0
  50. package/scripts/longlive-doctor.mjs +578 -0
  51. package/scripts/metrics-read.mjs +79 -0
  52. package/scripts/metrics-sample.mjs +215 -0
  53. package/scripts/migrate-180.mjs +163 -0
  54. package/scripts/migrate-a1-legacy.mjs +62 -0
  55. package/scripts/migrate-lifecycle.mjs +157 -0
  56. package/scripts/pack.mjs +392 -0
  57. package/scripts/recall-index-build.mjs +128 -0
  58. package/scripts/recall-links-build.mjs +420 -0
  59. package/scripts/rescore-cards.mjs +36 -0
  60. package/scripts/resident-watcher-status.ps1 +15 -0
  61. package/scripts/resident-watcher.ps1 +643 -0
  62. package/scripts/session-watch-drill.mjs +553 -0
  63. package/scripts/session-watch-status.ps1 +146 -0
  64. package/scripts/session-watch.mjs +1367 -0
  65. package/scripts/surgery-inspect.mjs +122 -0
  66. package/scripts/surgery-run.cmd +34 -0
  67. package/scripts/truncate-cli.mjs +279 -0
  68. package/scripts/unattended-surgery.ps1 +1019 -0
  69. package/scripts/uninstall-resident-watcher.ps1 +15 -0
  70. package/scripts/uninstall-session-watch.ps1 +192 -0
  71. package/scripts/verify-card-anchors.mjs +138 -0
  72. package/scripts/watch-loop.ps1 +916 -0
  73. package/src/actions/audit.js +125 -0
  74. package/src/actions/evidence.js +122 -0
  75. package/src/actions/fs.js +162 -0
  76. package/src/activity/index.js +873 -0
  77. package/src/activity/model.js +351 -0
  78. package/src/activity/store.js +786 -0
  79. package/src/activity/summary.js +180 -0
  80. package/src/activity/thinking.js +191 -0
  81. package/src/adapters/constants.js +11 -0
  82. package/src/adapters/engram/data/aliases.json +51 -0
  83. package/src/adapters/engram/data/policy.json +8 -0
  84. package/src/adapters/engram/data/routing-rules.json +546 -0
  85. package/src/adapters/engram/index.js +278 -0
  86. package/src/adapters/registry.js +315 -0
  87. package/src/answer/audit.js +238 -0
  88. package/src/answer/evidence.js +30 -0
  89. package/src/answer/guard.js +1370 -0
  90. package/src/answer/index.js +1086 -0
  91. package/src/answer/query.js +111 -0
  92. package/src/answer/second-hop.mjs +101 -0
  93. package/src/auto-truncate-status.js +164 -0
  94. package/src/auto-truncate.js +1181 -0
  95. package/src/autoprocedure/candidate.js +342 -0
  96. package/src/autoprocedure/config.js +122 -0
  97. package/src/autoprocedure/evidence.js +345 -0
  98. package/src/autoprocedure/index.js +83 -0
  99. package/src/autoprocedure/ledger.js +329 -0
  100. package/src/autoprocedure/lint.js +232 -0
  101. package/src/autoprocedure/llm.js +409 -0
  102. package/src/autoprocedure/locks.js +102 -0
  103. package/src/autoprocedure/paths.js +39 -0
  104. package/src/autoprocedure/privacy.js +87 -0
  105. package/src/autoprocedure/rules.js +288 -0
  106. package/src/autoprocedure/runtime.js +718 -0
  107. package/src/autoprocedure/session-reader.js +328 -0
  108. package/src/backup.js +146 -0
  109. package/src/bus/bus.mjs +1446 -0
  110. package/src/codec.js +269 -0
  111. package/src/compaction/cut-engine.js +44 -0
  112. package/src/compaction/engine-core.js +1237 -0
  113. package/src/compaction/entry.js +228 -0
  114. package/src/compaction.js +230 -0
  115. package/src/conclusion.js +366 -0
  116. package/src/config.js +824 -0
  117. package/src/d6/runtime.js +517 -0
  118. package/src/d6/surface.js +181 -0
  119. package/src/deps.js +189 -0
  120. package/src/engine-status.js +141 -0
  121. package/src/features.js +912 -0
  122. package/src/handoff/index.js +944 -0
  123. package/src/handoff/model.js +1010 -0
  124. package/src/handoff/store.js +1233 -0
  125. package/src/heartbeat.js +385 -0
  126. package/src/home.js +16 -0
  127. package/src/host-version.js +280 -0
  128. package/src/hot-truncate-diag.js +98 -0
  129. package/src/identity/card-marker.js +281 -0
  130. package/src/identity/handover.js +657 -0
  131. package/src/identity/index.js +337 -0
  132. package/src/identity/inject-position.js +131 -0
  133. package/src/identity/writeback.js +344 -0
  134. package/src/identity.js +118 -0
  135. package/src/index.js +647 -0
  136. package/src/lifecycle/gap-clocks.js +364 -0
  137. package/src/lifecycle/index.js +269 -0
  138. package/src/lifecycle/proactive.js +1426 -0
  139. package/src/live-target.js +212 -0
  140. package/src/live.js +1603 -0
  141. package/src/log-rotation.js +153 -0
  142. package/src/memory/a1-migration.js +124 -0
  143. package/src/memory/activity-capture.js +229 -0
  144. package/src/memory/anchor-fallback.js +116 -0
  145. package/src/memory/anchors.js +194 -0
  146. package/src/memory/audit-records.js +222 -0
  147. package/src/memory/auto-cards.js +441 -0
  148. package/src/memory/capture-host.js +228 -0
  149. package/src/memory/capture.js +457 -0
  150. package/src/memory/card-anchors.js +203 -0
  151. package/src/memory/card-priority.js +110 -0
  152. package/src/memory/cards.js +425 -0
  153. package/src/memory/conclusion-distill.js +332 -0
  154. package/src/memory/conclusion-drafts.js +239 -0
  155. package/src/memory/conflicts.js +147 -0
  156. package/src/memory/consolidate.js +815 -0
  157. package/src/memory/decay.js +311 -0
  158. package/src/memory/distill.js +485 -0
  159. package/src/memory/event-index.js +1826 -0
  160. package/src/memory/evidence-chain.js +295 -0
  161. package/src/memory/evidence.js +213 -0
  162. package/src/memory/filter-runner.js +555 -0
  163. package/src/memory/filter.js +1035 -0
  164. package/src/memory/forget-v2.js +410 -0
  165. package/src/memory/forget.js +512 -0
  166. package/src/memory/frames-activation.js +247 -0
  167. package/src/memory/frontmatter.js +454 -0
  168. package/src/memory/fts-query.js +342 -0
  169. package/src/memory/governance.js +604 -0
  170. package/src/memory/index-freshness.js +234 -0
  171. package/src/memory/index.js +362 -0
  172. package/src/memory/l2-gate.js +169 -0
  173. package/src/memory/lifecycle.js +107 -0
  174. package/src/memory/lock.js +121 -0
  175. package/src/memory/maintenance.js +785 -0
  176. package/src/memory/manifest.js +245 -0
  177. package/src/memory/migrate-lifecycle.js +1808 -0
  178. package/src/memory/migrate.js +139 -0
  179. package/src/memory/paths.js +229 -0
  180. package/src/memory/procedure.js +963 -0
  181. package/src/memory/provenance.js +119 -0
  182. package/src/memory/recall-v2.js +206 -0
  183. package/src/memory/recall.js +256 -0
  184. package/src/memory/reconcile.js +265 -0
  185. package/src/memory/records.js +433 -0
  186. package/src/memory/reinforce.js +145 -0
  187. package/src/memory/retention.js +128 -0
  188. package/src/memory/review.js +124 -0
  189. package/src/memory/state.js +279 -0
  190. package/src/memory/tiers.js +168 -0
  191. package/src/memory/topic-phrases.js +73 -0
  192. package/src/memory/trust.js +97 -0
  193. package/src/memory/version-chain.js +264 -0
  194. package/src/memory/wal.js +137 -0
  195. package/src/memory/working-frame.js +516 -0
  196. package/src/metrics/classify.mjs +189 -0
  197. package/src/metrics/estimate.mjs +108 -0
  198. package/src/metrics/index.mjs +204 -0
  199. package/src/metrics/measure.mjs +462 -0
  200. package/src/metrics/prestep-latency.mjs +307 -0
  201. package/src/metrics/store.mjs +264 -0
  202. package/src/original.js +294 -0
  203. package/src/policy/threshold-policy.js +224 -0
  204. package/src/policy-profile.js +463 -0
  205. package/src/recall/anaphora.mjs +87 -0
  206. package/src/recall/archive-fallback.mjs +235 -0
  207. package/src/recall/archive-search.mjs +425 -0
  208. package/src/recall/cards.mjs +202 -0
  209. package/src/recall/edges.js +379 -0
  210. package/src/recall/embedding.mjs +698 -0
  211. package/src/recall/entities.mjs +112 -0
  212. package/src/recall/explain.mjs +433 -0
  213. package/src/recall/force-policy.mjs +138 -0
  214. package/src/recall/index.js +1036 -0
  215. package/src/recall/inject-order.mjs +277 -0
  216. package/src/recall/link-recall.mjs +183 -0
  217. package/src/recall/links.mjs +696 -0
  218. package/src/recall/privacy.mjs +208 -0
  219. package/src/recall/recall-core.mjs +765 -0
  220. package/src/recall/shared-visibility.js +302 -0
  221. package/src/recall/time-normalizer.mjs +196 -0
  222. package/src/retention/config.js +106 -0
  223. package/src/retention/index.js +643 -0
  224. package/src/role/activation.js +191 -0
  225. package/src/role/attention.js +318 -0
  226. package/src/role/base.js +36 -0
  227. package/src/role/channels.js +423 -0
  228. package/src/role/index.js +425 -0
  229. package/src/role/interfaces.js +115 -0
  230. package/src/role/personality.js +370 -0
  231. package/src/role/readers.js +151 -0
  232. package/src/role/relationships.js +477 -0
  233. package/src/role/store.js +202 -0
  234. package/src/role/writeprotect.js +373 -0
  235. package/src/router/aliases.json +182 -0
  236. package/src/router/background/agent-runner.mjs +239 -0
  237. package/src/router/background/anchor.mjs +323 -0
  238. package/src/router/background/audit.mjs +337 -0
  239. package/src/router/background/budget-ledger.mjs +648 -0
  240. package/src/router/background/host-sim.mjs +451 -0
  241. package/src/router/background/index.mjs +81 -0
  242. package/src/router/background/memory.mjs +63 -0
  243. package/src/router/background/mock-llm.mjs +203 -0
  244. package/src/router/background/queue.mjs +224 -0
  245. package/src/router/background/retry.mjs +255 -0
  246. package/src/router/background/router.mjs +1459 -0
  247. package/src/router/background/stream.mjs +276 -0
  248. package/src/router/background/tool-policy.mjs +255 -0
  249. package/src/router/design-headings.json +221 -0
  250. package/src/router/face/config.mjs +155 -0
  251. package/src/router/face/context.mjs +284 -0
  252. package/src/router/face/face.mjs +466 -0
  253. package/src/router/face/identity.mjs +130 -0
  254. package/src/router/face/index.mjs +65 -0
  255. package/src/router/face/journal.mjs +119 -0
  256. package/src/router/face/llm.mjs +252 -0
  257. package/src/router/face/outbox.mjs +153 -0
  258. package/src/router/face/paths.mjs +54 -0
  259. package/src/router/judge.mjs +987 -0
  260. package/src/router/policies/generic.json +131 -0
  261. package/src/router/route.js +1766 -0
  262. package/src/router/router.mjs +535 -0
  263. package/src/router/routing-rules.json +816 -0
  264. package/src/router/run-sim.mjs +530 -0
  265. package/src/router/runtime.js +569 -0
  266. package/src/router/service/apply.mjs +1218 -0
  267. package/src/router/service/board.mjs +712 -0
  268. package/src/router/service/caller.mjs +131 -0
  269. package/src/router/service/config.mjs +361 -0
  270. package/src/router/service/context.mjs +314 -0
  271. package/src/router/service/hint.mjs +668 -0
  272. package/src/router/service/lease.mjs +494 -0
  273. package/src/router/service/live.mjs +251 -0
  274. package/src/router/service/lock.mjs +550 -0
  275. package/src/router/service/merge.mjs +255 -0
  276. package/src/router/service/model-resolve.mjs +350 -0
  277. package/src/router/service/paths.mjs +168 -0
  278. package/src/router/service/proposals.mjs +1461 -0
  279. package/src/router/service/queue.mjs +477 -0
  280. package/src/router/service/reconcile.mjs +271 -0
  281. package/src/router/service/service.mjs +2998 -0
  282. package/src/router/service/sources.mjs +352 -0
  283. package/src/router/service/status.mjs +520 -0
  284. package/src/router/service/store.mjs +476 -0
  285. package/src/router/service/ticklock.mjs +239 -0
  286. package/src/router/service/tokens.mjs +95 -0
  287. package/src/router/service/tools.mjs +248 -0
  288. package/src/router/service/wake.mjs +544 -0
  289. package/src/router/service/wal.mjs +685 -0
  290. package/src/router/shadow.mjs +821 -0
  291. package/src/surgery-recovery.js +1909 -0
  292. package/src/tool-output.js +485 -0
  293. package/src/tools.js +3146 -0
  294. package/src/truncate-visible.js +2416 -0
  295. package/src/truncate.js +999 -0
  296. package/src/ui/actions.js +1312 -0
  297. package/src/ui/flags.js +259 -0
  298. package/src/ui/panel-api.js +371 -0
  299. package/src/ui/panel-auth.js +251 -0
  300. package/src/ui/panel-integrity.js +243 -0
  301. package/src/ui/routes-readonly.js +759 -0
  302. package/src/ui/routes.js +284 -0
  303. package/src/util/append-store.js +368 -0
  304. package/src/util/local-day.js +30 -0
  305. package/src/util/redact.js +227 -0
  306. package/src/util/stale-locks.js +148 -0
  307. package/src/version.js +99 -0
  308. package/test/fixtures/pre-step-container.mjs +100 -0
  309. package/test/p1_probe.mjs +97 -0
@@ -0,0 +1,815 @@
1
+ // Daily consolidation proposals.
2
+ //
3
+ // Reads journal entries dated after the last consolidation and proposes which
4
+ // card each paragraph belongs in. Cards are never edited: the only card-facing
5
+ // output is a report under `.longlive/reports/`. The state file gains stable
6
+ // proposal ids (`seenProposals`) so the same (source, paragraph) is never
7
+ // proposed twice, and `lastConsolidated` advances only after every proposal
8
+ // recorded for the newest scanned day is resolved (accepted/rejected/
9
+ // superseded). The human still decides what gets merged.
10
+
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+ import crypto from 'node:crypto';
14
+
15
+ import { memoryRootFromConfig, resolveInside, relativePath, memoryError } from './paths.js';
16
+ import {
17
+ parseFrontmatter, dayString, isoStamp, isDayString,
18
+ } from './frontmatter.js';
19
+ import {
20
+ ensureDir, reportsDir, readState, updateState, listMarkdownFiles, writeFileAtomic, appendAudit,
21
+ } from './state.js';
22
+ import { scanCards } from './index.js';
23
+ import { writeCard } from './cards.js';
24
+
25
+ const RESOLVED_STATUS = new Set(['accepted', 'rejected', 'superseded']);
26
+ const AFFECT_KEYWORD = /^affect\b/i;
27
+
28
+ function collapse(text) {
29
+ return String(text ?? '').replace(/\s+/g, ' ').trim();
30
+ }
31
+
32
+ function stripComments(text) {
33
+ return String(text ?? '').replace(/<!--[\s\S]*?-->/g, ' ');
34
+ }
35
+
36
+ function commentsOf(text) {
37
+ return String(text ?? '').match(/<!--[\s\S]*?-->/g) ?? [];
38
+ }
39
+
40
+ // Routing v2 vocabulary. rc.5 counted every shared token — dates, ASCII
41
+ // fragments, generic words — and weighted titles x3, so a date in a card title
42
+ // could beat the one rare term that identified the paragraph. Content tokens
43
+ // drop addresses, numbers and CJK function words first.
44
+ const STOP_BIGRAMS = new Set([
45
+ '我们', '你们', '他们', '她们', '它们', '这个', '那个', '一个', '没有', '就是', '可以',
46
+ '因为', '所以', '但是', '如果', '已经', '还是', '不是', '什么', '这样', '那样', '现在',
47
+ '今天', '时候', '自己', '东西', '事情', '地方', '问题', '方法', '做法', '方式', '结果',
48
+ '开始', '然后', '之后', '之前', '一下', '一点', '这些', '那些', '这种', '那种', '内容',
49
+ '部分', '情况', '需要', '一定', '直接', '全部', '所有', '今日', '今晚', '同时', '以及',
50
+ ]);
51
+ const STOP_CHARS = new Set('的了是在我他你她它们这那就也都很和与及把被让给对从到为以于而其之等着呢吗吧啊哦嗯个不没有会要能可还只又再才更最');
52
+ const PLAN_PATTERN = /(挂起|暂(?:时)?不|下一步再|排(?:期)?到|在他点名前)/;
53
+ const CONCLUSION_PATTERN = /(决定|取消|改成|改为|不许|不准|只能|必须|禁止|结论|教训|根因|正确做法|规矩|铁律|硬约束|遗留|未处理|不再|一律|统一|定为)/;
54
+
55
+ /** Content tokens: ASCII words and CJK bigrams, with dates/numbers/function words dropped. */
56
+ function contentTokens(text) {
57
+ const source = String(text ?? '').toLowerCase()
58
+ // URLs and bare domains are addresses, not topics: drop them whole so
59
+ // `https` / `com` / `api` never become routing evidence.
60
+ .replace(/https?:\/\/\S+/g, ' ')
61
+ .replace(/\b[\w-]+\.(?:com|cn|net|org|io|dev|ai|app)\b/g, ' ');
62
+ const map = new Map();
63
+ const bump = (token) => map.set(token, (map.get(token) ?? 0) + 1);
64
+ for (const word of source.match(/[a-z0-9_]{2,}/g) ?? []) {
65
+ if (/^\d+$/.test(word) || /^(19|20)\d{2}$/.test(word)) continue;
66
+ bump(word);
67
+ }
68
+ for (const run of source.match(/[\u4e00-\u9fff]+/g) ?? []) {
69
+ for (let index = 0; index + 1 < run.length; index += 1) {
70
+ const bigram = run.slice(index, index + 2);
71
+ if (STOP_BIGRAMS.has(bigram)) continue;
72
+ if (STOP_CHARS.has(bigram[0]) || STOP_CHARS.has(bigram[1])) continue;
73
+ bump(bigram);
74
+ }
75
+ }
76
+ return map;
77
+ }
78
+
79
+ function journalDay(rel, fields) {
80
+ if (isDayString(fields?.date)) return fields.date.trim();
81
+ const base = path.posix.basename(rel);
82
+ const match = /^(\d{4})[-_.](\d{1,2})(?:[-_.](\d{1,2}))?/.exec(base);
83
+ if (!match) return null;
84
+ const month = Number(match[2]);
85
+ const day = match[3] ? Number(match[3]) : 1;
86
+ if (month < 1 || month > 12 || day < 1 || day > 31) return null;
87
+ return `${match[1]}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
88
+ }
89
+
90
+ /**
91
+ * A compact bullet list can pack several entries into one blank-line block:
92
+ * a `- **YYYY-MM-DD HH:MM**` line starts a new entry, and so does a bullet that
93
+ * opens with a conclusion word (`- 结论:…`) right after a finished sentence.
94
+ */
95
+ const ENTRY_TIMESTAMP = /^-\s*\*\*(?:\d{4}-\d{2}-\d{2}|\d{1,2}[-–]\d{1,2}(?:\s+\d{1,2}:\d{2})?)/;
96
+ const ENTRY_CONCLUSION = /^-\s*(?:结论|决定|教训|根因|规矩|铁律|下一步|遗留|未处理|正确做法)\s*[::]/;
97
+ const SENTENCE_END = /[。;!?;!?]$/;
98
+
99
+ function splitEntryGroups(lines) {
100
+ const groups = [];
101
+ let current = [];
102
+ for (const line of lines) {
103
+ const isEntry = /^-\s/.test(line.text)
104
+ && (ENTRY_TIMESTAMP.test(line.text) || ENTRY_CONCLUSION.test(line.text));
105
+ const previous = current[current.length - 1];
106
+ if (current.length && isEntry && previous && SENTENCE_END.test(previous.text.trim())) {
107
+ groups.push(current);
108
+ current = [];
109
+ }
110
+ current.push(line);
111
+ }
112
+ if (current.length) groups.push(current);
113
+ return groups;
114
+ }
115
+
116
+ /**
117
+ * Paragraphs of a journal file. Headings are dropped; a block that holds only
118
+ * HTML comments (the usual `<!-- affect: N | reason -->` on its own line)
119
+ * belongs to the paragraph before it, or to the next one at the top.
120
+ *
121
+ * Returns `{ text, startLine, endLine }` where the line numbers are 1-based
122
+ * inside `body`, shifted by `lineOffset` when the caller wants file lines.
123
+ * `splitEntries` (off by default) cuts a compact block into its entry units.
124
+ */
125
+ function paragraphUnits(body, { splitEntries = false, lineOffset = 0 } = {}) {
126
+ const lines = String(body ?? '').split(/\r?\n/);
127
+ const blocks = [];
128
+ let block = null;
129
+ for (let index = 0; index < lines.length; index += 1) {
130
+ const line = lines[index];
131
+ if (!line.trim()) {
132
+ block = null;
133
+ continue;
134
+ }
135
+ if (!block) {
136
+ block = [];
137
+ blocks.push(block);
138
+ }
139
+ block.push({ text: line, number: index + 1 });
140
+ }
141
+
142
+ const units = [];
143
+ let pending = null;
144
+ const attach = (target, text, lastLine) => {
145
+ target.text = `${target.text}\n${text}`;
146
+ target.endLine = lastLine;
147
+ };
148
+ for (const raw of blocks) {
149
+ const kept = raw.filter((line) => !/^\s{0,3}#{1,6}\s/.test(line.text));
150
+ if (!kept.length) continue;
151
+ const cleaned = kept.map((line) => line.text).join('\n').trim();
152
+ if (!collapse(stripComments(cleaned))) {
153
+ const target = units[units.length - 1] ?? pending;
154
+ if (target) attach(target, cleaned, kept[kept.length - 1].number);
155
+ else pending = { text: cleaned, startLine: kept[0].number, endLine: kept[kept.length - 1].number };
156
+ continue;
157
+ }
158
+ const groups = splitEntries ? splitEntryGroups(kept) : [kept];
159
+ for (const group of groups) {
160
+ const text = group.map((line) => line.text).join('\n').trim();
161
+ if (!text) continue;
162
+ const startLine = group[0].number;
163
+ const endLine = group[group.length - 1].number;
164
+ if (pending) {
165
+ units.push({
166
+ text: `${pending.text}\n${text}`,
167
+ startLine: pending.startLine,
168
+ endLine,
169
+ });
170
+ pending = null;
171
+ } else {
172
+ units.push({ text, startLine, endLine });
173
+ }
174
+ }
175
+ }
176
+ if (pending) units.push(pending);
177
+ return units.map((unit) => ({
178
+ text: unit.text,
179
+ startLine: unit.startLine + lineOffset,
180
+ endLine: unit.endLine + lineOffset,
181
+ }));
182
+ }
183
+
184
+ function parseAffectComment(comment) {
185
+ const inner = comment.replace(/^<!--/, '').replace(/-->$/, '').trim();
186
+ const rest = inner.replace(/^affect\b/i, '');
187
+ if (!/^\s*:/.test(rest)) {
188
+ return { ok: false, code: 'E_AFFECT_FORMAT', message: '缺少冒号,应为 <!-- affect: N | 理由 -->' };
189
+ }
190
+ const payload = rest.replace(/^\s*:/, '');
191
+ const bar = payload.indexOf('|');
192
+ if (bar < 0) {
193
+ return { ok: false, code: 'E_AFFECT_FORMAT', message: '缺少 "| 理由" 部分' };
194
+ }
195
+ const rawNumber = payload.slice(0, bar).trim();
196
+ const reason = payload.slice(bar + 1).trim();
197
+ if (!/^\d+$/.test(rawNumber)) {
198
+ return { ok: false, code: 'E_AFFECT_FORMAT', message: `N 不是整数:${rawNumber || '(空)'}` };
199
+ }
200
+ const number = Number(rawNumber);
201
+ if (number < 1 || number > 5) {
202
+ return { ok: false, code: 'E_AFFECT_RANGE', message: `N 越界:${number},必须在 1..5` };
203
+ }
204
+ if (!reason) {
205
+ return { ok: false, code: 'E_AFFECT_FORMAT', message: '缺少理由' };
206
+ }
207
+ return { ok: true, number, reason: collapse(reason) };
208
+ }
209
+
210
+ /**
211
+ * Parse the affect marker of one journal paragraph.
212
+ *
213
+ * `<!-- affect: N | 一句理由 -->` (N 1..5) wins. Without a marker the
214
+ * conservative regex fallback is used. A malformed or out-of-range marker is
215
+ * never thrown: it is returned in `bad` so a batch run can list it and move on.
216
+ */
217
+ export function parseAffect(text) {
218
+ const raw = String(text ?? '');
219
+ const bad = [];
220
+ let marked = null;
221
+ for (const comment of commentsOf(raw)) {
222
+ const inner = comment.replace(/^<!--/, '').replace(/-->$/, '').trim();
223
+ if (!AFFECT_KEYWORD.test(inner)) continue;
224
+ const parsed = parseAffectComment(comment);
225
+ if (parsed.ok) {
226
+ if (!marked) marked = parsed;
227
+ else {
228
+ bad.push({
229
+ marker: collapse(comment),
230
+ code: 'E_AFFECT_DUPLICATE',
231
+ message: '同一段有多个 affect 标记,只采信第一个',
232
+ });
233
+ }
234
+ } else {
235
+ bad.push({ marker: collapse(comment), code: parsed.code, message: parsed.message });
236
+ }
237
+ }
238
+ if (marked) {
239
+ return {
240
+ salience: marked.number,
241
+ salienceSource: 'marked',
242
+ affectReason: marked.reason,
243
+ bad,
244
+ };
245
+ }
246
+ const guess = salienceGuess(collapse(stripComments(raw)));
247
+ return { salience: guess.value, salienceSource: guess.source, affectReason: null, bad };
248
+ }
249
+
250
+ function salienceGuess(paragraph) {
251
+ if (/(铁律|永远|绝不|必须|生命|答应|死|永远记住)/.test(paragraph)) return { value: 5, source: 'heuristic' };
252
+ if (/(决定|规则|结论|方案|方向|定下)/.test(paragraph)) return { value: 4, source: 'heuristic' };
253
+ if (/(随手|备忘|琐事|笔记|临时)/.test(paragraph)) return { value: 2, source: 'heuristic' };
254
+ return { value: 3, source: 'default' };
255
+ }
256
+
257
+ function suggestSalience(paragraph) {
258
+ return salienceGuess(paragraph).value;
259
+ }
260
+
261
+ /** Stable identity of a (source, paragraph) pair: sha1(...)[:12]. */
262
+ export function proposalId(sourceRel, paragraphText) {
263
+ return crypto.createHash('sha1')
264
+ .update(`${sourceRel}\n${collapse(paragraphText)}`, 'utf8')
265
+ .digest('hex')
266
+ .slice(0, 12);
267
+ }
268
+
269
+ // Routing vocabulary is DECLARED, not inferred from body prose: title + a
270
+ // `scope:` frontmatter line (a comma-separated term list) + tags. Body text is
271
+ // only a fallback for cards that have not declared a scope yet, and carries the
272
+ // lowest weight. This is what stops "sessions" in a card body or a date in a
273
+ // title from outvoting the one term that names the paragraph's topic.
274
+ const ROUTING_TITLE_WEIGHT = 2;
275
+ const ROUTING_SCOPE_WEIGHT = 3;
276
+ const ROUTING_BODY_WEIGHT = 1;
277
+ const ROUTING_SCOPE_DISABLED = process.env.DSH_LONGLIVE_SCOPE === '0';
278
+ const ROUTING_MIN_COVERAGE = Number(process.env.DSH_LONGLIVE_MIN_COVERAGE ?? 0.03);
279
+
280
+ function stripFrontmatterText(text) {
281
+ const match = /^---\r?\n[\s\S]*?\r?\n---\r?\n?/.exec(String(text ?? ''));
282
+ return match ? String(text).slice(match[0].length) : String(text ?? '');
283
+ }
284
+
285
+ /** Build the routing vocabulary for the whole card set. */
286
+ function buildCardIndex(cards) {
287
+ const add = (tf, tokens, weight) => {
288
+ for (const [token, n] of tokens) tf.set(token, (tf.get(token) ?? 0) + n * weight);
289
+ };
290
+ const docs = cards.map((card) => {
291
+ const raw = card.abs ? fs.readFileSync(card.abs, 'utf8') : '';
292
+ const parsed = raw ? parseFrontmatter(raw) : { fields: {}, extras: {}, body: '' };
293
+ // `scope` is a known field now; reading extras too keeps older cards working.
294
+ const scope = String(parsed.fields?.scope ?? parsed.extras?.scope ?? card.fields?.scope ?? '').trim();
295
+ const tf = new Map();
296
+ add(tf, contentTokens(card.title), ROUTING_TITLE_WEIGHT);
297
+ if (!ROUTING_SCOPE_DISABLED) add(tf, contentTokens(scope), ROUTING_SCOPE_WEIGHT);
298
+ // Ablation arm (DSH_LONGLIVE_SCOPE=0): title + body prose only, i.e. what
299
+ // rc.5 actually had. Without a declared scope the body is the only vocabulary.
300
+ if (ROUTING_SCOPE_DISABLED || scope === '') {
301
+ add(tf, contentTokens(parsed.body ?? stripFrontmatterText(raw)), ROUTING_BODY_WEIGHT);
302
+ }
303
+ return { card, scope, tf };
304
+ });
305
+ const df = new Map();
306
+ for (const doc of docs) for (const token of doc.tf.keys()) df.set(token, (df.get(token) ?? 0) + 1);
307
+ const idf = (token) => Math.log((docs.length + 1) / ((df.get(token) ?? 0) + 0.5));
308
+ return { docs, idf, df };
309
+ }
310
+
311
+ /** Coverage: how much of the paragraph's IDF mass the card's declared scope explains. */
312
+ function coverageScore(paragraphTokens, doc, index) {
313
+ let matched = 0;
314
+ let total = 0;
315
+ for (const [token, n] of paragraphTokens) {
316
+ const w = n * index.idf(token);
317
+ total += w;
318
+ if (doc.tf.has(token)) matched += w;
319
+ }
320
+ return total ? matched / total : 0;
321
+ }
322
+
323
+ const cosineScore = coverageScore;
324
+
325
+ function splitSentences(text) {
326
+ return String(text ?? '')
327
+ .split(/\n|(?<=[。!?!?])/)
328
+ .map((part) => part.trim())
329
+ .filter(Boolean);
330
+ }
331
+
332
+ function evidenceQuality(span) {
333
+ const cjk = (span.match(/[\u4e00-\u9fff]/g) ?? []).length;
334
+ const latin = (span.match(/[a-zA-Z]/g) ?? []).length;
335
+ return cjk >= 2 || latin >= 3;
336
+ }
337
+
338
+ /** Pick the sentence sharing the most IDF mass with the chosen card; always an exact substring. */
339
+ function pickQuote(paragraph, doc, index) {
340
+ const sentences = splitSentences(paragraph);
341
+ let best = null;
342
+ for (const sentence of sentences) {
343
+ if (!evidenceQuality(sentence)) continue;
344
+ let mass = 0;
345
+ for (const [token, n] of contentTokens(sentence)) {
346
+ if (doc && doc.tf.has(token)) mass += n * index.idf(token);
347
+ }
348
+ if (!best || mass > best.mass) best = { sentence, mass };
349
+ }
350
+ const raw = best?.sentence ?? sentences.find(evidenceQuality) ?? String(paragraph ?? '');
351
+ return raw.slice(0, 120);
352
+ }
353
+
354
+ /** The conclusion/decision sentence — what the proposal should actually carry. */
355
+ function pickClaim(paragraph) {
356
+ const sentences = splitSentences(paragraph).filter(evidenceQuality);
357
+ let best = null;
358
+ for (const sentence of sentences) {
359
+ let score = 0;
360
+ if (CONCLUSION_PATTERN.test(sentence)) score += 3;
361
+ if (/\d/.test(sentence)) score += 1;
362
+ if (/[::]/.test(sentence)) score += 1;
363
+ score += Math.min(sentence.length / 60, 1);
364
+ if (!best || score > best.score) best = { sentence, score };
365
+ }
366
+ return (best?.sentence ?? sentences[0] ?? String(paragraph ?? '')).slice(0, 160);
367
+ }
368
+
369
+ function bestTarget(paragraph, index) {
370
+ const paragraphTokens = contentTokens(paragraph);
371
+ if (paragraphTokens.size === 0) return null;
372
+ const claim = pickClaim(paragraph);
373
+ // Route on the claim sentence, not the whole paragraph: a long log entry is
374
+ // mostly symptoms and timestamps, and its last conclusion is what should pick
375
+ // the card. Fall back to the whole paragraph when the claim is too short.
376
+ const claimTokens = contentTokens(claim);
377
+ const routingTokens = claimTokens.size >= 4 ? claimTokens : paragraphTokens;
378
+ const ranked = index.docs
379
+ .map((doc) => ({ doc, score: cosineScore(routingTokens, doc, index) }))
380
+ .sort((a, b) => b.score - a.score);
381
+ const best = ranked[0];
382
+ const quote = pickQuote(paragraph, best?.doc, index);
383
+
384
+ // A plan/priority statement is not a topic fact: 13 topic cards cannot own
385
+ // "do memory first, park music" — the honest proposal is a new card.
386
+ if (PLAN_PATTERN.test(paragraph)) {
387
+ return {
388
+ card: null,
389
+ score: best?.score ?? 0,
390
+ quote,
391
+ claim,
392
+ reason: `原文引用『${quote}』;这是排期/优先级指令,没有主题卡对应,建议新建卡`,
393
+ };
394
+ }
395
+ // Below the floor the best card shares only generic words; say so instead of
396
+ // filing the paragraph into a card it has nothing to do with.
397
+ if (!best || best.score < ROUTING_MIN_COVERAGE) {
398
+ return {
399
+ card: null,
400
+ score: best?.score ?? 0,
401
+ quote,
402
+ claim,
403
+ reason: `原文引用『${quote}』;没有足够的话题重合,建议新建卡(最高覆盖 ${((best?.score ?? 0) * 100).toFixed(0)}%)`,
404
+ };
405
+ }
406
+ const matched = [...routingTokens.keys()]
407
+ .filter((token) => best.doc.tf.has(token))
408
+ .sort((a, b) => index.idf(b) - index.idf(a))
409
+ .slice(0, 3);
410
+ return {
411
+ card: best.doc.card,
412
+ score: best.score,
413
+ quote,
414
+ claim,
415
+ reason: `原文引用『${quote}』;话题命中「${matched.join('、')}」`,
416
+ };
417
+ }
418
+
419
+ function reportText({
420
+ root, sinceDay, files, proposals, undated, badAffect, duplicates,
421
+ stateUpdated, lastConsolidated,
422
+ }) {
423
+ const lines = [
424
+ '# 巩固提案',
425
+ '',
426
+ `- 生成时间:${isoStamp()}`,
427
+ `- 记忆根:${root}`,
428
+ `- 增量起点:${sinceDay ?? '(无,读全部 journal)'}`,
429
+ `- journal 文件:${files.length}`,
430
+ `- 提案:${proposals.length}`,
431
+ `- 去重跳过(seenProposals 已见):${duplicates}`,
432
+ `- 状态:${stateUpdated ? `lastConsolidated → ${lastConsolidated}` : '未推进(仍有未决提案)'}`,
433
+ `- badAffect:${badAffect.length}`,
434
+ '',
435
+ ];
436
+ if (proposals.length === 0) {
437
+ lines.push('本次没有需要归档的新增段落(已见提案不会重复列出)。', '');
438
+ }
439
+ proposals.forEach((proposal, index) => {
440
+ lines.push(`## 提案 ${index + 1}`);
441
+ lines.push('');
442
+ lines.push(`- 提案 id:${proposal.id}`);
443
+ lines.push(`- 来源:${proposal.source}`);
444
+ if (proposal.lineStart) {
445
+ lines.push(`- 行号:${proposal.lineStart}${proposal.lineEnd && proposal.lineEnd !== proposal.lineStart ? `-${proposal.lineEnd}` : ''}`);
446
+ }
447
+ lines.push(`- 摘录:${proposal.excerpt}`);
448
+ lines.push(`- 原文引用:${proposal.quote ?? '(无)'}`);
449
+ lines.push(`- 结论句:${proposal.claim ?? '(无)'}`);
450
+ lines.push(`- 目标卡:${proposal.target ?? '(无匹配)'}${proposal.targetTitle ? `(${proposal.targetTitle})` : ''}`);
451
+ lines.push(`- 理由:${proposal.reason}`);
452
+ lines.push(`- 建议 salience:${proposal.suggestedSalience}`);
453
+ lines.push(`- salienceSource:${proposal.salienceSource}`);
454
+ lines.push(`- 标记理由:${proposal.affectReason ?? '(无标记,按正则/默认)'}`);
455
+ lines.push('');
456
+ });
457
+ if (badAffect.length) {
458
+ lines.push('## badAffect(坏掉的情绪标记,已忽略)', '');
459
+ for (const item of badAffect) {
460
+ lines.push(`- ${item.source}:「${item.marker}」— ${item.code} ${item.message}`);
461
+ }
462
+ lines.push('');
463
+ }
464
+ if (undated.length) {
465
+ lines.push('## 无日期的段落(未纳入增量)', '');
466
+ for (const item of undated) lines.push(`- ${item.source}:${item.excerpt}`);
467
+ lines.push('');
468
+ }
469
+ lines.push('> 本报告只提议,不改任何卡;state 只记录提案 id 与推进点。');
470
+ return `${lines.join('\n')}\n`;
471
+ }
472
+
473
+ function lastDayOf(value) {
474
+ if (typeof value !== 'string') return null;
475
+ if (isDayString(value)) return value.trim();
476
+ return /^\d{4}-\d{2}-\d{2}/.test(value) ? value.slice(0, 10) : null;
477
+ }
478
+
479
+ function proposalBacklog(entries) {
480
+ const list = Array.isArray(entries) ? entries.filter((entry) => entry && typeof entry.id === 'string') : [];
481
+ const counts = { proposed: 0, accepted: 0, rejected: 0, superseded: 0 };
482
+ for (const entry of list) {
483
+ const status = RESOLVED_STATUS.has(entry.status) ? entry.status : 'proposed';
484
+ counts[status] += 1;
485
+ }
486
+ const days = new Map();
487
+ for (const entry of list) {
488
+ const status = RESOLVED_STATUS.has(entry.status) ? entry.status : 'proposed';
489
+ if (!days.has(entry.day)) days.set(entry.day, { proposed: 0, resolved: 0 });
490
+ const day = days.get(entry.day);
491
+ if (status === 'proposed') day.proposed += 1;
492
+ else day.resolved += 1;
493
+ }
494
+ return {
495
+ total: list.length,
496
+ pending: counts.proposed,
497
+ resolved: counts.accepted + counts.rejected + counts.superseded,
498
+ ...counts,
499
+ byDay: [...days.entries()].filter(([day]) => typeof day === 'string').sort(([a], [b]) => a.localeCompare(b))
500
+ .map(([day, countsDay]) => ({ day, ...countsDay })),
501
+ };
502
+ }
503
+
504
+ function advanceLastConsolidated(state, entries) {
505
+ const current = lastDayOf(state.lastConsolidated);
506
+ const days = [...new Set(entries.map((entry) => entry.day).filter((day) => typeof day === 'string'))].sort();
507
+ let last = current;
508
+ for (const day of days) {
509
+ if (last !== null && day <= last) continue;
510
+ const dayEntries = entries.filter((entry) => entry.day === day);
511
+ if (dayEntries.length > 0 && dayEntries.every((entry) => RESOLVED_STATUS.has(entry.status))) last = day;
512
+ }
513
+ return last;
514
+ }
515
+
516
+ /**
517
+ * Accept or reject one consolidation proposal.
518
+ *
519
+ * accept -> write a NEW topic card through the normal `writeCard` path (old
520
+ * cards are never edited) + audit; reject -> record the operator's reason +
521
+ * audit. Both advance lastConsolidated over fully resolved days.
522
+ */
523
+ export function resolveConsolidationProposal(args = {}, config = {}) {
524
+ const action = args.action;
525
+ if (action !== 'accept' && action !== 'reject') {
526
+ throw memoryError('E_BAD_ARGUMENT', 'consolidation resolve 需要 action=accept|reject');
527
+ }
528
+ const proposalIdValue = typeof args.proposalId === 'string' ? args.proposalId.trim() : '';
529
+ if (!/^[0-9a-f]{12}$/i.test(proposalIdValue)) throw memoryError('E_BAD_ARGUMENT', '需要 12 位 proposalId');
530
+ const root = memoryRootFromConfig(config);
531
+ const now = config.now instanceof Date ? config.now : new Date();
532
+ const state = readState(root);
533
+ const entries = (Array.isArray(state.seenProposals) ? state.seenProposals : [])
534
+ .filter((entry) => entry && typeof entry.id === 'string');
535
+ const index = entries.findIndex((entry) => entry.id === proposalIdValue);
536
+ if (index < 0) throw memoryError('E_PROPOSAL_NOT_FOUND', `找不到提案 ${proposalIdValue}`);
537
+ const entry = entries[index];
538
+ if (RESOLVED_STATUS.has(entry.status)) {
539
+ throw memoryError('E_PROPOSAL_RESOLVED', `提案 ${proposalIdValue} 已是 ${entry.status}`);
540
+ }
541
+ let card = null;
542
+ let audited = null;
543
+ if (action === 'accept') {
544
+ const rel = `topics/consolidated/${proposalIdValue}.md`;
545
+ const title = collapse(entry.excerpt ?? entry.claim ?? proposalIdValue).slice(0, 80);
546
+ const claim = collapse(entry.claim ?? entry.excerpt ?? '').slice(0, 400);
547
+ const body = [
548
+ `# ${title}`,
549
+ '',
550
+ claim,
551
+ '',
552
+ `- proposal: ${proposalIdValue}`,
553
+ `- source: ${entry.source ?? 'journal'}${entry.lineStart ? `:${entry.lineStart}-${entry.lineEnd}` : ''}`,
554
+ `- accepted_at: ${now.toISOString()}`,
555
+ ].join('\n');
556
+ card = writeCard(root, {
557
+ rel,
558
+ title,
559
+ body,
560
+ fields: {
561
+ date: entry.day ?? dayString(now),
562
+ tags: ['consolidation'],
563
+ salience: Number.isInteger(entry.salience) ? entry.salience : 3,
564
+ },
565
+ extras: {
566
+ consolidation_proposal: proposalIdValue,
567
+ source_journal: entry.source ?? '',
568
+ source_lines: entry.lineStart ? `${entry.lineStart}-${entry.lineEnd}` : '',
569
+ },
570
+ }, { now });
571
+ entries[index] = { ...entry, status: 'accepted', resolvedAt: now.toISOString(), card: rel };
572
+ } else {
573
+ const reason = collapse(args.reason ?? '').slice(0, 300);
574
+ if (reason === '') throw memoryError('E_BAD_ARGUMENT', 'reject 需要 reason');
575
+ entries[index] = { ...entry, status: 'rejected', resolvedAt: now.toISOString(), reason };
576
+ }
577
+ const lastConsolidated = advanceLastConsolidated(state, entries);
578
+ updateState(root, {
579
+ seenProposals: entries,
580
+ ...(lastConsolidated !== lastDayOf(state.lastConsolidated) ? { lastConsolidated } : {}),
581
+ }, { now });
582
+ const actionName = action === 'accept' ? 'memory_consolidate_accept' : 'memory_consolidate_reject';
583
+ audited = appendAudit(root, {
584
+ action: actionName,
585
+ object: proposalIdValue,
586
+ result: action === 'accept'
587
+ ? `card=${card.rel}`
588
+ : `reason=${collapse(args.reason ?? '').slice(0, 200)}`,
589
+ now,
590
+ });
591
+ const backlog = proposalBacklog(entries);
592
+ return {
593
+ ok: true,
594
+ status: action,
595
+ proposalId: proposalIdValue,
596
+ card: card ? { rel: card.rel, sha256: card.sha256 ?? null } : null,
597
+ reason: action === 'reject' ? collapse(args.reason ?? '') : null,
598
+ lastConsolidated,
599
+ backlog,
600
+ audit: audited,
601
+ message: `${action === 'accept' ? '已接受' : '已拒绝'}提案 ${proposalIdValue};积压 ${backlog.pending} 条,lastConsolidated=${lastConsolidated ?? 'null'}`,
602
+ };
603
+ }
604
+
605
+ /**
606
+ * memory_consolidate: read-only with respect to cards. Writes exactly one
607
+ * report file; the state file gains new `seenProposals` entries and, only when
608
+ * every proposal of the newest scanned day is resolved, a new
609
+ * `lastConsolidated`. No card is ever edited.
610
+ */
611
+ export function memoryConsolidate(args = {}, config = {}) {
612
+ if (args.apply === true) {
613
+ throw memoryError('E_READ_ONLY', 'memory_consolidate 只出提案,不支持 apply — 请人工决定后再改卡');
614
+ }
615
+ if (args.action === 'accept' || args.action === 'reject') return resolveConsolidationProposal({ ...args, proposalId: args.proposalId ?? args.id }, config);
616
+ if (args.action === 'status') {
617
+ const statusRoot = memoryRootFromConfig(config);
618
+ const statusState = readState(statusRoot);
619
+ return {
620
+ ok: true,
621
+ status: 'backlog',
622
+ readOnly: true,
623
+ root: statusRoot,
624
+ backlog: proposalBacklog(statusState.seenProposals),
625
+ lastConsolidated: statusState.lastConsolidated ?? null,
626
+ };
627
+ }
628
+ if (args.action !== undefined && args.action !== 'report') {
629
+ throw memoryError('E_BAD_ARGUMENT', `memory_consolidate 不支持的 action:${JSON.stringify(args.action)}`);
630
+ }
631
+ const root = memoryRootFromConfig(config);
632
+ const now = config.now instanceof Date ? config.now : new Date();
633
+ const day = config.today ?? dayString(now);
634
+ const state = readState(root);
635
+ const requestedSince = typeof args.since === 'string' && args.since.trim() ? args.since.trim() : null;
636
+ const rawSince = requestedSince ?? state.lastConsolidated;
637
+ const sinceDay = isDayString(rawSince)
638
+ ? rawSince.slice(0, 10)
639
+ : (typeof rawSince === 'string' && /^\d{4}-\d{2}-\d{2}/.test(rawSince) ? rawSince.slice(0, 10) : null);
640
+
641
+ const seenProposals = (Array.isArray(state.seenProposals) ? state.seenProposals : [])
642
+ .filter((entry) => entry && typeof entry.id === 'string');
643
+ const seenById = new Map(seenProposals.map((entry) => [entry.id, entry]));
644
+ // Entry splitting is opt-in: a blank-line block may hold several `- ` entries,
645
+ // but cut points are only safe when the caller knows segment labels do not
646
+ // overlap (F6 in the A-group manifest: A-14 L59-73 and A-15 L71-72 do overlap).
647
+ const entrySplit = args.entrySplit === true;
648
+ const newEntries = [];
649
+ const allTopicCards = scanCards(root).filter((card) => card.rel.startsWith('topics/'));
650
+ // Locked cards are core memory: they are never merge targets (and journal
651
+ // paragraphs are never merged into them), so distill can not erode them.
652
+ const lockedSkipped = allTopicCards.filter((card) => (card.fields.status ?? 'active') === 'locked').length;
653
+ const topicCards = allTopicCards.filter((card) => (card.fields.status ?? 'active') !== 'locked');
654
+ const cardIndex = buildCardIndex(topicCards);
655
+ const files = listMarkdownFiles(root, 'journal');
656
+ const proposals = [];
657
+ const undated = [];
658
+ const badAffect = [];
659
+ const scannedDays = new Set();
660
+ let entries = 0;
661
+ let duplicates = 0;
662
+
663
+ for (const abs of files) {
664
+ const rel = relativePath(root, abs);
665
+ const text = fs.readFileSync(abs, 'utf8');
666
+ const parsed = parseFrontmatter(text);
667
+ const fileDay = journalDay(rel, parsed.fields);
668
+ // paragraphUnits numbers lines inside the body; shift them to file lines.
669
+ const lineOffset = text.slice(0, parsed.bodyStart).split(/\r?\n/).length - 1;
670
+ if (sinceDay && !fileDay) {
671
+ for (const unit of paragraphUnits(parsed.body, { lineOffset })) {
672
+ undated.push({ source: rel, excerpt: collapse(stripComments(unit.text)).slice(0, 120) });
673
+ }
674
+ continue;
675
+ }
676
+ if (sinceDay && fileDay <= sinceDay) continue;
677
+ if (fileDay) scannedDays.add(fileDay);
678
+
679
+ for (const unit of paragraphUnits(parsed.body, { splitEntries: entrySplit, lineOffset })) {
680
+ entries += 1;
681
+ const paragraphText = collapse(stripComments(unit.text));
682
+ const affect = parseAffect(unit.text);
683
+ for (const bad of affect.bad) {
684
+ badAffect.push({
685
+ source: rel,
686
+ date: fileDay,
687
+ excerpt: paragraphText.slice(0, 120),
688
+ marker: bad.marker,
689
+ code: bad.code,
690
+ message: bad.message,
691
+ });
692
+ }
693
+ const id = proposalId(rel, paragraphText);
694
+ if (seenById.has(id)) {
695
+ duplicates += 1;
696
+ continue;
697
+ }
698
+ const target = bestTarget(paragraphText, cardIndex);
699
+ const claim = target?.claim ?? paragraphText.slice(0, 160);
700
+ const proposal = {
701
+ id,
702
+ source: rel,
703
+ lineStart: unit.startLine,
704
+ lineEnd: unit.endLine,
705
+ date: fileDay,
706
+ excerpt: claim.slice(0, 120),
707
+ claim,
708
+ quote: target?.quote ?? null,
709
+ target: target?.card?.rel ?? null,
710
+ targetTitle: target?.card?.title ?? null,
711
+ reason: target?.reason ?? '没有明确匹配的主题卡,建议人工决定是否新建',
712
+ suggestedSalience: affect.salience,
713
+ salienceSource: affect.salienceSource,
714
+ affectReason: affect.affectReason,
715
+ };
716
+ proposals.push(proposal);
717
+ const entry = {
718
+ id,
719
+ status: 'proposed',
720
+ day: fileDay ?? day,
721
+ source: rel,
722
+ lineStart: unit.startLine,
723
+ lineEnd: unit.endLine,
724
+ excerpt: proposal.excerpt,
725
+ target: proposal.target,
726
+ targetTitle: proposal.targetTitle,
727
+ salience: proposal.suggestedSalience,
728
+ salienceSource: proposal.salienceSource,
729
+ proposedAt: day,
730
+ };
731
+ newEntries.push(entry);
732
+ seenById.set(id, entry);
733
+ }
734
+ }
735
+
736
+ // The newest day this run actually scanned is the only candidate for the
737
+ // incremental pointer. It moves only when every proposal recorded for that
738
+ // day is resolved; newly proposed ids keep it pinned, which is the point.
739
+ const candidateDay = [...scannedDays].sort().pop() ?? null;
740
+ const currentLastDay = lastDayOf(state.lastConsolidated);
741
+ const allEntries = [...seenProposals, ...newEntries];
742
+ const backlog = proposalBacklog(allEntries);
743
+ let lastConsolidated = state.lastConsolidated ?? null;
744
+ let stateUpdated = false;
745
+ if (candidateDay) {
746
+ const dayEntries = allEntries.filter((entry) => entry.day === candidateDay);
747
+ const unresolved = dayEntries.filter((entry) => !RESOLVED_STATUS.has(entry.status));
748
+ if (dayEntries.length > 0 && unresolved.length === 0 && (!currentLastDay || candidateDay > currentLastDay)) {
749
+ lastConsolidated = candidateDay;
750
+ stateUpdated = true;
751
+ }
752
+ }
753
+
754
+ const stateChanged = newEntries.length > 0 || stateUpdated;
755
+ let stateWrite = null;
756
+ if (stateChanged) {
757
+ stateWrite = updateState(root, {
758
+ ...(stateUpdated ? { lastConsolidated } : {}),
759
+ seenProposals: allEntries,
760
+ }, { now });
761
+ }
762
+
763
+ const dir = reportsDir(root);
764
+ ensureDir(root, dir);
765
+ const reportPath = resolveInside(root, path.join('.longlive', 'reports', `consolidate-${day}.md`));
766
+ const content = `${reportText({
767
+ root, sinceDay, files, proposals, undated, badAffect, duplicates,
768
+ stateUpdated, lastConsolidated: lastDayOf(lastConsolidated) ?? lastConsolidated,
769
+ })}\n- 提案积压:${backlog.pending} 待决 / ${backlog.total} 总数(accepted ${backlog.accepted}, rejected ${backlog.rejected})\n`;
770
+ if (fs.existsSync(reportPath)) {
771
+ const backupDir = resolveInside(root, path.join('.longlive', 'reports', '.backups'));
772
+ ensureDir(root, backupDir);
773
+ const stamp = isoStamp(now).replace(/[:.]/g, '-');
774
+ let backupName = `consolidate-${day}.${stamp}.md`;
775
+ // Two runs inside one millisecond used to produce the same backup name and
776
+ // the second copy silently overwrote the first. Never reuse a name.
777
+ for (let suffix = 2; fs.existsSync(path.join(backupDir, backupName)); suffix += 1) {
778
+ backupName = `consolidate-${day}.${stamp}-${suffix}.md`;
779
+ }
780
+ fs.copyFileSync(reportPath, path.join(backupDir, backupName));
781
+ }
782
+ const write = writeFileAtomic(root, reportPath, content, { backup: false, now });
783
+
784
+ return {
785
+ ok: true,
786
+ status: 'report',
787
+ readOnly: true,
788
+ stateUpdated,
789
+ stateWritten: stateChanged,
790
+ previousLastConsolidated: state.lastConsolidated ?? null,
791
+ lastConsolidated: lastDayOf(lastConsolidated) ?? null,
792
+ root,
793
+ since: sinceDay,
794
+ journalFiles: files.length,
795
+ entries,
796
+ proposals,
797
+ duplicatesSuppressed: duplicates,
798
+ lockedSkipped,
799
+ seenProposals: allEntries.length,
800
+ backlog,
801
+ badAffect,
802
+ undated,
803
+ reportPath,
804
+ reportRel: relativePath(root, reportPath),
805
+ sha256: write.sha256,
806
+ message:
807
+ `只读提案:${entries} 段增量 → ${proposals.length} 个新提案(已见跳过 ${duplicates} 段),` +
808
+ `badAffect ${badAffect.length} 条;locked 目标跳过 ${lockedSkipped} 张;报告 ${relativePath(root, reportPath)};` +
809
+ `${stateUpdated ? `lastConsolidated 推进到 ${lastConsolidated}` : 'lastConsolidated 未推进'};卡未改动`,
810
+ };
811
+ }
812
+
813
+ export {
814
+ contentTokens, buildCardIndex, cosineScore, coverageScore, pickQuote, pickClaim, paragraphUnits,
815
+ };