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,194 @@
1
+ /**
2
+ * S1–S3 Solver Self-Test Protocol (求解器自检门禁套件)
3
+ *
4
+ * 核心三道防线:
5
+ * - S1 (Injection Self-Test / 注入假死检出):注入必然未引用的假符号,求解器必须 100% 检出 (+1);
6
+ * - S2 (In-Use Protection / 在用保护):活跃在用符号绝不误杀 (0 误报);
7
+ * - S3 (Byte-Level Reproducibility / 逐字节一致可重复):同一 HEAD blob 两次执行逐字节 SHA-256 一致。
8
+ */
9
+
10
+ import { Solver } from './solver.mjs';
11
+ import { AndroidAdapter } from '../adapters/android/index.mjs';
12
+
13
+ export class SolverProtocol {
14
+ /**
15
+ * 执行完整的 S1-S3 自检门禁
16
+ * @param {object} [opts]
17
+ * @param {string} [opts.repoDir=process.cwd()]
18
+ * @param {boolean} [opts.verbose=true]
19
+ * @returns {Promise<{
20
+ * passed: boolean,
21
+ * s1: { passed: boolean, message: string },
22
+ * s2: { passed: boolean, message: string },
23
+ * s3: { passed: boolean, hash: string, message: string }
24
+ * }>}
25
+ */
26
+ static async runSelfTest(opts = {}) {
27
+ const repoDir = opts.repoDir || process.cwd();
28
+ const verbose = opts.verbose !== false;
29
+
30
+ if (verbose) {
31
+ console.log('🧪 正在执行 S1–S3 求解器自检协议 (Solver Protocol Preflight)...\n');
32
+ }
33
+
34
+ const androidAdapter = new AndroidAdapter();
35
+ const solver = new Solver({
36
+ repoDir,
37
+ ref: 'HEAD',
38
+ adapters: [androidAdapter],
39
+ });
40
+
41
+ // ──────────────────────────────────────────────────────────────────
42
+ // S1: 注入假死自检 (Injection Self-Test)
43
+ // ──────────────────────────────────────────────────────────────────
44
+ let s1Passed = false;
45
+ let s1Msg = '';
46
+ try {
47
+ const syntheticToken = `__ORPHAN_SYNTHETIC_DEAD_SYM_${Date.now().toString(16)}_DEADBEEF__`;
48
+
49
+ // 建立包含合成候选的 Mock 适配器
50
+ const mockDeadAdapter = {
51
+ id: 'synthetic-test',
52
+ name: 'Synthetic Test Adapter',
53
+ detect: () => true,
54
+ extractCandidates: () => [
55
+ {
56
+ id: 'synthetic-dead-1',
57
+ name: syntheticToken,
58
+ resType: 'drawable',
59
+ symbol: `R.drawable.${syntheticToken}`,
60
+ primaryPath: 'res/drawable/synthetic_dead_test.png',
61
+ qualifierPaths: ['res/drawable/synthetic_dead_test.png'],
62
+ lineNo: 1,
63
+ isFamily: false,
64
+ },
65
+ ],
66
+ };
67
+
68
+ const s1Solver = new Solver({
69
+ repoDir,
70
+ ref: 'HEAD',
71
+ adapters: [mockDeadAdapter],
72
+ });
73
+
74
+ const s1Result = s1Solver.solve({ includeAlive: false });
75
+ const found = s1Result.candidates.find(c => c.name === syntheticToken);
76
+
77
+ if (found && found.status === 'CONFIRMED_ORPHAN' && found.confidence >= 0.95) {
78
+ s1Passed = true;
79
+ s1Msg = `注入假死符号 ${syntheticToken} 被 100% 精确捕获为 CONFIRMED_ORPHAN (count: +1)`;
80
+ if (verbose) console.log(` ✅ [S1: 假死检出通过] ${s1Msg}`);
81
+ } else {
82
+ s1Passed = false;
83
+ s1Msg = `未能检出注入的假死符号或状态异常 (found: ${JSON.stringify(found)})`;
84
+ if (verbose) console.log(` ❌ [S1: 假死检出失败] ${s1Msg}`);
85
+ }
86
+ } catch (err) {
87
+ s1Passed = false;
88
+ s1Msg = `S1 执行异常: ${err.message}`;
89
+ if (verbose) console.log(` ❌ [S1: 假死检出异常] ${s1Msg}`);
90
+ }
91
+
92
+ // ──────────────────────────────────────────────────────────────────
93
+ // S2: 在用保护自检 (In-Use Protection)
94
+ // ──────────────────────────────────────────────────────────────────
95
+ let s2Passed = false;
96
+ let s2Msg = '';
97
+ try {
98
+ const activeToken = `__ORPHAN_ACTIVE_IN_USE_${Date.now().toString(16)}__`;
99
+
100
+ // 构造 Mock 活跃适配器并向索引注入强引用行
101
+ const mockActiveAdapter = {
102
+ id: 'active-test',
103
+ name: 'Active In-Use Test Adapter',
104
+ detect: () => true,
105
+ extractCandidates: () => [
106
+ {
107
+ id: 'synthetic-active-1',
108
+ name: activeToken,
109
+ resType: 'layout',
110
+ symbol: `R.layout.${activeToken}`,
111
+ primaryPath: 'res/layout/active_view.xml',
112
+ qualifierPaths: ['res/layout/active_view.xml'],
113
+ lineNo: 1,
114
+ isFamily: false,
115
+ },
116
+ ],
117
+ };
118
+
119
+ const s2Solver = new Solver({
120
+ repoDir,
121
+ ref: 'HEAD',
122
+ adapters: [mockActiveAdapter],
123
+ });
124
+
125
+ // 在求解时注入一条对 activeToken 的代码强引用
126
+ const s2Result = s2Solver.solve({
127
+ includeAlive: true,
128
+ extraBlobs: {
129
+ 'src/MainActivity.kt': `package com.example\nval view = setContentView(R.layout.${activeToken})`,
130
+ },
131
+ });
132
+ const activeCand = s2Result.candidates.find(c => c.name === activeToken);
133
+
134
+ if (activeCand && activeCand.status === 'ALIVE') {
135
+ s2Passed = true;
136
+ s2Msg = `在用符号 ${activeToken} 成功识别为 ALIVE,未被误判为孤儿 (0 误报)`;
137
+ if (verbose) console.log(` ✅ [S2: 在用保护通过] ${s2Msg}`);
138
+ } else {
139
+ s2Passed = false;
140
+ s2Msg = `在用符号被误判为孤儿或未检出 (candidate: ${JSON.stringify(activeCand)})`;
141
+ if (verbose) console.log(` ❌ [S2: 在用保护失败] ${s2Msg}`);
142
+ }
143
+ } catch (err) {
144
+ s2Passed = false;
145
+ s2Msg = `S2 执行异常: ${err.message}`;
146
+ if (verbose) console.log(` ❌ [S2: 在用保护异常] ${s2Msg}`);
147
+ }
148
+
149
+ // ──────────────────────────────────────────────────────────────────
150
+ // S3: 逐字节一致可重复 (Byte-Level Reproducibility)
151
+ // ──────────────────────────────────────────────────────────────────
152
+ let s3Passed = false;
153
+ let s3Msg = '';
154
+ let hash1 = '';
155
+ try {
156
+ const run1 = solver.solve();
157
+ const run2 = solver.solve();
158
+
159
+ hash1 = Solver.computeDeterministicHash(run1);
160
+ const hash2 = Solver.computeDeterministicHash(run2);
161
+
162
+ if (hash1 === hash2 && run1.candidates.length === run2.candidates.length) {
163
+ s3Passed = true;
164
+ s3Msg = `两次运行产出逐字节一致 SHA-256: ${hash1} (candidates count: ${run1.candidates.length})`;
165
+ if (verbose) console.log(` ✅ [S3: 逐字节一致通过] ${s3Msg}`);
166
+ } else {
167
+ s3Passed = false;
168
+ s3Msg = `两次运行哈希不一致! run1=${hash1}, run2=${hash2}`;
169
+ if (verbose) console.log(` ❌ [S3: 逐字节一致失败] ${s3Msg}`);
170
+ }
171
+ } catch (err) {
172
+ s3Passed = false;
173
+ s3Msg = `S3 执行异常: ${err.message}`;
174
+ if (verbose) console.log(` ❌ [S3: 逐字节一致异常] ${s3Msg}`);
175
+ }
176
+
177
+ const allPassed = s1Passed && s2Passed && s3Passed;
178
+ if (verbose) {
179
+ console.log();
180
+ if (allPassed) {
181
+ console.log('🎉 S1–S3 求解器自检协议全部通过 (Protocol Exit 0)!\n');
182
+ } else {
183
+ console.error('🚫 S1–S3 求解器自检门禁未通过 (Protocol Exit 1)!\n');
184
+ }
185
+ }
186
+
187
+ return {
188
+ passed: allPassed,
189
+ s1: { passed: s1Passed, message: s1Msg },
190
+ s2: { passed: s2Passed, message: s2Msg },
191
+ s3: { passed: s3Passed, hash: hash1, message: s3Msg },
192
+ };
193
+ }
194
+ }
@@ -0,0 +1,217 @@
1
+ /**
2
+ * Core Solver Engine (统一求解器引擎)
3
+ *
4
+ * 协调 BlobReader, InvertedIndex, Classifier 与 Adapters 进行全仓求值。
5
+ */
6
+
7
+ import { BlobReader } from './blob-reader.mjs';
8
+ import { InvertedIndex } from './inverted-index.mjs';
9
+ import { Classifier } from './classifier.mjs';
10
+ import crypto from 'node:crypto';
11
+
12
+ export class Solver {
13
+ /**
14
+ * @param {object} [options]
15
+ * @param {string} [options.repoDir=process.cwd()]
16
+ * @param {string} [options.ref='HEAD']
17
+ * @param {Array<any>} [options.adapters=[]]
18
+ */
19
+ constructor(options = {}) {
20
+ this.repoDir = options.repoDir || process.cwd();
21
+ this.ref = options.ref || 'HEAD';
22
+ this.adapters = options.adapters || [];
23
+ this.reader = new BlobReader(this.repoDir, this.ref);
24
+ this.index = new InvertedIndex();
25
+ }
26
+
27
+ /**
28
+ * 初始化并索引全量 Git HEAD 文本 Blobs
29
+ * @param {function(string): boolean} [filterFn]
30
+ * @param {Map<string, string>|Record<string, string>} [extraBlobs] 内存附加文件注入
31
+ */
32
+ buildIndex(filterFn = null, extraBlobs = null) {
33
+ const textBlobs = this.reader.loadAllTextBlobs(filterFn);
34
+ this.index.clear();
35
+ this.index.indexAll(textBlobs);
36
+
37
+ if (extraBlobs) {
38
+ if (extraBlobs instanceof Map) {
39
+ this.index.indexAll(extraBlobs);
40
+ } else {
41
+ const extraMap = new Map(Object.entries(extraBlobs));
42
+ this.index.indexAll(extraMap);
43
+ }
44
+ }
45
+
46
+ return {
47
+ indexedFiles: this.index.totalIndexedFiles,
48
+ indexedLines: this.index.totalIndexedLines,
49
+ };
50
+ }
51
+
52
+ /**
53
+ * 执行全量求解
54
+ * @param {object} [opts]
55
+ * @param {boolean} [opts.includeAlive=false] 是否包含在用符号
56
+ * @param {boolean} [opts.rebuildIndex=true] 是否重建索引
57
+ * @param {Map<string, string>|Record<string, string>} [opts.extraBlobs]
58
+ * @returns {object} candidates.json schema output
59
+ */
60
+ solve(opts = {}) {
61
+ const includeAlive = opts.includeAlive || false;
62
+ if (opts.rebuildIndex !== false) {
63
+ this.buildIndex(opts.filterFn || null, opts.extraBlobs || null);
64
+ }
65
+
66
+ const headCommit = this.reader.getHeadCommit();
67
+ const targetStack = opts.stack && opts.stack !== 'auto' ? opts.stack : null;
68
+ const activeAdapters = this.adapters.filter(a => {
69
+ if (targetStack) return a.id === targetStack;
70
+ return a.detect(this.reader);
71
+ });
72
+
73
+ const rawCandidates = [];
74
+ let hasReflectionRisk = false;
75
+
76
+ for (const adapter of activeAdapters) {
77
+ const candidates = adapter.extractCandidates(this.reader);
78
+ rawCandidates.push(...candidates.map(c => ({ ...c, adapterId: adapter.id })));
79
+ if (adapter.detectReflectionUsage && adapter.detectReflectionUsage(this.reader)) {
80
+ hasReflectionRisk = true;
81
+ }
82
+ }
83
+
84
+ const evaluated = [];
85
+
86
+ for (const cand of rawCandidates) {
87
+ // 排除自身声明文件路径
88
+ const ownPaths = new Set(cand.qualifierPaths || [cand.primaryPath]);
89
+
90
+ // 收集候选名称和符号的匹配引用
91
+ const refs = [];
92
+ const tokensToSearch = new Set();
93
+ if (cand.tokens && Array.isArray(cand.tokens)) {
94
+ for (const t of cand.tokens) tokensToSearch.add(t);
95
+ }
96
+ if (cand.name) tokensToSearch.add(cand.name);
97
+ if (cand.symbol) tokensToSearch.add(cand.symbol);
98
+ if (cand.resType && cand.name) {
99
+ tokensToSearch.add(`@${cand.resType}/${cand.name}`);
100
+ tokensToSearch.add(`R.${cand.resType}.${cand.name}`);
101
+ }
102
+
103
+ for (const tok of tokensToSearch) {
104
+ const matches = this.index.lookup(tok);
105
+ for (const m of matches) {
106
+ if (!ownPaths.has(m.path)) {
107
+ refs.push(m);
108
+ }
109
+ }
110
+ }
111
+
112
+ // 去重
113
+ const uniqueRefs = [];
114
+ const seen = new Set();
115
+ for (const r of refs) {
116
+ const key = `${r.path}:${r.lineNo}`;
117
+ if (!seen.has(key)) {
118
+ seen.add(key);
119
+ uniqueRefs.push(r);
120
+ }
121
+ }
122
+
123
+ const evalResult = Classifier.evaluate(uniqueRefs);
124
+
125
+ let status = 'CONFIRMED_ORPHAN';
126
+ let confidence = 1.0;
127
+ const reasons = [];
128
+
129
+ if (cand.isProtected) {
130
+ status = 'ALIVE';
131
+ confidence = 0.0;
132
+ reasons.push(cand.protectionReason || 'Protected by language/framework invariant');
133
+ } else if (evalResult.isAlive) {
134
+ status = 'ALIVE';
135
+ confidence = 0.0;
136
+ reasons.push(`Referenced in ${evalResult.strongCount} code lines and ${evalResult.mediumCount} resource lines`);
137
+ } else if (hasReflectionRisk || cand.isDynamicRisk) {
138
+ // Fail-Closed: 动态反射风险时降级为待证
139
+ status = 'PENDING_VERIFICATION';
140
+ confidence = 0.65;
141
+ reasons.push(cand.dynamicRiskReason || 'No direct static references found, but dynamic reflection patterns detected in codebase');
142
+ } else if (evalResult.hasWeakDocOnly) {
143
+ status = 'CONFIRMED_ORPHAN';
144
+ confidence = 0.95;
145
+ reasons.push(`No code/resource references. Only referenced in ${evalResult.weakCount} doc/comment lines`);
146
+ } else {
147
+ status = 'CONFIRMED_ORPHAN';
148
+ confidence = 1.0;
149
+ reasons.push('Zero references across all codebase files');
150
+ }
151
+
152
+ const weakRefs = evalResult.classified
153
+ .filter(c => c.kind === 'WEAK_DOC')
154
+ .map(c => ({
155
+ path: c.path,
156
+ line_no: c.lineNo,
157
+ content: c.lineText,
158
+ classification: c.kind,
159
+ }));
160
+
161
+ evaluated.push({
162
+ id: cand.id,
163
+ type: cand.kind || (cand.isFamily ? 'asset_resource_family' : 'asset_resource'),
164
+ stack: cand.adapterId || 'general',
165
+ name: cand.name,
166
+ symbol: cand.symbol || cand.name,
167
+ path: cand.primaryPath,
168
+ qualifier_paths: cand.qualifierPaths || [cand.primaryPath],
169
+ line_no: cand.lineNo || 1,
170
+ status,
171
+ confidence,
172
+ reasons,
173
+ weak_references: weakRefs,
174
+ });
175
+ }
176
+
177
+ // 确定性排序 (S3 逐字节一致保证)
178
+ evaluated.sort((a, b) => {
179
+ if (a.path !== b.path) return a.path.localeCompare(b.path);
180
+ if (a.line_no !== b.line_no) return a.line_no - b.line_no;
181
+ return a.name.localeCompare(b.name);
182
+ });
183
+
184
+ const filtered = includeAlive ? evaluated : evaluated.filter(c => c.status !== 'ALIVE');
185
+ const confirmedCount = filtered.filter(c => c.status === 'CONFIRMED_ORPHAN').length;
186
+ const pendingCount = filtered.filter(c => c.status === 'PENDING_VERIFICATION').length;
187
+
188
+ return {
189
+ $schema: 'https://lab.agent.toolkit/schemas/orphan-candidates-v1.json',
190
+ version: '1.0.0',
191
+ generated_at: new Date().toISOString(),
192
+ commit_sha: headCommit,
193
+ summary: {
194
+ total_scanned_files: this.index.totalIndexedFiles,
195
+ total_candidates: filtered.length,
196
+ confirmed_orphans: confirmedCount,
197
+ pending_verification: pendingCount,
198
+ },
199
+ candidates: filtered,
200
+ };
201
+ }
202
+
203
+ /**
204
+ * 计算输出对象的确定性 SHA-256 哈希
205
+ * @param {object} result
206
+ * @returns {string}
207
+ */
208
+ static computeDeterministicHash(result) {
209
+ // 剔除易变的时间戳字段
210
+ const clone = {
211
+ ...result,
212
+ generated_at: 'STABLE_REPRODUCIBILITY_TIMESTAMP',
213
+ };
214
+ const jsonStr = JSON.stringify(clone, Object.keys(clone).sort(), 2);
215
+ return crypto.createHash('sha256').update(jsonStr).digest('hex');
216
+ }
217
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Lab Agent Engineering Toolkit - Orphan Unit
3
+ *
4
+ * 导出符号引用分类器与生产调用者判定接口
5
+ */
6
+
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { InvertedIndex } from './core/inverted-index.mjs';
10
+ import { Classifier, ReferenceKind, CallerKind, isTestPath } from './core/classifier.mjs';
11
+ import { Solver } from './core/solver.mjs';
12
+ import { BlobReader } from './core/blob-reader.mjs';
13
+
14
+ export {
15
+ InvertedIndex,
16
+ Classifier,
17
+ ReferenceKind,
18
+ CallerKind,
19
+ isTestPath,
20
+ Solver,
21
+ BlobReader,
22
+ };
23
+
24
+ /**
25
+ * 快速判定或统计某个符号在项目中的生产调用者分布
26
+ * @param {string} symbolName 待检查的符号名
27
+ * @param {object} [options]
28
+ * @param {string} [options.repoRoot=process.cwd()] 仓库根目录
29
+ * @param {InvertedIndex} [options.index] 可复用的倒排索引实例
30
+ * @param {Map<string, string>} [options.filesMap] 可注入的内存文件映射
31
+ * @param {Array<string>} [options.excludePaths=[]] 排除的文件路径
32
+ * @returns {{
33
+ * symbolName: string,
34
+ * wiringStatus: 'wired' | 'test_only' | 'unwired',
35
+ * productionCallerCount: number,
36
+ * testCallerCount: number,
37
+ * docReferenceCount: number,
38
+ * productionCallers: Array<{ path: string, lineNo: number, lineText: string }>,
39
+ * testCallers: Array<{ path: string, lineNo: number, lineText: string }>,
40
+ * docReferences: Array<{ path: string, lineNo: number, lineText: string }>,
41
+ * isWiredInProduction: boolean,
42
+ * isTestOnly: boolean,
43
+ * isCompletelyOrphan: boolean,
44
+ * }}
45
+ */
46
+ export function countProductionCallers(symbolName, options = {}) {
47
+ const repoRoot = options.repoRoot || process.cwd();
48
+ let index = options.index;
49
+
50
+ if (!index) {
51
+ index = new InvertedIndex();
52
+ if (options.filesMap) {
53
+ index.indexAll(options.filesMap);
54
+ } else {
55
+ const ignoreDirs = new Set(['.git', 'node_modules', 'dist', 'build', '.worktrees', '.venv', 'venv']);
56
+ function walk(dir) {
57
+ let entries;
58
+ try {
59
+ entries = fs.readdirSync(dir, { withFileTypes: true });
60
+ } catch {
61
+ return;
62
+ }
63
+ for (const entry of entries) {
64
+ if (entry.isDirectory()) {
65
+ if (!ignoreDirs.has(entry.name)) {
66
+ walk(path.join(dir, entry.name));
67
+ }
68
+ } else if (entry.isFile()) {
69
+ const fullPath = path.join(dir, entry.name);
70
+ const relPath = path.relative(repoRoot, fullPath);
71
+ try {
72
+ const content = fs.readFileSync(fullPath, 'utf8');
73
+ index.indexFile(relPath, content);
74
+ } catch {
75
+ // ignore
76
+ }
77
+ }
78
+ }
79
+ }
80
+ walk(repoRoot);
81
+ }
82
+ }
83
+
84
+ // 使用倒排索引精准检索符号命中的行
85
+ const hits = index.lookup(symbolName) || [];
86
+
87
+ // 严格调用过滤:确保行内确实出现 symbolName(...) 或引用
88
+ const escaped = symbolName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
89
+ const callRegex = new RegExp(`(?<=^|[^a-zA-Z0-9_])${escaped}\\s*(?:\\(|$)`, 'g');
90
+
91
+ const filteredHits = hits.filter((h) => {
92
+ callRegex.lastIndex = 0;
93
+ return callRegex.test(h.lineText);
94
+ });
95
+
96
+ const evaluation = Classifier.evaluateCallers(filteredHits, {
97
+ excludePaths: options.excludePaths || [],
98
+ symbolName,
99
+ });
100
+
101
+ return {
102
+ symbolName,
103
+ ...evaluation,
104
+ };
105
+ }
@@ -0,0 +1,36 @@
1
+ name: Orphan Scavenger CI Gate
2
+
3
+ on:
4
+ pull_request:
5
+ branches: [main, master, develop]
6
+ push:
7
+ branches: [main, master]
8
+
9
+ jobs:
10
+ orphan-guard:
11
+ name: Check Incremental Orphan Code & Assets
12
+ runs-on: ubuntu-latest
13
+ steps:
14
+ - name: Checkout Code
15
+ uses: actions/checkout@v4
16
+ with:
17
+ fetch-depth: 0
18
+
19
+ - name: Set up Node.js
20
+ uses: actions/setup-node@v4
21
+ with:
22
+ node-version: '>=18'
23
+
24
+ - name: Install Lab Agent Toolkit
25
+ run: |
26
+ npm link || npm install -g lab-agent-toolkit || true
27
+
28
+ - name: Run Incremental Orphan Check Gate
29
+ run: |
30
+ if [ "${{ github.event_name }}" = "pull_request" ]; then
31
+ BASE_REF="origin/${{ github.base_ref }}"
32
+ else
33
+ BASE_REF="HEAD~1"
34
+ fi
35
+ echo "Running orphan check against base: $BASE_REF"
36
+ npx lab orphan check-diff --base "$BASE_REF"
@@ -0,0 +1,34 @@
1
+ #!/usr/bin/env bash
2
+ # orphan-guard 增量死代码防腐门禁(source: units/orphan/)
3
+ # 挂载进 .githooks/pre-commit.d/30-orphan-guard
4
+ # 在 git commit 暂存区检查时自动运行,拦截新增孤儿资产与死代码
5
+
6
+ set -uo pipefail
7
+
8
+ REPO_ROOT=$(git rev-parse --show-toplevel 2>/dev/null) || exit 0
9
+ cd "$REPO_ROOT" || exit 0
10
+
11
+ # 定位 lab-orphan CLI 执行文件
12
+ ORPHAN_BIN=""
13
+ if command -v lab >/dev/null 2>&1; then
14
+ ORPHAN_PATH=$(lab path orphan 2>/dev/null || true)
15
+ if [ -n "$ORPHAN_PATH" ] && [ -f "$ORPHAN_PATH/bin/lab-orphan.mjs" ]; then
16
+ ORPHAN_BIN="$ORPHAN_PATH/bin/lab-orphan.mjs"
17
+ fi
18
+ fi
19
+
20
+ if [ -z "$ORPHAN_BIN" ]; then
21
+ if [ -f "units/orphan/bin/lab-orphan.mjs" ]; then
22
+ ORPHAN_BIN="units/orphan/bin/lab-orphan.mjs"
23
+ elif [ -f "orphan/bin/lab-orphan.mjs" ]; then
24
+ ORPHAN_BIN="orphan/bin/lab-orphan.mjs"
25
+ fi
26
+ fi
27
+
28
+ if [ -z "$ORPHAN_BIN" ]; then
29
+ # 若未安装 orphan 模块则跳过
30
+ exit 0
31
+ fi
32
+
33
+ # 执行增量暂存区孤儿拦截
34
+ node "$ORPHAN_BIN" check-diff --staged
@@ -0,0 +1,51 @@
1
+ # 联邦分栈反未接线参考模板库 (Federated Wiring Recipes)
2
+
3
+ > **导读**:本目录沉淀了针对主流技术栈(Python / Rust / SwiftUI / 微信小程序)的**反未接线(Anti-Orphan)最佳实践与参考实现模板**。
4
+ > **架构定位**:遵循 [ADR-0009](file:///Users/churze/Documents/lab/group/architecture/adr/0009-anti-orphan-deterministic-wiring-governance-and-federated-guardrails.md) 的“联邦门禁”哲学——**本仓不强绑任何栈的特定门禁,仅提供验证模式,下游消费方 Agent 依据自身框架与工程规模按需取用、自适配落地。**
5
+
6
+ ---
7
+
8
+ ## 一、 快速索引表
9
+
10
+ | 技术栈 | 核心场景 | 推荐策略 / 模板 | 门禁分级建议 |
11
+ | :--- | :--- | :--- | :--- |
12
+ | **Python** | Agent 原语、Tool Schema、Planner 动作空间 | [`python-parity-test.py.template`](./python-parity-test.py.template) | **Fast Gate** (本地 pytest,纯内存对账,毫秒级) |
13
+ | **Rust** | 高可靠核心引擎、状态机、协议分发 | [`rust-exhaustive-match.md`](./rust-exhaustive-match.md) | **Fast Gate** (本地 `cargo check`) + **Heavy Gate** (CI `clippy -D warnings`) |
14
+ | **SwiftUI** | iOS 页面、ViewModel、导航树 | [`swift-periphery.md`](./swift-periphery.md) | **Heavy Gate** (CI 或 Pre-push 运行 Periphery,避免阻塞本地 commit) |
15
+ | **微信小程序 / TS** | 页面路由、组件依赖、云函数 | [`miniprogram-route-guard.js.template`](./miniprogram-route-guard.js.template) | **Fast Gate** (本地 pre-commit 轻量 AST 路由探针) |
16
+ | **Node.js / ESM** | CLI 子命令、公共导出原语、core 模块 | [`pre-commit-node.sh.template`](./pre-commit-node.sh.template) | **Fast Gate** (语法硬校验 + `lab-orphan check-diff --staged`,lab 实测 ~1.8–2.0s) |
17
+ | **通用项目接入** | 新项目 `AGENTS.md` / `GEMINI.md` 极简路由与 `preflight.conf` L1+L2 串联 | [`project-agents-gemini-templates.md`](./project-agents-gemini-templates.md) | **SSOT 指针** (`AGENTS.md <= 12` 行、`GEMINI.md <= 6` 行 + 4 项验收清单) |
18
+
19
+ ---
20
+
21
+ ## 二、 核心设计准则
22
+
23
+ 1. **拒绝高假阳性工具(The Vulture Lesson)**:
24
+ 动态语言(如 Python)严禁将全仓死代码扫描工具(如 `vulture`)配置为本地 Git Commit 的强阻断项。框架反射、动态装饰器与动态导入会产生大量假阳性,导致维护白名单成本极高,甚至促使 Agent 投机扩充白名单。
25
+ 2. **推崇“单一事实源(SSOT)+ 集合对等性测试(Parity Test)”**:
26
+ 底层使用装饰器(如 `@primitive` / `@tool`)自动提取元数据并向全局注册表注入;测试层直接比对 `set(implemented) <= set(planner_visible)`,执行确定性对账。
27
+ 3. **分级防御(Fast Local vs Heavy CI)**:
28
+ - 本地 `pre-commit` 门禁执行时间必须控制在 **2 秒以内**,保护本地心流;
29
+ - 依赖全量编译或深层 AST 依赖分析的重型工具(如 Periphery、全量 Clippy)统一放置在 `pre-push` 或 CI 阶段执行。
30
+ 4. **错误输出驱动自愈(Self-Healing Error Output)**:
31
+ 所有校验失败时,必须打印**具体缺失的原语/组件名称**以及**推荐的注册文件路径**,以便 Agent 能够根据错误日志一次性精准修复。
32
+
33
+ ---
34
+
35
+ ## 三、 层内自举:本仓(lab · Node.js/ESM)的挂载方式
36
+
37
+ 本仓自身是 Node.js/ESM 技术栈,因此**以第一消费方身份自举**该配方(防止“规范写了但自己没接线”):
38
+
39
+ ```bash
40
+ # 从统一本地模板库挂载(推荐,跨项目复用)
41
+ ln -sf ~/dev-templates/hooks/pre-commit-node .git/hooks/pre-commit
42
+
43
+ # 或直接从本仓模板就地挂载(无全局模板库时)
44
+ ln -sf "$(pwd)/units/orphan/templates/wiring/pre-commit-node.sh.template" .git/hooks/pre-commit
45
+ ```
46
+
47
+ * **SSOT 约定**:本文件 `pre-commit-node.sh.template` 为**唯一事实源**;`~/dev-templates/hooks/pre-commit-node` 是联邦边缘副本。修改顺序恒为「先改本仓模板 → 再 `cp` 覆盖边缘副本」,禁止反向就地修改边缘副本。
48
+ * **三层结构**:L1 `node --check` 暂存区语法硬校验 → L2 `lab-orphan check-diff --staged` 增量接线对账(O(Δ))→ L3 新增导出符号垂直切片提示。
49
+ * **耗时实测**:lab 全仓 185 个受跟踪文本文件 / 2.9 万行下约 **1.8–2.0s**,恰在 Fast Gate ≤ 2s 预算内。其中约 1.2s 消耗在 145 个 `.md` 文档(1.28 万行)的分词入索引上;纯代码仓(md 稀少)会显著更快。
50
+ > 若某消费方仓库文档极密集且超预算,优先评估「排除 `.md` 弱引用索引」而非缩短检查面(`.md` 仅影响 `hasWeakDocOnly` 诊断文案,不影响 pass/fail 判定)。
51
+ * **紧急豁免**:`SKIP_WIRING_GATE=1 git commit ...`,豁免后必须在 PR/回执中补交 Wiring Proof。