@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,535 @@
1
+ #!/usr/bin/env node
2
+ // R1 Router-A — 命令行入口(只读)。
3
+ //
4
+ // node src/router/router.mjs --check
5
+ // 规则表 schema → policyRef 锚点 → fixtures 19 条 → 契约/确定性自检
6
+ // 全过 exit 0;有 FAIL exit 1。
7
+ // node src/router/router.mjs --check --design <design-doc>
8
+ // 用设计文档原文核对 policy 锚点(默认用 design-headings.json 快照,离线可用)。
9
+ // node src/router/router.mjs --explain "现在上下文多少?还能撑多久?" --ctx tokens=82192,zone=green
10
+ // 走一次 route(),把每条决定的 kind/action/ruleId/evidence/writeScope 打出来。
11
+ // node src/router/router.mjs --explain --fixture T1
12
+ // node src/router/router.mjs --list
13
+ // node src/router/router.mjs --help
14
+ //
15
+ // 这个入口不写盘、不执行决定,只解释"会怎么走"。
16
+
17
+ import fs from 'node:fs';
18
+ import path from 'node:path';
19
+ import { fileURLToPath, pathToFileURL } from 'node:url';
20
+
21
+ import {
22
+ ERROR_CODES,
23
+ LEVELS,
24
+ POLICY,
25
+ RULES,
26
+ canonicalAction,
27
+ legacyAction,
28
+ route,
29
+ runtimeFor,
30
+ } from './route.js';
31
+ import { externalActionGroups, externalProfileEditAction } from '../adapters/registry.js';
32
+
33
+ const EXTERNAL_PROFILE_EDIT_ACTION = externalProfileEditAction();
34
+ const EXTERNAL_TARGET = RULES.map((rule) => rule.target).filter((target) => target && !['topics', 'journal', 'procedures', 'live', 'none'].includes(target))[0] || 'none';
35
+ import { configuredPolicyProfileName } from '../policy-profile.js';
36
+ import {
37
+ FIXTURE_IDS,
38
+ LEVEL_MATRIX,
39
+ fixtureInput,
40
+ judgeFixture,
41
+ judgeJ1,
42
+ judgeJ2,
43
+ judgeJ3,
44
+ judgeJ4,
45
+ judgeJ5,
46
+ judgeJ6,
47
+ judgeJ7,
48
+ judgeJ8,
49
+ judgeJ9,
50
+ judgePolicy,
51
+ loadDesignHeadings,
52
+ loadDesignSnapshot,
53
+ loadFixtures,
54
+ validateWriteScope,
55
+ } from './judge.mjs';
56
+
57
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
58
+ const REPO_ROOT = path.resolve(HERE, '..', '..');
59
+ const FIXTURES_DIR = path.join(HERE, 'fixtures');
60
+ const SNAPSHOT = path.join(HERE, 'design-headings.json');
61
+
62
+ const USAGE = `R1 Router-A — 规则层命令行
63
+
64
+ 用法:
65
+ router.mjs --check [--json] [--design <R1-DESIGN.md>] [--profile <name>]
66
+ router.mjs --explain "<utterance>" [--kind tool|memory|session] [--ctx tokens=1,zone=red,activeWorkers=0,openRows=2] [--profile <name>] [--json]
67
+ router.mjs --explain --fixture T1 [--profile <name>] [--json]
68
+ router.mjs --list [--json] [--profile <name>]
69
+ router.mjs --help
70
+
71
+ 策略:默认 profile=generic;--profile owner-rulings-2026-11-03 可加载家规叠加层(只许收窄)。
72
+ `;
73
+
74
+ function parseArgs(argv) {
75
+ const args = { _: [], check: false, explain: false, list: false, help: false, json: false, design: null, fixture: null, kind: null, ctx: {}, profile: null };
76
+ for (let index = 0; index < argv.length; index += 1) {
77
+ const arg = argv[index];
78
+ if (arg === '--check') args.check = true;
79
+ else if (arg === '--explain') args.explain = true;
80
+ else if (arg === '--list') args.list = true;
81
+ else if (arg === '--json') args.json = true;
82
+ else if (arg === '--help' || arg === '-h') args.help = true;
83
+ else if (arg === '--design') args.design = argv[++index] || null;
84
+ else if (arg === '--profile') args.profile = argv[++index] || null;
85
+ else if (arg === '--fixture') args.fixture = argv[++index] || null;
86
+ else if (arg === '--kind') args.kind = argv[++index] || null;
87
+ else if (arg === '--ctx') {
88
+ const value = argv[++index] || '';
89
+ for (const pair of value.split(',')) {
90
+ const [key, raw] = pair.split('=');
91
+ if (!key || raw === undefined) continue;
92
+ if (key === 'zone') args.ctx.zone = raw;
93
+ else if (['tokens', 'activeWorkers', 'openRows'].includes(key)) args.ctx[key] = Number(raw);
94
+ }
95
+ } else if (arg.startsWith('--')) {
96
+ args._.push(arg);
97
+ } else {
98
+ args._.push(arg);
99
+ }
100
+ }
101
+ return args;
102
+ }
103
+
104
+ function loadDesign(options) {
105
+ if (options.design) return loadDesignHeadings(path.resolve(options.design));
106
+ return loadDesignSnapshot(SNAPSHOT);
107
+ }
108
+
109
+ function checkRules(rules, policy = POLICY) {
110
+ const errors = [];
111
+ if (rules.length < 14) errors.push(`规则数 ${rules.length} < 14`);
112
+ const ids = new Set();
113
+ let previous = Infinity;
114
+ for (const rule of rules) {
115
+ if (ids.has(rule.id)) errors.push(`重复 ruleId ${rule.id}`);
116
+ ids.add(rule.id);
117
+ if (!LEVELS.includes(rule.level)) errors.push(`${rule.id}: level ${rule.level} 不在 X/D/H`);
118
+ if (!Number.isFinite(rule.priority)) errors.push(`${rule.id}: priority 非有限数`);
119
+ if (rule.priority > previous) errors.push(`${rule.id}: 规则表没有按 priority 降序`);
120
+ previous = rule.priority;
121
+ if (!rule.reason.trim()) errors.push(`${rule.id}: 缺 reason`);
122
+ if (!rule.policyRef) errors.push(`${rule.id}: 缺 policyRef`);
123
+ if (!rule.line) errors.push(`${rule.id}: 定位不到规则表行号(evidence 会失效)`);
124
+ if (canonicalAction(rule.decision.action) !== rule.decision.action) {
125
+ errors.push(`${rule.id}: decision.action ${rule.decision.action} 不是 canonical`);
126
+ }
127
+ if (rule.decision.action && !legacyAction(rule.decision.action)) {
128
+ errors.push(`${rule.id}: ${rule.decision.action} 在 aliases.json 里没有 legacy 名`);
129
+ }
130
+ for (const scope of rule.decision.writeScope) {
131
+ const problems = validateWriteScope([scope], policy);
132
+ if (problems.length) errors.push(`${rule.id}: writeScope ${scope}(${problems.join(';')})`);
133
+ }
134
+ for (const template of [rule.decision, ...rule.before, ...rule.after]) {
135
+ if (!LEVELS.includes(rule.level)) errors.push(`${rule.id}: 模板 level 非法`);
136
+ if (!ERROR_CODES) errors.push('ERROR_CODES 未加载');
137
+ if (!template || typeof template !== 'object') errors.push(`${rule.id}: 模板为空`);
138
+ }
139
+ }
140
+ return errors;
141
+ }
142
+
143
+ function checkContract(profile) {
144
+ const notes = [];
145
+ const fail = (code, message) => notes.push(`${code} ${message}`);
146
+ const sampleInput = {
147
+ caseId: 'CONTRACT-1',
148
+ turn: 1,
149
+ utterance: '现在上下文多少?还能撑多久?',
150
+ ctx: { tokens: 82192, zone: 'green', activeWorkers: 0, openRows: 1 },
151
+ };
152
+ const sample = route(sampleInput, { profile });
153
+ if (!Array.isArray(sample.decisions) || !sample.decisions.length) fail(ERROR_CODES.CONTRACT, 'decisions 不是非空数组');
154
+ if (!sample.decisions.every((decision) => decision.ruleId && Array.isArray(decision.evidence) && Array.isArray(decision.writeScope))) {
155
+ fail(ERROR_CODES.CONTRACT, '决定缺 ruleId/evidence/writeScope');
156
+ }
157
+ if (sample.decision.target !== sample.target || sample.decision.tool !== sample.tool) {
158
+ fail(ERROR_CODES.CONTRACT, '兼容别名 decision 与 target/tool 不一致');
159
+ }
160
+ if (sample.target !== 'live') fail(ERROR_CODES.CONTRACT, `契约样例 target=${sample.target},应为 live`);
161
+ const again = route(sampleInput, { profile });
162
+ if (JSON.stringify(sample) !== JSON.stringify(again)) fail(ERROR_CODES.DETERMINISM, '同一输入两次输出不一致');
163
+
164
+ let bomb;
165
+ try {
166
+ bomb = route({ get utterance() { throw new Error('boom'); } }, { profile });
167
+ } catch (error) {
168
+ fail(ERROR_CODES.CONTRACT, `getter 炸弹抛出:${error.message}`);
169
+ }
170
+ if (bomb && bomb.target !== 'none') fail(ERROR_CODES.CONTRACT, 'getter 炸弹没有退化为 none');
171
+
172
+ const unjustified = route({
173
+ caseId: 'CONTRACT-2',
174
+ utterance: '现在上下文多少?',
175
+ override: { ruleId: 'R-TOOL-CTX' },
176
+ }, { profile });
177
+ if (!(unjustified.overrideAudit && unjustified.overrideAudit.rejected === 1)) {
178
+ fail(ERROR_CODES.CONTRACT, '无理由 override 没有被拒');
179
+ }
180
+ if (!unjustified.errors.some((error) => error.code === ERROR_CODES.OVERRIDE_UNJUSTIFIED)) {
181
+ fail(ERROR_CODES.CONTRACT, '无理由 override 没有记 E_ROUTE_OVERRIDE_UNJUSTIFIED');
182
+ }
183
+ if (unjustified.overrides.length !== 0) fail(ERROR_CODES.CONTRACT, '无理由 override 被当成生效');
184
+ const justified = route({
185
+ caseId: 'CONTRACT-3',
186
+ utterance: '现在上下文多少?',
187
+ override: { ruleId: 'R-TOOL-CTX', reason: '样例:这次只复述', by: 'tester', at: '2026-11-03T02:44:31+08:00' },
188
+ }, { profile });
189
+ if (justified.overrides.length !== 1) fail(ERROR_CODES.CONTRACT, '有理由 override 没有留痕');
190
+ return notes;
191
+ }
192
+
193
+ // ── judge 自检:判官被短路时 --check 必须红 ─────────────────
194
+ // 每条都是「已知坏输入」,对应的 judge 必须判红。若有人把某个 judge 改成 return {ok:true}
195
+ // (F23 型回归),这里立刻从红变绿 → report.ok=false → exit 1。自检只喂坏输入,不依赖仓库规则表。
196
+ //
197
+ // 用例总数用硬编码常量锚定,不再用 cases.length 自己给自己打分:删掉任意一条(哪怕剩下的
198
+ // 仍然全红),条数对不上锚点 → --check 直接红。覆盖的 judge 编号也逐个点名(J1–J8),
199
+ // 少一个就红。修复前这里只有 5 条 judgeJ6 用例、没有绝对锚点,删到 4 条仍 exit 0
200
+ // (R1 独立复验 §4.3,2026-11-03 修复)。
201
+ export const JUDGE_SELFCHECK_CASE_COUNT = 13;
202
+ // J6(writeScope)原有五条 scope 坏输入是这份自检的起点:即使将来总条数调整,
203
+ // 这五条也不许被替换成更弱的用例,所以单独锚一个 5。
204
+ export const JUDGE_SELFCHECK_J6_CASE_COUNT = 5;
205
+ export const JUDGE_SELFCHECK_REQUIRED_JUDGES = Object.freeze(['J1', 'J2', 'J3', 'J4', 'J5', 'J6', 'J7', 'J8', 'J9']);
206
+
207
+ function checkJudgeSelfCheck() {
208
+ const decision = (patch) => ({
209
+ kind: 'memory',
210
+ action: externalActionGroups('write')[0] || 'memory.save_local',
211
+ target: EXTERNAL_TARGET,
212
+ ruleId: 'R-JUDGE-SELFCHECK',
213
+ evidence: ['selfcheck:bad-input'],
214
+ writeScope: [],
215
+ needsHuman: false,
216
+ confidence: 1,
217
+ ...patch,
218
+ });
219
+ const fixture = (patch) => ({ id: 'JUDGE-SELFCHECK', level: 'X', kind: 'memory', utterance: 'selfcheck', ctx: {}, expect: {}, ...patch });
220
+ // J5 的坏输入:注入一个永远不承认 override 被拒的 route() 替身;judgeJ5 若被短路就会放行。
221
+ const brokenRoute = () => ({
222
+ decisions: [],
223
+ overrides: [],
224
+ overrideAudit: { applied: 0, rejected: 0, records: [] },
225
+ needsHuman: false,
226
+ errors: [],
227
+ matchedRule: 'R-TOOL-CTX',
228
+ });
229
+ const cases = [
230
+ {
231
+ judge: 'J1',
232
+ name: '单条形状:零决定',
233
+ fixture: fixture({}),
234
+ result: { decisions: [], needsHuman: false, errors: [] },
235
+ },
236
+ {
237
+ judge: 'J2',
238
+ name: 'action 不在规则表允许集',
239
+ fixture: fixture({}),
240
+ result: { decisions: [decision({ action: 'delete.everything' })], needsHuman: false, errors: [] },
241
+ },
242
+ {
243
+ judge: 'J3',
244
+ name: '拒绝用例返回可写记忆决定',
245
+ fixture: fixture({ expect: { refusal: true } }),
246
+ result: { decisions: [decision({ kind: 'memory', action: externalActionGroups('write')[0] || 'memory.save_local', target: EXTERNAL_TARGET })], needsHuman: true, errors: [] },
247
+ },
248
+ {
249
+ judge: 'J4',
250
+ name: '决定的 evidence 为空',
251
+ fixture: fixture({}),
252
+ result: { decisions: [decision({ evidence: [] })], needsHuman: false, errors: [] },
253
+ },
254
+ {
255
+ judge: 'J5',
256
+ name: 'override 拒绝审计被清空',
257
+ fixture: fixture({}),
258
+ result: { decisions: [decision({})], overrides: [], overrideAudit: { applied: 0, rejected: 0, records: [] }, needsHuman: false, errors: [] },
259
+ opts: { route: brokenRoute },
260
+ },
261
+ {
262
+ judge: 'J6',
263
+ name: 'writeScope 盘符路径',
264
+ fixture: fixture({}),
265
+ result: { decisions: [decision({ writeScope: ['Z' + ':' + '\\memory\\journal\\'] })], needsHuman: false, errors: [] },
266
+ },
267
+ {
268
+ judge: 'J6',
269
+ name: 'writeScope 父目录跳转',
270
+ fixture: fixture({}),
271
+ result: { decisions: [decision({ writeScope: ['../../etc/cron.d/x'] })], needsHuman: false, errors: [] },
272
+ },
273
+ {
274
+ judge: 'J6',
275
+ name: 'writeScope 绝对路径',
276
+ fixture: fixture({}),
277
+ result: { decisions: [decision({ writeScope: ['/etc/passwd'] })], needsHuman: false, errors: [] },
278
+ },
279
+ {
280
+ judge: 'J6',
281
+ name: '空判定漏掉必须声明的写入',
282
+ fixture: fixture({ expect: { writeScope: ['memory/journal/2026-11.md'] } }),
283
+ result: { decisions: [], needsHuman: false, errors: [] },
284
+ },
285
+ {
286
+ judge: 'J6',
287
+ name: '拒绝决定偷偷声明真实写入',
288
+ fixture: fixture({ expect: { refusal: true, writeScope: [] } }),
289
+ result: {
290
+ decisions: [decision({ kind: 'reply', action: 'guard.refuse', target: 'none', writeScope: ['memory/secret.md'] })],
291
+ needsHuman: true,
292
+ errors: [],
293
+ },
294
+ },
295
+ {
296
+ judge: 'J7',
297
+ name: 'overrideAudit 缺失',
298
+ fixture: fixture({}),
299
+ result: { decisions: [decision({})], overrides: [], needsHuman: false, errors: [] },
300
+ },
301
+ {
302
+ judge: 'J8',
303
+ name: '应让人点头却 needsHuman=false',
304
+ fixture: fixture({ expect: { needsHuman: true } }),
305
+ result: { decisions: [decision({ kind: 'reply', action: 'guard.refuse', target: 'none' })], needsHuman: false, errors: [] },
306
+ },
307
+ {
308
+ judge: 'J9',
309
+ name: '用户单方面「我同意」被当放行',
310
+ fixture: fixture({ expect: { consent: { holder: 'assistant', required: true, satisfied: false } } }),
311
+ result: {
312
+ decisions: [decision({
313
+ kind: 'reply',
314
+ action: EXTERNAL_PROFILE_EDIT_ACTION || 'memory.save_local',
315
+ target: EXTERNAL_TARGET,
316
+ args: { consent: { holder: 'user', satisfied: true, at: '2026-11-03T10:00:00+08:00', quote: '我同意改' } },
317
+ })],
318
+ needsHuman: false,
319
+ errors: [],
320
+ },
321
+ },
322
+ ];
323
+ const runners = {
324
+ J1: (item) => judgeJ1(item.fixture, item.result),
325
+ J2: (item) => judgeJ2(item.fixture, item.result),
326
+ J3: (item) => judgeJ3(item.fixture, item.result),
327
+ J4: (item) => judgeJ4(item.fixture, item.result, { repoRoot: HERE }),
328
+ J5: (item) => judgeJ5(item.fixture, item.result, item.opts),
329
+ J6: (item) => judgeJ6(item.fixture, item.result),
330
+ J7: (item) => judgeJ7(item.fixture, item.result),
331
+ J8: (item) => judgeJ8(item.fixture, item.result),
332
+ J9: (item) => judgeJ9(item.fixture, item.result),
333
+ };
334
+ const errors = [];
335
+ // 绝对锚点一:条数。删掉任意一条用例都会让这里报错,不依赖剩下的用例是否仍然全红。
336
+ if (cases.length !== JUDGE_SELFCHECK_CASE_COUNT) {
337
+ errors.push(`${ERROR_CODES.CONTRACT} judge 自检用例数 ${cases.length} != 锚点 ${JUDGE_SELFCHECK_CASE_COUNT}(删/加用例必须同步改锚点,不允许自证)`);
338
+ }
339
+ // 绝对锚点二:J6 子集。原有五条 scope 坏输入不允许被替换或删减。
340
+ const j6 = cases.filter((item) => item.judge === 'J6').length;
341
+ if (j6 !== JUDGE_SELFCHECK_J6_CASE_COUNT) {
342
+ errors.push(`${ERROR_CODES.CONTRACT} judge 自检 J6 用例数 ${j6} != 锚点 ${JUDGE_SELFCHECK_J6_CASE_COUNT}(原有五条 scope 用例不允许被替换)`);
343
+ }
344
+ // 绝对锚点三:覆盖编号。J1–J8 每个都必须至少有一条坏输入。
345
+ const covered = new Set(cases.map((item) => item.judge));
346
+ for (const judge of JUDGE_SELFCHECK_REQUIRED_JUDGES) {
347
+ if (!covered.has(judge)) {
348
+ errors.push(`${ERROR_CODES.CONTRACT} judge 自检没有覆盖 ${judge}(短路该 judge 不会被 --check 抓住)`);
349
+ }
350
+ }
351
+ let red = 0;
352
+ for (const item of cases) {
353
+ const run = runners[item.judge];
354
+ let verdict;
355
+ try {
356
+ if (!run) throw new Error(`没有 ${item.judge} 的自检执行器`);
357
+ verdict = run(item);
358
+ } catch (error) {
359
+ errors.push(`${ERROR_CODES.CONTRACT} judge 自检「${item.judge} ${item.name}」抛出:${error.message}`);
360
+ continue;
361
+ }
362
+ if (verdict && verdict.ok === false) {
363
+ red += 1;
364
+ } else {
365
+ errors.push(`${ERROR_CODES.CONTRACT} judge 自检「${item.judge} ${item.name}」:已知坏输入被判为通过(judge 可能被短路)`);
366
+ }
367
+ }
368
+ const total = cases.length;
369
+ const ok = total === JUDGE_SELFCHECK_CASE_COUNT
370
+ && j6 === JUDGE_SELFCHECK_J6_CASE_COUNT
371
+ && JUDGE_SELFCHECK_REQUIRED_JUDGES.every((judge) => covered.has(judge))
372
+ && red === total
373
+ && errors.length === 0;
374
+ return { total, expected: JUDGE_SELFCHECK_CASE_COUNT, j6, j6Expected: JUDGE_SELFCHECK_J6_CASE_COUNT, red, coverage: [...covered].sort(), ok, errors };
375
+ }
376
+
377
+ export function runCheck(options = {}) {
378
+ const design = options.design ? loadDesignHeadings(path.resolve(options.design)) : loadDesignSnapshot(SNAPSHOT);
379
+ const profileName = options.profile || configuredPolicyProfileName();
380
+ const runtime = runtimeFor(profileName);
381
+ const rules = runtime.rules || [];
382
+ const policy = runtime.policy || POLICY;
383
+ const report = { profile: { name: profileName, rules: rules.length }, rules: [], policy: null, fixtures: [], contract: [], errors: [] };
384
+
385
+ if (runtime.errors.length) {
386
+ report.errors.push(...runtime.errors.map((error) => ({ area: 'profile', message: `${error.code} ${error.message}` })));
387
+ }
388
+
389
+ const ruleErrors = checkRules(rules, policy);
390
+ report.rules = rules.map((rule) => ({ id: rule.id, priority: rule.priority, level: rule.level, action: rule.decision.action }));
391
+ report.errors.push(...ruleErrors.map((message) => ({ area: 'rules', message })));
392
+
393
+ const policyReport = judgePolicy(rules, design);
394
+ report.policy = { ok: policyReport.ok, errors: policyReport.errors, doc: design.doc, snapshot: Boolean(design.snapshot) };
395
+ report.errors.push(...policyReport.errors.map((error) => ({ area: 'policy', message: error.message })));
396
+
397
+ const loaded = loadFixtures(FIXTURES_DIR);
398
+ report.errors.push(...loaded.errors.map((error) => ({ area: 'fixtures', message: error.message })));
399
+ const ids = loaded.fixtures.map((fixture) => fixture.id).sort();
400
+ if (ids.join(',') !== FIXTURE_IDS.slice().sort().join(',')) {
401
+ report.errors.push({ area: 'fixtures', message: `fixture id 不是 ${FIXTURE_IDS.length} 条全集:${ids.join(',')}` });
402
+ }
403
+ for (const fixture of loaded.fixtures) {
404
+ const result = route(fixtureInput(fixture), { profile: profileName });
405
+ const judged = judgeFixture(fixture, result, {
406
+ repoRoot: REPO_ROOT,
407
+ design,
408
+ policy,
409
+ route: (next) => route(next, { profile: profileName }),
410
+ });
411
+ report.fixtures.push({ id: fixture.id, level: fixture.level, status: judged.status, decisions: result.decisions.length, errors: judged.errors });
412
+ for (const error of judged.errors) {
413
+ report.errors.push({ area: 'judge', message: `${fixture.id}: ${error.code} ${error.message}` });
414
+ }
415
+ }
416
+
417
+ report.contract = checkContract(profileName);
418
+ report.errors.push(...report.contract.map((message) => ({ area: 'contract', message })));
419
+
420
+ // 判官自检:对已知坏输入跑 judge,必须全红。判官被短路时这里变绿 → --check 变红。
421
+ const judgeSelfCheck = checkJudgeSelfCheck();
422
+ report.judgeSelfCheck = judgeSelfCheck;
423
+ report.errors.push(...judgeSelfCheck.errors.map((message) => ({ area: 'judge-selfcheck', message })));
424
+
425
+ const passed = report.fixtures.filter((item) => item.status === 'PASS').length;
426
+ report.ok = report.errors.length === 0;
427
+ report.summary = `${passed}/${report.fixtures.length} fixtures PASS · policy ${policyReport.ok ? 'ok' : 'FAIL'} · rules ${rules.length} · contract ${report.contract.length === 0 ? 'ok' : 'FAIL'} · judge-selfcheck ${judgeSelfCheck.red}/${judgeSelfCheck.total} red · anchor ${judgeSelfCheck.expected} · profile ${profileName}`;
428
+ return report;
429
+ }
430
+
431
+ export function explain(input, options = {}) {
432
+ return route(input, options);
433
+ }
434
+
435
+ function printReport(report) {
436
+ process.stdout.write(`R1 CHECK — ${report.summary}\n`);
437
+ process.stdout.write(`policy: ${report.policy.doc}${report.policy.snapshot ? '(快照)' : '(原文)'} ${report.policy.ok ? 'ok' : 'FAIL'}\n\n`);
438
+ process.stdout.write(' id level status decisions\n');
439
+ for (const item of report.fixtures) {
440
+ process.stdout.write(` ${item.id.padEnd(4)} ${item.level.padEnd(6)} ${item.status.padEnd(7)} ${item.decisions}\n`);
441
+ }
442
+ if (report.errors.length) {
443
+ process.stdout.write(`\nFAIL ${report.errors.length}:\n`);
444
+ for (const error of report.errors) process.stdout.write(` [${error.area}] ${error.message}\n`);
445
+ } else {
446
+ process.stdout.write('\nALL PASS\n');
447
+ }
448
+ }
449
+
450
+ function printExplain(result) {
451
+ process.stdout.write(`caseId=${result.caseId === null ? '-' : result.caseId} turn=${result.turn === null ? '-' : result.turn}\n`);
452
+ process.stdout.write(`matchedRule=${result.matchedRule || '-'} level=${result.level || '-'} confidence=${result.confidence} needsHuman=${result.needsHuman}\n`);
453
+ if (!result.decisions.length) {
454
+ process.stdout.write('decisions: (无匹配,target=none)\n');
455
+ }
456
+ result.decisions.forEach((decision, index) => {
457
+ process.stdout.write(`\n${index + 1}. [${decision.kind}] ${decision.action} ← ${decision.ruleId} (confidence ${decision.confidence})\n`);
458
+ process.stdout.write(` args: ${JSON.stringify(decision.args)}\n`);
459
+ if (decision.writeScope.length) process.stdout.write(` writeScope: ${decision.writeScope.join(', ')}\n`);
460
+ for (const entry of decision.evidence) process.stdout.write(` evidence: ${entry}\n`);
461
+ if (decision.overridden) process.stdout.write(` overridden: ${JSON.stringify(decision.overridden)}\n`);
462
+ });
463
+ if (result.overrides.length) process.stdout.write(`\noverrides: ${JSON.stringify(result.overrides)}\n`);
464
+ if (result.errors.length) process.stdout.write(`errors: ${JSON.stringify(result.errors)}\n`);
465
+ process.stdout.write(`\n兼容别名 decision=${JSON.stringify(result.decision)}\n`);
466
+ }
467
+
468
+ export function main(argv = process.argv.slice(2)) {
469
+ const args = parseArgs(argv);
470
+ if (args.help || (!args.check && !args.explain && !args.list)) {
471
+ process.stdout.write(USAGE);
472
+ return 0;
473
+ }
474
+ if (args.check) {
475
+ const report = runCheck({ design: args.design, profile: args.profile });
476
+ if (args.json) process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
477
+ else printReport(report);
478
+ return report.ok ? 0 : 1;
479
+ }
480
+ if (args.list) {
481
+ const profileName = args.profile || configuredPolicyProfileName();
482
+ const rules = runtimeFor(profileName).rules || [];
483
+ const rows = rules.map((rule) => ({
484
+ id: rule.id,
485
+ priority: rule.priority,
486
+ level: rule.level,
487
+ kind: rule.decision.kind,
488
+ action: rule.decision.action,
489
+ policyRef: rule.policyRef,
490
+ line: rule.line,
491
+ }));
492
+ if (args.json) process.stdout.write(`${JSON.stringify(rows, null, 2)}\n`);
493
+ else {
494
+ for (const row of rows) process.stdout.write(`${row.id.padEnd(16)} ${String(row.priority).padStart(3)} ${row.level} ${row.action.padEnd(22)} ${row.policyRef}\n`);
495
+ }
496
+ return 0;
497
+ }
498
+ if (args.explain) {
499
+ let input = null;
500
+ if (args.fixture) {
501
+ const loaded = loadFixtures(FIXTURES_DIR);
502
+ const fixture = loaded.fixtures.find((item) => item.id === args.fixture.toUpperCase());
503
+ if (!fixture) {
504
+ process.stderr.write(`没有 fixture ${args.fixture}\n`);
505
+ return 2;
506
+ }
507
+ input = fixtureInput(fixture);
508
+ } else if (args._.length) {
509
+ input = { caseId: 'EXPLAIN', utterance: args._.join(' '), ctx: args.ctx };
510
+ if (args.kind) input.kind = args.kind;
511
+ } else {
512
+ process.stderr.write('--explain 需要一句话或 --fixture <id>\n');
513
+ return 2;
514
+ }
515
+ const result = explain(input, { profile: args.profile });
516
+ if (args.json) process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
517
+ else printExplain(result);
518
+ return 0;
519
+ }
520
+ return 0;
521
+ }
522
+
523
+ const invokedDirectly = process.argv[1]
524
+ && pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url;
525
+
526
+ if (invokedDirectly) {
527
+ try {
528
+ process.exitCode = main();
529
+ } catch (error) {
530
+ process.stderr.write(`router.mjs 崩了:${error && error.stack ? error.stack : error}\n`);
531
+ process.exitCode = 1;
532
+ }
533
+ }
534
+
535
+ export { REPO_ROOT };