@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,821 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * R1 影子模式(shadow mode)—— 只记录,不执行。
4
+ *
5
+ * 定位:R1 的 route() 是一层纯决策函数,本身不执行任何工具。但在把 R1 接到
6
+ * 真实执行链路之前,不能仅凭 route() 的输出就放行——故障注入实验(见
7
+ * test/router-faults.mjs)已经证明:规则表被删/损坏、action 写错、override
8
+ * 指错规则、决策数爆炸等情况下,route() 会静默返回空结果或错误的可执行决定。
9
+ *
10
+ * 所以本文件做三件事,且只做三件事:
11
+ * 1. 调 route() 拿判定;
12
+ * 2. 用 guard() 独立复核这份判定(fail-closed:任何可疑一律 needsHuman);
13
+ * 3. 把「输入 + 判定 + 复核结果」追加到 decisions-<date>.jsonl。
14
+ *
15
+ * 硬约束(代码结构保证,不是开关):
16
+ * - 没有 exec/spawn/child_process/http/fetch 任何引用;
17
+ * - 唯一的写操作 appendJsonl(),目标被限制在 outDir 之内;
18
+ * - 不读外部记忆库 / profile / <memory-root>,ctx 只来自调用方注入。
19
+ *
20
+ * 用法见 SHADOW-RUN.md;`node src/router/shadow.mjs --help`。
21
+ */
22
+
23
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
24
+ import path from 'node:path';
25
+ import { pluginEvidencePrefixes } from '../adapters/registry.js';
26
+ import { fileURLToPath } from 'node:url';
27
+
28
+ import { RULES, route } from './route.js';
29
+ import { loadFixtures, fixtureInput } from './judge.mjs';
30
+
31
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
32
+ const DEFAULT_OUT = process.env.R1_SHADOW_DIR || path.join(process.cwd(), 'shadow-out');
33
+ const SHADOW_MODE = 'dry'; // 只有一种模式:记录。没有 execute 分支。
34
+ const MAX_DECISIONS = 8;
35
+ const MIN_RULES = 14;
36
+ const BENIGN_TOOL_ACTIONS = new Set(['acp_status', 'guard.dryRun']);
37
+
38
+ export const SHADOW_CODES = Object.freeze({
39
+ TABLE: 'E_SHADOW_TABLE',
40
+ UNMATCHED: 'E_SHADOW_UNMATCHED',
41
+ SCOPE: 'E_SHADOW_SCOPE',
42
+ EXPLOSION: 'E_SHADOW_EXPLOSION',
43
+ AMBIGUOUS: 'E_SHADOW_AMBIGUOUS',
44
+ CTX: 'E_SHADOW_CTX',
45
+ OVERRIDE: 'E_SHADOW_OVERRIDE',
46
+ ACTION: 'E_SHADOW_ACTION',
47
+ RECORD: 'E_SHADOW_RECORD',
48
+ });
49
+
50
+ export { SHADOW_MODE, MAX_DECISIONS, MIN_RULES };
51
+
52
+ // ---------------------------------------------------------------------------
53
+ // 工具函数
54
+ // ---------------------------------------------------------------------------
55
+
56
+ function textOr(value) {
57
+ return typeof value === 'string' ? value.trim() : '';
58
+ }
59
+
60
+ function shaLike(value) {
61
+ // 轻量稳定哈希:只用于采样与去重,不做安全用途。
62
+ let h = 2166136261;
63
+ const s = String(value);
64
+ for (let i = 0; i < s.length; i += 1) {
65
+ h ^= s.charCodeAt(i);
66
+ h = Math.imul(h, 16777619);
67
+ }
68
+ return (h >>> 0).toString(16).padStart(8, '0');
69
+ }
70
+
71
+ function err(code, message, extra = {}) {
72
+ return { code, message, ...extra };
73
+ }
74
+
75
+ function isInside(child, parent) {
76
+ const c = path.resolve(child);
77
+ const p = path.resolve(parent);
78
+ const rel = path.relative(p, c);
79
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
80
+ }
81
+
82
+ // ---------------------------------------------------------------------------
83
+ // 1. 规则表体检:表坏了,任何判定都不可信 → 直接拒绝
84
+ // ---------------------------------------------------------------------------
85
+
86
+ export function checkTable(rules = RULES) {
87
+ const errors = [];
88
+ if (!Array.isArray(rules)) {
89
+ return { ok: false, errors: [err(SHADOW_CODES.TABLE, '规则表不是数组:无法判定,拒绝')] };
90
+ }
91
+ if (rules.length < MIN_RULES) {
92
+ errors.push(err(SHADOW_CODES.TABLE, `规则表只有 ${rules.length} 条(< ${MIN_RULES}):疑似文件缺失/损坏,拒绝`, {
93
+ count: rules.length,
94
+ }));
95
+ }
96
+ const seen = new Set();
97
+ let lastPriority = Number.POSITIVE_INFINITY;
98
+ for (const rule of rules) {
99
+ if (!rule || !textOr(rule.id)) {
100
+ errors.push(err(SHADOW_CODES.TABLE, '存在无 id 的规则:拒绝'));
101
+ continue;
102
+ }
103
+ if (seen.has(rule.id)) errors.push(err(SHADOW_CODES.TABLE, `规则 id 重复:${rule.id}`, { ruleId: rule.id }));
104
+ seen.add(rule.id);
105
+ if (!Number.isFinite(rule.priority)) {
106
+ errors.push(err(SHADOW_CODES.TABLE, `规则 ${rule.id} priority 非法`, { ruleId: rule.id }));
107
+ } else if (rule.priority > lastPriority) {
108
+ errors.push(err(SHADOW_CODES.TABLE, `规则 ${rule.id} 优先级未降序(表可能被改坏)`, { ruleId: rule.id }));
109
+ } else {
110
+ lastPriority = rule.priority;
111
+ }
112
+ if (!rule.decision || !textOr(rule.decision.action)) {
113
+ errors.push(err(SHADOW_CODES.TABLE, `规则 ${rule.id} 无 decision.action`, { ruleId: rule.id }));
114
+ }
115
+ if (!textOr(rule.reason)) {
116
+ errors.push(err(SHADOW_CODES.TABLE, `规则 ${rule.id} 无 reason(审计要求)`, { ruleId: rule.id }));
117
+ }
118
+ }
119
+ return { ok: errors.length === 0, errors };
120
+ }
121
+
122
+ // ---------------------------------------------------------------------------
123
+ // 2. 歧义与 ctx 缺失:route() 只看第一条命中的规则,影子层要看见全部竞争者
124
+ // ---------------------------------------------------------------------------
125
+
126
+ function readCandidates(input) {
127
+ if (!input || typeof input !== 'object') return [];
128
+ const raw = input.candidates;
129
+ if (!Array.isArray(raw)) return [];
130
+ return raw
131
+ .map((value) => (typeof value === 'string' ? value.trim().toLowerCase() : ''))
132
+ .filter(Boolean);
133
+ }
134
+
135
+ function readContext(input) {
136
+ const src = input && typeof input === 'object' && input.ctx && typeof input.ctx === 'object' ? input.ctx : {};
137
+ const out = { raw: src };
138
+ if (typeof src.tokens === 'number' && Number.isFinite(src.tokens)) out.tokens = src.tokens;
139
+ if (typeof src.activeWorkers === 'number' && Number.isFinite(src.activeWorkers)) out.activeWorkers = src.activeWorkers;
140
+ if (typeof src.openRows === 'number' && Number.isFinite(src.openRows)) out.openRows = src.openRows;
141
+ if (typeof src.zone === 'string' && src.zone.trim()) out.zone = src.zone.trim().toLowerCase();
142
+ return out;
143
+ }
144
+
145
+ function evaluateCtxStrict(matcher, ctx) {
146
+ if (!matcher) return null;
147
+ if (typeof matcher.tokensGte === 'number') {
148
+ if (typeof ctx.tokens !== 'number' || ctx.tokens < matcher.tokensGte) return false;
149
+ }
150
+ if (typeof matcher.activeWorkersGte === 'number') {
151
+ if (typeof ctx.activeWorkers !== 'number' || ctx.activeWorkers < matcher.activeWorkersGte) return false;
152
+ }
153
+ if (typeof matcher.openRowsGte === 'number') {
154
+ if (typeof ctx.openRows !== 'number' || ctx.openRows < matcher.openRowsGte) return false;
155
+ }
156
+ if (Array.isArray(matcher.zoneIn)) {
157
+ if (typeof ctx.zone !== 'string' || !matcher.zoneIn.includes(ctx.zone)) return false;
158
+ }
159
+ return true;
160
+ }
161
+
162
+ function ctxFieldPresent(matcher, ctx) {
163
+ // 只看「字段在不在、类型对不对」,不看阈值——用来区分「条件不满足」和「ctx 没给」。
164
+ const missing = [];
165
+ if (!matcher) return missing;
166
+ if (typeof matcher.tokensGte === 'number' && typeof ctx.tokens !== 'number') missing.push('tokens');
167
+ if (typeof matcher.activeWorkersGte === 'number' && typeof ctx.activeWorkers !== 'number') {
168
+ missing.push('activeWorkers');
169
+ }
170
+ if (typeof matcher.openRowsGte === 'number' && typeof ctx.openRows !== 'number') missing.push('openRows');
171
+ if (Array.isArray(matcher.zoneIn) && typeof ctx.zone !== 'string') missing.push('zone');
172
+ return missing;
173
+ }
174
+
175
+ export function competingRules(input, rules = RULES) {
176
+ const text = textOr(input && (input.utterance ?? input.text)).toLowerCase();
177
+ const kind = textOr(input && input.kind).toLowerCase();
178
+ const candidates = readCandidates(input);
179
+ const ctx = readContext(input);
180
+ const hitsList = [];
181
+ for (const rule of rules) {
182
+ if (kind && rule.kind !== '*' && rule.kind !== kind) continue;
183
+ const hits = (rule.keywordKeys || []).filter((k) => k && text.includes(k));
184
+ const toolHit = Boolean(rule.matchToolKey && candidates.includes(rule.matchToolKey));
185
+ const ctxOk = evaluateCtxStrict(rule.matchCtx, ctx);
186
+ const missingCtx = rule.matchCtx ? ctxFieldPresent(rule.matchCtx, ctx) : [];
187
+ let matched = false;
188
+ if (rule.ctxOnly) matched = ctxOk === true;
189
+ else if (hits.length || toolHit) matched = ctxOk !== false;
190
+ if (!matched) continue;
191
+ hitsList.push({
192
+ ruleId: rule.id,
193
+ priority: rule.priority,
194
+ action: rule.decision.action,
195
+ kind: rule.decision.kind,
196
+ hits: hits.length,
197
+ toolHit,
198
+ ctxMissing: missingCtx,
199
+ });
200
+ }
201
+ return hitsList;
202
+ }
203
+
204
+ // 关键词命中但 ctx 字段缺/类型错:这类规则被 route() 静默跳过,必须让人看见。
205
+ export function ctxWarnings(input, hits, rules = RULES) {
206
+ const warnings = [];
207
+ const byId = new Map(rules.map((rule) => [rule.id, rule]));
208
+ const ctx = readContext(input);
209
+ for (const rule of rules) {
210
+ if (!rule.matchCtx) continue;
211
+ const text = textOr(input && (input.utterance ?? input.text)).toLowerCase();
212
+ const kind = textOr(input && input.kind).toLowerCase();
213
+ if (kind && rule.kind !== '*' && rule.kind !== kind) continue;
214
+ const hitsCount = (rule.keywordKeys || []).filter((k) => k && text.includes(k)).length;
215
+ if (hitsCount === 0) continue;
216
+ const missing = ctxFieldPresent(rule.matchCtx, ctx);
217
+ if (missing.length === 0) continue;
218
+ if (!byId.has(rule.id)) continue;
219
+ warnings.push({
220
+ ruleId: rule.id,
221
+ missing,
222
+ message: `规则 ${rule.id} 关键词命中,但 ctx.${missing.join('/')} 缺失或类型不对,route() 会静默跳过它`,
223
+ actual: Object.fromEntries(missing.map((field) => [field, ctx.raw ? ctx.raw[field] ?? null : null])),
224
+ hits: hitsCount,
225
+ });
226
+ }
227
+ return warnings;
228
+ }
229
+
230
+ // ---------------------------------------------------------------------------
231
+ // 3. guard:对 route() 的判定做独立复核(fail-closed)
232
+ // ---------------------------------------------------------------------------
233
+
234
+ export function classifyDecision(decision) {
235
+ const kind = textOr(decision && decision.kind);
236
+ const action = textOr(decision && decision.action);
237
+ if (kind === 'memory' || kind === 'session') return 'side-effect';
238
+ if (kind === 'tool') return BENIGN_TOOL_ACTIONS.has(action) ? 'read-only' : 'side-effect';
239
+ if (kind === 'reply') return 'no-write';
240
+ return 'unknown';
241
+ }
242
+
243
+ export function guard(input, result, { rules = RULES, maxDecisions = MAX_DECISIONS } = {}) {
244
+ const errors = [];
245
+ const warnings = [];
246
+ const table = checkTable(rules);
247
+ errors.push(...table.errors);
248
+
249
+ const decisions = Array.isArray(result && result.decisions) ? result.decisions : [];
250
+ const hits = competingRules(input, rules);
251
+ const ctxMissing = ctxWarnings(input, hits, rules);
252
+
253
+ if (decisions.length === 0) {
254
+ errors.push(
255
+ err(SHADOW_CODES.UNMATCHED, '没有任何规则命中(空判定):不允许默认执行,交人判断', {
256
+ competing: hits.map((hit) => hit.ruleId),
257
+ }),
258
+ );
259
+ }
260
+ if (decisions.length > maxDecisions) {
261
+ errors.push(
262
+ err(SHADOW_CODES.EXPLOSION, `决策数 ${decisions.length} 超过上限 ${maxDecisions}:疑似规则表被污染,拒绝`, {
263
+ count: decisions.length,
264
+ limit: maxDecisions,
265
+ }),
266
+ );
267
+ }
268
+
269
+ // 歧义:>=2 条规则同时命中,且最高两条同优先级 → 谁是赢家只由文件顺序决定。
270
+ if (hits.length > 1) {
271
+ const sorted = [...hits].sort((a, b) => b.priority - a.priority || 0);
272
+ const tie = sorted.filter((hit) => hit.priority === sorted[0].priority);
273
+ if (tie.length > 1) {
274
+ const actions = new Set(tie.map((hit) => `${hit.kind}:${hit.action}`));
275
+ errors.push(
276
+ err(SHADOW_CODES.AMBIGUOUS, `同优先级规则同时命中 ${tie.length} 条:${tie.map((h) => h.ruleId).join(', ')}`, {
277
+ rules: tie.map((hit) => hit.ruleId),
278
+ distinctActions: actions.size,
279
+ }),
280
+ );
281
+ } else if (hits.length > 1) {
282
+ warnings.push({
283
+ code: SHADOW_CODES.AMBIGUOUS,
284
+ message: `${hits.length} 条规则同时命中,route() 按优先级只取最高的一条:${sorted[0].ruleId}`,
285
+ rules: hits.map((hit) => hit.ruleId),
286
+ distinctActions: new Set(hits.map((hit) => `${hit.kind}:${hit.action}`)).size,
287
+ });
288
+ }
289
+ }
290
+
291
+ for (const warning of ctxMissing) {
292
+ errors.push(err(SHADOW_CODES.CTX, warning.message, { ruleId: warning.ruleId, missing: warning.missing }));
293
+ }
294
+
295
+ for (const decision of decisions) {
296
+ const action = textOr(decision.action);
297
+ if (!action) {
298
+ errors.push(err(SHADOW_CODES.ACTION, '决策缺少 action:拒绝', { ruleId: decision.ruleId || null }));
299
+ }
300
+ for (const scope of Array.isArray(decision.writeScope) ? decision.writeScope : []) {
301
+ if (!validWriteScope(scope)) {
302
+ errors.push(
303
+ err(SHADOW_CODES.SCOPE, `writeScope 越界:${scope}`, { ruleId: decision.ruleId || null, scope }),
304
+ );
305
+ }
306
+ }
307
+ }
308
+
309
+ // override:route() 找不到 ruleId 时会静默改第一条决策——影子层必须点名。
310
+ const applied = result && result.overrideAudit ? result.overrideAudit.applied : 0;
311
+ if (applied > 0) {
312
+ const ruleIds = new Set(rules.map((rule) => rule.id));
313
+ for (const record of (result.overrides || [])) {
314
+ const target = textOr(record && record.ruleId);
315
+ if (!ruleIds.has(target)) {
316
+ errors.push(err(SHADOW_CODES.OVERRIDE, `override 指向不存在的规则 ${target}:route() 会改到第一条决策上`, {
317
+ ruleId: target,
318
+ }));
319
+ }
320
+ }
321
+ }
322
+
323
+ // route() 自己报的错一律升级为拒绝。
324
+ for (const error of (result && result.errors) || []) {
325
+ errors.push(err(textOr(error.code) || SHADOW_CODES.RECORD, textOr(error.message) || 'route() 报错', {
326
+ ruleId: error.ruleId || null,
327
+ source: 'route',
328
+ }));
329
+ }
330
+
331
+ const sideEffects = decisions.filter((decision) => classifyDecision(decision) === 'side-effect');
332
+ const needsHuman = Boolean(result && result.needsHuman) || errors.length > 0;
333
+ return {
334
+ ok: errors.length === 0,
335
+ mode: SHADOW_MODE,
336
+ needsHuman,
337
+ errors,
338
+ warnings,
339
+ competing: hits,
340
+ ctxMissing,
341
+ counts: {
342
+ decisions: decisions.length,
343
+ sideEffects: sideEffects.length,
344
+ errors: errors.length,
345
+ warnings: warnings.length,
346
+ },
347
+ // 影子层的最终动作:永远不是「执行」。
348
+ action: errors.length > 0 ? 'refuse' : 'record-only',
349
+ };
350
+ }
351
+
352
+ // writeScope 判定与 judge.mjs 的 validateWriteScope 同一套口径(此处不 import judge,
353
+ // 避免影子层把 judge 的耦合带进来;两边一致性由 test/router-shadow.test.mjs 对齐断言)。
354
+ export function validWriteScope(scope) {
355
+ const value = textOr(scope);
356
+ if (!value) return true; // 空 = 不写
357
+ if (/^[A-Za-z]:/.test(value)) return false;
358
+ if (value.startsWith('/') || value.startsWith('\\')) return false;
359
+ if (value.includes('..')) return false;
360
+ if (value.includes('~')) return false;
361
+ const prefixes = ['memory/', ...pluginEvidencePrefixes(), 'taskboard:', 'sandbox:', 'evidence:', 'fixtures:'];
362
+ return prefixes.some((prefix) => value.startsWith(prefix));
363
+ }
364
+
365
+ // ---------------------------------------------------------------------------
366
+ // 4. 采样(稳定哈希:同一 seed + caseId 永远同组,双跑可复现)
367
+ // ---------------------------------------------------------------------------
368
+
369
+ export function sampleHit(key, { rate = 1, seed = 'r1-shadow' } = {}) {
370
+ const r = Number(rate);
371
+ if (!Number.isFinite(r) || r >= 1) return true;
372
+ if (r <= 0) return false;
373
+ const bucket = parseInt(shaLike(`${seed}:${key}`).slice(0, 4), 16) / 0xffff;
374
+ return bucket < r;
375
+ }
376
+
377
+ // ---------------------------------------------------------------------------
378
+ // 5. 单条分析 + 记录
379
+ // ---------------------------------------------------------------------------
380
+
381
+ export function analyze(input, { rules = RULES, routeImpl = route } = {}) {
382
+ const result = routeImpl(input);
383
+ const verdict = guard(input, result, { rules });
384
+ return {
385
+ caseId: (result && result.caseId) || (input && input.caseId) || null,
386
+ turn: (result && result.turn) ?? (input && input.turn) ?? null,
387
+ input: {
388
+ utterance: textOr(input && (input.utterance ?? input.text)),
389
+ kind: textOr(input && input.kind) || null,
390
+ candidates: readCandidates(input),
391
+ ctx: readContext(input).raw || {},
392
+ },
393
+ decision: {
394
+ matchedRule: result.matchedRule,
395
+ matchedRules: result.matchedRules,
396
+ target: result.target,
397
+ confidence: result.confidence,
398
+ needsHuman: result.needsHuman,
399
+ decisions: (result.decisions || []).map((decision) => ({
400
+ kind: decision.kind,
401
+ action: decision.action,
402
+ ruleId: decision.ruleId,
403
+ writeScope: decision.writeScope,
404
+ needsHuman: decision.needsHuman === true,
405
+ confidence: decision.confidence,
406
+ })),
407
+ errors: (result.errors || []).map((error) => ({ code: error.code, message: error.message })),
408
+ overrideAudit: result.overrideAudit,
409
+ },
410
+ guard: verdict,
411
+ };
412
+ }
413
+
414
+ export function toRecord(analysis, { at = new Date().toISOString() } = {}) {
415
+ return {
416
+ ts: at,
417
+ mode: SHADOW_MODE,
418
+ caseId: analysis.caseId,
419
+ turn: analysis.turn,
420
+ input: analysis.input,
421
+ decision: analysis.decision,
422
+ guard: {
423
+ ok: analysis.guard.ok,
424
+ needsHuman: analysis.guard.needsHuman,
425
+ action: analysis.guard.action,
426
+ errors: analysis.guard.errors,
427
+ warnings: analysis.guard.warnings,
428
+ competing: analysis.guard.competing,
429
+ counts: analysis.guard.counts,
430
+ },
431
+ human: { verdict: null, note: '' },
432
+ };
433
+ }
434
+
435
+ // ---------------------------------------------------------------------------
436
+ // 6. 指标
437
+ // ---------------------------------------------------------------------------
438
+
439
+ function rate(part, whole) {
440
+ if (!whole) return 0;
441
+ return Math.round((part / whole) * 1000) / 10; // 百分比,一位小数
442
+ }
443
+
444
+ export function computeMetrics(records) {
445
+ const list = Array.isArray(records) ? records : [];
446
+ const total = list.length;
447
+ const by = { needsHuman: 0, guardReject: 0, ambiguous: 0, ctxMissing: 0, unmatched: 0, scope: 0, override: 0, explosion: 0 };
448
+ const byRule = {};
449
+ const byAction = {};
450
+ const decisionCounts = [];
451
+ let confidenceSum = 0;
452
+ let confidenceN = 0;
453
+ for (const record of list) {
454
+ const guardErrors = (record.guard && record.guard.errors) || [];
455
+ if (record.guard && record.guard.needsHuman) by.needsHuman += 1;
456
+ if (record.guard && record.guard.action === 'refuse') by.guardReject += 1;
457
+ if (guardErrors.some((error) => error.code === SHADOW_CODES.AMBIGUOUS)) by.ambiguous += 1;
458
+ if (guardErrors.some((error) => error.code === SHADOW_CODES.CTX)) by.ctxMissing += 1;
459
+ if (guardErrors.some((error) => error.code === SHADOW_CODES.UNMATCHED)) by.unmatched += 1;
460
+ if (guardErrors.some((error) => error.code === SHADOW_CODES.SCOPE)) by.scope += 1;
461
+ if (guardErrors.some((error) => error.code === SHADOW_CODES.OVERRIDE)) by.override += 1;
462
+ if (guardErrors.some((error) => error.code === SHADOW_CODES.EXPLOSION)) by.explosion += 1;
463
+ const rule = (record.decision && record.decision.matchedRule) || '(none)';
464
+ byRule[rule] = (byRule[rule] || 0) + 1;
465
+ const decisions = (record.decision && record.decision.decisions) || [];
466
+ decisionCounts.push(decisions.length);
467
+ for (const decision of decisions) {
468
+ const key = `${decision.kind}:${decision.action}`;
469
+ byAction[key] = (byAction[key] || 0) + 1;
470
+ }
471
+ if (typeof record.decision?.confidence === 'number') {
472
+ confidenceSum += record.decision.confidence;
473
+ confidenceN += 1;
474
+ }
475
+ }
476
+ const sorted = [...decisionCounts].sort((a, b) => a - b);
477
+ const pct = (p) => (sorted.length ? sorted[Math.min(sorted.length - 1, Math.floor((p / 100) * sorted.length))] : 0);
478
+ return {
479
+ total,
480
+ rates: {
481
+ needsHuman: rate(by.needsHuman, total),
482
+ guardReject: rate(by.guardReject, total),
483
+ ambiguous: rate(by.ambiguous, total),
484
+ ctxMissing: rate(by.ctxMissing, total),
485
+ unmatched: rate(by.unmatched, total),
486
+ scope: rate(by.scope, total),
487
+ override: rate(by.override, total),
488
+ explosion: rate(by.explosion, total),
489
+ },
490
+ counts: by,
491
+ byRule,
492
+ byAction,
493
+ decisionsPerTurn: { p50: pct(50), p95: pct(95), max: sorted.length ? sorted[sorted.length - 1] : 0 },
494
+ avgConfidence: confidenceN ? Math.round((confidenceSum / confidenceN) * 1000) / 1000 : null,
495
+ };
496
+ }
497
+
498
+ export function computeMetricsFromFile(file) {
499
+ const text = readFileSync(file, 'utf8');
500
+ const records = text
501
+ .split(/\r?\n/)
502
+ .filter((line) => line.trim())
503
+ .map((line) => {
504
+ try {
505
+ return JSON.parse(line);
506
+ } catch {
507
+ return null;
508
+ }
509
+ })
510
+ .filter(Boolean);
511
+ return { records: records.length, metrics: computeMetrics(records) };
512
+ }
513
+
514
+ // ---------------------------------------------------------------------------
515
+ // 7. 人工判读抽样与一致性打分
516
+ // ---------------------------------------------------------------------------
517
+
518
+ function priorityScore(record) {
519
+ let score = 0;
520
+ const guardErrors = (record.guard && record.guard.errors) || [];
521
+ if (guardErrors.length) score += 10;
522
+ if (guardErrors.some((error) => error.code === SHADOW_CODES.AMBIGUOUS)) score += 5;
523
+ if (guardErrors.some((error) => error.code === SHADOW_CODES.UNMATCHED)) score += 4;
524
+ if (guardErrors.some((error) => error.code === SHADOW_CODES.CTX)) score += 3;
525
+ if (record.guard && record.guard.needsHuman) score += 2;
526
+ return score;
527
+ }
528
+
529
+ export function pickReviewSample(records, size = 20) {
530
+ const n = Math.max(0, Number(size) || 0);
531
+ if (!n) return [];
532
+ const ranked = records.map((record, index) => ({ record, index, score: priorityScore(record) }));
533
+ ranked.sort((a, b) => b.score - a.score || a.index - b.index);
534
+ // 高风险优先,剩余名额用等距抽样补足,保证覆盖到「正常」样本。
535
+ const head = ranked.slice(0, n);
536
+ if (head.length >= n) return head.map((entry) => entry.record);
537
+ const rest = ranked.slice(head.length);
538
+ const picked = [...head];
539
+ const need = n - head.length;
540
+ const step = Math.max(1, Math.floor(rest.length / Math.max(1, need)));
541
+ for (let i = 0; i < rest.length && picked.length < n; i += step) picked.push(rest[i]);
542
+ return picked.map((entry) => entry.record);
543
+ }
544
+
545
+ export function scoreReview(records) {
546
+ const reviewed = records.filter((record) => record.human && ['agree', 'disagree'].includes(record.human.verdict));
547
+ const disagree = reviewed.filter((record) => record.human.verdict === 'disagree');
548
+ return {
549
+ reviewed: reviewed.length,
550
+ agree: reviewed.length - disagree.length,
551
+ disagree: disagree.length,
552
+ disagreeRate: rate(disagree.length, reviewed.length),
553
+ disagreements: disagree.map((record) => ({
554
+ caseId: record.caseId,
555
+ turn: record.turn,
556
+ utterance: record.input && record.input.utterance,
557
+ shadowRule: record.decision && record.decision.matchedRule,
558
+ note: record.human.note,
559
+ })),
560
+ };
561
+ }
562
+
563
+ // ---------------------------------------------------------------------------
564
+ // 8. 落盘(唯一写入口,锁在 outDir 内)
565
+ // ---------------------------------------------------------------------------
566
+
567
+ export function resolveOutDir(outDir = DEFAULT_OUT) {
568
+ return path.resolve(outDir);
569
+ }
570
+
571
+ export function decisionsPath(outDir, date) {
572
+ return path.join(resolveOutDir(outDir), `decisions-${date}.jsonl`);
573
+ }
574
+
575
+ function assertInside(target, outDir) {
576
+ if (!isInside(target, outDir)) {
577
+ throw new Error(`shadow 只允许写 ${outDir},拒绝写 ${target}`);
578
+ }
579
+ }
580
+
581
+ export function appendRecords(records, { outDir = DEFAULT_OUT, date, at = new Date() } = {}) {
582
+ const dir = resolveOutDir(outDir);
583
+ const stamp = date || at.toISOString().slice(0, 10);
584
+ const file = decisionsPath(dir, stamp);
585
+ assertInside(file, dir);
586
+ mkdirSync(dir, { recursive: true });
587
+ const body = records.map((record) => JSON.stringify(record)).join('\n');
588
+ if (!body) return { file, written: 0 };
589
+ appendFileSync(file, `${body}\n`, 'utf8');
590
+ return { file, written: records.length };
591
+ }
592
+
593
+ export function writeJsonl(file, records) {
594
+ writeFileSync(file, records.map((record) => JSON.stringify(record)).join('\n') + '\n', 'utf8');
595
+ return file;
596
+ }
597
+
598
+ export function reviewPath(outDir, date) {
599
+ return path.join(resolveOutDir(outDir), `review-${date}.jsonl`);
600
+ }
601
+
602
+ // ---------------------------------------------------------------------------
603
+ // 9. 批量运行
604
+ // ---------------------------------------------------------------------------
605
+
606
+ export function inputsFromFixtures(dir) {
607
+ const { fixtures, errors } = loadFixtures(dir || path.join(HERE, 'fixtures'));
608
+ if (errors.length) {
609
+ return { inputs: [], errors };
610
+ }
611
+ return { inputs: fixtures.map((fixture) => ({ ...fixtureInput(fixture), source: `fixture:${fixture.id}` })), errors: [] };
612
+ }
613
+
614
+ export function runShadow(inputs, {
615
+ outDir = DEFAULT_OUT,
616
+ date,
617
+ rate = 1,
618
+ seed = 'r1-shadow',
619
+ record = true,
620
+ now = () => new Date(),
621
+ } = {}) {
622
+ const at = now();
623
+ const stamp = date || at.toISOString().slice(0, 10);
624
+ const analyzed = [];
625
+ const skipped = [];
626
+ for (const input of inputs) {
627
+ const key = `${input.caseId ?? ''}:${input.turn ?? ''}:${shaLike(textOr(input.utterance ?? input.text))}`;
628
+ if (!sampleHit(key, { rate, seed })) {
629
+ skipped.push(key);
630
+ continue;
631
+ }
632
+ const analysis = analyze(input);
633
+ analyzed.push(toRecord(analysis, { at: at.toISOString() }));
634
+ }
635
+ const written = record && analyzed.length
636
+ ? appendRecords(analyzed, { outDir, date: stamp, at })
637
+ : { file: null, written: 0 };
638
+ return {
639
+ date: stamp,
640
+ total: inputs.length,
641
+ sampled: analyzed.length,
642
+ skipped: skipped.length,
643
+ records: analyzed,
644
+ metrics: computeMetrics(analyzed),
645
+ out: written,
646
+ mode: SHADOW_MODE,
647
+ };
648
+ }
649
+
650
+ // ---------------------------------------------------------------------------
651
+ // 10. CLI
652
+ // ---------------------------------------------------------------------------
653
+
654
+ const HELP = `R1 影子模式(只记录,不执行)
655
+
656
+ node src/router/shadow.mjs [选项]
657
+
658
+ --from-fixtures 用 19 条 fixtures 跑一遍(默认)
659
+ --input <file> 读取 .jsonl / .json 输入(每行 {caseId,turn,utterance,kind,ctx,candidates})
660
+ --out <dir> 记录目录(默认 ${DEFAULT_OUT})
661
+ --date YYYY-MM-DD 记录文件名日期(默认今天)
662
+ --sample <0..1> 采样率(默认 1,稳定哈希,双跑一致)
663
+ --seed <str> 采样种子(默认 r1-shadow)
664
+ --no-record 只算指标,不写文件
665
+ --print 逐条打印到 stdout
666
+ --review-sample <n> 额外产出 review-<date>.jsonl(待人工判读)
667
+ --score-review <file> 读人工判读后的 jsonl,算不一致率
668
+ --metrics <file> 从已记录 jsonl 重算指标
669
+ --json 机器可读输出
670
+ --help
671
+
672
+ 本命令没有任何执行分支:不会调工具、不会写记忆库、不会碰外部记忆库/profile。
673
+ `;
674
+
675
+ function parseArgs(argv) {
676
+ const options = {
677
+ fromFixtures: false,
678
+ input: null,
679
+ out: DEFAULT_OUT,
680
+ date: null,
681
+ sample: 1,
682
+ seed: 'r1-shadow',
683
+ record: true,
684
+ print: false,
685
+ reviewSample: 0,
686
+ scoreReview: null,
687
+ metrics: null,
688
+ json: false,
689
+ help: false,
690
+ };
691
+ for (let i = 0; i < argv.length; i += 1) {
692
+ const arg = argv[i];
693
+ switch (arg) {
694
+ case '--from-fixtures': options.fromFixtures = true; break;
695
+ case '--input': options.input = argv[++i]; break;
696
+ case '--out': options.out = argv[++i]; break;
697
+ case '--date': options.date = argv[++i]; break;
698
+ case '--sample': options.sample = Number(argv[++i]); break;
699
+ case '--seed': options.seed = argv[++i]; break;
700
+ case '--no-record': options.record = false; break;
701
+ case '--print': options.print = true; break;
702
+ case '--review-sample': options.reviewSample = Number(argv[++i]) || 0; break;
703
+ case '--score-review': options.scoreReview = argv[++i]; break;
704
+ case '--metrics': options.metrics = argv[++i]; break;
705
+ case '--json': options.json = true; break;
706
+ case '--help': case '-h': options.help = true; break;
707
+ default:
708
+ throw new Error(`未知参数:${arg}(影子模式没有 --execute;它不会执行任何东西)`);
709
+ }
710
+ }
711
+ return options;
712
+ }
713
+
714
+ function readInputs(file) {
715
+ const text = readFileSync(file, 'utf8');
716
+ if (file.toLowerCase().endsWith('.jsonl')) {
717
+ return text
718
+ .split(/\r?\n/)
719
+ .filter((line) => line.trim())
720
+ .map((line, index) => {
721
+ try {
722
+ return JSON.parse(line);
723
+ } catch (error) {
724
+ throw new Error(`${file}:${index + 1} JSON 解析失败:${error.message}`);
725
+ }
726
+ });
727
+ }
728
+ const parsed = JSON.parse(text);
729
+ const list = Array.isArray(parsed) ? parsed : Array.isArray(parsed.inputs) ? parsed.inputs : null;
730
+ if (!list) throw new Error(`${file} 不是数组,也没有 inputs[]`);
731
+ return list;
732
+ }
733
+
734
+ export function main(argv) {
735
+ const options = parseArgs(argv);
736
+ if (options.help) {
737
+ process.stdout.write(HELP);
738
+ return 0;
739
+ }
740
+ if (options.scoreReview) {
741
+ const records = readInputs(options.scoreReview);
742
+ const score = scoreReview(records);
743
+ process.stdout.write(`${JSON.stringify(score, null, 2)}\n`);
744
+ return 0;
745
+ }
746
+ if (options.metrics) {
747
+ const result = computeMetricsFromFile(options.metrics);
748
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
749
+ return 0;
750
+ }
751
+
752
+ let inputs;
753
+ if (options.input) {
754
+ inputs = readInputs(options.input);
755
+ } else {
756
+ const loaded = inputsFromFixtures();
757
+ if (loaded.errors.length) {
758
+ process.stderr.write(`fixtures 读取失败:${JSON.stringify(loaded.errors)}\n`);
759
+ return 1;
760
+ }
761
+ inputs = loaded.inputs;
762
+ }
763
+
764
+ const run = runShadow(inputs, {
765
+ outDir: options.out,
766
+ date: options.date,
767
+ rate: options.sample,
768
+ seed: options.seed,
769
+ record: options.record,
770
+ });
771
+
772
+ if (options.reviewSample > 0) {
773
+ const picked = pickReviewSample(run.records, options.reviewSample);
774
+ const file = reviewPath(options.out, run.date);
775
+ writeJsonl(file, picked);
776
+ run.review = { file, size: picked.length };
777
+ }
778
+
779
+ if (options.print) {
780
+ for (const record of run.records) {
781
+ const guardCodes = record.guard.errors.map((error) => error.code).join(',') || '-';
782
+ process.stdout.write(
783
+ `${record.caseId || '-'}\t${record.decision.matchedRule || '(none)'}\t${record.guard.action}\t${guardCodes}\t${record.input.utterance.slice(0, 48)}\n`,
784
+ );
785
+ }
786
+ }
787
+
788
+ if (options.json) {
789
+ process.stdout.write(`${JSON.stringify({
790
+ mode: run.mode,
791
+ date: run.date,
792
+ total: run.total,
793
+ sampled: run.sampled,
794
+ skipped: run.skipped,
795
+ out: run.out,
796
+ review: run.review || null,
797
+ metrics: run.metrics,
798
+ }, null, 2)}\n`);
799
+ } else {
800
+ process.stdout.write([
801
+ `R1 SHADOW(${run.mode})— ${run.date}`,
802
+ `输入 ${run.total} 条 · 采样 ${run.sampled} 条 · 跳过 ${run.skipped} 条`,
803
+ `needsHuman ${run.metrics.rates.needsHuman}% · guard 拒绝 ${run.metrics.rates.guardReject}% · 歧义 ${run.metrics.rates.ambiguous}% · ctx 缺失 ${run.metrics.rates.ctxMissing}%`,
804
+ run.out.file ? `记录 → ${run.out.file}(${run.out.written} 条)` : '未落盘(--no-record)',
805
+ run.review ? `人工判读抽样 → ${run.review.file}(${run.review.size} 条)` : '',
806
+ ].filter(Boolean).join('\n') + '\n');
807
+ }
808
+ return 0;
809
+ }
810
+
811
+ const invokedDirectly = Boolean(process.argv[1])
812
+ && path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url));
813
+
814
+ if (invokedDirectly) {
815
+ try {
816
+ process.exitCode = main(process.argv.slice(2));
817
+ } catch (error) {
818
+ process.stderr.write(`shadow 失败:${error.stack || error.message}\n`);
819
+ process.exitCode = 1;
820
+ }
821
+ }