@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,238 @@
1
+ // answer/store.js — 生成后审计的落盘与查询。
2
+ //
3
+ // 审计文件固定落在 `<memoryRoot>/.longlive/answer-audit/audit.jsonl`:一行一轮,
4
+ // 只追加、不改助手正文。写失败只返回 {ok:false},调用方 fail-open。
5
+ //
6
+ // 轮转:文件超过 maxBytes 时先把现有文件改名为 `answer-audit/audit.1.jsonl`
7
+ // (覆盖上一份 .1),再继续追加。审计是证据不是账本,保留最近两份足够。
8
+
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+
12
+ import { appendJsonLine, withFileLock } from '../util/append-store.js';
13
+ import { scrubJsonValue, redactionMetadata } from '../util/redact.js';
14
+
15
+ export const AUDIT_DIRNAME = '.longlive';
16
+ export const AUDIT_FILENAME = 'answer-audit/audit.jsonl';
17
+ export const AUDIT_MAX_BYTES_DEFAULT = 2 * 1024 * 1024;
18
+ /** S1: 审计行默认 TTL 元数据(删除执行归 S5 retention,本层只标注)。 */
19
+ export const AUDIT_RETENTION_DAYS_DEFAULT = 30;
20
+
21
+ export function auditFilePath(memoryRoot) {
22
+ if (typeof memoryRoot !== 'string' || memoryRoot.trim() === '') return '';
23
+ return path.join(memoryRoot, AUDIT_DIRNAME, AUDIT_FILENAME);
24
+ }
25
+
26
+ /**
27
+ * 追加一行审计。永远不抛。
28
+ *
29
+ * S1 追加纪律:单写锁 + fsync + 坏行隔离(append-store)+ 写入前凭据 scrub。
30
+ * scrub 后仍保留审计用途:`redaction.originalSha256` / `originalLength` / `hits`
31
+ * 与 `retentionDays` + `retainUntil` 元数据;原文不落盘。
32
+ *
33
+ * @param {string} memoryRoot
34
+ * @param {object} row
35
+ * @param {{maxBytes?:number, redact?:boolean, retentionDays?:number, now?:Function}} [options]
36
+ * @returns {{ok:boolean,path:string,rotated?:boolean,code?:string,error?:string}}
37
+ */
38
+ export function appendAuditRow(memoryRoot, row, options = {}) {
39
+ const file = auditFilePath(memoryRoot);
40
+ if (file === '') return { ok: false, path: '', code: 'E_NO_MEMORY_ROOT', error: 'E_NO_MEMORY_ROOT' };
41
+ const maxBytes = Number.isFinite(Number(options.maxBytes))
42
+ ? Math.max(64 * 1024, Number(options.maxBytes))
43
+ : AUDIT_MAX_BYTES_DEFAULT;
44
+ const retentionDays = Number.isInteger(Number(options.retentionDays)) && Number(options.retentionDays) > 0
45
+ ? Number(options.retentionDays)
46
+ : AUDIT_RETENTION_DAYS_DEFAULT;
47
+ const at = row && typeof row === 'object' && typeof row.at === 'string' ? row.at : new Date().toISOString();
48
+ const redact = options.redact !== false;
49
+ // 先 scrub(只改字符串叶子,不改行结构),再补审计元数据。
50
+ const scrubbed = scrubJsonValue(row && typeof row === 'object' ? row : { value: row }, { enabled: redact });
51
+ const auditRow = scrubbed.value && typeof scrubbed.value === 'object' && !Array.isArray(scrubbed.value)
52
+ ? { ...scrubbed.value }
53
+ : { value: scrubbed.value };
54
+ const meta = redactionMetadata(scrubbed, { retentionDays, at });
55
+ auditRow.redaction = meta;
56
+ auditRow.retentionDays = retentionDays;
57
+ auditRow.retainUntil = meta.retainUntil;
58
+
59
+ const write = () => {
60
+ let rotated = false;
61
+ try {
62
+ const stat = fs.statSync(file);
63
+ if (stat.size >= maxBytes) {
64
+ fs.renameSync(file, `${file.replace(/\.jsonl$/u, '')}.1.jsonl`);
65
+ rotated = true;
66
+ }
67
+ } catch (error) {
68
+ if (error?.code !== 'ENOENT') throw error;
69
+ }
70
+ const written = appendJsonLine({
71
+ file,
72
+ row: auditRow,
73
+ label: 'answer-audit',
74
+ skipLock: true,
75
+ healthRoot: memoryRoot,
76
+ now: options.now,
77
+ quarantineDir: path.join(path.resolve(String(memoryRoot)), '.longlive', 'quarantine'),
78
+ });
79
+ return { written, rotated };
80
+ };
81
+
82
+ try {
83
+ fs.mkdirSync(path.dirname(file), { recursive: true });
84
+ // 轮转 + 追加在同一个 per-file 锁内完成,避免两个进程同时 rename/append。
85
+ const locked = withFileLock(file, write, { waitMs: 2_000 });
86
+ if (!locked.ok) {
87
+ return { ok: false, path: file, code: locked.code ?? 'E_APPEND_LOCKED', error: locked.error?.message ?? locked.code ?? 'E_APPEND_LOCKED' };
88
+ }
89
+ const { written, rotated } = locked.value;
90
+ if (!written.ok) {
91
+ return { ok: false, path: file, code: written.code ?? 'E_APPEND_IO', error: written.error?.message ?? written.code ?? 'E_APPEND_IO', rotated };
92
+ }
93
+ return { ok: true, path: file, rotated };
94
+ } catch (error) {
95
+ return { ok: false, path: file, code: error?.code ?? 'E_APPEND_IO', error: String(error?.message ?? error) };
96
+ }
97
+ }
98
+
99
+ /**
100
+ * 读审计行,按筛选条件过滤。永远不抛;坏行跳过并计入 corrupt。
101
+ *
102
+ * @param {string} memoryRoot
103
+ * @param {{limit?:number,sessionId?:string,turn?:number,verdict?:string,code?:string,
104
+ * since?:string,newestFirst?:boolean}} [filter]
105
+ * @returns {{ok:boolean,path:string,total:number,matched:number,corrupt:number,
106
+ * byVerdict:object,byCode:object,sessions:string[],rows:object[],error?:string}}
107
+ */
108
+ export function readAuditRows(memoryRoot, filter = {}) {
109
+ const file = auditFilePath(memoryRoot);
110
+ const empty = {
111
+ ok: false,
112
+ path: file,
113
+ total: 0,
114
+ matched: 0,
115
+ corrupt: 0,
116
+ byVerdict: {},
117
+ byCode: {},
118
+ sessions: [],
119
+ rows: [],
120
+ };
121
+ if (file === '') return { ...empty, error: 'E_NO_MEMORY_ROOT' };
122
+
123
+ let text;
124
+ try {
125
+ const rotated = file.replace(/\.jsonl$/u, '.1.jsonl');
126
+ let older = '';
127
+ let current = '';
128
+ try {
129
+ older = fs.readFileSync(rotated, 'utf8');
130
+ } catch (error) {
131
+ if (error?.code !== 'ENOENT') throw error;
132
+ }
133
+ try {
134
+ current = fs.readFileSync(file, 'utf8');
135
+ } catch (error) {
136
+ if (error?.code !== 'ENOENT') throw error;
137
+ if (older === '') return { ...empty, ok: true, error: 'E_NO_AUDIT_FILE' };
138
+ }
139
+ text = `${older}\n${current}`;
140
+ } catch (error) {
141
+ return { ...empty, error: String(error?.code ?? error?.message ?? error) };
142
+ }
143
+
144
+ const limit = Number.isFinite(Number(filter.limit)) ? Math.max(1, Math.min(500, Number(filter.limit))) : 50;
145
+ const wantSession = typeof filter.sessionId === 'string' ? filter.sessionId.trim() : '';
146
+ const wantTurn = Number.isFinite(Number(filter.turn)) ? Number(filter.turn) : null;
147
+ const wantVerdict = typeof filter.verdict === 'string' ? filter.verdict.trim() : '';
148
+ const wantCode = typeof filter.code === 'string' ? filter.code.trim() : '';
149
+ const since = typeof filter.since === 'string' && filter.since.trim() !== '' ? Date.parse(filter.since) : null;
150
+
151
+ const rows = [];
152
+ const byVerdict = {};
153
+ const byCode = {};
154
+ const sessions = new Set();
155
+ let total = 0;
156
+ let corrupt = 0;
157
+ for (const line of text.split('\n')) {
158
+ if (line.trim() === '') continue;
159
+ total += 1;
160
+ let row;
161
+ try {
162
+ row = JSON.parse(line);
163
+ } catch {
164
+ corrupt += 1;
165
+ continue;
166
+ }
167
+ if (!row || typeof row !== 'object') {
168
+ corrupt += 1;
169
+ continue;
170
+ }
171
+ if (row.sessionId) sessions.add(String(row.sessionId));
172
+ byVerdict[row.verdict ?? 'unknown'] = (byVerdict[row.verdict ?? 'unknown'] ?? 0) + 1;
173
+ for (const flag of Array.isArray(row.flags) ? row.flags : []) {
174
+ const code = String(flag?.code ?? 'UNKNOWN');
175
+ byCode[code] = (byCode[code] ?? 0) + 1;
176
+ }
177
+ if (wantSession !== '' && String(row.sessionId ?? '') !== wantSession) continue;
178
+ if (wantTurn !== null && Number(row.turn) !== wantTurn) continue;
179
+ if (wantVerdict !== '' && String(row.verdict ?? '') !== wantVerdict) continue;
180
+ if (wantCode !== '' && !(Array.isArray(row.flags) ? row.flags : []).some((flag) => String(flag?.code ?? '') === wantCode)) continue;
181
+ if (since !== null && Number.isFinite(since)) {
182
+ const at = Date.parse(String(row.at ?? ''));
183
+ if (!Number.isFinite(at) || at < since) continue;
184
+ }
185
+ rows.push(row);
186
+ }
187
+
188
+ const newestFirst = filter.newestFirst !== false;
189
+ if (newestFirst) rows.reverse();
190
+ const matched = rows.length;
191
+ return {
192
+ ok: true,
193
+ path: file,
194
+ total,
195
+ matched,
196
+ corrupt,
197
+ byVerdict,
198
+ byCode,
199
+ sessions: [...sessions].sort(),
200
+ rows: rows.slice(0, limit),
201
+ };
202
+ }
203
+
204
+ /** 审计行里是否含「编引用/编数字/编执行」。 */
205
+ export function hasFabrication(row) {
206
+ return (Array.isArray(row?.flags) ? row.flags : []).some((flag) => flag?.severity === 'fabrication');
207
+ }
208
+
209
+ /**
210
+ * 四指标口径(只统计已有审计行,不推断未审计的轮)。
211
+ * @param {object[]} rows
212
+ */
213
+ export function auditMetrics(rows) {
214
+ const list = Array.isArray(rows) ? rows : [];
215
+ const total = list.length;
216
+ const flagged = list.filter((row) => row?.verdict === 'flagged').length;
217
+ const fabrication = list.filter(hasFabrication).length;
218
+ const unsupported = list.filter((row) => (Array.isArray(row?.flags) ? row.flags : []).some((flag) => flag?.severity === 'unsupported')).length;
219
+ return {
220
+ turns: total,
221
+ clean: total - flagged,
222
+ flagged,
223
+ fabrication,
224
+ unsupported,
225
+ flaggedRate: total === 0 ? 0 : Number((flagged / total).toFixed(4)),
226
+ fabricationRate: total === 0 ? 0 : Number((fabrication / total).toFixed(4)),
227
+ };
228
+ }
229
+
230
+ // 1.8.0 合并:生成后审计的纯函数(从 answer-guard core 单源导出,供 query/index 使用)。
231
+ export {
232
+ auditTurn,
233
+ buildAuditRow,
234
+ composeAuditContext,
235
+ tailTextParts,
236
+ isFabricationRow,
237
+ AUDIT_CONTEXT_MARKER,
238
+ } from './guard.js';
@@ -0,0 +1,234 @@
1
+ // src/answer/claim-guard.mjs — D22 防编(W2 写侧,批 D)
2
+ //
3
+ // 设计依据(计划 v3.6.4 §4⑪ / §15 裁决):
4
+ // * 只读复用 answer/guard.js(HISTORY_CLAIM_RE / TOOL_CLAIM_RE / extractNumberClaims /
5
+ // SOURCE_GATE_HARD_CODES / auditTurn),不新建分析器、不改 guard.js / audit.js;
6
+ // * 触发点 = 宿主 pre-step 扫上一轮 assistant 文本(W4:src/recall/index.js),
7
+ // 不改 answer/index.js(含 :932)、不增改性点;
8
+ // * 命中 requires-source 时注入一条 ≤50 字的提醒(「称『我记得/上次』须指卡」),
9
+ // 同时经 recall/gate-log.mjs 的 appendGateLog 写 hg.d22.fail(decision=fail),
10
+ // 不阻断回答;分析失败一律 catch(写 warn),不得把主流程拖垮。
11
+ //
12
+ // fail-closed:参数缺失返回结构化错误码(不抛进调用方主流程的,是 apply/record 这类
13
+ // 预处理器;scanClaimGuard 作为纯函数在文本非法时也返回 ok:false 而不是编一个结果)。
14
+
15
+ import {
16
+ HISTORY_CLAIM_RE,
17
+ SOURCE_GATE_HARD_CODES,
18
+ auditTurn,
19
+ isAbstention,
20
+ } from './guard.js';
21
+ import { appendGateLog } from '../recall/gate-log.mjs';
22
+
23
+ export const BATCH = 'D';
24
+ export const SKELETON = Object.freeze({ version: '2.0.0', failClosed: true, implemented: true });
25
+ export const REQUIRES_SOURCE_MARK = 'requires-source';
26
+ export const INJECT_BUDGET_CHARS = 50;
27
+ export const GATE_EVENT = 'hg.d22.fail';
28
+ export const UNIMPLEMENTED_CODE = 'E_HG_CLAIM_GUARD_UNIMPLEMENTED';
29
+
30
+ export const FLAG_CODES = Object.freeze([
31
+ 'HISTORY_CLAIM_NO_CITATION',
32
+ 'ANSWERED_WITHOUT_EVIDENCE',
33
+ 'FAKE_TOOL_CLAIM',
34
+ 'UNGROUNDED_NUMBER',
35
+ 'FAKE_TURN_REF',
36
+ 'FAKE_CARD_REF',
37
+ ]);
38
+
39
+ /** 命中 requires-source 时的注入前缀(计划原文:「称『我记得/上次』须指卡」)。 */
40
+ export const INJECT_PREFIX = '称『我记得/上次』须指卡:';
41
+
42
+ function clip(text, max) {
43
+ const chars = Array.from(String(text ?? ''));
44
+ if (chars.length <= max) return chars.join('');
45
+ return chars.slice(0, Math.max(0, max - 1)).join('') + '…';
46
+ }
47
+
48
+ function isHardFlag(flag) {
49
+ if (!flag || typeof flag.code !== 'string') return false;
50
+ return flag.severity === 'fabrication' || SOURCE_GATE_HARD_CODES.includes(flag.code);
51
+ }
52
+
53
+ function buildInjectText(flags) {
54
+ const codes = [...new Set(flags.filter(isHardFlag).map((flag) => flag.code))].slice(0, 3);
55
+ const body = codes.length > 0 ? `${INJECT_PREFIX}${codes.join('/')}` : `${INJECT_PREFIX}先指卡再答`;
56
+ return clip(body, INJECT_BUDGET_CHARS);
57
+ }
58
+
59
+ /**
60
+ * 纯扫描:把一段 assistant 文本交给 guard.auditTurn 判定,登记防编结果。
61
+ *
62
+ * @param {object} input {text, turn?, question?, historyQuestion?, zeroHit?, evidenceTurns?,
63
+ * evidenceUnits?, toolNames?, sessionToolNames?, sessionTurns?, knownTools?, cardExists?,
64
+ * contextText?, contextTruncated?, canAbstain?, difficulty?, questionType?, now?}
65
+ * @returns {{ok:boolean,code?:string,requiresSource:boolean,hardCodes:string[],flags:object[],
66
+ * injectText:string,verdict:string|null,evidence:object}}
67
+ */
68
+ export function scanClaimGuard(input = {}) {
69
+ const text = String(input?.text ?? '');
70
+ if (text.trim() === '') {
71
+ return {
72
+ ok: false,
73
+ code: 'E_HG_D22_NO_TEXT',
74
+ requiresSource: false,
75
+ hardCodes: [],
76
+ flags: [],
77
+ injectText: '',
78
+ verdict: null,
79
+ evidence: { reason: 'empty-text' },
80
+ };
81
+ }
82
+ let audit;
83
+ try {
84
+ audit = auditTurn({
85
+ text,
86
+ turn: Number.isInteger(Number(input.turn)) ? Number(input.turn) : 0,
87
+ question: String(input.question ?? text),
88
+ historyQuestion: input.historyQuestion === true || HISTORY_CLAIM_RE.test(text),
89
+ zeroHit: input.zeroHit === true,
90
+ evidenceTurns: Array.isArray(input.evidenceTurns) ? input.evidenceTurns : [],
91
+ evidenceUnits: input.evidenceUnits,
92
+ toolNames: Array.isArray(input.toolNames) ? input.toolNames : [],
93
+ sessionToolNames: Array.isArray(input.sessionToolNames) ? input.sessionToolNames : [],
94
+ sessionTurns: Array.isArray(input.sessionTurns) ? input.sessionTurns : [],
95
+ knownTools: Array.isArray(input.knownTools) ? input.knownTools : [],
96
+ cardExists: typeof input.cardExists === 'function' ? input.cardExists : () => true,
97
+ contextText: String(input.contextText ?? ''),
98
+ contextTruncated: input.contextTruncated === true,
99
+ canAbstain: input.canAbstain === true,
100
+ difficulty: String(input.difficulty ?? ''),
101
+ questionType: String(input.questionType ?? ''),
102
+ now: input.now,
103
+ sessionId: input.sessionId,
104
+ });
105
+ } catch (error) {
106
+ return {
107
+ ok: false,
108
+ code: 'E_HG_D22_AUDIT_FAILED',
109
+ requiresSource: false,
110
+ hardCodes: [],
111
+ flags: [],
112
+ injectText: '',
113
+ verdict: null,
114
+ evidence: { reason: 'audit-threw', message: clip(error?.message ?? String(error), 200) },
115
+ };
116
+ }
117
+ const flags = Array.isArray(audit.flags) ? audit.flags : [];
118
+ const hardCodes = [...new Set(flags.filter(isHardFlag).map((flag) => flag.code))];
119
+ const requiresSource = hardCodes.length > 0;
120
+ const zeroHit = audit.zeroHit === true;
121
+ return {
122
+ ok: true,
123
+ requiresSource,
124
+ hardCodes,
125
+ flags,
126
+ injectText: requiresSource ? buildInjectText(flags) : '',
127
+ verdict: typeof audit.verdict === 'string' ? audit.verdict : null,
128
+ evidence: {
129
+ mode: audit.answerMode ?? null,
130
+ zeroHit,
131
+ abstained: isAbstention(text),
132
+ historyQuestion: audit.historyQuestion === true,
133
+ turnRefs: audit.checks?.turnRefs ?? [],
134
+ cardRefs: audit.checks?.cardRefs ?? [],
135
+ },
136
+ };
137
+ }
138
+
139
+ /**
140
+ * 写 hg.d22.fail(唯一门事件入口:appendGateLog)。
141
+ * 失败吞掉(返回 written:false),调用方据此只记录 warn。
142
+ */
143
+ export function recordClaimGuardFailure(input = {}) {
144
+ const memoryRoot = input?.memoryRoot;
145
+ if (typeof memoryRoot !== 'string' || memoryRoot.trim() === '') {
146
+ return { ok: false, code: 'E_HG_D22_NO_ROOT', written: false };
147
+ }
148
+ const at = input.now instanceof Date ? input.now : new Date(input.now ?? Date.now());
149
+ const codes = Array.isArray(input.codes) ? input.codes : [];
150
+ const reason = codes.length > 0 ? codes.join('+') : String(input.code ?? 'E_HG_D22_FAIL');
151
+ try {
152
+ appendGateLog(memoryRoot, {
153
+ at: at.toISOString(),
154
+ sessionId: input.sessionId,
155
+ turn: Number.isInteger(Number(input.turn)) ? Number(input.turn) : undefined,
156
+ gate: GATE_EVENT,
157
+ decision: 'fail',
158
+ reason,
159
+ evidence: [String(input.detail ?? ''), ...codes].filter((item) => item !== ''),
160
+ });
161
+ return { ok: true, written: true, gate: GATE_EVENT, reason };
162
+ } catch (error) {
163
+ return {
164
+ ok: false,
165
+ written: false,
166
+ code: 'E_HG_D22_GATELOG_FAILED',
167
+ message: clip(error?.message ?? String(error), 200),
168
+ };
169
+ }
170
+ }
171
+
172
+ /**
173
+ * 预处理器:扫描上一轮 assistant 文本,requires-source 时生成注入提醒并写门事件。
174
+ * 永不 throw(catch 后 warn),返回结构化结果供 W4 合并注入。
175
+ */
176
+ export function applyClaimGuard(context = {}) {
177
+ const memoryRoot = context?.memoryRoot;
178
+ const warn = typeof context.warn === 'function' ? context.warn : null;
179
+ const text = String(context?.text ?? '');
180
+ if (text.trim() === '') {
181
+ return { ok: true, requiresSource: false, injectText: '', gateWritten: false, code: 'E_HG_D22_NO_TEXT' };
182
+ }
183
+ try {
184
+ const scan = scanClaimGuard({
185
+ text,
186
+ turn: context.turn,
187
+ question: context.question,
188
+ historyQuestion: context.historyQuestion,
189
+ zeroHit: context.zeroHit,
190
+ evidenceTurns: context.evidenceTurns,
191
+ evidenceUnits: context.evidenceUnits,
192
+ toolNames: context.toolNames,
193
+ sessionToolNames: context.sessionToolNames,
194
+ sessionTurns: context.sessionTurns,
195
+ knownTools: context.knownTools,
196
+ cardExists: context.cardExists,
197
+ contextText: context.contextText,
198
+ contextTruncated: context.contextTruncated,
199
+ canAbstain: context.canAbstain,
200
+ difficulty: context.difficulty,
201
+ questionType: context.questionType,
202
+ now: context.now,
203
+ sessionId: context.sessionId,
204
+ });
205
+ if (!scan.ok) {
206
+ warn?.(`[claim-guard] scan 未完成(${scan.code}):${scan.evidence?.message ?? ''}`);
207
+ return { ok: false, requiresSource: false, injectText: '', gateWritten: false, code: scan.code };
208
+ }
209
+ if (!scan.requiresSource) {
210
+ return { ok: true, requiresSource: false, injectText: '', gateWritten: false, code: null, flags: scan.flags };
211
+ }
212
+ const record = recordClaimGuardFailure({
213
+ memoryRoot,
214
+ sessionId: context.sessionId,
215
+ turn: context.turn,
216
+ now: context.now,
217
+ codes: scan.hardCodes,
218
+ detail: clip(text, 200),
219
+ });
220
+ if (!record.ok) warn?.(`[claim-guard] 门事件写入失败(${record.code}):${record.message ?? ''}`);
221
+ return {
222
+ ok: true,
223
+ requiresSource: true,
224
+ injectText: scan.injectText,
225
+ gateWritten: record.written === true,
226
+ code: REQUIRES_SOURCE_MARK,
227
+ flags: scan.flags,
228
+ hardCodes: scan.hardCodes,
229
+ };
230
+ } catch (error) {
231
+ warn?.(`[claim-guard] apply 异常已吞(${error?.code ?? 'E_HG_D22_INTERNAL'}):${error?.message ?? error}`);
232
+ return { ok: false, requiresSource: false, injectText: '', gateWritten: false, code: 'E_HG_D22_INTERNAL' };
233
+ }
234
+ }
@@ -0,0 +1,30 @@
1
+ // src/answer/evidence.js — 证据注入面(1.8.0 answer-guard 合并)。
2
+ //
3
+ // 单一实现位于 guard.js(移植自 answer-guard src/answer/core.mjs);
4
+ // 本文件只做语义分组导出,方便 feature wiring 与面板/评测按面引用。
5
+ export {
6
+ EVIDENCE_MARK,
7
+ NO_EVIDENCE_MARK,
8
+ RULE_MARK,
9
+ RULE_TEXT,
10
+ ANSWER_GUARD_VERSION,
11
+ extractKeywords,
12
+ turnText,
13
+ scoreTurn,
14
+ retrieveEvidence,
15
+ renderEvidencePacket,
16
+ renderNoEvidence,
17
+ renderRuleBlock,
18
+ numberCorpus,
19
+ isGroundedNumber,
20
+ decideAnswerMode,
21
+ // FIX-05:answerMode / evidenceUnits / sourceGate / tier 纯函数(确定性、无模型调用)。
22
+ ANSWER_MODE_VALUES,
23
+ SOURCE_GATE_HARD_CODES,
24
+ normalizeEvidenceUnits,
25
+ collectHardFlagCodes,
26
+ buildSourceGate,
27
+ hasReadableSubstantiveAnswer,
28
+ deriveAnswerMode,
29
+ deriveAnswerModeFields,
30
+ } from './guard.js';