@jjh32456/longlive 0.0.0-stage → 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 (331) hide show
  1. package/CHANGELOG.md +235 -0
  2. package/LICENSE +21 -0
  3. package/QUICKSTART.md +362 -0
  4. package/README.en.md +64 -0
  5. package/README.md +256 -2
  6. package/SPEC.md +211 -0
  7. package/build-info.json +1665 -0
  8. package/cordis.patch.yml +208 -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 +839 -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 +48 -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 +163 -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-200.mjs +8 -0
  55. package/scripts/migrate-a1-legacy.mjs +62 -0
  56. package/scripts/migrate-lifecycle.mjs +157 -0
  57. package/scripts/pack.mjs +392 -0
  58. package/scripts/recall-index-build.mjs +128 -0
  59. package/scripts/recall-links-build.mjs +420 -0
  60. package/scripts/rescore-cards.mjs +36 -0
  61. package/scripts/resident-watcher-status.ps1 +15 -0
  62. package/scripts/resident-watcher.ps1 +643 -0
  63. package/scripts/session-watch-drill.mjs +553 -0
  64. package/scripts/session-watch-status.ps1 +146 -0
  65. package/scripts/session-watch.mjs +1367 -0
  66. package/scripts/surgery-inspect.mjs +122 -0
  67. package/scripts/surgery-run.cmd +34 -0
  68. package/scripts/truncate-cli.mjs +279 -0
  69. package/scripts/unattended-surgery.ps1 +1019 -0
  70. package/scripts/uninstall-resident-watcher.ps1 +15 -0
  71. package/scripts/uninstall-session-watch.ps1 +192 -0
  72. package/scripts/verify-card-anchors.mjs +138 -0
  73. package/scripts/watch-loop.ps1 +916 -0
  74. package/src/actions/audit.js +125 -0
  75. package/src/actions/evidence.js +122 -0
  76. package/src/actions/fs.js +162 -0
  77. package/src/activity/index.js +873 -0
  78. package/src/activity/model.js +351 -0
  79. package/src/activity/store.js +786 -0
  80. package/src/activity/summary.js +180 -0
  81. package/src/activity/thinking.js +191 -0
  82. package/src/adapters/constants.js +11 -0
  83. package/src/adapters/engram/data/aliases.json +51 -0
  84. package/src/adapters/engram/data/policy.json +8 -0
  85. package/src/adapters/engram/data/routing-rules.json +546 -0
  86. package/src/adapters/engram/index.js +278 -0
  87. package/src/adapters/registry.js +315 -0
  88. package/src/answer/audit.js +238 -0
  89. package/src/answer/claim-guard.mjs +234 -0
  90. package/src/answer/evidence.js +30 -0
  91. package/src/answer/guard.js +1370 -0
  92. package/src/answer/index.js +1086 -0
  93. package/src/answer/query.js +111 -0
  94. package/src/answer/second-hop.mjs +101 -0
  95. package/src/auto-truncate-status.js +164 -0
  96. package/src/auto-truncate.js +1181 -0
  97. package/src/autoprocedure/candidate.js +342 -0
  98. package/src/autoprocedure/config.js +122 -0
  99. package/src/autoprocedure/evidence.js +345 -0
  100. package/src/autoprocedure/index.js +83 -0
  101. package/src/autoprocedure/ledger.js +329 -0
  102. package/src/autoprocedure/lint.js +232 -0
  103. package/src/autoprocedure/llm.js +409 -0
  104. package/src/autoprocedure/locks.js +102 -0
  105. package/src/autoprocedure/paths.js +39 -0
  106. package/src/autoprocedure/privacy.js +87 -0
  107. package/src/autoprocedure/rules.js +288 -0
  108. package/src/autoprocedure/runtime.js +718 -0
  109. package/src/autoprocedure/session-reader.js +328 -0
  110. package/src/backup.js +310 -0
  111. package/src/bus/bus.mjs +1446 -0
  112. package/src/codec.js +269 -0
  113. package/src/compaction/cut-engine.js +44 -0
  114. package/src/compaction/engine-core.js +1237 -0
  115. package/src/compaction/entry.js +228 -0
  116. package/src/compaction.js +230 -0
  117. package/src/conclusion.js +366 -0
  118. package/src/config.js +835 -0
  119. package/src/d6/runtime.js +517 -0
  120. package/src/d6/surface.js +181 -0
  121. package/src/deps.js +189 -0
  122. package/src/engine-status.js +141 -0
  123. package/src/features.js +1035 -0
  124. package/src/handoff/index.js +1077 -0
  125. package/src/handoff/model.js +1058 -0
  126. package/src/handoff/store.js +1233 -0
  127. package/src/heartbeat.js +385 -0
  128. package/src/home.js +16 -0
  129. package/src/host-version.js +280 -0
  130. package/src/hot-truncate-diag.js +98 -0
  131. package/src/identity/card-marker.js +281 -0
  132. package/src/identity/handover.js +845 -0
  133. package/src/identity/index.js +337 -0
  134. package/src/identity/inject-position.js +133 -0
  135. package/src/identity/writeback.js +344 -0
  136. package/src/identity.js +118 -0
  137. package/src/index.js +647 -0
  138. package/src/lifecycle/gap-clocks.js +364 -0
  139. package/src/lifecycle/index.js +269 -0
  140. package/src/lifecycle/proactive.js +1426 -0
  141. package/src/live-target.js +212 -0
  142. package/src/live.js +1603 -0
  143. package/src/log-rotation.js +153 -0
  144. package/src/memory/a1-migration.js +190 -0
  145. package/src/memory/activity-capture.js +229 -0
  146. package/src/memory/anchor-fallback.js +116 -0
  147. package/src/memory/anchors.js +194 -0
  148. package/src/memory/archive-cold-state.mjs +794 -0
  149. package/src/memory/archive-staging.mjs +305 -0
  150. package/src/memory/archive.mjs +415 -0
  151. package/src/memory/audit-records.js +222 -0
  152. package/src/memory/auto-cards.js +441 -0
  153. package/src/memory/capture-host.js +297 -0
  154. package/src/memory/capture.js +496 -0
  155. package/src/memory/card-anchors.js +203 -0
  156. package/src/memory/card-priority.js +110 -0
  157. package/src/memory/cards.js +425 -0
  158. package/src/memory/catchup.mjs +534 -0
  159. package/src/memory/conclusion-distill.js +381 -0
  160. package/src/memory/conclusion-drafts.js +243 -0
  161. package/src/memory/conflicts.js +1060 -0
  162. package/src/memory/consolidate.js +834 -0
  163. package/src/memory/decay.js +311 -0
  164. package/src/memory/distill.js +485 -0
  165. package/src/memory/event-index.js +1826 -0
  166. package/src/memory/evidence-chain.js +295 -0
  167. package/src/memory/evidence.js +213 -0
  168. package/src/memory/filter-runner.js +555 -0
  169. package/src/memory/filter.js +1035 -0
  170. package/src/memory/forget-v2.js +680 -0
  171. package/src/memory/forget.js +531 -0
  172. package/src/memory/frames-activation.js +249 -0
  173. package/src/memory/frontmatter.js +454 -0
  174. package/src/memory/fts-query.js +342 -0
  175. package/src/memory/governance.js +604 -0
  176. package/src/memory/index-freshness.js +234 -0
  177. package/src/memory/index.js +435 -0
  178. package/src/memory/l2-gate.js +169 -0
  179. package/src/memory/land.mjs +743 -0
  180. package/src/memory/lifecycle.js +235 -0
  181. package/src/memory/lock.js +121 -0
  182. package/src/memory/maintenance.js +1149 -0
  183. package/src/memory/manifest.js +245 -0
  184. package/src/memory/memory-health.mjs +607 -0
  185. package/src/memory/migrate-200.js +1681 -0
  186. package/src/memory/migrate-lifecycle.js +1808 -0
  187. package/src/memory/migrate.js +139 -0
  188. package/src/memory/paths.js +229 -0
  189. package/src/memory/procedure-candidate.mjs +377 -0
  190. package/src/memory/procedure.js +982 -0
  191. package/src/memory/prospective-memory.mjs +362 -0
  192. package/src/memory/provenance.js +119 -0
  193. package/src/memory/recall-feedback.mjs +406 -0
  194. package/src/memory/recall-v2.js +218 -0
  195. package/src/memory/recall.js +357 -0
  196. package/src/memory/reconcile.js +265 -0
  197. package/src/memory/records.js +433 -0
  198. package/src/memory/reinforce.js +281 -0
  199. package/src/memory/retention.js +162 -0
  200. package/src/memory/review.js +124 -0
  201. package/src/memory/state.js +279 -0
  202. package/src/memory/tiers.js +168 -0
  203. package/src/memory/topic-phrases.js +73 -0
  204. package/src/memory/trust.js +97 -0
  205. package/src/memory/turn-budget.mjs +290 -0
  206. package/src/memory/version-chain.js +264 -0
  207. package/src/memory/wake-bridge.mjs +2999 -0
  208. package/src/memory/wal.js +137 -0
  209. package/src/memory/working-frame.js +779 -0
  210. package/src/metrics/classify.mjs +191 -0
  211. package/src/metrics/estimate.mjs +108 -0
  212. package/src/metrics/index.mjs +204 -0
  213. package/src/metrics/measure.mjs +462 -0
  214. package/src/metrics/prestep-latency.mjs +307 -0
  215. package/src/metrics/store.mjs +264 -0
  216. package/src/original.js +294 -0
  217. package/src/policy/threshold-policy.js +224 -0
  218. package/src/policy-profile.js +463 -0
  219. package/src/recall/anaphora.mjs +87 -0
  220. package/src/recall/archive-config.mjs +130 -0
  221. package/src/recall/archive-fallback.mjs +390 -0
  222. package/src/recall/archive-search.mjs +428 -0
  223. package/src/recall/archive-state.mjs +588 -0
  224. package/src/recall/brain.mjs +501 -0
  225. package/src/recall/cards.mjs +202 -0
  226. package/src/recall/current-line.mjs +110 -0
  227. package/src/recall/edges.js +398 -0
  228. package/src/recall/embedding.mjs +698 -0
  229. package/src/recall/entities.mjs +112 -0
  230. package/src/recall/explain.mjs +443 -0
  231. package/src/recall/force-policy.mjs +138 -0
  232. package/src/recall/gate-log.mjs +280 -0
  233. package/src/recall/gate-metrics.mjs +191 -0
  234. package/src/recall/index.js +1337 -0
  235. package/src/recall/inject-order.mjs +279 -0
  236. package/src/recall/link-recall.mjs +183 -0
  237. package/src/recall/links.mjs +696 -0
  238. package/src/recall/privacy.mjs +208 -0
  239. package/src/recall/recall-core.mjs +810 -0
  240. package/src/recall/shared-visibility.js +302 -0
  241. package/src/recall/time-normalizer.mjs +196 -0
  242. package/src/recall/turn-budget-inject.mjs +154 -0
  243. package/src/retention/cold-gate.mjs +146 -0
  244. package/src/retention/config.js +163 -0
  245. package/src/retention/index.js +801 -0
  246. package/src/role/activation.js +191 -0
  247. package/src/role/attention.js +318 -0
  248. package/src/role/base.js +36 -0
  249. package/src/role/channels.js +423 -0
  250. package/src/role/index.js +425 -0
  251. package/src/role/interfaces.js +115 -0
  252. package/src/role/personality.js +370 -0
  253. package/src/role/readers.js +151 -0
  254. package/src/role/relationships.js +477 -0
  255. package/src/role/store.js +202 -0
  256. package/src/role/writeprotect.js +373 -0
  257. package/src/router/aliases.json +182 -0
  258. package/src/router/background/agent-runner.mjs +239 -0
  259. package/src/router/background/anchor.mjs +323 -0
  260. package/src/router/background/audit.mjs +337 -0
  261. package/src/router/background/budget-ledger.mjs +648 -0
  262. package/src/router/background/host-sim.mjs +451 -0
  263. package/src/router/background/index.mjs +81 -0
  264. package/src/router/background/memory.mjs +63 -0
  265. package/src/router/background/mock-llm.mjs +203 -0
  266. package/src/router/background/queue.mjs +224 -0
  267. package/src/router/background/retry.mjs +255 -0
  268. package/src/router/background/router.mjs +1459 -0
  269. package/src/router/background/stream.mjs +276 -0
  270. package/src/router/background/tool-policy.mjs +255 -0
  271. package/src/router/design-headings.json +221 -0
  272. package/src/router/face/config.mjs +155 -0
  273. package/src/router/face/context.mjs +284 -0
  274. package/src/router/face/face.mjs +466 -0
  275. package/src/router/face/identity.mjs +130 -0
  276. package/src/router/face/index.mjs +65 -0
  277. package/src/router/face/journal.mjs +119 -0
  278. package/src/router/face/llm.mjs +252 -0
  279. package/src/router/face/outbox.mjs +153 -0
  280. package/src/router/face/paths.mjs +54 -0
  281. package/src/router/judge.mjs +987 -0
  282. package/src/router/policies/generic.json +131 -0
  283. package/src/router/route.js +1766 -0
  284. package/src/router/router.mjs +535 -0
  285. package/src/router/routing-rules.json +816 -0
  286. package/src/router/run-sim.mjs +530 -0
  287. package/src/router/runtime.js +569 -0
  288. package/src/router/service/apply.mjs +1218 -0
  289. package/src/router/service/board.mjs +712 -0
  290. package/src/router/service/caller.mjs +131 -0
  291. package/src/router/service/config.mjs +361 -0
  292. package/src/router/service/context.mjs +314 -0
  293. package/src/router/service/hint.mjs +668 -0
  294. package/src/router/service/lease.mjs +494 -0
  295. package/src/router/service/live.mjs +251 -0
  296. package/src/router/service/lock.mjs +550 -0
  297. package/src/router/service/merge.mjs +255 -0
  298. package/src/router/service/model-resolve.mjs +350 -0
  299. package/src/router/service/paths.mjs +168 -0
  300. package/src/router/service/proposals.mjs +1461 -0
  301. package/src/router/service/queue.mjs +477 -0
  302. package/src/router/service/reconcile.mjs +271 -0
  303. package/src/router/service/service.mjs +2998 -0
  304. package/src/router/service/sources.mjs +352 -0
  305. package/src/router/service/status.mjs +520 -0
  306. package/src/router/service/store.mjs +476 -0
  307. package/src/router/service/ticklock.mjs +239 -0
  308. package/src/router/service/tokens.mjs +95 -0
  309. package/src/router/service/tools.mjs +248 -0
  310. package/src/router/service/wake.mjs +544 -0
  311. package/src/router/service/wal.mjs +685 -0
  312. package/src/router/shadow.mjs +821 -0
  313. package/src/surgery-recovery.js +1909 -0
  314. package/src/tool-output.js +485 -0
  315. package/src/tools.js +3262 -0
  316. package/src/truncate-visible.js +2416 -0
  317. package/src/truncate.js +999 -0
  318. package/src/ui/actions.js +1312 -0
  319. package/src/ui/flags.js +259 -0
  320. package/src/ui/panel-api.js +371 -0
  321. package/src/ui/panel-auth.js +251 -0
  322. package/src/ui/panel-integrity.js +243 -0
  323. package/src/ui/routes-readonly.js +759 -0
  324. package/src/ui/routes.js +284 -0
  325. package/src/util/append-store.js +368 -0
  326. package/src/util/local-day.js +30 -0
  327. package/src/util/redact.js +227 -0
  328. package/src/util/stale-locks.js +148 -0
  329. package/src/version.js +99 -0
  330. package/test/fixtures/pre-step-container.mjs +100 -0
  331. package/test/p1_probe.mjs +97 -0
@@ -0,0 +1,555 @@
1
+ // Memory admission filter — passive runtime driver.
2
+ //
3
+ // This module is deliberately boring: it reads journal/*.md and the card
4
+ // catalog, calls the pure classifier in ./filter.js once per paragraph/bullet,
5
+ // and writes the audit trail under <memoryRoot>/.longlive/filter/. It never
6
+ // calls an LLM, never touches journal/topics/external-memory, and never throws into the
7
+ // plugin: every failure is a warning and the next tool call is unaffected.
8
+ //
9
+ // Layout (DESIGN.md §4.2):
10
+ // .longlive/filter/decisions-YYYY-MM-DD.jsonl one panel-ready row per unit
11
+ // .longlive/filter/queue/YYYY-MM-DD.json units that need a human
12
+ // .longlive/filter/runs/YYYY-MM-DDTHHMM.json full run result (maf-1)
13
+ // .longlive/filter/state.json unitId -> decision + policy
14
+ //
15
+ // The panel reads decisions-*.jsonl; the other three are the audit trail.
16
+
17
+ import { createHash } from 'node:crypto';
18
+ import {
19
+ appendFileSync,
20
+ mkdirSync,
21
+ readFileSync,
22
+ readdirSync,
23
+ renameSync,
24
+ statSync,
25
+ writeFileSync,
26
+ } from 'node:fs';
27
+ import { join, relative, resolve, sep } from 'node:path';
28
+ import { fileURLToPath } from 'node:url';
29
+
30
+ import {
31
+ POLICY_VERSION,
32
+ THRESHOLDS,
33
+ classifyEntry,
34
+ normalizeText,
35
+ } from './filter.js';
36
+
37
+ const SCHEMA_VERSION = 'maf-1';
38
+ const FILTER_DIR = ['.longlive', 'filter'];
39
+ const MAX_JOURNAL_FILES = 24;
40
+ const MAX_UNITS = 500;
41
+ const DIM_NAMES = Object.freeze({
42
+ R1: '断言性',
43
+ R2: '复用跨度',
44
+ R3: '禁令/偏好',
45
+ R4: '踩坑修法',
46
+ R5: '决策/取代',
47
+ R6: '去重',
48
+ R7: '关系/身份',
49
+ R8: '产物承载',
50
+ });
51
+
52
+ function pad2(value) {
53
+ return String(value).padStart(2, '0');
54
+ }
55
+
56
+ export function localDate(date = new Date()) {
57
+ return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}`;
58
+ }
59
+
60
+ function localClock(date = new Date()) {
61
+ return `${pad2(date.getHours())}${pad2(date.getMinutes())}`;
62
+ }
63
+
64
+ function sha256(text) {
65
+ return createHash('sha256').update(String(text)).digest('hex');
66
+ }
67
+
68
+ function toPosix(value) {
69
+ return String(value).split(sep).join('/');
70
+ }
71
+
72
+ function readJson(file, fallback = null) {
73
+ try {
74
+ return JSON.parse(readFileSync(file, 'utf8'));
75
+ } catch {
76
+ return fallback;
77
+ }
78
+ }
79
+
80
+ function writeJsonAtomic(file, value) {
81
+ const tmp = `${file}.tmp-${process.pid}`;
82
+ writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
83
+ renameSync(tmp, file);
84
+ }
85
+
86
+ function listMarkdown(dir) {
87
+ try {
88
+ return readdirSync(dir, { withFileTypes: true })
89
+ .filter((entry) => entry.isFile() && entry.name.toLowerCase().endsWith('.md'))
90
+ .map((entry) => join(dir, entry.name))
91
+ .sort();
92
+ } catch {
93
+ return [];
94
+ }
95
+ }
96
+
97
+ /** First meaningful 240 characters of a card, without frontmatter/headings. */
98
+ function cardSummary(text) {
99
+ const lines = String(text).split(/\r?\n/);
100
+ let index = 0;
101
+ if (lines[0] === '---') {
102
+ index = lines.indexOf('---', 1);
103
+ index = index < 0 ? lines.length : index + 1;
104
+ }
105
+ const parts = [];
106
+ for (; index < lines.length; index += 1) {
107
+ const line = lines[index].trim();
108
+ if (!line || line.startsWith('#') || line.startsWith('<!--')) continue;
109
+ parts.push(line.replace(/^[-*+]\s+/, '').replace(/[*`]/g, ''));
110
+ if (parts.join(' ').length >= 240) break;
111
+ }
112
+ return parts.join(' ').replace(/\s+/g, ' ').trim().slice(0, 240);
113
+ }
114
+
115
+ /**
116
+ * The card catalog R6 compares against: topics/ and procedures/ in stable
117
+ * path order. Ordering is part of the determinism contract (P6).
118
+ */
119
+ export function buildExistingCards(memoryRoot) {
120
+ const cards = [];
121
+ for (const room of ['topics', 'procedures']) {
122
+ for (const file of listMarkdown(join(memoryRoot, room))) {
123
+ const summary = cardSummary(readFileSync(file, 'utf8'));
124
+ if (!summary) continue;
125
+ cards.push({ cardId: toPosix(relative(memoryRoot, file)), summary });
126
+ }
127
+ }
128
+ return cards.sort((a, b) => a.cardId.localeCompare(b.cardId));
129
+ }
130
+
131
+ /**
132
+ * Split one journal file into adjudication units. A unit is one bullet or one
133
+ * blank-line-separated paragraph; a heading only supplies the date/heading.
134
+ */
135
+ export function parseJournal(text) {
136
+ // Journal files are written with a UTF-8 BOM on Windows; without stripping
137
+ // it the first line is "\uFEFF---" and the whole YAML frontmatter is scored
138
+ // as body text (and line numbers point into the header).
139
+ const lines = String(text).replace(/^\uFEFF/, '').split(/\r?\n/);
140
+ const units = [];
141
+ let inFrontmatter = lines[0] === '---';
142
+ let heading = null;
143
+ let date = null;
144
+ let current = null;
145
+
146
+ const flush = () => {
147
+ if (!current) return;
148
+ const body = current.text.replace(/\s+/g, ' ').trim();
149
+ if (body) {
150
+ units.push({
151
+ text: body,
152
+ lineStart: current.lineStart,
153
+ lineEnd: current.lineEnd,
154
+ heading,
155
+ date,
156
+ kind: current.kind,
157
+ });
158
+ }
159
+ current = null;
160
+ };
161
+
162
+ for (let i = 0; i < lines.length; i += 1) {
163
+ const raw = lines[i];
164
+ const line = raw.trimEnd();
165
+ if (inFrontmatter) {
166
+ if (i > 0 && line === '---') inFrontmatter = false;
167
+ continue;
168
+ }
169
+ if (!line.trim()) {
170
+ flush();
171
+ continue;
172
+ }
173
+ if (/^#{1,6}\s+/.test(line)) {
174
+ flush();
175
+ if (/^##\s+/.test(line)) {
176
+ heading = line.replace(/^##\s+/, '').trim();
177
+ const match = heading.match(/^(\d{4}-\d{2}-\d{2})/);
178
+ date = match ? match[1] : null;
179
+ }
180
+ continue;
181
+ }
182
+ if (/^(?:---+|\*\*\*+|___+)$/.test(line.trim())) {
183
+ flush();
184
+ continue;
185
+ }
186
+ if (/^[-*+]\s+/.test(line)) {
187
+ flush();
188
+ current = {
189
+ text: line.replace(/^[-*+]\s+/, ''),
190
+ lineStart: i + 1,
191
+ lineEnd: i + 1,
192
+ kind: 'bullet',
193
+ };
194
+ continue;
195
+ }
196
+ if (current) {
197
+ // Indented continuation of the current bullet/paragraph.
198
+ current.text += ` ${line.trim()}`;
199
+ current.lineEnd = i + 1;
200
+ continue;
201
+ }
202
+ current = { text: line.trim(), lineStart: i + 1, lineEnd: i + 1, kind: 'paragraph' };
203
+ }
204
+ flush();
205
+ return units;
206
+ }
207
+
208
+ /** All journal units, newest file first, capped for a fail-open startup run. */
209
+ export function collectUnits(memoryRoot) {
210
+ const journalDir = join(memoryRoot, 'journal');
211
+ const files = [];
212
+ for (const entry of (() => {
213
+ try {
214
+ return readdirSync(journalDir, { withFileTypes: true });
215
+ } catch {
216
+ return [];
217
+ }
218
+ })()) {
219
+ if (!entry.isFile() || !entry.name.toLowerCase().endsWith('.md')) continue;
220
+ const abs = join(journalDir, entry.name);
221
+ try {
222
+ files.push({ abs, mtimeMs: statSync(abs).mtimeMs });
223
+ } catch {
224
+ /* unreadable file: skip, never fail the run */
225
+ }
226
+ }
227
+ files.sort((a, b) => b.mtimeMs - a.mtimeMs || a.abs.localeCompare(b.abs));
228
+
229
+ const units = [];
230
+ const seen = new Set();
231
+ for (const file of files.slice(0, MAX_JOURNAL_FILES)) {
232
+ let text;
233
+ try {
234
+ text = readFileSync(file.abs, 'utf8');
235
+ } catch {
236
+ continue;
237
+ }
238
+ const rel = toPosix(relative(memoryRoot, file.abs));
239
+ for (const unit of parseJournal(text)) {
240
+ if (normalizeText(unit.text).length < 8) continue;
241
+ // A lead-in such as "关键教训:" is a label, not a statement.
242
+ if (normalizeText(unit.text).length < 16 && /[::]$/.test(unit.text)) continue;
243
+ const unitId = sha256(normalizeText(unit.text)).slice(0, 16);
244
+ if (seen.has(unitId)) continue;
245
+ seen.add(unitId);
246
+ units.push({ ...unit, unitId, file: rel, textSha256: sha256(unit.text) });
247
+ if (units.length >= MAX_UNITS) return units;
248
+ }
249
+ }
250
+ return units;
251
+ }
252
+
253
+ function dimMap(dims) {
254
+ const out = {};
255
+ for (const dim of Array.isArray(dims) ? dims : []) {
256
+ if (dim && typeof dim.id === 'string') out[dim.id] = dim;
257
+ }
258
+ return out;
259
+ }
260
+
261
+ function hardSignalsOf(target, dims) {
262
+ const map = dimMap(dims);
263
+ const hits = [];
264
+ const r7 = Number(map.R7?.score) || 0;
265
+ const r1 = Number(map.R1?.score) || 0;
266
+ if (target === 'remember' && r7 >= 2) hits.push('R7');
267
+ if (target === 'remember' && r1 === 2) {
268
+ hits.push('R1');
269
+ for (const id of ['R2', 'R3', 'R4', 'R5']) {
270
+ if (Number(map[id]?.score) === 2) hits.push(id);
271
+ }
272
+ }
273
+ if (!hits.length) {
274
+ for (const dim of dims || []) {
275
+ if (dim && dim.max >= 2 && dim.score === dim.max && dim.score > 0) hits.push(dim.id);
276
+ }
277
+ }
278
+ return [...new Set(hits)].slice(0, 8);
279
+ }
280
+
281
+ function privacyOf(result) {
282
+ const blocked = result?.target === 'local_only' || (result?.privacy && result.privacy.verdict === 'block');
283
+ return blocked
284
+ ? { verdict: 'blocked', marker: 'V1_PRIVACY_BLOCK' }
285
+ : { verdict: 'pass', marker: null };
286
+ }
287
+
288
+ function dedupOf(result) {
289
+ const dims = dimMap(result?.dims);
290
+ const delta = Number(dims.R6?.score) || 0;
291
+ const nearest = result?.dedupe && typeof result.dedupe.nearestCardId === 'string'
292
+ ? result.dedupe.nearestCardId
293
+ : null;
294
+ return { nearestUnitId: nearest, delta };
295
+ }
296
+
297
+ function panelDecision(unit, result, generatedAt, human) {
298
+ const dims = (Array.isArray(result?.dims) ? result.dims : []).map((dim) => ({
299
+ id: String(dim.id ?? ''),
300
+ name: DIM_NAMES[dim.id] ?? String(dim.name ?? dim.id ?? ''),
301
+ score: Number(dim.score) || 0,
302
+ max: Number(dim.max) || 0,
303
+ why: String(dim.why ?? ''),
304
+ }));
305
+ const target = ['remember', 'archive_only', 'human', 'local_only'].includes(result?.target)
306
+ ? result.target
307
+ : 'human';
308
+ return {
309
+ ts: generatedAt,
310
+ unitId: unit.unitId,
311
+ turn: null,
312
+ target,
313
+ score: Number.isFinite(Number(result?.score)) ? Number(result.score) : 0,
314
+ dims,
315
+ hardSignals: hardSignalsOf(target, dims),
316
+ privacy: privacyOf(result),
317
+ needsHuman: Boolean(result?.needsHuman) || target === 'human' || target === 'local_only',
318
+ human: human && typeof human === 'object'
319
+ ? { verdict: String(human.verdict ?? 'pending'), note: String(human.note ?? '') }
320
+ : { verdict: 'pending', note: '' },
321
+ source: {
322
+ file: unit.file,
323
+ lineStart: unit.lineStart,
324
+ lineEnd: unit.lineEnd,
325
+ },
326
+ // DESIGN §3 V1: never echo the matched value or the offending text.
327
+ excerpt: null,
328
+ dedup: dedupOf(result),
329
+ };
330
+ }
331
+
332
+ function runUnit(unit, existingCards) {
333
+ try {
334
+ // artifacts: [] is explicit context ("no artifact catalog supplied"),
335
+ // not "missing": R8 may still apply and never marks the dimension skipped.
336
+ return classifyEntry(unit.text, { existingCards, artifacts: [] });
337
+ } catch (error) {
338
+ return {
339
+ target: 'human',
340
+ score: 0,
341
+ dims: [],
342
+ needsHuman: true,
343
+ privacy: { verdict: 'none', reasons: ['classifier-error'] },
344
+ reasons: [error?.message ?? 'classifier-error'],
345
+ policyVersion: POLICY_VERSION,
346
+ band: 'human',
347
+ dedupe: { verdict: 'error', similarity: null, nearestCardId: null, newInfo: [], mustKeepOld: false },
348
+ excerpt: null,
349
+ };
350
+ }
351
+ }
352
+
353
+ function decisionIdsIn(file) {
354
+ const ids = new Set();
355
+ try {
356
+ for (const line of readFileSync(file, 'utf8').split(/\r?\n/)) {
357
+ if (!line.trim()) continue;
358
+ try {
359
+ const row = JSON.parse(line);
360
+ if (row && typeof row.unitId === 'string') ids.add(row.unitId);
361
+ } catch {
362
+ /* a broken line must not block new decisions */
363
+ }
364
+ }
365
+ } catch {
366
+ /* no file yet */
367
+ }
368
+ return ids;
369
+ }
370
+
371
+ function logWarning(logger, message) {
372
+ try {
373
+ if (typeof logger === 'function') logger(message);
374
+ else if (logger && typeof logger.warn === 'function') logger.warn(message);
375
+ } catch {
376
+ /* logging must never break the caller */
377
+ }
378
+ }
379
+
380
+ function rulesSha256() {
381
+ try {
382
+ return sha256(readFileSync(fileURLToPath(new URL('./filter.js', import.meta.url)), 'utf8'));
383
+ } catch {
384
+ return null;
385
+ }
386
+ }
387
+
388
+ /**
389
+ * Run the filter once. Always resolves; returns a small summary for tests.
390
+ *
391
+ * @param {object} options
392
+ * @param {string} options.memoryRoot
393
+ * @param {Date|number} [options.now]
394
+ * @param {(message:string)=>void} [options.logger]
395
+ * @param {boolean} [options.force] append rows already present today
396
+ */
397
+ export function runFilter(options = {}) {
398
+ const startedAt = Date.now();
399
+ try {
400
+ if (!options.memoryRoot) return { ok: false, reason: 'E_MEMORY_ROOT_UNSET' };
401
+ const memoryRoot = resolve(options.memoryRoot);
402
+ const filterDir = join(memoryRoot, ...FILTER_DIR);
403
+ const now = options.now instanceof Date ? options.now : new Date(options.now ?? Date.now());
404
+ const generatedAt = now.toISOString();
405
+ const date = localDate(now);
406
+ const out = {
407
+ decisions: join(filterDir, `decisions-${date}.jsonl`),
408
+ queue: join(filterDir, 'queue', `${date}.json`),
409
+ run: join(filterDir, 'runs', `${date}T${localClock(now)}.json`),
410
+ state: join(filterDir, 'state.json'),
411
+ };
412
+
413
+ mkdirSync(join(filterDir, 'queue'), { recursive: true });
414
+ mkdirSync(join(filterDir, 'runs'), { recursive: true });
415
+
416
+ const units = collectUnits(memoryRoot);
417
+ const existingCards = buildExistingCards(memoryRoot);
418
+ const state = readJson(out.state, {}) || {};
419
+ const stateUnits = state && typeof state.units === 'object' && state.units ? state.units : {};
420
+ const already = options.force ? new Set() : decisionIdsIn(out.decisions);
421
+
422
+ const rows = [];
423
+ const resultUnits = [];
424
+ const queue = [];
425
+ let fresh = 0;
426
+ for (const unit of units) {
427
+ const result = runUnit(unit, existingCards);
428
+ const previous = stateUnits[unit.unitId];
429
+ const human = previous && previous.policyVersion === POLICY_VERSION && previous.sourceSha === unit.textSha256
430
+ ? previous.human
431
+ : null;
432
+ const row = panelDecision(unit, result, generatedAt, human);
433
+ rows.push(row);
434
+ fresh += already.has(unit.unitId) ? 0 : 1;
435
+
436
+ stateUnits[unit.unitId] = {
437
+ decision: row.target,
438
+ policyVersion: POLICY_VERSION,
439
+ decidedAt: generatedAt,
440
+ sourceSha: unit.textSha256,
441
+ source: row.source,
442
+ human: row.human,
443
+ };
444
+
445
+ if (row.target === 'human' || row.needsHuman) {
446
+ queue.push({
447
+ unitId: row.unitId,
448
+ ts: row.ts,
449
+ score: row.score,
450
+ target: row.target,
451
+ reason: row.privacy.verdict === 'blocked' ? 'V1_PRIVACY_BLOCK' : 'needsHuman',
452
+ source: row.source,
453
+ });
454
+ }
455
+
456
+ resultUnits.push({
457
+ unitId: unit.unitId,
458
+ source: {
459
+ path: row.source.file,
460
+ lineStart: row.source.lineStart,
461
+ lineEnd: row.source.lineEnd,
462
+ heading: unit.heading,
463
+ date: unit.date,
464
+ },
465
+ textSha256: unit.textSha256,
466
+ decision: row.target,
467
+ score: row.score,
468
+ band: result?.band ?? row.target,
469
+ hits: row.dims
470
+ .filter((dim) => dim.score !== 0)
471
+ .map((dim) => ({ ruleId: dim.id, polarity: dim.score > 0 ? '+' : '-', weight: dim.score, quote: dim.why })),
472
+ dedupe: {
473
+ nearest: row.dedup.nearestUnitId,
474
+ similarity: result?.dedupe?.similarity ?? null,
475
+ verdict: result?.dedupe?.verdict ?? 'skipped',
476
+ newInfo: result?.dedupe?.newInfo ?? [],
477
+ },
478
+ privacy: {
479
+ class: row.privacy.verdict === 'blocked' ? 'local_only' : 'none',
480
+ markers: row.privacy.marker ? [row.privacy.marker] : [],
481
+ },
482
+ next: { route: row.target, requiresHuman: row.needsHuman },
483
+ review: { human: row.human },
484
+ policyVersion: POLICY_VERSION,
485
+ });
486
+ }
487
+
488
+ const appended = options.force ? rows : rows.filter((row) => !already.has(row.unitId));
489
+ if (appended.length) {
490
+ appendFileSync(out.decisions, `${appended.map((row) => JSON.stringify(row)).join('\n')}\n`, 'utf8');
491
+ }
492
+
493
+ writeJsonAtomic(out.queue, { generatedAt, policyVersion: POLICY_VERSION, count: queue.length, items: queue });
494
+ writeJsonAtomic(out.state, {
495
+ schema: 1,
496
+ policyVersion: POLICY_VERSION,
497
+ updatedAt: generatedAt,
498
+ units: stateUnits,
499
+ });
500
+
501
+ const counts = {
502
+ remember: rows.filter((row) => row.target === 'remember').length,
503
+ archive_only: rows.filter((row) => row.target === 'archive_only').length,
504
+ human: rows.filter((row) => row.target === 'human').length,
505
+ local_only: rows.filter((row) => row.target === 'local_only').length,
506
+ humanQuotaExceeded: false,
507
+ };
508
+ const runId = `filter-${date.replace(/-/g, '')}-${localClock(now)}-${Math.random().toString(36).slice(2, 8)}`;
509
+ writeJsonAtomic(out.run, {
510
+ schemaVersion: SCHEMA_VERSION,
511
+ runId,
512
+ generatedAt,
513
+ policy: {
514
+ version: POLICY_VERSION,
515
+ rulesSha256: rulesSha256(),
516
+ thresholds: THRESHOLDS,
517
+ },
518
+ counts,
519
+ units: resultUnits,
520
+ });
521
+
522
+ return {
523
+ ok: true,
524
+ runId,
525
+ units: units.length,
526
+ appended: appended.length,
527
+ fresh,
528
+ counts,
529
+ dir: filterDir,
530
+ files: out,
531
+ latencyMs: Date.now() - startedAt,
532
+ };
533
+ } catch (error) {
534
+ logWarning(options.logger, `memory filter 运行失败(${error?.code ?? error?.message ?? error})— 已跳过,不影响工具`);
535
+ return { ok: false, reason: error?.code ?? 'E_FILTER_RUN_FAILED', error: String(error?.message ?? error) };
536
+ }
537
+ }
538
+
539
+ /** Startup entry used by src/index.js; async so the plugin never waits on IO. */
540
+ export function scheduleFilterRun(memoryRoot, { logger, now, delayMs = 25 } = {}) {
541
+ if (!memoryRoot) return null;
542
+ try {
543
+ const timer = setTimeout(() => {
544
+ runFilter({ memoryRoot, logger, now });
545
+ }, delayMs);
546
+ if (timer && typeof timer.unref === 'function') timer.unref();
547
+ return timer;
548
+ } catch (error) {
549
+ logWarning(logger, `memory filter 定时器创建失败(${error?.message ?? error})— 已跳过`);
550
+ return null;
551
+ }
552
+ }
553
+
554
+ export { POLICY_VERSION };
555
+ export const FILTER_SUBDIR = FILTER_DIR.join('/');