reasonweave 0.0.0-stage → 1.3.2

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 (228) hide show
  1. package/AGENTS.md +101 -0
  2. package/INSTALL.md +258 -0
  3. package/README.md +280 -2
  4. package/bin/lab.mjs +888 -0
  5. package/constitution.md +55 -0
  6. package/docs/CONSUMER-PROMPTS.md +474 -0
  7. package/docs/backlogs/01-forward-wait-self-detach.md +18 -0
  8. package/docs/backlogs/02-decouple-wait-and-daemon-for-agent-hosts.md +35 -0
  9. package/docs/backlogs/03-baton-wait-multi-id-lightweight-pubsub.md +34 -0
  10. package/docs/backlogs/04-adr-cross-repo-automated-dispatch-boundary.md +19 -0
  11. package/docs/backlogs/05-feat-units-worktree-isolation-engine.md +23 -0
  12. package/docs/backlogs/06-feat-blind-audit-automated-clean-runner.md +22 -0
  13. package/docs/backlogs/07-feat-attention-throttle-silent-pipe.md +23 -0
  14. package/docs/backlogs/08-future-units-shadow-ledger.md +22 -0
  15. package/docs/backlogs/09-feat-agent-baton-core-convergence-and-resilience.md +42 -0
  16. package/docs/backlogs/10-feat-anti-orphan-deterministic-wiring-governance.md +35 -0
  17. package/docs/backlogs/11-perf-orphan-index-fs-read.md +16 -0
  18. package/docs/backlogs/12-feat-vibe-security-anti-suppression-and-orphan-deps.md +43 -0
  19. package/docs/backlogs/13-feat-sdd-reppit-tiered-guardrails.md +40 -0
  20. package/docs/backlogs/14-feat-universal-cli-contract-and-hermetic-test-fixtures.md +48 -0
  21. package/docs/backlogs/15-feat-reasonweave-rebranding-and-doc-code-synchronization-invariant.md +44 -0
  22. package/docs/backlogs/16-feat-micro-engineering-skills-and-sdd-baton-fusion.md +52 -0
  23. package/docs/codegraph-readiness-check.md +49 -0
  24. package/group/architecture/adr/0001-handoff-async-wait-and-reactive-wakeup.md +87 -0
  25. package/group/architecture/adr/0002-de-ritualize-handoff-prompt-for-intra-repo.md +53 -0
  26. package/group/architecture/adr/0003-attention-throttle-and-workspace-driver.md +65 -0
  27. package/group/architecture/adr/0004-spec-guard-and-drift-prevention.md +90 -0
  28. package/group/architecture/adr/0005-global-orphan-scavenger-and-read-only-invariants.md +94 -0
  29. package/group/architecture/adr/0006-triad-engineering-defense-and-mutation-sensitivity.md +68 -0
  30. package/group/architecture/adr/0007-agent-baton-state-machine-defense-and-workspace-jail-spec.md +86 -0
  31. package/group/architecture/adr/0008-agent-baton-core-convergence-and-heterogeneous-session-resilience.md +133 -0
  32. package/group/architecture/adr/0009-anti-orphan-deterministic-wiring-governance-and-federated-guardrails.md +108 -0
  33. package/group/architecture/adr/0010-agent-baton-identity-security-cryptographic-credentials-and-prompt-anti-confusion.md +119 -0
  34. package/group/architecture/adr/0011-vibe-security-anti-suppression-and-dependency-reachability.md +161 -0
  35. package/group/architecture/adr/0012-spec-driven-development-reppit-and-tiered-guardrails.md +130 -0
  36. package/group/architecture/adr/0013-universal-cli-contract-hermetic-testing-and-defensive-probes.md +110 -0
  37. package/group/architecture/adr/0014-reasonweave-rebranding-and-doc-code-synchronization-invariant.md +108 -0
  38. package/group/architecture/adr/0015-micro-engineering-skills-and-dual-core-gate-invariant.md +127 -0
  39. package/group/architecture/adr/INDEX.md +29 -0
  40. package/group/architecture/adr/templates/adr-template.md +33 -0
  41. package/group/architecture/dependency-graph.md +60 -0
  42. package/group/contracts/npm-packaging.md +69 -0
  43. package/group/product/intent.md +24 -0
  44. package/package.json +93 -4
  45. package/scripts/sync-all-consumers.mjs +174 -0
  46. package/specs/RFC-20261110-SPEC-GUARD-UNIT.md +353 -0
  47. package/specs/templates/01-research.md.template +23 -0
  48. package/specs/templates/02-proposals.md.template +22 -0
  49. package/specs/templates/03-spec.md.template +33 -0
  50. package/specs/templates/04-tasks.md.template +29 -0
  51. package/specs/templates/05-evidence.md.template +29 -0
  52. package/specs/templates/README.md +26 -0
  53. package/units/adr/AGENTS.md +85 -0
  54. package/units/adr/CHANGELOG.md +20 -0
  55. package/units/adr/README.md +88 -0
  56. package/units/adr/VERSION.md +10 -0
  57. package/units/adr/docs/existing-project-prompt.md +24 -0
  58. package/units/adr/docs/new-project-prompt.md +36 -0
  59. package/units/adr/scripts/adr-init.sh +101 -0
  60. package/units/adr/templates/INDEX.md +19 -0
  61. package/units/adr/templates/adr-frozen.md +33 -0
  62. package/units/adr/templates/adr-light.md +56 -0
  63. package/units/adr/templates/adr-standard.md +61 -0
  64. package/units/backlog/AGENTS.md +53 -0
  65. package/units/backlog/AUTONOMOUS-GOVERNANCE.md +98 -0
  66. package/units/backlog/CHANGELOG.md +37 -0
  67. package/units/backlog/README.md +124 -0
  68. package/units/backlog/VERSION.md +11 -0
  69. package/units/backlog/docs/existing-project-ironrules-prompt.md +31 -0
  70. package/units/backlog/docs/existing-project-prompt.md +24 -0
  71. package/units/backlog/docs/new-project-prompt.md +19 -0
  72. package/units/backlog/templates/entry.md +39 -0
  73. package/units/backlog/templates/project-ironrules.md +36 -0
  74. package/units/handoffs/AGENT-GUIDE.md +118 -0
  75. package/units/handoffs/AGENTS.md +28 -0
  76. package/units/handoffs/CHANGELOG.md +498 -0
  77. package/units/handoffs/CLAUDE.md +28 -0
  78. package/units/handoffs/COMMANDS.md +187 -0
  79. package/units/handoffs/DESIGN.md +74 -0
  80. package/units/handoffs/README.md +456 -0
  81. package/units/handoffs/RESPONSE-TEMPLATE.md +138 -0
  82. package/units/handoffs/VERSION.md +1 -0
  83. package/units/handoffs/handoff-status.mjs +1017 -0
  84. package/units/handoffs/handoff.mjs +5675 -0
  85. package/units/orphan/CHANGELOG.md +118 -0
  86. package/units/orphan/DESIGN.md +484 -0
  87. package/units/orphan/README.md +143 -0
  88. package/units/orphan/VERSION.md +1 -0
  89. package/units/orphan/adapters/android/index.mjs +140 -0
  90. package/units/orphan/adapters/python/index.mjs +232 -0
  91. package/units/orphan/adapters/web/index.mjs +280 -0
  92. package/units/orphan/bin/lab-orphan.mjs +298 -0
  93. package/units/orphan/core/blob-reader.mjs +142 -0
  94. package/units/orphan/core/classifier.mjs +261 -0
  95. package/units/orphan/core/cleaner.mjs +166 -0
  96. package/units/orphan/core/diff-checker.mjs +341 -0
  97. package/units/orphan/core/inverted-index.mjs +124 -0
  98. package/units/orphan/core/orphan-deps.mjs +192 -0
  99. package/units/orphan/core/protocol-s1-s3.mjs +194 -0
  100. package/units/orphan/core/solver.mjs +217 -0
  101. package/units/orphan/index.mjs +105 -0
  102. package/units/orphan/templates/ci/orphan-guard.yml +36 -0
  103. package/units/orphan/templates/pre-commit.d/30-orphan-guard +34 -0
  104. package/units/orphan/templates/wiring/README.md +51 -0
  105. package/units/orphan/templates/wiring/miniprogram-route-guard.js.template +80 -0
  106. package/units/orphan/templates/wiring/pre-commit-node.sh.template +73 -0
  107. package/units/orphan/templates/wiring/project-agents-gemini-templates.md +60 -0
  108. package/units/orphan/templates/wiring/python-parity-test.py.template +100 -0
  109. package/units/orphan/templates/wiring/rust-exhaustive-match.md +65 -0
  110. package/units/orphan/templates/wiring/swift-periphery.md +56 -0
  111. package/units/orphan/tests/adapters.test.mjs +243 -0
  112. package/units/orphan/tests/orphan-deps.test.mjs +131 -0
  113. package/units/orphan/tests/phase3-gates.test.mjs +135 -0
  114. package/units/playbook/README.md +106 -0
  115. package/units/playbook/ZSPEC-AGENT-GUIDE.md +99 -0
  116. package/units/playbook/docs/01-architecture.md +99 -0
  117. package/units/playbook/docs/02-bootstrap.md +126 -0
  118. package/units/playbook/docs/03-units.md +91 -0
  119. package/units/playbook/docs/04-constitution.md +113 -0
  120. package/units/playbook/docs/05-adr.md +33 -0
  121. package/units/playbook/docs/06-spec-kit.md +76 -0
  122. package/units/playbook/docs/07-backlog.md +30 -0
  123. package/units/playbook/docs/08-codegraph.md +79 -0
  124. package/units/playbook/docs/09-skills.md +101 -0
  125. package/units/playbook/docs/10-handoff.md +72 -0
  126. package/units/playbook/docs/11-evidence.md +163 -0
  127. package/units/playbook/docs/12-gates.md +124 -0
  128. package/units/playbook/docs/13-parallel.md +115 -0
  129. package/units/playbook/docs/14-dependency-graph.md +86 -0
  130. package/units/playbook/docs/15-memory.md +153 -0
  131. package/units/playbook/docs/16-change-control.md +121 -0
  132. package/units/playbook/docs/17-prompts.md +121 -0
  133. package/units/playbook/docs/18-shift-left.md +97 -0
  134. package/units/playbook/docs/19-anti-orphan-vertical-slicing.md +102 -0
  135. package/units/playbook/docs/20-vibe-security-and-anti-suppression.md +88 -0
  136. package/units/playbook/docs/21-spec-driven-reppit-closed-loop.md +88 -0
  137. package/units/playbook/examples/owisel.md +80 -0
  138. package/units/playbook/references/Agent-Engineering-Framework-AEF-v1.0.md +2033 -0
  139. package/units/playbook/references/links.md +103 -0
  140. package/units/playbook/templates/AGENTS.root.md +44 -0
  141. package/units/playbook/templates/AGENTS.unit.md +52 -0
  142. package/units/playbook/templates/adr/INDEX.md +17 -0
  143. package/units/playbook/templates/adr/NNNN-template.md +56 -0
  144. package/units/playbook/templates/backlogs/entry.md +30 -0
  145. package/units/playbook/templates/constitution.md +93 -0
  146. package/units/playbook/templates/evidence/README.md +36 -0
  147. package/units/playbook/templates/group/architecture/dependency-graph.md +48 -0
  148. package/units/playbook/templates/group/architecture/system.md +59 -0
  149. package/units/playbook/templates/group/contracts/api.md +67 -0
  150. package/units/playbook/templates/group/product/intent.md +30 -0
  151. package/units/playbook/templates/group/product/requirements.md +48 -0
  152. package/units/playbook/templates/unit-skeleton/README.md +35 -0
  153. package/units/preflight/AGENTS.md +45 -0
  154. package/units/preflight/CHANGELOG.md +55 -0
  155. package/units/preflight/INSTALL.md +65 -0
  156. package/units/preflight/README.md +104 -0
  157. package/units/preflight/VERSION.md +3 -0
  158. package/units/preflight/docs/audit-requirements.md +114 -0
  159. package/units/preflight/docs/existing-project-prompt.md +25 -0
  160. package/units/preflight/docs/new-project-prompt.md +25 -0
  161. package/units/preflight/docs/transfers/CONSUMER-INSTALL.md +40 -0
  162. package/units/preflight/docs/transfers/CONSUMER-SELFCHECK.md +51 -0
  163. package/units/preflight/docs/transfers/README.md +39 -0
  164. package/units/preflight/docs/transfers/prospero.md +26 -0
  165. package/units/preflight/templates/check.sh +43 -0
  166. package/units/preflight/templates/pre-commit +55 -0
  167. package/units/preflight/templates/pre-commit.d/20-preflight +15 -0
  168. package/units/preflight/templates/preflight.conf.example +21 -0
  169. package/units/preflight/templates/preflight.sh +189 -0
  170. package/units/preflight/templates/wrap-up.md +9 -0
  171. package/units/review-gate/AGENTS.md +42 -0
  172. package/units/review-gate/CHANGELOG.md +58 -0
  173. package/units/review-gate/README.md +118 -0
  174. package/units/review-gate/VERSION.md +3 -0
  175. package/units/review-gate/clean-runner.mjs +350 -0
  176. package/units/review-gate/docs/existing-project-prompt.md +28 -0
  177. package/units/review-gate/docs/new-project-prompt.md +38 -0
  178. package/units/review-gate/docs/transfers/iggle.md +34 -0
  179. package/units/review-gate/docs/transfers/prospero.md +35 -0
  180. package/units/review-gate/docs/transfers/swoop.md +36 -0
  181. package/units/review-gate/docs/transfers/yiqiyihuihua.md +35 -0
  182. package/units/review-gate/templates/.semgrepignore +37 -0
  183. package/units/review-gate/templates/pre-commit +130 -0
  184. package/units/review-gate/templates/scan.sh +158 -0
  185. package/units/skills/AGENTS.md +17 -0
  186. package/units/skills/CHANGELOG.md +18 -0
  187. package/units/skills/README.md +63 -0
  188. package/units/skills/VERSION.md +1 -0
  189. package/units/skills/bin/review-package.mjs +99 -0
  190. package/units/skills/bin/task-brief.mjs +102 -0
  191. package/units/skills/catalog/brainstorming/SKILL.md +75 -0
  192. package/units/skills/catalog/brainstorming/references/design-doc-template.md +28 -0
  193. package/units/skills/catalog/systematic-debugging/SKILL.md +101 -0
  194. package/units/skills/catalog/systematic-debugging/references/root-cause-tracing.md +23 -0
  195. package/units/skills/catalog/test-driven-development/SKILL.md +88 -0
  196. package/units/skills/catalog/test-driven-development/references/writing-good-tests.md +13 -0
  197. package/units/skills/catalog/verification-before-completion/SKILL.md +73 -0
  198. package/units/skills/skills.mjs +181 -0
  199. package/units/skills/tests/pipeline.test.mjs +131 -0
  200. package/units/skills/tests/skill-contract.test.mjs +67 -0
  201. package/units/skills/tests/skills-cli.test.mjs +107 -0
  202. package/units/spec-guard/AGENTS.md +43 -0
  203. package/units/spec-guard/CHANGELOG.md +88 -0
  204. package/units/spec-guard/README.md +148 -0
  205. package/units/spec-guard/VERSION.md +1 -0
  206. package/units/spec-guard/bin/spec-guard.mjs +431 -0
  207. package/units/spec-guard/core/adr-parser.mjs +540 -0
  208. package/units/spec-guard/core/matrix-checker.mjs +587 -0
  209. package/units/spec-guard/core/mutation-runner.mjs +267 -0
  210. package/units/spec-guard/core/scanner.mjs +333 -0
  211. package/units/spec-guard/core/telemetry_authenticator.mjs +484 -0
  212. package/units/spec-guard/core/wiring_tracer.mjs +306 -0
  213. package/units/spec-guard/templates/annotations/ContractOnly.kt +19 -0
  214. package/units/spec-guard/templates/annotations/Invariant.kt +16 -0
  215. package/units/spec-guard/templates/annotations/invariant.go +19 -0
  216. package/units/spec-guard/templates/annotations/invariant.py +38 -0
  217. package/units/spec-guard/templates/annotations/invariant.ts +39 -0
  218. package/units/spec-guard/templates/ci/spec-guard-audit.yml +23 -0
  219. package/units/spec-guard/templates/pre-commit.d/15-spec-guard +72 -0
  220. package/units/spec-guard/templates/spec-matrix.overlay.yml +70 -0
  221. package/units/spec-guard/tests/spec-guard.test.mjs +716 -0
  222. package/units/spec-guard/tests/telemetry_authenticator.test.mjs +633 -0
  223. package/units/worktree/AGENTS.md +22 -0
  224. package/units/worktree/CHANGELOG.md +14 -0
  225. package/units/worktree/README.md +65 -0
  226. package/units/worktree/VERSION.md +1 -0
  227. package/units/worktree/worktree.mjs +352 -0
  228. package//344/275/277/347/224/250/350/257/264/346/230/216.md +322 -0
@@ -0,0 +1,484 @@
1
+ /**
2
+ * telemetry_authenticator.mjs
3
+ *
4
+ * 负责 ADR 实测数据自述与机器信任根对账 (spec-guard v2.0):
5
+ * 1. 扫描 ADR 表格与正文中的量化性能指标 (ms, s, MB, FPS, %, Tokens, P95, P99, INT8 等)
6
+ * 2. 检查 ADR 是否绑定机器信任根 (evidence_ref: evidence/*.json 与 digest: sha256:...)
7
+ * 3. 校验凭据文件 SHA-256 哈希完整性,严禁用裸 signature 占位符跳过哈希校验
8
+ * 4. 容差恒等于 0%:逐指标全量对账,所有 ADR 声明数值必须在凭据 JSON 中精确命中
9
+ * 5. 发现违规时熔断阻断,报告「ADR-XXX: 实测数据自述漂移(违反 ADR-064 机器信任根)」
10
+ */
11
+
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+ import crypto from 'node:crypto';
15
+ import { findAdrFiles, parseAdrFile, loadOverlayConfig } from './adr-parser.mjs';
16
+
17
+ /**
18
+ * 量化指标正则:匹配延迟、吞吐、内存、精度等量化数值与关键字
19
+ */
20
+ export const QUANTITATIVE_METRICS_REGEX = /(?:\b\d+(?:\.\d+)?\s*(?:ms|MB|GB|FPS|Tokens?|tok|KB|μs|us)\b|\b\d+(?:\.\d+)?\s*%|\b\d+(?:\.\d+)?\s*s\b|\bP95\b|\bP99\b|\bINT8\b)/gi;
21
+
22
+ /**
23
+ * 实测基准上下文线索关键字(避免将背景设备参数如 4GB RAM 或章节序号误判为实测基准声明)
24
+ */
25
+ const MEASUREMENT_CONTEXT_REGEX = /(?:实测|基准|均值|P95|P99|INT8|冷启|推理|拟合斜率|准确率|Top-?1|ECE|Latency|Throughput|Tokens?\/s|FPS|耗时|执行时间|软拷贝|基线|Benchmark|Spike|采样|常驻|阈值)/i;
26
+
27
+ /**
28
+ * 实测基准章节标题正则
29
+ */
30
+ const MEASUREMENT_SECTION_REGEX = /(?:Implementation\s+Status|落地情况|Benchmark|基准|实测|Evaluation|性能|Spike|测试数据|压测|^\s*验证\s*$)/i;
31
+
32
+ /**
33
+ * 提取文本中出现的量化性能指标(具备上下文感知能力与豁免规则)
34
+ */
35
+ export function extractTelemetryMetrics(content, options = {}) {
36
+ const lines = content.split('\n');
37
+ const metrics = [];
38
+ let currentSection = '';
39
+ let inIgnoreBlock = false;
40
+
41
+ const rawPatterns = [
42
+ ...(options.ignorePatterns || []),
43
+ ...(options.telemetry_ignore_patterns || []),
44
+ ...(options.config?.telemetry_ignore_patterns || []),
45
+ ...(options.config?.telemetry?.ignore_patterns || []),
46
+ ];
47
+
48
+ // 预编译忽略规则(支持纯字符串子串匹配或 /pattern/i 正则)
49
+ const compiledIgnorePatterns = rawPatterns
50
+ .map((pat) => {
51
+ if (!pat) return null;
52
+ if (pat instanceof RegExp) return pat;
53
+ const str = String(pat).trim();
54
+ if (str.startsWith('/') && str.endsWith('/') && str.length > 2) {
55
+ try {
56
+ return new RegExp(str.slice(1, -1), 'i');
57
+ } catch (e) {
58
+ return str;
59
+ }
60
+ }
61
+ return str;
62
+ })
63
+ .filter(Boolean);
64
+
65
+ for (let lineIdx = 0; lineIdx < lines.length; lineIdx++) {
66
+ const line = lines[lineIdx];
67
+ const trimmed = line.trim();
68
+
69
+ // 0. 块级忽略注释检查 <!-- telemetry: ignore-start --> / <!-- telemetry: ignore-end -->
70
+ if (/<!--\s*telemetry:\s*(?:ignore-start|skip-start)\s*-->/i.test(line)) {
71
+ inIgnoreBlock = true;
72
+ continue;
73
+ }
74
+ if (/<!--\s*telemetry:\s*(?:ignore-end|skip-end)\s*-->/i.test(line)) {
75
+ inIgnoreBlock = false;
76
+ continue;
77
+ }
78
+ if (inIgnoreBlock) {
79
+ continue;
80
+ }
81
+
82
+ // 1. 行级内联忽略注释检查:<!-- telemetry: ignore --> / <!-- telemetry: skip --> / <!-- telemetry: convention -->
83
+ if (
84
+ /<!--\s*telemetry:\s*(?:ignore|skip|convention|exempt)\s*-->/i.test(line) ||
85
+ /<!--\s*telemetry-ignore\s*-->/i.test(line)
86
+ ) {
87
+ continue;
88
+ }
89
+
90
+ // 跟踪当前章节标题
91
+ const headerMatch = trimmed.match(/^#{2,4}\s+(.+)$/);
92
+ if (headerMatch) {
93
+ currentSection = headerMatch[1].trim();
94
+ continue;
95
+ }
96
+
97
+ // 忽略日期行,如 2026-11-14
98
+ if (/^\s*[-*]?\s*\**.*?(?:日期|Date).*?\**\s*[::]/i.test(line)) {
99
+ continue;
100
+ }
101
+
102
+ // 上下文判断:必须处于测量节内,或该行明确包含实测/性能/基准关键词
103
+ const inMeasurementSection = MEASUREMENT_SECTION_REGEX.test(currentSection);
104
+ const hasMeasurementKeyword = MEASUREMENT_CONTEXT_REGEX.test(line);
105
+
106
+ if (!inMeasurementSection && !hasMeasurementKeyword) {
107
+ continue;
108
+ }
109
+
110
+ // 2. 检查整行是否匹配 ignore_patterns(约定阈值等)
111
+ if (compiledIgnorePatterns.length > 0) {
112
+ const lineIgnored = compiledIgnorePatterns.some((p) => {
113
+ if (p instanceof RegExp) return p.test(line);
114
+ return line.includes(p);
115
+ });
116
+ if (lineIgnored) {
117
+ continue;
118
+ }
119
+ }
120
+
121
+ QUANTITATIVE_METRICS_REGEX.lastIndex = 0;
122
+ let match;
123
+ while ((match = QUANTITATIVE_METRICS_REGEX.exec(line)) !== null) {
124
+ const matchedText = match[0].trim();
125
+
126
+ // 3. 检查具体提取出的 metric 是否命中 ignore_patterns
127
+ if (compiledIgnorePatterns.length > 0) {
128
+ const metricIgnored = compiledIgnorePatterns.some((p) => {
129
+ if (p instanceof RegExp) return p.test(matchedText);
130
+ return matchedText === p;
131
+ });
132
+ if (metricIgnored) {
133
+ continue;
134
+ }
135
+ }
136
+
137
+ metrics.push({
138
+ metric: matchedText,
139
+ line: lineIdx + 1,
140
+ lineContent: line.trim(),
141
+ });
142
+ }
143
+ }
144
+
145
+ return metrics;
146
+ }
147
+
148
+ /**
149
+ * 从 ADR 文本中提取凭证引用 (evidence_ref) 与数字签名/摘要 (digest/signature)
150
+ */
151
+ export function extractEvidenceReferences(content) {
152
+ const evidenceFiles = [];
153
+ let declaredDigest = '';
154
+ let signature = '';
155
+
156
+ const lines = content.split('\n');
157
+
158
+ for (const line of lines) {
159
+ const trimmed = line.trim();
160
+ // 清理 Markdown 加粗与反引号标记,便于正则匹配元数据键值
161
+ const cleanLine = trimmed.replace(/[*`]/g, '');
162
+
163
+ // 匹配 evidence_ref: evidence/...json 或 evidence_ref = "evidence/...json"
164
+ const refMatch = cleanLine.match(/(?:evidence_ref|evidence)\s*[:=:]\s*["']?([^"'\s,)]+\.json)["']?/i);
165
+ if (refMatch) {
166
+ evidenceFiles.push(refMatch[1]);
167
+ }
168
+
169
+ // 匹配 Markdown 列表中对 evidence/*.json 的直接引用
170
+ const listJsonMatch = cleanLine.match(/[-*]?\s*(evidence\/[^"'\s]+\.json)/i);
171
+ if (listJsonMatch && !evidenceFiles.includes(listJsonMatch[1])) {
172
+ evidenceFiles.push(listJsonMatch[1]);
173
+ }
174
+
175
+ // 匹配 digest: sha256:... 或 sha256: ...
176
+ const digestMatch = cleanLine.match(/(?:digest|sha256|hash)\s*[:=:]\s*["']?(?:sha256:)?([a-fA-F0-9]{64})["']?/i);
177
+ if (digestMatch && !declaredDigest) {
178
+ declaredDigest = digestMatch[1].toLowerCase();
179
+ }
180
+
181
+ // 匹配 signature
182
+ const sigMatch = cleanLine.match(/(?:signature|sig)\s*[:=:]\s*["']?([a-zA-Z0-9+/=_-]{32,})["']?/i);
183
+ if (sigMatch && !signature) {
184
+ signature = sigMatch[1];
185
+ }
186
+ }
187
+
188
+ return {
189
+ evidenceFiles: [...new Set(evidenceFiles)],
190
+ declaredDigest,
191
+ signature,
192
+ };
193
+ }
194
+
195
+ /**
196
+ * 递归从 JSON 对象中抽取所有数值与扁平键值对
197
+ */
198
+ function extractNumericValuesFromJson(obj, prefix = '') {
199
+ const map = new Map();
200
+ if (typeof obj === 'number') {
201
+ map.set(prefix, obj);
202
+ return map;
203
+ }
204
+ if (!obj || typeof obj !== 'object') {
205
+ return map;
206
+ }
207
+
208
+ for (const [key, val] of Object.entries(obj)) {
209
+ const currentKey = prefix ? `${prefix}.${key}` : key;
210
+ if (typeof val === 'number') {
211
+ map.set(currentKey, val);
212
+ } else if (typeof val === 'object' && val !== null) {
213
+ const nested = extractNumericValuesFromJson(val, currentKey);
214
+ for (const [nKey, nVal] of nested.entries()) {
215
+ map.set(nKey, nVal);
216
+ }
217
+ }
218
+ }
219
+ return map;
220
+ }
221
+
222
+ /**
223
+ * 验证单个 ADR 的实测数据自述凭证
224
+ */
225
+ export function verifyAdrTelemetry(adrData, repoRoot, options = {}) {
226
+ const adrId = adrData.adrId || 'ADR-UNKNOWN';
227
+ const filePath = adrData.filePath || '';
228
+ const content = typeof adrData.content === 'string' ? adrData.content : fs.readFileSync(filePath, 'utf8');
229
+
230
+ // 0. 检查是否显式声明或配置豁免
231
+ const exemptAdrs = [
232
+ ...(options.exemptAdrs || []),
233
+ ...(options.telemetry_exempt_adrs || []),
234
+ ...(options.config?.telemetry_exempt_adrs || []),
235
+ ...(options.config?.telemetry?.exempt_adrs || []),
236
+ ].map((id) => String(id).toUpperCase());
237
+
238
+ if (adrData.telemetryExempt || (adrId && exemptAdrs.includes(adrId.toUpperCase()))) {
239
+ return {
240
+ adrId,
241
+ filePath,
242
+ hasMetrics: false,
243
+ metricsCount: 0,
244
+ metrics: [],
245
+ status: 'SKIPPED',
246
+ isCompliant: true,
247
+ reason: '声明或配置豁免(telemetry: exempt / telemetry_exempt_adrs),豁免机器信任根强校验',
248
+ evidenceFiles: [],
249
+ declaredDigest: null,
250
+ actualDigest: null,
251
+ details: [],
252
+ };
253
+ }
254
+
255
+ // 1. 扫描是否包含量化性能自述指标
256
+ const rawMetrics = extractTelemetryMetrics(content, options);
257
+ const metricStrings = rawMetrics.map((m) => m.metric);
258
+
259
+ if (rawMetrics.length === 0) {
260
+ return {
261
+ adrId,
262
+ filePath,
263
+ hasMetrics: false,
264
+ metricsCount: 0,
265
+ metrics: [],
266
+ status: 'SKIPPED',
267
+ isCompliant: true,
268
+ reason: '未包含量化性能指标自述,豁免机器信任根强校验',
269
+ evidenceFiles: [],
270
+ declaredDigest: null,
271
+ actualDigest: null,
272
+ details: [],
273
+ };
274
+ }
275
+
276
+ // 2. 提取凭据引用与签名摘要
277
+ const { evidenceFiles, declaredDigest, signature } = extractEvidenceReferences(content);
278
+
279
+ // 3. 校验:若有量化指标,必须绑定凭据文件
280
+ if (evidenceFiles.length === 0) {
281
+ const sample = metricStrings.slice(0, 3).join(', ');
282
+ const reason = `${adrId}: 实测数据自述漂移(违反 ADR-064 机器信任根)`;
283
+ const detail = `包含量化指标声明 (${sample} 等 ${rawMetrics.length} 处) 但缺少 evidence/*.json 凭证引用与机器签名摘要`;
284
+ return {
285
+ adrId,
286
+ filePath,
287
+ hasMetrics: true,
288
+ metricsCount: rawMetrics.length,
289
+ metrics: metricStrings,
290
+ status: 'FAIL',
291
+ isCompliant: false,
292
+ reason,
293
+ evidenceFiles: [],
294
+ declaredDigest: null,
295
+ actualDigest: null,
296
+ details: [detail],
297
+ };
298
+ }
299
+
300
+ // 4. 遍历并校验引用的凭据文件
301
+ const details = [];
302
+ let allFilesValid = true;
303
+ let primaryActualDigest = null;
304
+ let totalVerifiedMetrics = 0;
305
+
306
+ for (const refPath of evidenceFiles) {
307
+ // 搜索候选物理路径
308
+ const candidatePaths = [
309
+ path.resolve(repoRoot, refPath),
310
+ path.resolve(path.dirname(filePath), refPath),
311
+ path.resolve(repoRoot, 'evidence', path.basename(refPath)),
312
+ path.resolve(repoRoot, 'mcp-server', 'evidence', path.basename(refPath)),
313
+ ];
314
+
315
+ let resolvedPath = null;
316
+ for (const cp of candidatePaths) {
317
+ if (fs.existsSync(cp)) {
318
+ resolvedPath = cp;
319
+ break;
320
+ }
321
+ }
322
+
323
+ if (!resolvedPath) {
324
+ allFilesValid = false;
325
+ details.push(`凭证文件物理不存在: ${refPath}`);
326
+ continue;
327
+ }
328
+
329
+ // 计算凭证文件 SHA-256 摘要
330
+ const fileBuf = fs.readFileSync(resolvedPath);
331
+ const actualDigest = crypto.createHash('sha256').update(fileBuf).digest('hex').toLowerCase();
332
+ primaryActualDigest = actualDigest;
333
+
334
+ // 强制机器 SHA-256 完整性摘要检验(严禁以裸 signature 占位符跳过哈希校验)
335
+ if (!declaredDigest) {
336
+ allFilesValid = false;
337
+ details.push(`凭证 ${refPath} 缺少机器哈希摘要或数字签名 (缺少机器 SHA-256 哈希摘要 digest: sha256:...),严禁以裸 signature 占位符跳过机器信任根`);
338
+ continue;
339
+ }
340
+
341
+ if (declaredDigest.toLowerCase() !== actualDigest.toLowerCase()) {
342
+ allFilesValid = false;
343
+ details.push(`凭证 ${refPath} 哈希不匹配 (期望: ${declaredDigest}, 实际: ${actualDigest})`);
344
+ continue;
345
+ }
346
+
347
+ // 5. 数据真实性判定:逐指标全量 0% 强对账(所有 ADR 声明的数值必须全量在凭据 JSON 中命中)
348
+ let jsonContent;
349
+ try {
350
+ jsonContent = JSON.parse(fileBuf.toString('utf8'));
351
+ } catch (e) {
352
+ allFilesValid = false;
353
+ details.push(`凭证 ${refPath} 不是有效的 JSON 格式文件`);
354
+ continue;
355
+ }
356
+
357
+ // 提取 JSON 中的所有数值
358
+ const jsonNumericMap = extractNumericValuesFromJson(jsonContent);
359
+ const jsonNumbers = Array.from(jsonNumericMap.values());
360
+
361
+ const matchedMetrics = [];
362
+ const unmatchedMetrics = [];
363
+
364
+ for (const m of rawMetrics) {
365
+ // 排除分位标称/精度标签(如 P95, P99, INT8, FP16 等,其数值由紧随的实测数值表征)
366
+ if (/^(?:P\d+|INT\d+|FP\d+)$/i.test(m.metric)) {
367
+ matchedMetrics.push(m.metric);
368
+ continue;
369
+ }
370
+
371
+ const numMatch = m.metric.match(/(\d+(?:\.\d+)?)/);
372
+ if (numMatch) {
373
+ const val = parseFloat(numMatch[1]);
374
+ const hit = jsonNumbers.some((jsonVal) => {
375
+ // 1. 完全一致
376
+ if (Math.abs(jsonVal - val) < 1e-6 || String(jsonVal) === numMatch[1]) {
377
+ return true;
378
+ }
379
+ // 2. 四舍五入保留位数一致(人类可读文档四舍五入对账)
380
+ const decimals = (numMatch[1].split('.')[1] || '').length;
381
+ if (decimals > 0 && Math.abs(parseFloat(jsonVal.toFixed(decimals)) - val) < 1e-6) {
382
+ return true;
383
+ }
384
+ return false;
385
+ });
386
+ if (hit) {
387
+ matchedMetrics.push(m.metric);
388
+ } else {
389
+ unmatchedMetrics.push(m.metric);
390
+ }
391
+ }
392
+ }
393
+
394
+ // 0% 容差铁律:所有 ADR 文本中提取的量化实测指标必须 100% 在凭据 JSON 中命中,但凡有 1 处未命中即判 FAIL 阻断
395
+ if (unmatchedMetrics.length > 0) {
396
+ allFilesValid = false;
397
+ details.push(
398
+ `凭证 ${refPath} 实测数值与 ADR 文本自述数值脱节,存在 ${unmatchedMetrics.length} 处未验证指标 (${unmatchedMetrics.slice(0, 5).join(', ')}),违反 0% 容差铁律 (容差 $0%)`
399
+ );
400
+ } else {
401
+ totalVerifiedMetrics += matchedMetrics.length;
402
+ }
403
+ }
404
+
405
+ if (!allFilesValid) {
406
+ return {
407
+ adrId,
408
+ filePath,
409
+ hasMetrics: true,
410
+ metricsCount: rawMetrics.length,
411
+ metrics: metricStrings,
412
+ status: 'FAIL',
413
+ isCompliant: false,
414
+ reason: `${adrId}: 实测数据自述漂移(违反 ADR-064 机器信任根)`,
415
+ evidenceFiles,
416
+ declaredDigest,
417
+ actualDigest: primaryActualDigest,
418
+ details,
419
+ };
420
+ }
421
+
422
+ return {
423
+ adrId,
424
+ filePath,
425
+ hasMetrics: true,
426
+ metricsCount: rawMetrics.length,
427
+ metrics: metricStrings,
428
+ status: 'PASS',
429
+ isCompliant: true,
430
+ reason: `✅ 机器信任根验签通过 (SHA-256: ${primaryActualDigest.slice(0, 8)}... | 全部 ${totalVerifiedMetrics} 处实测指标 0% 容差对账吻合)`,
431
+ evidenceFiles,
432
+ declaredDigest,
433
+ actualDigest: primaryActualDigest,
434
+ details: [],
435
+ };
436
+ }
437
+
438
+ /**
439
+ * 校验指定目录下所有 ADR 的实测数据信任根
440
+ */
441
+ export function verifyAllAdrsTelemetry(repoRoot, options = {}) {
442
+ const config = options.config || loadOverlayConfig(repoRoot, options.overlay || options.overlayPath || '');
443
+ const mergedOptions = { ...config, ...options };
444
+ const adrPaths = findAdrFiles(repoRoot, mergedOptions);
445
+ const targetId = options.targetAdrId ? options.targetAdrId.toUpperCase() : null;
446
+
447
+ const reports = [];
448
+ let auditedCount = 0;
449
+ let passedCount = 0;
450
+ let failedCount = 0;
451
+ let skippedCount = 0;
452
+
453
+ for (const adrPath of adrPaths) {
454
+ const parsed = parseAdrFile(adrPath, mergedOptions);
455
+ if (targetId && parsed.adrId.toUpperCase() !== targetId) {
456
+ continue;
457
+ }
458
+
459
+ const verification = verifyAdrTelemetry(parsed, repoRoot, mergedOptions);
460
+ reports.push(verification);
461
+
462
+ if (verification.hasMetrics) {
463
+ auditedCount++;
464
+ if (verification.isCompliant) {
465
+ passedCount++;
466
+ } else {
467
+ failedCount++;
468
+ }
469
+ } else {
470
+ skippedCount++;
471
+ }
472
+ }
473
+
474
+ return {
475
+ repoRoot,
476
+ totalAdrs: adrPaths.length,
477
+ auditedCount,
478
+ passedCount,
479
+ failedCount,
480
+ skippedCount,
481
+ reports,
482
+ isHealthy: failedCount === 0,
483
+ };
484
+ }