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,540 @@
1
+ /**
2
+ * adr-parser.mjs
3
+ *
4
+ * 负责健壮解析 ADR 架构规约文件:
5
+ * 1. 状态行(Status)与 🔒Frozen 检查(支持 frontmatter id / status 及自定义 frozen_states 映射)
6
+ * 2. ## Implementation Status 落地状态节与表格抽取(支持节标题别名如 ## 验证)
7
+ * 3. ## Invariants 不变量抽取,实行严格的边界正则匹配(防 H-1 误伤 H-10 / H-1-OBSOLETE)
8
+ * 4. 支持项目侧配置 adr_dirs, adr_id_pattern, section_aliases
9
+ */
10
+
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+
14
+ /**
15
+ * 转义正则特殊字符
16
+ */
17
+ export function escapeRegex(str) {
18
+ return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
19
+ }
20
+
21
+ /**
22
+ * 构造严格词界匹配正则
23
+ * 确保 targetId 前后不能是字母、数字、下划线或连字符
24
+ * 例如 targetId = "H-1",绝不能匹配 "H-10" 或 "H-1-OBSOLETE" 或 "MY_H-1"
25
+ */
26
+ export function makeStrictBoundaryRegex(targetId, flags = 'g') {
27
+ const escaped = escapeRegex(targetId);
28
+ return new RegExp(`(?<=^|[^a-zA-Z0-9_-])${escaped}(?=$|[^a-zA-Z0-9_-])`, flags);
29
+ }
30
+
31
+ /**
32
+ * 测试文本中是否包含指定的不变量 ID(严格边界)
33
+ */
34
+ export function containsStrictInvariant(text, targetId) {
35
+ const regex = makeStrictBoundaryRegex(targetId, '');
36
+ return regex.test(text);
37
+ }
38
+
39
+ /**
40
+ * 极简 YAML 提取器(提取 invariants, adr_dirs, adr_id_pattern, frozen_states, section_aliases)
41
+ */
42
+ export function parseSimpleYamlOverlay(yamlContent) {
43
+ const config = {
44
+ version: '1.0',
45
+ adr_dirs: [],
46
+ adr_id_pattern: '',
47
+ frozen_states: [],
48
+ section_aliases: {
49
+ decision: [],
50
+ implementation: [],
51
+ invariants: [],
52
+ },
53
+ telemetry_ignore_patterns: [],
54
+ telemetry_exempt_adrs: [],
55
+ invariants: [],
56
+ };
57
+
58
+ const lines = yamlContent.split('\n');
59
+ let currentSection = '';
60
+ let currentSubSection = '';
61
+ let currentInv = null;
62
+ let inSymbols = false;
63
+
64
+ for (const line of lines) {
65
+ const rawLine = line.replace(/#.*$/, '');
66
+ const trimmed = rawLine.trim();
67
+ if (!trimmed) continue;
68
+
69
+ // Top-level key
70
+ const topMatch = rawLine.match(/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/);
71
+ if (topMatch && !rawLine.startsWith(' ') && !rawLine.startsWith('\t')) {
72
+ const key = topMatch[1].trim();
73
+ const val = topMatch[2].trim();
74
+ currentSection = key;
75
+ currentSubSection = '';
76
+ inSymbols = false;
77
+ if (currentInv) {
78
+ config.invariants.push(currentInv);
79
+ currentInv = null;
80
+ }
81
+
82
+ if (key === 'version') {
83
+ config.version = val.replace(/["']/g, '');
84
+ } else if (key === 'adr_id_pattern') {
85
+ config.adr_id_pattern = val.replace(/^["']|["']$/g, '').replace(/\\\\/g, '\\');
86
+ }
87
+ continue;
88
+ }
89
+
90
+ // Sub-keys under section_aliases
91
+ if (currentSection === 'section_aliases') {
92
+ const subMatch = rawLine.match(/^\s{1,4}([A-Za-z0-9_-]+)\s*:\s*(.*)$/);
93
+ if (subMatch) {
94
+ currentSubSection = subMatch[1].trim();
95
+ continue;
96
+ }
97
+ if (currentSubSection && trimmed.startsWith('-')) {
98
+ const itemVal = trimmed.replace(/^-\s*/, '').replace(/^["']|["']$/g, '').trim();
99
+ if (!config.section_aliases[currentSubSection]) {
100
+ config.section_aliases[currentSubSection] = [];
101
+ }
102
+ config.section_aliases[currentSubSection].push(itemVal);
103
+ continue;
104
+ }
105
+ }
106
+
107
+ // Sub-keys under telemetry
108
+ if (currentSection === 'telemetry') {
109
+ const subMatch = rawLine.match(/^\s{1,4}([A-Za-z0-9_-]+)\s*:\s*(.*)$/);
110
+ if (subMatch) {
111
+ currentSubSection = subMatch[1].trim();
112
+ continue;
113
+ }
114
+ if (currentSubSection && trimmed.startsWith('-')) {
115
+ const itemVal = trimmed.replace(/^-\s*/, '').replace(/^["']|["']$/g, '').replace(/\\\\/g, '\\').trim();
116
+ if (currentSubSection === 'ignore_patterns' || currentSubSection === 'telemetry_ignore_patterns') {
117
+ config.telemetry_ignore_patterns.push(itemVal);
118
+ } else if (currentSubSection === 'exempt_adrs' || currentSubSection === 'telemetry_exempt_adrs') {
119
+ config.telemetry_exempt_adrs.push(itemVal);
120
+ }
121
+ continue;
122
+ }
123
+ }
124
+
125
+ // Flat list items under telemetry_ignore_patterns
126
+ if (currentSection === 'telemetry_ignore_patterns' && trimmed.startsWith('-')) {
127
+ const patVal = trimmed.replace(/^-\s*/, '').replace(/^["']|["']$/g, '').replace(/\\\\/g, '\\').trim();
128
+ config.telemetry_ignore_patterns.push(patVal);
129
+ continue;
130
+ }
131
+
132
+ // Flat list items under telemetry_exempt_adrs
133
+ if (currentSection === 'telemetry_exempt_adrs' && trimmed.startsWith('-')) {
134
+ const adrVal = trimmed.replace(/^-\s*/, '').replace(/^["']|["']$/g, '').trim();
135
+ config.telemetry_exempt_adrs.push(adrVal);
136
+ continue;
137
+ }
138
+
139
+ // List items under adr_dirs
140
+ if (currentSection === 'adr_dirs' && trimmed.startsWith('-')) {
141
+ const dirVal = trimmed.replace(/^-\s*/, '').replace(/^["']|["']$/g, '').trim();
142
+ config.adr_dirs.push(dirVal);
143
+ continue;
144
+ }
145
+
146
+ // List items under frozen_states
147
+ if (currentSection === 'frozen_states' && trimmed.startsWith('-')) {
148
+ const stateVal = trimmed.replace(/^-\s*/, '').replace(/^["']|["']$/g, '').trim();
149
+ config.frozen_states.push(stateVal);
150
+ continue;
151
+ }
152
+
153
+ // Flat section aliases
154
+ if (currentSection === 'decision_section_aliases' && trimmed.startsWith('-')) {
155
+ config.section_aliases.decision.push(trimmed.replace(/^-\s*/, '').replace(/^["']|["']$/g, '').trim());
156
+ continue;
157
+ }
158
+ if (currentSection === 'implementation_section_aliases' && trimmed.startsWith('-')) {
159
+ config.section_aliases.implementation.push(trimmed.replace(/^-\s*/, '').replace(/^["']|["']$/g, '').trim());
160
+ continue;
161
+ }
162
+ if (currentSection === 'invariants_section_aliases' && trimmed.startsWith('-')) {
163
+ config.section_aliases.invariants.push(trimmed.replace(/^-\s*/, '').replace(/^["']|["']$/g, '').trim());
164
+ continue;
165
+ }
166
+
167
+ // Invariants list parsing (preserves existing logic)
168
+ if (currentSection === 'invariants') {
169
+ if (trimmed.startsWith('- id:')) {
170
+ if (currentInv) config.invariants.push(currentInv);
171
+ const idMatch = trimmed.match(/- id:\s*["']?([^"']+)["']?/);
172
+ currentInv = { id: idMatch ? idMatch[1] : '', isOverlay: true, productionSymbols: [] };
173
+ inSymbols = false;
174
+ } else if (currentInv) {
175
+ if (trimmed.startsWith('name:')) {
176
+ const m = trimmed.match(/name:\s*["']?([^"']+)["']?/);
177
+ if (m) currentInv.name = m[1];
178
+ inSymbols = false;
179
+ } else if (trimmed.startsWith('status:')) {
180
+ const m = trimmed.match(/status:\s*["']?([^"']+)["']?/);
181
+ if (m) currentInv.status = m[1];
182
+ inSymbols = false;
183
+ } else if (trimmed.startsWith('symbols:')) {
184
+ inSymbols = true;
185
+ } else if (inSymbols && trimmed.startsWith('-')) {
186
+ const symMatch = trimmed.match(/-\s*["']?([^"'\s]+)["']?/);
187
+ if (symMatch) {
188
+ let rawSym = symMatch[1];
189
+ if (rawSym.includes('#')) rawSym = rawSym.split('#')[1];
190
+ currentInv.productionSymbols.push(rawSym);
191
+ }
192
+ }
193
+ }
194
+ }
195
+ }
196
+
197
+ if (currentInv) {
198
+ config.invariants.push(currentInv);
199
+ }
200
+
201
+ return config;
202
+ }
203
+
204
+ /**
205
+ * 读取可选的 spec-matrix.overlay.yml 文件
206
+ */
207
+ export function loadOverlayConfig(repoRoot, customPath = '') {
208
+ const candidatePaths = [
209
+ customPath ? (path.isAbsolute(customPath) ? customPath : path.resolve(repoRoot, customPath)) : '',
210
+ path.join(repoRoot, 'spec-matrix.overlay.yml'),
211
+ path.join(repoRoot, 'spec-matrix.yml'),
212
+ path.join(repoRoot, '.spec-matrix.yml'),
213
+ ].filter(Boolean);
214
+
215
+ for (const p of candidatePaths) {
216
+ if (fs.existsSync(p)) {
217
+ try {
218
+ const content = fs.readFileSync(p, 'utf8');
219
+ return parseSimpleYamlOverlay(content);
220
+ } catch (err) {
221
+ // ignore overlay parse failure
222
+ }
223
+ }
224
+ }
225
+ return {
226
+ version: '1.0',
227
+ adr_dirs: [],
228
+ adr_id_pattern: '',
229
+ frozen_states: [],
230
+ section_aliases: { decision: [], implementation: [], invariants: [] },
231
+ invariants: [],
232
+ };
233
+ }
234
+
235
+ /**
236
+ * 递归根据文件路径寻找工程根目录(包含 spec-matrix / .handoffs / .git 等)
237
+ */
238
+ export function findRepoRootFromPath(startPath) {
239
+ let curr = path.resolve(startPath);
240
+ if (fs.existsSync(curr) && fs.statSync(curr).isFile()) {
241
+ curr = path.dirname(curr);
242
+ }
243
+ while (curr && curr !== path.dirname(curr)) {
244
+ if (
245
+ fs.existsSync(path.join(curr, 'spec-matrix.overlay.yml')) ||
246
+ fs.existsSync(path.join(curr, 'spec-matrix.yml')) ||
247
+ fs.existsSync(path.join(curr, '.handoffs')) ||
248
+ fs.existsSync(path.join(curr, '.git')) ||
249
+ fs.existsSync(path.join(curr, 'package.json'))
250
+ ) {
251
+ return curr;
252
+ }
253
+ curr = path.dirname(curr);
254
+ }
255
+ return null;
256
+ }
257
+
258
+ /**
259
+ * 查找可能包含 ADR 的目录与文件(支持项目侧配置与缺省四目录回退)
260
+ */
261
+ export function findAdrFiles(repoRoot, options = {}) {
262
+ let config = options;
263
+ if (!config || (!config.adr_dirs && !config.adrDirs && !config.adr_id_pattern && !config.adrIdPattern)) {
264
+ const loaded = loadOverlayConfig(repoRoot, options.overlayPath || options.overlay || '');
265
+ config = { ...loaded, ...options };
266
+ }
267
+
268
+ const configuredDirs = (config.adr_dirs && config.adr_dirs.length > 0)
269
+ ? config.adr_dirs
270
+ : ((config.adrDirs && config.adrDirs.length > 0) ? config.adrDirs : null);
271
+
272
+ const candidateDirs = configuredDirs
273
+ ? configuredDirs.map((d) => path.resolve(repoRoot, d))
274
+ : [
275
+ path.join(repoRoot, 'group', 'architecture', 'adr'),
276
+ path.join(repoRoot, 'docs', 'adr'),
277
+ path.join(repoRoot, 'adr'),
278
+ path.join(repoRoot, 'docs', 'proposals'),
279
+ ];
280
+
281
+ const idPattern = config.adr_id_pattern || config.adrIdPattern || null;
282
+ const customIdRegex = idPattern ? new RegExp(idPattern, 'i') : null;
283
+
284
+ const results = [];
285
+ for (const dir of candidateDirs) {
286
+ if (fs.existsSync(dir)) {
287
+ try {
288
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
289
+ for (const entry of entries) {
290
+ if (entry.isFile() && (entry.name.endsWith('.md') || entry.name.endsWith('.markdown'))) {
291
+ let matched = false;
292
+ if (customIdRegex) {
293
+ matched = customIdRegex.test(entry.name);
294
+ } else {
295
+ matched = /ADR-\d+/i.test(entry.name) || /^\d{4}-/i.test(entry.name);
296
+ }
297
+ if (matched) {
298
+ results.push(path.join(dir, entry.name));
299
+ }
300
+ }
301
+ }
302
+ } catch (err) {
303
+ // ignore read error
304
+ }
305
+ }
306
+ }
307
+ return results;
308
+ }
309
+
310
+ /**
311
+ * 解析单个 ADR Markdown 文件内容
312
+ */
313
+ export function parseAdrContent(content, filePath = '', options = {}) {
314
+ let config = options;
315
+ if (!config || Object.keys(config).length === 0) {
316
+ if (filePath) {
317
+ const root = findRepoRootFromPath(filePath);
318
+ if (root) config = loadOverlayConfig(root);
319
+ }
320
+ }
321
+ config = config || {};
322
+
323
+ const lines = content.split('\n');
324
+
325
+ // 1. 抽取 frontmatter
326
+ let frontmatter = null;
327
+ const fmM = content.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n/);
328
+ if (fmM) {
329
+ frontmatter = {};
330
+ for (const l of fmM[1].split(/\r?\n/)) {
331
+ const idx = l.indexOf(':');
332
+ if (idx !== -1) {
333
+ const k = l.slice(0, idx).trim();
334
+ let v = l.slice(idx + 1).trim();
335
+ if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) {
336
+ v = v.slice(1, -1);
337
+ }
338
+ frontmatter[k] = v;
339
+ }
340
+ }
341
+ }
342
+
343
+ // 2. 抽取 ADR 编号与标题
344
+ let adrId = '';
345
+ let title = '';
346
+
347
+ const idPattern = config.adr_id_pattern || config.adrIdPattern || null;
348
+ const idRegex = idPattern ? new RegExp(idPattern, 'i') : /(ADR-\d+)/i;
349
+
350
+ if (frontmatter && frontmatter.id) {
351
+ adrId = frontmatter.id.trim().toUpperCase();
352
+ }
353
+
354
+ const filename = filePath ? path.basename(filePath) : '';
355
+ if (!adrId && filename) {
356
+ const fileMatch = filename.match(idRegex);
357
+ if (fileMatch) {
358
+ adrId = (fileMatch[1] || fileMatch[0]).toUpperCase();
359
+ }
360
+ }
361
+
362
+ let status = (frontmatter && frontmatter.status) ? frontmatter.status : 'Unknown';
363
+ let isFrozen = false;
364
+ let telemetryExempt = false;
365
+
366
+ if (frontmatter && frontmatter.telemetry) {
367
+ const t = String(frontmatter.telemetry).toLowerCase().trim();
368
+ if (['exempt', 'skip', 'ignore', 'false', 'none', 'convention', 'disabled'].includes(t)) {
369
+ telemetryExempt = true;
370
+ }
371
+ }
372
+
373
+ const frozenStates = config.frozen_states || config.frozenStates || [];
374
+
375
+ if (frontmatter && frontmatter.status) {
376
+ const s = frontmatter.status.trim();
377
+ if (frozenStates.length > 0) {
378
+ isFrozen = frozenStates.some((fs) => fs.toLowerCase() === s.toLowerCase() || (fs === '🔒' && s.includes('🔒')));
379
+ } else {
380
+ isFrozen = s.includes('🔒') || /\bfrozen\b/i.test(s);
381
+ }
382
+ }
383
+
384
+ // 扫描前 35 行获取标题和状态
385
+ for (let i = 0; i < Math.min(lines.length, 35); i++) {
386
+ const line = lines[i].trim();
387
+ if (!title && line.startsWith('# ')) {
388
+ title = line.replace(/^#\s*/, '').trim();
389
+ if (!adrId) {
390
+ const idMatch = title.match(idRegex);
391
+ if (idMatch) adrId = (idMatch[1] || idMatch[0]).toUpperCase();
392
+ }
393
+ }
394
+ // 匹配状态行,如: - **状态(Status)**:Proposed / 🔒 Frozen
395
+ if (!frontmatter || !frontmatter.status) {
396
+ if (/^\s*[-*]?\s*\**状态.*?\**\s*[::]/i.test(line) || /^\s*[-*]?\s*\**Status\**\s*[::]/i.test(line)) {
397
+ status = line.replace(/^.*?[::]\s*/, '').trim();
398
+ if (frozenStates.length > 0) {
399
+ isFrozen = frozenStates.some((fs) => fs.toLowerCase() === status.toLowerCase() || (fs === '🔒' && status.includes('🔒')));
400
+ } else {
401
+ if (status.includes('🔒') || /Frozen/i.test(status)) {
402
+ isFrozen = true;
403
+ }
404
+ }
405
+ }
406
+ }
407
+ }
408
+
409
+ if (!adrId) {
410
+ adrId = 'ADR-UNKNOWN';
411
+ }
412
+
413
+ // 3. 节标题别名匹配
414
+ const secAliases = config.section_aliases || config.sectionAliases || {};
415
+ const implAliases = [
416
+ 'Implementation\\s+Status',
417
+ '落地情况',
418
+ ...(secAliases.implementation || config.implementation_section_aliases || ['验证']),
419
+ ];
420
+ const invAliases = [
421
+ 'Invariants?',
422
+ '不可变量',
423
+ ...(secAliases.invariants || config.invariants_section_aliases || ['不变量']),
424
+ ];
425
+
426
+ const implRegex = new RegExp(implAliases.join('|'), 'i');
427
+ const invRegex = new RegExp(invAliases.join('|'), 'i');
428
+
429
+ let hasImplementationStatus = false;
430
+ let implementationItems = [];
431
+
432
+ let hasInvariantsSection = false;
433
+ let invariants = [];
434
+
435
+ let currentSection = '';
436
+ let inTable = false;
437
+ let tableHeader = [];
438
+
439
+ for (let i = 0; i < lines.length; i++) {
440
+ const line = lines[i];
441
+ const trimmed = line.trim();
442
+
443
+ // 识别二级或三级标题
444
+ const headerMatch = trimmed.match(/^#{2,3}\s+(.+)$/);
445
+ if (headerMatch) {
446
+ currentSection = headerMatch[1].trim();
447
+ inTable = false;
448
+ tableHeader = [];
449
+
450
+ if (implRegex.test(currentSection)) {
451
+ hasImplementationStatus = true;
452
+ }
453
+ if (invRegex.test(currentSection)) {
454
+ hasInvariantsSection = true;
455
+ }
456
+ continue;
457
+ }
458
+
459
+ // 解析 Implementation Status 节的表格
460
+ if (implRegex.test(currentSection)) {
461
+ if (trimmed.startsWith('|') && trimmed.endsWith('|')) {
462
+ const cells = trimmed
463
+ .split('|')
464
+ .slice(1, -1)
465
+ .map((c) => c.trim());
466
+ if (cells.every((c) => /^[-:]+$/.test(c))) {
467
+ // 分隔行
468
+ inTable = true;
469
+ continue;
470
+ }
471
+ if (!inTable) {
472
+ tableHeader = cells;
473
+ continue;
474
+ }
475
+ // 表格数据行
476
+ if (inTable && cells.length >= 2) {
477
+ const itemCol = cells[0];
478
+ const statusCol = cells[1];
479
+ const noteCol = cells[2] || '';
480
+
481
+ let normalizedStatus = 'in_progress';
482
+ if (statusCol.includes('✅') || /已实现|Done|Wired/i.test(statusCol)) {
483
+ normalizedStatus = 'verified';
484
+ } else if (statusCol.includes('❌') || /未实现|Unwired/i.test(statusCol)) {
485
+ normalizedStatus = 'unwired';
486
+ } else if (statusCol.includes('⚠️') || /未固化|进行中|In\s*Progress/i.test(statusCol)) {
487
+ normalizedStatus = 'in_progress';
488
+ }
489
+
490
+ implementationItems.push({
491
+ name: itemCol,
492
+ rawStatus: statusCol,
493
+ status: normalizedStatus,
494
+ note: noteCol,
495
+ });
496
+ }
497
+ }
498
+ }
499
+
500
+ // 解析 Invariants 节的不变量标识 (如 H-1, H-2, Gate1, D3, INV-01)
501
+ if (invRegex.test(currentSection)) {
502
+ const invMatch = trimmed.match(/^[-*\d.]+\s*(?:\*\*)?([A-Za-z0-9_-]+)(?:\*\*)?\s*[::((]\s*(.*)$/);
503
+ if (invMatch) {
504
+ const localId = invMatch[1].trim();
505
+ const desc = invMatch[2].replace(/[))]$/, '').trim();
506
+ if (/^(?:[A-Z]-\d+|Gate\d+|[A-Z]\d+|INV-[A-Za-z0-9_-]+)$/i.test(localId)) {
507
+ const canonicalId = `${adrId}:${localId}`;
508
+ invariants.push({
509
+ localId,
510
+ canonicalId,
511
+ description: desc,
512
+ line: i + 1,
513
+ });
514
+ }
515
+ }
516
+ }
517
+ }
518
+
519
+ return {
520
+ filePath,
521
+ adrId,
522
+ title,
523
+ status,
524
+ isFrozen,
525
+ telemetryExempt,
526
+ frontmatter,
527
+ hasImplementationStatus,
528
+ implementationItems,
529
+ hasInvariantsSection,
530
+ invariants,
531
+ };
532
+ }
533
+
534
+ /**
535
+ * 解析文件路径下的 ADR
536
+ */
537
+ export function parseAdrFile(filePath, options = {}) {
538
+ const content = fs.readFileSync(filePath, 'utf8');
539
+ return parseAdrContent(content, filePath, options);
540
+ }