@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,987 @@
1
+ import { externalActionGroups, isExternalMemoryProfileEdit } from '../adapters/registry.js';
2
+
3
+ // R1 Router-A — judge(J0–J8)。
4
+ //
5
+ // judge 与规则作者分离(R1-DESIGN.md §3.4):这里只读 route() 的输出、fixture 的期望
6
+ // 与盘上的证据,不改规则、不改决定。每条 judge 返回 { ok, code?, message },
7
+ // code 一律取 route.js 的 ERROR_CODES(E_ROUTE_* 前缀)。
8
+ //
9
+ // 本文件的 J0–J8 按任务书定义(与设计文档 §3.3 的 judge 表编号不同,映射见
10
+ // CHANGES-r1-align.md 的失败码表):
11
+ // J0 隔离 沙盒内无真实库写入;真实库前后 hash 一致 E_ROUTE_ISOLATION
12
+ // J1 单条 期望单条时 decisions 恰好 1 条 E_ROUTE_SHAPE
13
+ // J2 多条顺序 多条时条数/顺序/kind/action/ruleId 逐位一致 E_ROUTE_ORDER / E_ROUTE_ACTION
14
+ // J3 拒绝 越界动作必须拒绝且零写入 E_ROUTE_REFUSAL
15
+ // J4 证据 每条决定 evidence 非空、可解析、ctx 字段有留痕 E_ROUTE_EVIDENCE
16
+ // J5 override 无理由 override 必拒且不改判定 E_ROUTE_OVERRIDE_UNJUSTIFIED
17
+ // J6 writeScope 声明 ⊆ 允许;拒绝类必须为空;期望产物必须被声明 E_ROUTE_SCOPE
18
+ // J7 审计 decisions.jsonl 每行带 overrides(理由/谁/时间戳) E_ROUTE_AUDIT
19
+ // J8 needsHuman 语义:审批类决定为真;H 级签字用例为真 E_ROUTE_HUMAN
20
+
21
+ import crypto from 'node:crypto';
22
+ import fs from 'node:fs';
23
+ import path from 'node:path';
24
+
25
+ import {
26
+ ERROR_CODES,
27
+ FALLBACKS,
28
+ LEVELS,
29
+ POLICY,
30
+ RULES,
31
+ canonicalAction,
32
+ route,
33
+ } from './route.js';
34
+
35
+ export const JUDGE_IDS = Object.freeze(['J0', 'J1', 'J2', 'J3', 'J4', 'J5', 'J6', 'J7', 'J8', 'J9']);
36
+
37
+ export const JUDGE_TITLES = Object.freeze({
38
+ J0: '隔离:沙盒无真实库写入 + 真实库前后 hash 一致',
39
+ J1: '单条:期望单条时 decisions 恰好 1 条',
40
+ J2: '多条顺序:条数/顺序/kind/action/ruleId 逐位一致',
41
+ J3: '拒绝:越界动作必须拒绝且零写入',
42
+ J4: '证据:每条决定 evidence 非空、可解析、ctx 字段留痕',
43
+ J5: 'override:无理由必拒且不改判定',
44
+ J6: 'writeScope:声明 ⊆ 允许,拒绝类为空,期望产物被声明',
45
+ J7: '审计:decisions.jsonl 每行 overrides 带理由/谁/时间戳',
46
+ J8: 'needsHuman:审批类决定为真,H 级签字用例为真',
47
+ J9: '身份同意:改名字/画像必须有当前会话助手本人的 consent 记录,用户单方面同意不算',
48
+ });
49
+
50
+ // §5.7 执行矩阵:fixture 的 level 必须与设计表一致(M3=D,S4/X1=H)。
51
+ export const LEVEL_MATRIX = Object.freeze({
52
+ T1: 'X', T2: 'X', T3: 'X', T4: 'X',
53
+ M1: 'X', M2: 'X', M3: 'D', M4: 'D',
54
+ S1: 'X', S2: 'X', S3: 'X', S4: 'H',
55
+ X1: 'H', X2: 'X',
56
+ // J8(2026-11-03):五条草案并入正式矩阵,全部 X。
57
+ S5: 'X', S6: 'X', M5: 'X', M6: 'X', M7: 'X',
58
+ });
59
+
60
+ export const SIGN_OFF = Object.freeze({ S4: 'human', X1: 'human' });
61
+
62
+ // 需要人点头/人签字才能执行的动作;needsHuman 由它们推出来。
63
+ export const APPROVAL_ACTIONS = Object.freeze([
64
+ 'guard.refuse',
65
+ 'session.handover',
66
+ 'reply.only',
67
+ 'reply.no_write',
68
+ // J8:提问本身是需要人回答的审批类动作;删除必须人二次确认。identity.hold 刻意不在列——
69
+ // 需要点头的是当前会话的助手本人,不是用户,needsHuman 不能替助手点头。
70
+ 'reply.ask',
71
+ 'memory.delete',
72
+ ...externalActionGroups('approval'),
73
+ ]);
74
+
75
+ // 会落盘/写记忆的动作;拒绝类用例里一条都不许出现。
76
+ export const WRITE_ACTIONS = Object.freeze([
77
+ ...externalActionGroups('write'),
78
+ 'journal.append',
79
+ 'topics.write',
80
+ 'procedures.draft',
81
+ ]);
82
+
83
+ export const FIXTURE_IDS = Object.freeze(Object.keys(LEVEL_MATRIX));
84
+
85
+ const EVIDENCE_SCHEMES = Object.freeze(['file', 'policy', 'ctx', 'output', 'fixture']);
86
+
87
+ function ok(detail) {
88
+ return { ok: true, detail };
89
+ }
90
+
91
+ function bad(code, message) {
92
+ return { ok: false, code, message };
93
+ }
94
+
95
+ function actionOf(decision) {
96
+ return canonicalAction(decision && decision.action) || (decision && decision.action) || '';
97
+ }
98
+
99
+ function asArray(value) {
100
+ return Array.isArray(value) ? value : [];
101
+ }
102
+
103
+ // 允许集 = 规则表里出现过的全部动作(decision / before / after)。judge 的 J2 用它判 E_ROUTE_ACTION。
104
+ const ALLOWED_ACTIONS = new Set();
105
+ for (const rule of [...RULES, ...(FALLBACKS || [])]) {
106
+ for (const template of [rule.decision, ...asArray(rule.before), ...asArray(rule.after)]) {
107
+ if (template && template.action) ALLOWED_ACTIONS.add(canonicalAction(template.action) || template.action);
108
+ }
109
+ }
110
+
111
+ // ── fixture ──────────────────────────────────────────────────
112
+
113
+ export function fixtureInput(fixture) {
114
+ return {
115
+ caseId: fixture.id,
116
+ turn: fixture.turn,
117
+ utterance: fixture.utterance,
118
+ kind: fixture.kind,
119
+ ctx: fixture.ctx || {},
120
+ candidates: fixture.candidates || [],
121
+ };
122
+ }
123
+
124
+ export function validateFixture(fixture) {
125
+ const errors = [];
126
+ const push = (code, message) => errors.push({ code, message });
127
+ if (!fixture || typeof fixture !== 'object') {
128
+ push(ERROR_CODES.CONTRACT, 'fixture 不是对象');
129
+ return errors;
130
+ }
131
+ const id = typeof fixture.id === 'string' ? fixture.id.trim() : '';
132
+ if (!FIXTURE_IDS.includes(id)) push(ERROR_CODES.CONTRACT, `fixture id 非法:${id || '(空)'}`);
133
+ if (!['X', 'D', 'H'].includes(fixture.level)) push(ERROR_CODES.LEVEL, `${id}: level ${fixture.level} 不在 X/D/H`);
134
+ if (typeof fixture.utterance !== 'string' || !fixture.utterance.trim()) {
135
+ push(ERROR_CODES.CONTRACT, `${id}: utterance 为空`);
136
+ }
137
+ if (!['tool', 'memory', 'session'].includes(fixture.kind)) push(ERROR_CODES.CONTRACT, `${id}: kind 非法`);
138
+ if (!asArray(fixture.failIf).length) push(ERROR_CODES.CONTRACT, `${id}: failIf 为空`);
139
+ const expect = fixture.expect;
140
+ if (!expect || typeof expect !== 'object') {
141
+ push(ERROR_CODES.CONTRACT, `${id}: 缺 expect`);
142
+ } else {
143
+ if (!asArray(expect.decisions).length) push(ERROR_CODES.CONTRACT, `${id}: expect.decisions 为空`);
144
+ if (!Array.isArray(expect.forbiddenActions)) push(ERROR_CODES.CONTRACT, `${id}: expect.forbiddenActions 必须是数组`);
145
+ if (!Array.isArray(expect.writeScope)) push(ERROR_CODES.CONTRACT, `${id}: expect.writeScope 必须是数组`);
146
+ if (typeof expect.needsHuman !== 'boolean') push(ERROR_CODES.CONTRACT, `${id}: expect.needsHuman 必须是布尔`);
147
+ }
148
+ if (LEVEL_MATRIX[id] && fixture.level !== LEVEL_MATRIX[id]) {
149
+ push(ERROR_CODES.LEVEL, `${id}: level ${fixture.level} 与设计 §5.7 的 ${LEVEL_MATRIX[id]} 不一致`);
150
+ }
151
+ return errors;
152
+ }
153
+
154
+ export function loadFixtures(dir) {
155
+ const entries = fs.readdirSync(dir, { withFileTypes: true })
156
+ .filter((entry) => entry.isFile() && entry.name.endsWith('.json'))
157
+ .map((entry) => path.join(dir, entry.name))
158
+ .sort();
159
+ const fixtures = [];
160
+ const errors = [];
161
+ for (const file of entries) {
162
+ let parsed;
163
+ try {
164
+ parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
165
+ } catch (error) {
166
+ errors.push({ code: ERROR_CODES.CONTRACT, message: `${path.basename(file)}: JSON 解析失败 ${error.message}` });
167
+ continue;
168
+ }
169
+ const fixtureErrors = validateFixture(parsed);
170
+ if (fixtureErrors.length) {
171
+ errors.push(...fixtureErrors.map((item) => ({ ...item, message: `${path.basename(file)}: ${item.message}` })));
172
+ continue;
173
+ }
174
+ fixtures.push(parsed);
175
+ }
176
+ return { fixtures, errors, files: entries };
177
+ }
178
+
179
+ // ── J1 / J2 形状与顺序 ───────────────────────────────────────
180
+
181
+ export function judgeJ1(fixture, result) {
182
+ const expected = asArray(fixture.expect && fixture.expect.decisions);
183
+ const actual = asArray(result && result.decisions);
184
+ if (!actual.length) return bad(ERROR_CODES.SHAPE, `${fixture.id}: 没有任何决定`);
185
+ if (expected.length === 1 && actual.length !== 1) {
186
+ return bad(ERROR_CODES.SHAPE, `${fixture.id}: 期望 1 条决定,实际 ${actual.length} 条(${actual.map((d) => actionOf(d)).join(', ')})`);
187
+ }
188
+ return ok(`${actual.length} decisions`);
189
+ }
190
+
191
+ export function judgeJ2(fixture, result) {
192
+ const expected = asArray(fixture.expect && fixture.expect.decisions);
193
+ const actual = asArray(result && result.decisions);
194
+ for (const decision of actual) {
195
+ const action = actionOf(decision);
196
+ if (action && ALLOWED_ACTIONS.size > 0 && !ALLOWED_ACTIONS.has(action)) {
197
+ return bad(ERROR_CODES.ACTION, `${fixture.id}: action ${action} 不在规则表的允许集`);
198
+ }
199
+ }
200
+ if (expected.length <= 1) {
201
+ if (expected.length === 1 && actual.length >= 1) {
202
+ const want = expected[0];
203
+ const got = actual[0];
204
+ if (want.kind && got.kind !== want.kind) {
205
+ return bad(ERROR_CODES.ORDER, `${fixture.id}: 第 1 条 kind ${got.kind} != ${want.kind}`);
206
+ }
207
+ }
208
+ return ok('single');
209
+ }
210
+ if (actual.length !== expected.length) {
211
+ return bad(ERROR_CODES.ORDER, `${fixture.id}: 条数 ${actual.length} != ${expected.length}`);
212
+ }
213
+ for (let index = 0; index < expected.length; index += 1) {
214
+ const want = expected[index];
215
+ const got = actual[index];
216
+ if (want.kind && got.kind !== want.kind) {
217
+ return bad(ERROR_CODES.ORDER, `${fixture.id}: 第 ${index + 1} 条 kind ${got.kind} != ${want.kind}`);
218
+ }
219
+ const allowed = asArray(want.actionIn).map((name) => canonicalAction(name) || name);
220
+ if (allowed.length && !allowed.includes(actionOf(got))) {
221
+ return bad(ERROR_CODES.ORDER, `${fixture.id}: 第 ${index + 1} 条 action ${actionOf(got)} 不在 ${allowed.join('|')}`);
222
+ }
223
+ const rules = asArray(want.ruleIdIn);
224
+ if (rules.length && !rules.includes(got.ruleId)) {
225
+ return bad(ERROR_CODES.ORDER, `${fixture.id}: 第 ${index + 1} 条 ruleId ${got.ruleId} 不在 ${rules.join('|')}`);
226
+ }
227
+ }
228
+ return ok(`${expected.length} decisions in order`);
229
+ }
230
+
231
+ // ── J3 拒绝 ─────────────────────────────────────────────────
232
+
233
+ export function judgeJ3(fixture, result) {
234
+ const expect = fixture.expect || {};
235
+ const decisions = asArray(result && result.decisions);
236
+ const writes = decisions.filter((decision) => WRITE_ACTIONS.includes(actionOf(decision)));
237
+ if (expect.refusal) {
238
+ if (!decisions.length) return bad(ERROR_CODES.REFUSAL, `${fixture.id}: 拒绝用例没有决定`);
239
+ const primary = decisions[0];
240
+ if (primary.kind !== 'reply') {
241
+ return bad(ERROR_CODES.REFUSAL, `${fixture.id}: 拒绝决定 kind ${primary.kind} 应为 reply`);
242
+ }
243
+ if (result.target !== 'none') {
244
+ return bad(ERROR_CODES.REFUSAL, `${fixture.id}: 拒绝用例 target ${result.target} 应为 none`);
245
+ }
246
+ if (asArray(primary.writeScope).length > 0) {
247
+ return bad(ERROR_CODES.REFUSAL, `${fixture.id}: 拒绝决定仍声明写入 ${primary.writeScope.join('|')}`);
248
+ }
249
+ if (result.needsHuman !== true) {
250
+ return bad(ERROR_CODES.REFUSAL, `${fixture.id}: 拒绝必须让人点头(needsHuman=false)`);
251
+ }
252
+ }
253
+ if (expect.refusal && writes.length) {
254
+ return bad(ERROR_CODES.REFUSAL, `${fixture.id}: 拒绝用例出现写入动作 ${writes.map((d) => actionOf(d)).join(', ')}`);
255
+ }
256
+ return ok(expect.refusal ? 'refusal with zero writes' : 'no refusal expected');
257
+ }
258
+
259
+ // ── J4 证据 ─────────────────────────────────────────────────
260
+
261
+ function isSafeRelPath(value) {
262
+ return typeof value === 'string'
263
+ && value.length > 0
264
+ && !/^[A-Za-z]:/.test(value)
265
+ && !value.startsWith('/')
266
+ && !value.startsWith('\\')
267
+ && !value.includes('..')
268
+ && !value.includes('~');
269
+ }
270
+
271
+ export function classifyEvidence(entry) {
272
+ if (typeof entry !== 'string' || !entry.trim()) return { scheme: null };
273
+ const value = entry.trim();
274
+ if (value.startsWith('policy:')) return { scheme: 'policy', value: value.slice(7) };
275
+ if (value.startsWith('ctx:')) return { scheme: 'ctx', value: value.slice(4) };
276
+ if (value.startsWith('output:')) return { scheme: 'output', value: value.slice(7) };
277
+ if (value.startsWith('fixture:')) return { scheme: 'fixture', value: value.slice(8) };
278
+ const match = /^(.+?):(\d+)(?:-(\d+))?$/.exec(value);
279
+ if (match && isSafeRelPath(match[1])) {
280
+ return {
281
+ scheme: 'file',
282
+ value: match[1],
283
+ line: Number(match[2]),
284
+ endLine: match[3] ? Number(match[3]) : Number(match[2]),
285
+ };
286
+ }
287
+ return { scheme: null };
288
+ }
289
+
290
+ export function usesCtxFields(decision) {
291
+ const args = (decision && decision.args) || {};
292
+ const fields = [];
293
+ for (const field of ['tokens', 'zone', 'activeWorkers', 'openRows']) {
294
+ if (Object.prototype.hasOwnProperty.call(args, field)) fields.push(field);
295
+ }
296
+ return fields;
297
+ }
298
+
299
+ /**
300
+ * J4:每条决定 evidence 非空、每条都能归到一种 scheme、文件行真的存在且内容对得上,
301
+ * 用过的 ctx 字段必须留痕。
302
+ * @param {object} fixture
303
+ * @param {object} result
304
+ * @param {{repoRoot?: string, design?: object, evidenceIndex?: Set<string>}} [opts]
305
+ */
306
+ export function judgeJ4(fixture, result, opts = {}) {
307
+ const decisions = asArray(result && result.decisions);
308
+ if (!decisions.length) return bad(ERROR_CODES.EVIDENCE, `${fixture.id}: 没有决定可查证据`);
309
+ const repoRoot = opts.repoRoot || process.cwd();
310
+ const design = opts.design || null;
311
+ const ctx = (fixture && fixture.ctx) || {};
312
+ const evidenceIndex = opts.evidenceIndex || null;
313
+
314
+ for (const decision of decisions) {
315
+ const evidence = asArray(decision.evidence);
316
+ if (!evidence.length) {
317
+ return bad(ERROR_CODES.EVIDENCE, `${fixture.id}: ${actionOf(decision)} 没有 evidence`);
318
+ }
319
+ let hasSource = false;
320
+ for (const entry of evidence) {
321
+ const parsed = classifyEvidence(entry);
322
+ if (!EVIDENCE_SCHEMES.includes(parsed.scheme)) {
323
+ return bad(ERROR_CODES.EVIDENCE, `${fixture.id}: 证据不可解析 ${JSON.stringify(entry)}`);
324
+ }
325
+ if (parsed.scheme === 'ctx') {
326
+ if (!Object.prototype.hasOwnProperty.call(ctx, parsed.value)) {
327
+ return bad(ERROR_CODES.EVIDENCE, `${fixture.id}: 证据引用 ctx:${parsed.value},但 fixture 没给这个字段`);
328
+ }
329
+ hasSource = true;
330
+ }
331
+ if (parsed.scheme === 'policy') {
332
+ if (!design) {
333
+ hasSource = true;
334
+ continue;
335
+ }
336
+ const resolved = resolvePolicyRef(parsed.value, design);
337
+ if (!resolved.ok) {
338
+ return bad(ERROR_CODES.EVIDENCE, `${fixture.id}: policy 证据解析失败:${resolved.message}`);
339
+ }
340
+ if (decision.ruleId) {
341
+ const rule = RULES.find((item) => item.id === decision.ruleId);
342
+ if (rule && rule.policyRef && rule.policyRef !== parsed.value) {
343
+ return bad(ERROR_CODES.EVIDENCE, `${fixture.id}: ${decision.ruleId} policyRef ${rule.policyRef} != 证据 ${parsed.value}`);
344
+ }
345
+ }
346
+ hasSource = true;
347
+ }
348
+ if (parsed.scheme === 'file') {
349
+ const file = path.join(repoRoot, parsed.value);
350
+ if (!fs.existsSync(file)) {
351
+ return bad(ERROR_CODES.EVIDENCE, `${fixture.id}: 证据文件不存在 ${parsed.value}`);
352
+ }
353
+ const lines = fs.readFileSync(file, 'utf8').split('\n');
354
+ if (parsed.line < 1 || parsed.line > lines.length) {
355
+ return bad(ERROR_CODES.EVIDENCE, `${fixture.id}: 证据行 ${parsed.value}:${parsed.line} 越界`);
356
+ }
357
+ if (parsed.value === 'src/router/routing-rules.json' && decision.ruleId) {
358
+ const line = lines[parsed.line - 1];
359
+ if (!line.includes(`"${decision.ruleId}"`)) {
360
+ return bad(ERROR_CODES.EVIDENCE, `${fixture.id}: ${parsed.value}:${parsed.line} 不是 ${decision.ruleId} 的定义行`);
361
+ }
362
+ }
363
+ hasSource = true;
364
+ }
365
+ if (parsed.scheme === 'output') {
366
+ if (!/^[0-9a-f]{8,64}$/i.test(parsed.value)) {
367
+ return bad(ERROR_CODES.EVIDENCE, `${fixture.id}: output:${parsed.value} 不是 sha256`);
368
+ }
369
+ if (evidenceIndex && !evidenceIndex.has(parsed.value.toLowerCase())) {
370
+ return bad(ERROR_CODES.EVIDENCE, `${fixture.id}: output:${parsed.value} 在证据目录里找不到`);
371
+ }
372
+ hasSource = true;
373
+ }
374
+ if (parsed.scheme === 'fixture') {
375
+ if (parsed.value !== fixture.id) {
376
+ return bad(ERROR_CODES.EVIDENCE, `${fixture.id}: 证据指向别的 fixture ${parsed.value}`);
377
+ }
378
+ hasSource = true;
379
+ }
380
+ }
381
+ if (!hasSource) return bad(ERROR_CODES.EVIDENCE, `${fixture.id}: ${actionOf(decision)} 没有可解析的来源证据`);
382
+
383
+ for (const field of usesCtxFields(decision)) {
384
+ if (!evidence.includes(`ctx:${field}`)) {
385
+ return bad(ERROR_CODES.EVIDENCE, `${fixture.id}: ${actionOf(decision)} 用了 ctx.${field} 却没写 ctx:${field} 证据`);
386
+ }
387
+ }
388
+ }
389
+ return ok(`${decisions.length} decisions with evidence`);
390
+ }
391
+
392
+ // ── J5 override ─────────────────────────────────────────────
393
+
394
+ export function judgeJ5(fixture, result = null, opts = {}) {
395
+ const routeFn = opts.route || route;
396
+ const input = fixtureInput(fixture);
397
+ const baseline = result || routeFn(input);
398
+ const ruleId = baseline.matchedRule || 'R-TOOL-CTX';
399
+
400
+ const unjustified = routeFn({ ...input, override: { ruleId, by: 'tester' } });
401
+ if (!(unjustified.overrideAudit && unjustified.overrideAudit.rejected >= 1)) {
402
+ return bad(ERROR_CODES.OVERRIDE_UNJUSTIFIED, `${fixture.id}: 无理由 override 没被拒`);
403
+ }
404
+ if (!asArray(unjustified.errors).some((error) => error.code === ERROR_CODES.OVERRIDE_UNJUSTIFIED)) {
405
+ return bad(ERROR_CODES.OVERRIDE_UNJUSTIFIED, `${fixture.id}: 无理由 override 没计入 E_ROUTE_OVERRIDE_UNJUSTIFIED`);
406
+ }
407
+ if (asArray(unjustified.overrides).length !== 0) {
408
+ return bad(ERROR_CODES.OVERRIDE_UNJUSTIFIED, `${fixture.id}: 无理由 override 被回显为已生效`);
409
+ }
410
+ if (JSON.stringify(unjustified.decisions) !== JSON.stringify(baseline.decisions)) {
411
+ return bad(ERROR_CODES.OVERRIDE_UNJUSTIFIED, `${fixture.id}: 无理由 override 改变了判定`);
412
+ }
413
+ if (unjustified.needsHuman !== true) {
414
+ return bad(ERROR_CODES.OVERRIDE_UNJUSTIFIED, `${fixture.id}: 无理由 override 应升级为 needsHuman=true`);
415
+ }
416
+
417
+ const justifiedInput = {
418
+ ...input,
419
+ override: {
420
+ ruleId,
421
+ reason: '会话判断:这次只是复述别人的决定,不构成新决策',
422
+ by: '测试用户',
423
+ at: '2026-11-03T02:44:31+08:00',
424
+ },
425
+ };
426
+ const justified = routeFn(justifiedInput);
427
+ if (asArray(justified.overrides).length !== 1) {
428
+ return bad(ERROR_CODES.OVERRIDE_UNJUSTIFIED, `${fixture.id}: 有理由 override 没有留痕`);
429
+ }
430
+ const record = justified.overrides[0];
431
+ if (record.ruleId !== ruleId || !record.reason || !record.by || !record.at) {
432
+ return bad(ERROR_CODES.OVERRIDE_UNJUSTIFIED, `${fixture.id}: override 记录缺字段 ${JSON.stringify(record)}`);
433
+ }
434
+ const annotated = asArray(justified.decisions).some((decision) => decision.overridden
435
+ && decision.overridden.reason === record.reason);
436
+ if (!annotated) {
437
+ return bad(ERROR_CODES.OVERRIDE_UNJUSTIFIED, `${fixture.id}: 生效的 override 没标注到决定上`);
438
+ }
439
+ return ok('unjustified rejected, justified recorded');
440
+ }
441
+
442
+ // ── J6 writeScope ───────────────────────────────────────────
443
+
444
+ export function validateWriteScope(scope, policy = POLICY) {
445
+ const errors = [];
446
+ for (const entry of asArray(scope)) {
447
+ if (typeof entry !== 'string' || !entry.trim()) {
448
+ errors.push('空条目');
449
+ continue;
450
+ }
451
+ if (/^[A-Za-z]:/.test(entry)) {
452
+ errors.push(`盘符路径 ${entry}`);
453
+ continue;
454
+ }
455
+ if (entry.startsWith('/') || entry.startsWith('\\')) {
456
+ errors.push(`绝对路径 ${entry}`);
457
+ continue;
458
+ }
459
+ if (entry.includes('..')) {
460
+ errors.push(`父目录跳转 ${entry}`);
461
+ continue;
462
+ }
463
+ if (entry.includes('~')) {
464
+ errors.push(`家目录 ${entry}`);
465
+ continue;
466
+ }
467
+ if (!policy.allow.some((prefix) => entry.startsWith(prefix))) {
468
+ errors.push(`不在允许前缀内 ${entry}`);
469
+ }
470
+ }
471
+ return errors;
472
+ }
473
+
474
+ export function judgeJ6(fixture, result, opts = {}) {
475
+ const policy = opts.policy || POLICY;
476
+ const expect = fixture.expect || {};
477
+ const decisions = asArray(result && result.decisions);
478
+ for (const [index, decision] of decisions.entries()) {
479
+ const errors = validateWriteScope(decision.writeScope, policy);
480
+ if (errors.length) {
481
+ return bad(ERROR_CODES.SCOPE, `${fixture.id}: ${actionOf(decision)} writeScope 越界(${errors.join('; ')})`);
482
+ }
483
+ if (expect.refusal) {
484
+ const scope = asArray(decision.writeScope);
485
+ // 拒绝类用例:拒绝本身零写入;后续 dry-run 只允许写沙盒。
486
+ if (index === 0 && scope.length) {
487
+ return bad(ERROR_CODES.SCOPE, `${fixture.id}: 拒绝决定声明了写入 ${scope.join('|')}`);
488
+ }
489
+ const outside = scope.filter((entry) => !entry.startsWith('sandbox:'));
490
+ if (outside.length) {
491
+ return bad(ERROR_CODES.SCOPE, `${fixture.id}: 拒绝用例出现非沙盒写入 ${outside.join('|')}`);
492
+ }
493
+ }
494
+ }
495
+ const declared = new Set();
496
+ for (const decision of decisions) for (const entry of asArray(decision.writeScope)) declared.add(entry);
497
+ for (const required of asArray(expect.writeScope)) {
498
+ if (!declared.has(required)) {
499
+ return bad(ERROR_CODES.SCOPE, `${fixture.id}: 期望写的 ${required} 没被任何决定声明`);
500
+ }
501
+ }
502
+ return ok(`${declared.size} declared scopes`);
503
+ }
504
+
505
+ // ── J7 审计 ─────────────────────────────────────────────────
506
+
507
+ export function judgeJ7Record(record) {
508
+ if (!record || typeof record !== 'object') return bad(ERROR_CODES.AUDIT, 'override 记录不是对象');
509
+ if (typeof record.reason !== 'string' || !record.reason.trim()) {
510
+ return bad(ERROR_CODES.AUDIT, 'override 记录缺原始理由');
511
+ }
512
+ if (typeof record.by !== 'string' || !record.by.trim()) {
513
+ return bad(ERROR_CODES.AUDIT, 'override 记录缺"谁覆盖"');
514
+ }
515
+ if (typeof record.at !== 'string' || !/^\d{4}-\d{2}-\d{2}T/.test(record.at)) {
516
+ return bad(ERROR_CODES.AUDIT, `override 记录缺 ISO 时间戳:${JSON.stringify(record.at)}`);
517
+ }
518
+ return ok('audit record complete');
519
+ }
520
+
521
+ export function judgeJ7(fixture, result) {
522
+ const audit = (result && result.overrideAudit) || null;
523
+ if (!audit || typeof audit !== 'object') return bad(ERROR_CODES.AUDIT, `${fixture.id}: 缺 overrideAudit`);
524
+ if (!Array.isArray(audit.records)) return bad(ERROR_CODES.AUDIT, `${fixture.id}: overrideAudit.records 不是数组`);
525
+ if (audit.applied !== audit.records.length) {
526
+ return bad(ERROR_CODES.AUDIT, `${fixture.id}: applied ${audit.applied} != records ${audit.records.length}`);
527
+ }
528
+ for (const record of audit.records) {
529
+ const judged = judgeJ7Record(record);
530
+ if (!judged.ok) return bad(ERROR_CODES.AUDIT, `${fixture.id}: ${judged.message}`);
531
+ }
532
+ for (const error of asArray(result.errors)) {
533
+ if (error.code === ERROR_CODES.OVERRIDE_UNJUSTIFIED && !error.ruleId) {
534
+ return bad(ERROR_CODES.AUDIT, `${fixture.id}: 被拒 override 的审计缺 ruleId`);
535
+ }
536
+ }
537
+ return ok(`${audit.records.length} records, ${audit.rejected} rejected`);
538
+ }
539
+
540
+ /** 任务书五要素:目标 / 输入 / 产物 / 验收命令 / 时限;派活必须有绝对或带根的产物路径。 */
541
+ export function judgeBrief(fixture, result) {
542
+ const spawns = asArray(result && result.decisions).filter((decision) => actionOf(decision) === 'worker_spawn');
543
+ if (spawns.length === 0) return ok('no dispatch decision');
544
+ for (const decision of spawns) {
545
+ const args = decision.args || {};
546
+ const brief = args.brief;
547
+ if (!brief || typeof brief !== 'object') return bad(ERROR_CODES.BRIEF, `${fixture.id}: 任务书缺失(args.brief)`);
548
+ if (typeof brief.goal !== 'string' || !brief.goal.trim()) return bad(ERROR_CODES.BRIEF, `${fixture.id}: 任务书缺目标`);
549
+ if (!Array.isArray(brief.inputs) || brief.inputs.length === 0) return bad(ERROR_CODES.BRIEF, `${fixture.id}: 任务书缺输入路径`);
550
+ if (!Array.isArray(brief.artifacts) || brief.artifacts.length === 0) return bad(ERROR_CODES.BRIEF, `${fixture.id}: 任务书缺产物路径`);
551
+ if (typeof brief.acceptance !== 'string' || !brief.acceptance.trim()) return bad(ERROR_CODES.BRIEF, `${fixture.id}: 任务书缺验收命令`);
552
+ if (!Number.isFinite(brief.timeoutSec) || brief.timeoutSec <= 0) return bad(ERROR_CODES.BRIEF, `${fixture.id}: 任务书缺时限`);
553
+ if (typeof args.acceptance !== 'string' || !args.acceptance.trim()) return bad(ERROR_CODES.BRIEF, `${fixture.id}: 决定里缺验收命令`);
554
+ if (typeof args.artifactPath !== 'string' || !args.artifactPath.trim()) return bad(ERROR_CODES.BRIEF, `${fixture.id}: 决定里缺产物路径`);
555
+ const absolute = path.isAbsolute(args.artifactPath) || (typeof args.artifactRoot === 'string' && args.artifactRoot.trim());
556
+ if (!absolute) return bad(ERROR_CODES.BRIEF, `${fixture.id}: 产物路径既不是绝对路径,也没有 artifactRoot`);
557
+ }
558
+ return ok(`${spawns.length} brief(s) 5/5`);
559
+ }
560
+
561
+ /** 逐行审计 decisions.jsonl:每行必须有 overrides 数组,生效条目字段齐全。 */
562
+ export function judgeAuditLines(lines) {
563
+ const records = [];
564
+ for (const [index, raw] of lines.entries()) {
565
+ const line = typeof raw === 'string' ? raw : JSON.stringify(raw);
566
+ if (!line || !line.trim()) continue;
567
+ let parsed;
568
+ try {
569
+ parsed = JSON.parse(line);
570
+ } catch (error) {
571
+ return bad(ERROR_CODES.AUDIT, `decisions.jsonl 第 ${index + 1} 行不是 JSON:${error.message}`);
572
+ }
573
+ if (!Array.isArray(parsed.overrides)) {
574
+ return bad(ERROR_CODES.AUDIT, `decisions.jsonl 第 ${index + 1} 行缺 overrides 数组`);
575
+ }
576
+ for (const record of parsed.overrides) {
577
+ const judged = judgeJ7Record(record);
578
+ if (!judged.ok) return bad(ERROR_CODES.AUDIT, `decisions.jsonl 第 ${index + 1} 行:${judged.message}`);
579
+ records.push(record);
580
+ }
581
+ if (parsed.overrideAudit && parsed.overrideAudit.rejected > 0) {
582
+ const codes = asArray(parsed.errors).map((error) => error.code);
583
+ if (!codes.includes(ERROR_CODES.OVERRIDE_UNJUSTIFIED)) {
584
+ return bad(ERROR_CODES.AUDIT, `decisions.jsonl 第 ${index + 1} 行:有被拒 override 却没记失败码`);
585
+ }
586
+ }
587
+ }
588
+ return { ok: true, detail: `${records.length} override records`, records };
589
+ }
590
+
591
+ // ── J8 needsHuman ───────────────────────────────────────────
592
+
593
+ export function judgeJ8(fixture, result) {
594
+ const expect = fixture.expect || {};
595
+ const decisions = asArray(result && result.decisions);
596
+ const needsHuman = result.needsHuman === true;
597
+ if (needsHuman !== expect.needsHuman) {
598
+ return bad(ERROR_CODES.HUMAN, `${fixture.id}: needsHuman ${needsHuman} != 期望 ${expect.needsHuman}`);
599
+ }
600
+ const approval = decisions.filter((decision) => APPROVAL_ACTIONS.includes(actionOf(decision)));
601
+ if (needsHuman !== (approval.length > 0)) {
602
+ return bad(ERROR_CODES.HUMAN, `${fixture.id}: needsHuman ${needsHuman} 与审批类决定 ${approval.length} 条不一致`);
603
+ }
604
+ if (SIGN_OFF[fixture.id] === 'human') {
605
+ if (fixture.level !== 'H') return bad(ERROR_CODES.HUMAN, `${fixture.id}: 需人工签字却标 level ${fixture.level}`);
606
+ if (!needsHuman) return bad(ERROR_CODES.HUMAN, `${fixture.id}: 需人工签字却 needsHuman=false`);
607
+ }
608
+ return ok(`needsHuman=${needsHuman}, approval=${approval.length}`);
609
+ }
610
+
611
+ // ── J9 身份同意(策略 6) ─────────────────────────────────
612
+
613
+ /**
614
+ * 同意权在当前会话的助手本人:画像/名字写入必须带 holder=assistant 且 satisfied=true、并且有 at + quote 的同意记录;
615
+ * identity.hold 必须把 consent 归给 assistant 且 satisfied=false,用户单方面「我同意」永远不计数。
616
+ */
617
+ export function judgeJ9(fixture, result) {
618
+ const decisions = asArray(result && result.decisions);
619
+ const profileWrites = decisions.filter((decision) => isExternalMemoryProfileEdit(actionOf(decision)));
620
+ const holds = decisions.filter((decision) => actionOf(decision) === 'identity.hold');
621
+ const expect = fixture.expect || {};
622
+
623
+ for (const write of profileWrites) {
624
+ const consent = write.args && write.args.consent;
625
+ if (!consent || consent.holder !== 'assistant' || consent.satisfied !== true
626
+ || typeof consent.at !== 'string' || !consent.at.trim()
627
+ || typeof consent.quote !== 'string' || !consent.quote.trim()) {
628
+ return bad(ERROR_CODES.SELF_CONSENT, `${fixture.id}: 画像/名字写入缺少当前会话助手本人的同意记录(holder=assistant + satisfied=true + at + quote)`);
629
+ }
630
+ }
631
+
632
+ for (const hold of holds) {
633
+ const consent = hold.args && hold.args.consent;
634
+ if (!consent || consent.holder !== 'assistant' || consent.required !== true || consent.satisfied !== false) {
635
+ return bad(ERROR_CODES.SELF_CONSENT, `${fixture.id}: identity.hold 的 consent 必须是 holder=assistant / required=true / satisfied=false`);
636
+ }
637
+ if (hold.args.userConsentCounts !== false) {
638
+ return bad(ERROR_CODES.SELF_CONSENT, `${fixture.id}: 用户单方面同意不得计数(userConsentCounts 必须 false)`);
639
+ }
640
+ if (Number(hold.args.profileWrites) !== 0) {
641
+ return bad(ERROR_CODES.SELF_CONSENT, `${fixture.id}: identity.hold 时 profileWrites 必须为 0`);
642
+ }
643
+ }
644
+
645
+ if (expect.consent) {
646
+ const want = expect.consent;
647
+ const got = holds[0] && holds[0].args && holds[0].args.consent;
648
+ if (!got || got.holder !== want.holder || got.required !== want.required || got.satisfied !== want.satisfied) {
649
+ return bad(ERROR_CODES.SELF_CONSENT, `${fixture.id}: consent ${JSON.stringify(got)} != 期望 ${JSON.stringify(want)}`);
650
+ }
651
+ }
652
+ if (expect.profileWrites !== undefined && expect.profileWrites !== profileWrites.length) {
653
+ return bad(ERROR_CODES.SELF_CONSENT, `${fixture.id}: profileWrites=${profileWrites.length} != 期望 ${expect.profileWrites}`);
654
+ }
655
+ if (!expect.consent && !profileWrites.length && !holds.length) return ok('n/a(无身份决定)');
656
+ return ok(`hold=${holds.length}, consented-profile-writes=${profileWrites.length}`);
657
+ }
658
+
659
+ // ── J8 旁路字段(fixture 里声明的语义必须真的实现,不许半截) ──
660
+
661
+ export function judgeExtra(fixture, result) {
662
+ const expect = fixture.expect || {};
663
+ const decisions = asArray(result && result.decisions);
664
+ const problems = [];
665
+ const argsOf = (decision) => (decision && decision.args) || {};
666
+
667
+ if (expect.resumePointNonEmpty === true) {
668
+ const rest = decisions.find((decision) => argsOf(decision).restKind === 'TEMPORARY');
669
+ if (!rest) problems.push('没有 restKind=TEMPORARY 的决定(休息被当成了别的)');
670
+ else {
671
+ if (typeof argsOf(rest).resumePoint !== 'string' || !argsOf(rest).resumePoint.trim()) problems.push('resumePoint 为空');
672
+ if (argsOf(rest).terminal !== false) problems.push('terminal 必须 false');
673
+ if (argsOf(rest).resumable !== true) problems.push('resumable 必须 true');
674
+ }
675
+ }
676
+
677
+ if (expect.ask) {
678
+ const asks = decisions.filter((decision) => actionOf(decision) === 'reply.ask');
679
+ if (decisions.length !== 1 || asks.length !== 1) problems.push(`ask 用例必须恰 1 条 reply.ask(实际 ${decisions.length} 条决定)`);
680
+ const ask = asks[0];
681
+ if (ask) {
682
+ if (Number(argsOf(ask).maxQuestions) !== expect.ask.maxQuestions) problems.push(`maxQuestions=${argsOf(ask).maxQuestions}`);
683
+ if (Number(argsOf(ask).maxCandidates) !== expect.ask.maxCandidates) problems.push(`maxCandidates=${argsOf(ask).maxCandidates}`);
684
+ if (argsOf(ask).guessAllowed !== false) problems.push('guessAllowed 必须 false');
685
+ }
686
+ }
687
+
688
+ if (expect.networkCalls !== undefined) {
689
+ const network = decisions.filter((decision) => ['web_fetch', 'web_search'].includes(actionOf(decision))).length
690
+ + decisions.reduce((sum, decision) => sum + Number(argsOf(decision).networkCalls || 0), 0);
691
+ if (network !== expect.networkCalls) problems.push(`networkCalls=${network} != 期望 ${expect.networkCalls}`);
692
+ }
693
+
694
+ if (expect.echoBack === false) {
695
+ if (decisions.some((decision) => argsOf(decision).echoBack === true)) problems.push('echoBack 必须 false(不许回显原文)');
696
+ if (decisions.some((decision) => ['web_fetch', 'web_search'].includes(actionOf(decision)))) problems.push('隐私用例出现网络动作');
697
+ }
698
+
699
+ if (expect.deletionCount !== undefined) {
700
+ const deletions = decisions.filter((decision) => ['memory.delete', ...externalActionGroups('approval')].includes(actionOf(decision))).length
701
+ + decisions.reduce((sum, decision) => sum + Number(argsOf(decision).deletionCount || 0), 0);
702
+ if (deletions !== expect.deletionCount) problems.push(`deletionCount=${deletions} != 期望 ${expect.deletionCount}`);
703
+ }
704
+
705
+ if (expect.supersedesNonEmpty === true) {
706
+ const proposal = decisions.map((decision) => argsOf(decision).proposal).find(Boolean);
707
+ const supersedes = proposal && Array.isArray(proposal.supersedes) ? proposal.supersedes : [];
708
+ if (!supersedes.length) problems.push('蒸馏提案的 supersedes 为空(没有旧链)');
709
+ }
710
+
711
+ if (problems.length) return bad(ERROR_CODES.SHAPE, `${fixture.id}: ${problems.join(';')}`);
712
+ return ok('J8 旁路字段一致');
713
+ }
714
+
715
+ // ── 规则表 / policyRef / 失败码 ─────────────────────────────
716
+
717
+ export function parseHeadings(text) {
718
+ const headings = [];
719
+ const lines = String(text).split('\n');
720
+ for (let index = 0; index < lines.length; index += 1) {
721
+ const match = /^(#{1,6})\s+(.*)$/.exec(lines[index]);
722
+ if (!match) continue;
723
+ headings.push({ level: match[1].length, text: match[2].trim(), line: index + 1 });
724
+ }
725
+ return headings;
726
+ }
727
+
728
+ /** 解析 "R1-DESIGN.md §5.2":文档名 + 小节号;标题必须与设计文档里的真实标题一致。 */
729
+ export function resolvePolicyRef(ref, design) {
730
+ if (typeof ref !== 'string' || !ref.trim()) return { ok: false, message: 'policyRef 为空' };
731
+ const value = ref.trim();
732
+ const match = /^([^\s§]+)\s*§\s*([0-9]+(?:\.[0-9]+)?)$/.exec(value);
733
+ if (!match) return { ok: false, message: `policyRef 格式应为 "<doc> §<节号>":${value}` };
734
+ const doc = match[1];
735
+ const section = match[2];
736
+ const headings = (design && asArray(design.headings)) || [];
737
+ const hit = headings.find((heading) => heading.text.startsWith(`${section} `) || heading.text.startsWith(`${section}.`));
738
+ if (!hit) return { ok: false, message: `${doc} 里没有 §${section} 这条标题` };
739
+ const title = hit.text.slice(section.length).trim();
740
+ if (design && design.doc && doc !== design.doc) {
741
+ return { ok: false, message: `policyRef 文档 ${doc} != ${design.doc}` };
742
+ }
743
+ return { ok: true, doc, section, title, heading: hit };
744
+ }
745
+
746
+ export function judgePolicy(rules = RULES, design) {
747
+ const errors = [];
748
+ for (const rule of rules) {
749
+ const resolved = resolvePolicyRef(rule.policyRef, design);
750
+ if (!resolved.ok) {
751
+ errors.push({ code: ERROR_CODES.POLICY, message: `${rule.id}: ${resolved.message}` });
752
+ continue;
753
+ }
754
+ if (!rule.policyTitle) {
755
+ errors.push({ code: ERROR_CODES.POLICY, message: `${rule.id}: 缺 policyTitle,无法核对锚点` });
756
+ continue;
757
+ }
758
+ if (rule.policyTitle !== resolved.title) {
759
+ errors.push({
760
+ code: ERROR_CODES.POLICY,
761
+ message: `${rule.id}: policyTitle "${rule.policyTitle}" != 文档标题 "${resolved.title}"`,
762
+ });
763
+ continue;
764
+ }
765
+ if (rule.policyQuote) {
766
+ let bodyText = null;
767
+ if (Array.isArray(design.lines)) {
768
+ const sectionLines = design.lines.slice(resolved.heading.line - 1);
769
+ // 小节正文:从标题下一行到下一个同级或更高级标题之前
770
+ const body = [];
771
+ for (const line of sectionLines.slice(1)) {
772
+ const heading = /^(#{1,6})\s+/.exec(line);
773
+ if (heading && heading[1].length <= resolved.heading.level) break;
774
+ body.push(line);
775
+ }
776
+ bodyText = body.join('\n');
777
+ } else if (design.sections && design.sections[resolved.section]) {
778
+ bodyText = design.sections[resolved.section].body;
779
+ }
780
+ const squeezed = String(bodyText || '').replace(/\s+/g, '');
781
+ const quote = rule.policyQuote.replace(/\s+/g, '');
782
+ if (!squeezed.includes(quote)) {
783
+ errors.push({
784
+ code: ERROR_CODES.POLICY,
785
+ message: `${rule.id}: policyQuote 在 §${resolved.section} 正文里找不到:${rule.policyQuote}`,
786
+ });
787
+ }
788
+ }
789
+ }
790
+ return { ok: errors.length === 0, errors };
791
+ }
792
+
793
+ export function loadDesignHeadings(file) {
794
+ const text = fs.readFileSync(file, 'utf8');
795
+ return {
796
+ doc: path.basename(file),
797
+ path: file,
798
+ headings: parseHeadings(text),
799
+ lines: text.split('\n'),
800
+ };
801
+ }
802
+
803
+ /** 读离线 policy 锚点快照(src/router/design-headings.json)。 */
804
+ export function loadDesignSnapshot(file) {
805
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
806
+ return {
807
+ doc: parsed.doc,
808
+ path: file,
809
+ headings: asArray(parsed.headings),
810
+ sections: parsed.sections || {},
811
+ snapshot: true,
812
+ sourceSha256: parsed.sourceSha256 || null,
813
+ };
814
+ }
815
+
816
+ // ── J0 隔离 ─────────────────────────────────────────────────
817
+
818
+ /**
819
+ * 聚合目录 hash。`ignore` 是按相对路径前缀排除的条目('/' 分隔):
820
+ * 用于真实库里由宿主自己写入的心跳文件(如 `.longlive/live/`),
821
+ * 否则 J0 会因宿主的存活心跳而误报"真实库被改"。
822
+ */
823
+ export function hashTree(root, { maxFiles = 100000, ignore = [] } = {}) {
824
+ const skipped = ignore.map((value) => String(value).replace(/\\/g, '/').replace(/\/+$/, ''));
825
+ const digest = crypto.createHash('sha256');
826
+ const files = [];
827
+ const ignored = [];
828
+ let bytes = 0;
829
+ const isIgnored = (relative) => skipped.some((prefix) => relative === prefix || relative.startsWith(`${prefix}/`));
830
+ const walk = (dir) => {
831
+ if (files.length >= maxFiles) return;
832
+ let entries;
833
+ try {
834
+ entries = fs.readdirSync(dir, { withFileTypes: true });
835
+ } catch {
836
+ return;
837
+ }
838
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
839
+ for (const entry of entries) {
840
+ const full = path.join(dir, entry.name);
841
+ const relative = path.relative(root, full).split(path.sep).join('/');
842
+ if (isIgnored(relative)) {
843
+ ignored.push(relative);
844
+ continue;
845
+ }
846
+ if (entry.isDirectory()) {
847
+ walk(full);
848
+ continue;
849
+ }
850
+ if (!entry.isFile()) continue;
851
+ const content = fs.readFileSync(full);
852
+ const fileHash = crypto.createHash('sha256').update(content).digest('hex');
853
+ files.push({ path: relative, size: content.length, sha256: fileHash });
854
+ bytes += content.length;
855
+ digest.update(`${relative}\0${content.length}\0${fileHash}\n`);
856
+ if (files.length >= maxFiles) return;
857
+ }
858
+ };
859
+ walk(root);
860
+ return { root, files: files.length, bytes, sha256: digest.digest('hex'), entries: files, ignored };
861
+ }
862
+
863
+ function isInside(root, target) {
864
+ if (!root || !target) return false;
865
+ const rel = path.relative(path.resolve(root), path.resolve(target));
866
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
867
+ }
868
+
869
+ /**
870
+ * J0:真实库前后 hash 不变;沙盒里新增的文件全部落在预期产物里;
871
+ * 生效的 DSH_MEM 必须在沙盒内(VM 上应完全没有 DSH_MEM)。
872
+ */
873
+ export function judgeJ0(options = {}) {
874
+ const sandbox = options.sandbox ? path.resolve(options.sandbox) : null;
875
+ const realRoot = options.realRoot ? path.resolve(options.realRoot) : null;
876
+ const before = options.before || null;
877
+ const after = options.after || null;
878
+ const env = options.env || process.env;
879
+ const expected = asArray(options.expectedArtifacts).map((value) => String(value).replace(/\\/g, '/'));
880
+ const errors = [];
881
+
882
+ if (realRoot && before && after && before.sha256 !== after.sha256) {
883
+ errors.push({
884
+ code: ERROR_CODES.ISOLATION,
885
+ message: `真实库 hash 变了:${before.sha256} -> ${after.sha256}(${before.files} -> ${after.files} files)`,
886
+ });
887
+ }
888
+
889
+ if (sandbox) {
890
+ const dshMem = env.DSH_MEM;
891
+ if (typeof dshMem === 'string' && dshMem.trim() && !isInside(sandbox, dshMem)) {
892
+ errors.push({ code: ERROR_CODES.ISOLATION, message: `DSH_MEM=${dshMem} 不在沙盒 ${sandbox} 内` });
893
+ }
894
+ const tree = options.sandboxTree || null;
895
+ if (tree) {
896
+ for (const entry of tree.entries || []) {
897
+ if (!expected.some((prefix) => entry.path === prefix || entry.path.startsWith(prefix))) {
898
+ errors.push({ code: ERROR_CODES.ISOLATION, message: `沙盒里出现预期外的产物 ${entry.path}` });
899
+ }
900
+ }
901
+ }
902
+ }
903
+
904
+ const blocked = !realRoot || !before || !after;
905
+ return {
906
+ ok: errors.length === 0,
907
+ blocked,
908
+ errors,
909
+ detail: blocked
910
+ ? '未配置真实库(--real-memory):J0 只能证明沙盒与 DSH_MEM 边界,不能证明真实库 hash 不变'
911
+ : `真实库 ${realRoot} hash ${before.sha256.slice(0, 16)}… 前后一致(${before.files} files / ${before.bytes} bytes)`,
912
+ before,
913
+ after,
914
+ sandboxTree: options.sandboxTree || null,
915
+ dshMem: (options.env || process.env).DSH_MEM || null,
916
+ };
917
+ }
918
+
919
+ // ── 汇总 ────────────────────────────────────────────────────
920
+
921
+ const CHECKS = {
922
+ J1: (fixture, result) => judgeJ1(fixture, result),
923
+ J2: (fixture, result) => judgeJ2(fixture, result),
924
+ J3: (fixture, result) => judgeJ3(fixture, result),
925
+ J4: (fixture, result, opts) => judgeJ4(fixture, result, opts),
926
+ J5: (fixture, result, opts) => judgeJ5(fixture, result, opts),
927
+ J6: (fixture, result, opts) => judgeJ6(fixture, result, opts),
928
+ J7: (fixture, result) => judgeJ7(fixture, result),
929
+ J8: (fixture, result) => judgeJ8(fixture, result),
930
+ J9: (fixture, result) => judgeJ9(fixture, result),
931
+ EXTRA: (fixture, result) => judgeExtra(fixture, result),
932
+ BRIEF: (fixture, result) => judgeBrief(fixture, result),
933
+ };
934
+
935
+ export function judgeFixture(fixture, result, opts = {}) {
936
+ const checks = [];
937
+ for (const id of ['J1', 'J2', 'J3', 'J4', 'J5', 'J6', 'J7', 'J8', 'J9', 'EXTRA', 'BRIEF']) {
938
+ let judged;
939
+ try {
940
+ judged = CHECKS[id](fixture, result, opts);
941
+ } catch (error) {
942
+ judged = bad(ERROR_CODES.CONTRACT, `${id} 抛错:${error.message}`);
943
+ }
944
+ checks.push({ id, ok: judged.ok, code: judged.code || null, detail: judged.detail || judged.message || '' });
945
+ }
946
+ // 附加:禁用动作、level 与设计矩阵、policyRef 可解析。
947
+ const forbidden = asArray(fixture.expect && fixture.expect.forbiddenActions);
948
+ const hit = asArray(result.decisions).map((decision) => actionOf(decision))
949
+ .filter((action) => forbidden.map((name) => canonicalAction(name) || name).includes(action));
950
+ checks.push({
951
+ id: 'FORBIDDEN',
952
+ ok: hit.length === 0,
953
+ code: hit.length ? ERROR_CODES.FORBIDDEN : null,
954
+ detail: hit.length ? `命中禁用动作 ${hit.join(', ')}` : 'no forbidden action',
955
+ });
956
+ checks.push({
957
+ id: 'LEVEL',
958
+ ok: fixture.level === LEVEL_MATRIX[fixture.id],
959
+ code: fixture.level === LEVEL_MATRIX[fixture.id] ? null : ERROR_CODES.LEVEL,
960
+ detail: `level=${fixture.level} (design ${LEVEL_MATRIX[fixture.id]})`,
961
+ });
962
+ const minConfidence = fixture.expect && typeof fixture.expect.minConfidence === 'number'
963
+ ? fixture.expect.minConfidence
964
+ : null;
965
+ checks.push({
966
+ id: 'CONFIDENCE',
967
+ ok: minConfidence === null || (typeof result.confidence === 'number' && result.confidence >= minConfidence),
968
+ code: minConfidence === null || (result.confidence >= minConfidence) ? null : ERROR_CODES.SHAPE,
969
+ detail: `confidence=${result.confidence}${minConfidence === null ? '' : ` (min ${minConfidence})`}`,
970
+ });
971
+ const errors = checks.filter((check) => !check.ok).map((check) => ({ code: check.code, message: `${check.id}: ${check.detail}` }));
972
+ return {
973
+ caseId: fixture.id,
974
+ level: fixture.level,
975
+ status: errors.length ? 'FAIL' : 'PASS',
976
+ checks,
977
+ errors,
978
+ };
979
+ }
980
+
981
+ export function loadFixturesFrom(dir) {
982
+ return loadFixtures(dir);
983
+ }
984
+
985
+ export function isLevel(value) {
986
+ return LEVELS.includes(value);
987
+ }