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,341 @@
1
+ /**
2
+ * Incremental Diff Checker (增量防腐门禁引擎)
3
+ *
4
+ * 遵循「增量只扫新增(O(Δ) 复杂度)」与「Fail-Closed 门禁阻断」原则:
5
+ * 1. 仅提取 git diff 中新增加的代码行与新增资产文件;
6
+ * 2. 毫秒级提取新增符号并在全仓倒排索引中排查是否有真实引用;
7
+ * 3. 凡检出 CONFIRMED_ORPHAN 即刻判定 Exit 1 阻断提交;PENDING_VERIFICATION 告警提示。
8
+ */
9
+
10
+ import { execSync } from 'node:child_process';
11
+ import path from 'node:path';
12
+ import fs from 'node:fs';
13
+ import { InvertedIndex } from './inverted-index.mjs';
14
+ import { Classifier } from './classifier.mjs';
15
+
16
+ export class DiffChecker {
17
+ /**
18
+ * @param {object} [options]
19
+ * @param {string} [options.repoDir=process.cwd()]
20
+ * @param {Array<any>} [options.adapters=[]]
21
+ */
22
+ constructor(options = {}) {
23
+ this.repoDir = path.resolve(options.repoDir || process.cwd());
24
+ this.adapters = options.adapters || [];
25
+ }
26
+
27
+ /**
28
+ * 解析 git diff 文本,提取新增文件与新增行
29
+ * @param {string} diffText
30
+ * @returns {Array<{ path: string, isNewFile: boolean, addedLines: Array<{ lineNo: number, text: string }> }>}
31
+ */
32
+ static parseDiff(diffText) {
33
+ const files = [];
34
+ if (!diffText || !diffText.trim()) return files;
35
+
36
+ const diffSections = diffText.split(/^diff --git /m);
37
+ for (const section of diffSections) {
38
+ if (!section.trim()) continue;
39
+
40
+ const lines = section.split(/\r?\n/);
41
+ let targetPath = '';
42
+ let isNewFile = false;
43
+
44
+ // 提取目标路径
45
+ for (const line of lines) {
46
+ if (line.startsWith('+++ b/')) {
47
+ targetPath = line.slice(6).trim();
48
+ break;
49
+ } else if (line.startsWith('new file mode')) {
50
+ isNewFile = true;
51
+ }
52
+ }
53
+
54
+ if (!targetPath || targetPath === '/dev/null') continue;
55
+
56
+ const addedLines = [];
57
+ let currentLineNo = 1;
58
+
59
+ for (const line of lines) {
60
+ // 解析 hunk header: @@ -1,4 +10,6 @@
61
+ const hunkMatch = line.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
62
+ if (hunkMatch) {
63
+ currentLineNo = parseInt(hunkMatch[1], 10);
64
+ continue;
65
+ }
66
+
67
+ if (line.startsWith('+') && !line.startsWith('+++')) {
68
+ addedLines.push({
69
+ lineNo: currentLineNo,
70
+ text: line.slice(1),
71
+ });
72
+ currentLineNo++;
73
+ } else if (!line.startsWith('-')) {
74
+ currentLineNo++;
75
+ }
76
+ }
77
+
78
+ if (isNewFile || addedLines.length > 0) {
79
+ files.push({
80
+ path: targetPath,
81
+ isNewFile,
82
+ addedLines,
83
+ });
84
+ }
85
+ }
86
+
87
+ return files;
88
+ }
89
+
90
+ /**
91
+ * 从新增行中提取新增的候选声明
92
+ * @param {string} filePath
93
+ * @param {Array<{ lineNo: number, text: string }>} addedLines
94
+ * @param {boolean} isNewFile
95
+ * @returns {Array<{ name: string, symbol: string, lineNo: number, kind: string, isProtected?: boolean, protectionReason?: string }>}
96
+ */
97
+ extractAddedCandidates(filePath, addedLines, isNewFile) {
98
+ const candidates = [];
99
+ const ext = path.extname(filePath).toLowerCase();
100
+
101
+ // 1. Android / 通用资产文件 (整文件新增且在 res/ 或 assets/ 目录)
102
+ if (isNewFile && (filePath.includes('/res/') || filePath.includes('/assets/'))) {
103
+ const baseName = path.basename(filePath).replace(/\.[^.]+$/, '');
104
+ const resMatch = filePath.match(/(?:^|\/)res\/([a-z]+)(?:-[a-zA-Z0-9_-]+)?\/([a-zA-Z0-9_]+)\.[a-zA-Z0-9]+$/);
105
+ const resType = resMatch ? resMatch[1] : 'asset';
106
+ const name = resMatch ? resMatch[2] : baseName;
107
+ candidates.push({
108
+ name,
109
+ symbol: `R.${resType}.${name}`,
110
+ resType,
111
+ lineNo: 1,
112
+ kind: 'asset_resource',
113
+ });
114
+ return candidates;
115
+ }
116
+
117
+ // 2. Python 新增定义
118
+ if (ext === '.py') {
119
+ let prevDecorator = '';
120
+ for (const item of addedLines) {
121
+ const trimmed = item.text.trim();
122
+ if (trimmed.startsWith('@')) {
123
+ prevDecorator = trimmed;
124
+ continue;
125
+ }
126
+
127
+ const funcMatch = trimmed.match(/^(?:async\s+)?def\s+([a-zA-Z0-9_]+)\s*\(/);
128
+ if (funcMatch) {
129
+ const name = funcMatch[1];
130
+ let isProtected = false;
131
+ let protectionReason = '';
132
+
133
+ if (name.startsWith('test_') || prevDecorator.includes('@pytest.fixture')) {
134
+ isProtected = true;
135
+ protectionReason = 'Pytest test function / fixture';
136
+ } else if (/^__[a-zA-Z0-9_]+__$/.test(name)) {
137
+ isProtected = true;
138
+ protectionReason = 'Magic method';
139
+ } else if (prevDecorator.startsWith('@app.') || prevDecorator.startsWith('@router.')) {
140
+ isProtected = true;
141
+ protectionReason = 'Route decorator';
142
+ }
143
+
144
+ candidates.push({
145
+ name,
146
+ symbol: name,
147
+ lineNo: item.lineNo,
148
+ kind: 'function',
149
+ isProtected,
150
+ protectionReason,
151
+ });
152
+ prevDecorator = '';
153
+ continue;
154
+ }
155
+
156
+ const classMatch = trimmed.match(/^class\s+([a-zA-Z0-9_]+)(?:\s*\(|:)/);
157
+ if (classMatch) {
158
+ const name = classMatch[1];
159
+ candidates.push({
160
+ name,
161
+ symbol: name,
162
+ lineNo: item.lineNo,
163
+ kind: 'class',
164
+ isProtected: name.startsWith('Test'),
165
+ protectionReason: name.startsWith('Test') ? 'Pytest test class' : undefined,
166
+ });
167
+ prevDecorator = '';
168
+ continue;
169
+ }
170
+
171
+ prevDecorator = '';
172
+ }
173
+ return candidates;
174
+ }
175
+
176
+ // 3. Web / TS 新增 export
177
+ if (ext === '.ts' || ext === '.tsx' || ext === '.js' || ext === '.jsx' || ext === '.mjs') {
178
+ for (const item of addedLines) {
179
+ const trimmed = item.text.trim();
180
+ if (!trimmed.startsWith('export ') && !trimmed.startsWith('exports.')) continue;
181
+
182
+ const funcOrClassMatch = trimmed.match(/^export\s+(?:async\s+)?(function|class)\s+([a-zA-Z0-9_$]+)/);
183
+ if (funcOrClassMatch) {
184
+ candidates.push({
185
+ name: funcOrClassMatch[2],
186
+ symbol: funcOrClassMatch[2],
187
+ lineNo: item.lineNo,
188
+ kind: `export_${funcOrClassMatch[1]}`,
189
+ });
190
+ continue;
191
+ }
192
+
193
+ const varMatch = trimmed.match(/^export\s+(?:const|let|var)\s+([a-zA-Z0-9_$]+)\s*[:=]/);
194
+ if (varMatch) {
195
+ candidates.push({
196
+ name: varMatch[1],
197
+ symbol: varMatch[1],
198
+ lineNo: item.lineNo,
199
+ kind: 'export_variable',
200
+ });
201
+ continue;
202
+ }
203
+ }
204
+ return candidates;
205
+ }
206
+
207
+ return candidates;
208
+ }
209
+
210
+ /**
211
+ * 构建全仓当前状态的倒排索引 (从工作区已跟踪文件或暂存区提取)
212
+ * @returns {InvertedIndex}
213
+ */
214
+ buildCurrentIndex() {
215
+ const index = new InvertedIndex();
216
+ try {
217
+ const filesRaw = execSync('git ls-files', {
218
+ cwd: this.repoDir,
219
+ encoding: 'utf8',
220
+ stdio: ['pipe', 'pipe', 'ignore'],
221
+ });
222
+ const files = filesRaw.split(/\r?\n/).filter(Boolean);
223
+
224
+ for (const relPath of files) {
225
+ const abs = path.join(this.repoDir, relPath);
226
+ if (fs.existsSync(abs) && fs.statSync(abs).isFile()) {
227
+ // 仅索引非二进制常用文本
228
+ const ext = path.extname(relPath).toLowerCase();
229
+ if (['.py', '.js', '.mjs', '.cjs', '.ts', '.tsx', '.jsx', '.kt', '.java', '.xml', '.json', '.yaml', '.yml', '.md', '.html'].includes(ext)) {
230
+ try {
231
+ const content = fs.readFileSync(abs, 'utf8');
232
+ index.indexFile(relPath, content);
233
+ } catch {}
234
+ }
235
+ }
236
+ }
237
+ } catch {}
238
+ return index;
239
+ }
240
+
241
+ /**
242
+ * 执行增量差异检查
243
+ * @param {object} [opts]
244
+ * @param {boolean} [opts.staged=false] 是否仅检查暂存区
245
+ * @param {string} [opts.base='HEAD~1'] 基准分支或 commit
246
+ * @returns {Promise<{
247
+ * passed: boolean,
248
+ * totalAddedCandidates: number,
249
+ * orphans: Array<any>,
250
+ * warnings: Array<any>
251
+ * }>}
252
+ */
253
+ async checkDiff(opts = {}) {
254
+ const isStaged = opts.staged || false;
255
+ const base = opts.base || 'HEAD~1';
256
+
257
+ let diffCmd = isStaged ? 'git diff --cached --unified=0' : `git diff ${base}...HEAD --unified=0`;
258
+ let diffOutput = '';
259
+ try {
260
+ diffOutput = execSync(diffCmd, {
261
+ cwd: this.repoDir,
262
+ encoding: 'utf8',
263
+ stdio: ['pipe', 'pipe', 'ignore'],
264
+ });
265
+ } catch {
266
+ // 若基准不存在尝试降级为对比 HEAD
267
+ try {
268
+ diffOutput = execSync('git diff HEAD --unified=0', {
269
+ cwd: this.repoDir,
270
+ encoding: 'utf8',
271
+ stdio: ['pipe', 'pipe', 'ignore'],
272
+ });
273
+ } catch {
274
+ diffOutput = '';
275
+ }
276
+ }
277
+
278
+ const diffFiles = DiffChecker.parseDiff(diffOutput);
279
+ if (!diffFiles.length) {
280
+ return {
281
+ passed: true,
282
+ totalAddedCandidates: 0,
283
+ orphans: [],
284
+ warnings: [],
285
+ };
286
+ }
287
+
288
+ const index = this.buildCurrentIndex();
289
+ const confirmedOrphans = [];
290
+ const warnings = [];
291
+ let totalAdded = 0;
292
+
293
+ for (const f of diffFiles) {
294
+ const candidates = this.extractAddedCandidates(f.path, f.addedLines, f.isNewFile);
295
+ totalAdded += candidates.length;
296
+
297
+ for (const cand of candidates) {
298
+ if (cand.isProtected) continue;
299
+
300
+ const tokensToSearch = new Set([cand.name]);
301
+ if (cand.symbol) tokensToSearch.add(cand.symbol);
302
+ if (cand.resType) {
303
+ tokensToSearch.add(`@${cand.resType}/${cand.name}`);
304
+ tokensToSearch.add(`R.${cand.resType}.${cand.name}`);
305
+ }
306
+
307
+ const refs = [];
308
+ for (const tok of tokensToSearch) {
309
+ const matches = index.lookup(tok, f.path);
310
+ refs.push(...matches);
311
+ }
312
+
313
+ const evalResult = Classifier.evaluate(refs);
314
+
315
+ if (!evalResult.isAlive) {
316
+ const item = {
317
+ name: cand.name,
318
+ symbol: cand.symbol,
319
+ path: f.path,
320
+ line_no: cand.lineNo,
321
+ kind: cand.kind,
322
+ reasons: ['Newly added in diff but has zero references across other codebase files'],
323
+ };
324
+
325
+ if (evalResult.hasWeakDocOnly) {
326
+ item.reasons = [`Only referenced in ${evalResult.weakCount} doc/comment lines`];
327
+ }
328
+
329
+ confirmedOrphans.push(item);
330
+ }
331
+ }
332
+ }
333
+
334
+ return {
335
+ passed: confirmedOrphans.length === 0,
336
+ totalAddedCandidates: totalAdded,
337
+ orphans: confirmedOrphans,
338
+ warnings,
339
+ };
340
+ }
341
+ }
@@ -0,0 +1,124 @@
1
+ /**
2
+ * In-Memory Line-Level Inverted Index (内存行级倒排索引)
3
+ *
4
+ * 为全仓跨语言引用提供毫秒级逆向检索与精确行级证据追溯。
5
+ */
6
+
7
+ export class InvertedIndex {
8
+ constructor() {
9
+ /** @type {Map<string, Array<{ path: string, lineNo: number, lineText: string }>>} */
10
+ this.tokenMap = new Map();
11
+ this.totalIndexedFiles = 0;
12
+ this.totalIndexedLines = 0;
13
+ }
14
+
15
+ /**
16
+ * 提取行内所有有效 Token (包括驼峰、下划线分词与整体标识符)
17
+ * @param {string} line
18
+ * @returns {Set<string>}
19
+ */
20
+ static extractTokens(line) {
21
+ const tokens = new Set();
22
+ if (!line) return tokens;
23
+
24
+ // 匹配常规标识符与 XML/资源引用模式
25
+ const matches = line.match(/[a-zA-Z0-9_$-]+/g);
26
+ if (!matches) return tokens;
27
+
28
+ for (const raw of matches) {
29
+ if (raw.length < 2) continue;
30
+ tokens.add(raw);
31
+
32
+ // 处理下划线与中划线切分
33
+ if (raw.includes('_') || raw.includes('-')) {
34
+ const parts = raw.split(/[-_]+/);
35
+ for (const p of parts) {
36
+ if (p.length >= 2) tokens.add(p);
37
+ }
38
+ }
39
+
40
+ // 处理驼峰切分 (e.g. MySpecialComponent -> My, Special, Component)
41
+ const camelParts = raw.replace(/([a-z])([A-Z])/g, '$1 $2').split(' ');
42
+ if (camelParts.length > 1) {
43
+ for (const cp of camelParts) {
44
+ if (cp.length >= 2) tokens.add(cp);
45
+ }
46
+ }
47
+ }
48
+
49
+ return tokens;
50
+ }
51
+
52
+ /**
53
+ * 将一个文件的全量文本行索引进倒排索引
54
+ * @param {string} filePath 相对文件路径
55
+ * @param {string} content 文件文本内容
56
+ */
57
+ indexFile(filePath, content) {
58
+ if (!content) return;
59
+ this.totalIndexedFiles++;
60
+
61
+ const lines = content.split(/\r?\n/);
62
+ for (let i = 0; i < lines.length; i++) {
63
+ const lineNo = i + 1;
64
+ const lineText = lines[i];
65
+ this.totalIndexedLines++;
66
+
67
+ const tokens = InvertedIndex.extractTokens(lineText);
68
+ for (const tok of tokens) {
69
+ let list = this.tokenMap.get(tok);
70
+ if (!list) {
71
+ list = [];
72
+ this.tokenMap.set(tok, list);
73
+ }
74
+ list.push({
75
+ path: filePath,
76
+ lineNo,
77
+ lineText: lineText.trim(),
78
+ });
79
+ }
80
+ }
81
+ }
82
+
83
+ /**
84
+ * 批量索引 Map<filePath, content>
85
+ * @param {Map<string, string>} filesMap
86
+ */
87
+ indexAll(filesMap) {
88
+ for (const [filePath, content] of filesMap.entries()) {
89
+ this.indexFile(filePath, content);
90
+ }
91
+ }
92
+
93
+ /**
94
+ * 精确查询某个 Token 的所有行级命中引用
95
+ * @param {string} token 目标符号
96
+ * @param {string} [excludePath] 排除自身声明所在文件
97
+ * @returns {Array<{ path: string, lineNo: number, lineText: string }>}
98
+ */
99
+ lookup(token, excludePath = null) {
100
+ const list = this.tokenMap.get(token);
101
+ if (!list) return [];
102
+ if (!excludePath) return list;
103
+ return list.filter(item => item.path !== excludePath);
104
+ }
105
+
106
+ /**
107
+ * 检查某个 Token 是否在倒排索引中出现
108
+ * @param {string} token
109
+ * @param {string} [excludePath]
110
+ * @returns {boolean}
111
+ */
112
+ has(token, excludePath = null) {
113
+ return this.lookup(token, excludePath).length > 0;
114
+ }
115
+
116
+ /**
117
+ * 清空索引
118
+ */
119
+ clear() {
120
+ this.tokenMap.clear();
121
+ this.totalIndexedFiles = 0;
122
+ this.totalIndexedLines = 0;
123
+ }
124
+ }
@@ -0,0 +1,192 @@
1
+ /**
2
+ * orphan-deps.mjs — 孤儿依赖与未导入第三方包求解器 (ADR-0011 / ADR-0012)
3
+ *
4
+ * 核心逻辑:
5
+ * 1. 解析项目清单(requirements.txt / package.json / pyproject.toml);
6
+ * 2. 扫描源码中真实的 import / require 声明;
7
+ * 3. 求解差集:标出 0 引用的孤儿依赖,从物理层面消除 90%+ 虚假 CVE 报警。
8
+ */
9
+
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { execSync } from 'node:child_process';
13
+
14
+ const PYPI_TO_IMPORT_MAP = {
15
+ 'python_dotenv': 'dotenv',
16
+ 'pyyaml': 'yaml',
17
+ 'scikit_learn': 'sklearn',
18
+ 'pillow': 'pil',
19
+ 'beautifulsoup4': 'bs4',
20
+ 'opencv_python': 'cv2',
21
+ 'protobuf': 'google',
22
+ };
23
+
24
+ export class OrphanDepsSolver {
25
+ constructor(options = {}) {
26
+ this.repoDir = options.repoDir || process.cwd();
27
+ }
28
+
29
+ /**
30
+ * 自动探测并扫描依赖清单与实际导入
31
+ */
32
+ async scan() {
33
+ const results = [];
34
+
35
+ // 1. Python 依赖清单
36
+ const reqFile = path.join(this.repoDir, 'requirements.txt');
37
+ if (fs.existsSync(reqFile)) {
38
+ const declared = this.parseRequirementsTxt(fs.readFileSync(reqFile, 'utf8'));
39
+ const imported = this.scanPythonImports();
40
+ const orphans = declared.filter(pkg => {
41
+ const norm = this.normalizePkgName(pkg);
42
+ const alias = PYPI_TO_IMPORT_MAP[norm];
43
+ return !imported.has(norm) && (!alias || !imported.has(alias));
44
+ });
45
+ results.push({
46
+ manifest: 'requirements.txt',
47
+ type: 'python',
48
+ total_declared: declared.length,
49
+ active_imported: declared.length - orphans.length,
50
+ orphans,
51
+ declared,
52
+ });
53
+ }
54
+
55
+ // 2. Node.js 依赖清单
56
+ const pkgFile = path.join(this.repoDir, 'package.json');
57
+ if (fs.existsSync(pkgFile)) {
58
+ try {
59
+ const pkgJson = JSON.parse(fs.readFileSync(pkgFile, 'utf8'));
60
+ const deps = Object.keys(pkgJson.dependencies || {});
61
+ const imported = this.scanNodeImports();
62
+ const orphans = deps.filter(pkg => !imported.has(pkg));
63
+ results.push({
64
+ manifest: 'package.json',
65
+ type: 'node',
66
+ total_declared: deps.length,
67
+ active_imported: deps.length - orphans.length,
68
+ orphans,
69
+ declared: deps,
70
+ });
71
+ } catch (e) {
72
+ // ignore parse error
73
+ }
74
+ }
75
+
76
+ return results;
77
+ }
78
+
79
+ normalizePkgName(name) {
80
+ return name.toLowerCase().replace(/[-_.]+/g, '_');
81
+ }
82
+
83
+ parseRequirementsTxt(content) {
84
+ const pkgs = [];
85
+ for (let line of content.split('\n')) {
86
+ line = line.trim();
87
+ if (!line || line.startsWith('#') || line.startsWith('-')) continue;
88
+ const match = line.match(/^([a-zA-Z0-9_\-\.]+)/);
89
+ if (match) {
90
+ pkgs.push(match[1]);
91
+ }
92
+ }
93
+ return pkgs;
94
+ }
95
+
96
+ scanPythonImports() {
97
+ const imported = new Set();
98
+ const files = this.getTrackedFiles(/\.py$/);
99
+ for (const f of files) {
100
+ const fullPath = path.join(this.repoDir, f);
101
+ if (!fs.existsSync(fullPath)) continue;
102
+ const content = fs.readFileSync(fullPath, 'utf8');
103
+ const lines = content.split('\n');
104
+ for (const line of lines) {
105
+ const trimmed = line.trim();
106
+ const m1 = trimmed.match(/^import\s+([a-zA-Z0-9_]+)/);
107
+ if (m1) imported.add(this.normalizePkgName(m1[1]));
108
+ const m2 = trimmed.match(/^from\s+([a-zA-Z0-9_]+)/);
109
+ if (m2) imported.add(this.normalizePkgName(m2[1]));
110
+ }
111
+ }
112
+ return imported;
113
+ }
114
+
115
+ scanNodeImports() {
116
+ const imported = new Set();
117
+ const files = this.getTrackedFiles(/\.(js|mjs|cjs|ts|tsx|jsx)$/);
118
+ for (const f of files) {
119
+ const fullPath = path.join(this.repoDir, f);
120
+ if (!fs.existsSync(fullPath)) continue;
121
+ const content = fs.readFileSync(fullPath, 'utf8');
122
+ const matches = content.matchAll(/(?:from\s+['"]|import\s*\(?['"]|require\s*\(\s*['"])(@?[a-zA-Z0-9_\-\.\/]+)['"]/g);
123
+ for (const m of matches) {
124
+ let pkg = m[1];
125
+ if (pkg.startsWith('.')) continue; // 排除相对路径
126
+ if (pkg.startsWith('@')) {
127
+ const parts = pkg.split('/');
128
+ pkg = parts.slice(0, 2).join('/');
129
+ } else {
130
+ pkg = pkg.split('/')[0];
131
+ }
132
+ imported.add(pkg);
133
+ }
134
+ }
135
+ return imported;
136
+ }
137
+
138
+ getTrackedFiles(pattern) {
139
+ try {
140
+ const output = execSync('git ls-files', { cwd: this.repoDir, encoding: 'utf8' });
141
+ return output.split('\n').filter(f => f && (!pattern || pattern.test(f)));
142
+ } catch {
143
+ return [];
144
+ }
145
+ }
146
+
147
+ /**
148
+ * 零调用假凭证扫描探针 (Zero-Call Secret Hunter)
149
+ */
150
+ scanSecrets() {
151
+ const suspiciousPatterns = [
152
+ /(?:api[_-]?key|secret|token|auth[_-]?token|password)\s*[:=]\s*["']([a-zA-Z0-9_\-\.]{16,})["']/gi,
153
+ /(?:ghp_[a-zA-Z0-9]{36}|sk-[a-zA-Z0-9]{32,}|xox[baprs]-[a-zA-Z0-9]{10,})/g,
154
+ ];
155
+
156
+ const findings = [];
157
+ const files = this.getTrackedFiles(/\.(py|js|mjs|ts|json|yaml|yml|env|sh)$/);
158
+
159
+ for (const f of files) {
160
+ if (f.includes('package-lock.json') || f.includes('pnpm-lock') || f.endsWith('.min.js')) continue;
161
+ const fullPath = path.join(this.repoDir, f);
162
+ if (!fs.existsSync(fullPath)) continue;
163
+ const content = fs.readFileSync(fullPath, 'utf8');
164
+ const lines = content.split('\n');
165
+
166
+ for (let i = 0; i < lines.length; i++) {
167
+ const line = lines[i];
168
+ if (line.includes('AUDIT-') || line.includes('sha256:')) continue;
169
+ const lineSeen = new Set();
170
+ for (const pattern of suspiciousPatterns) {
171
+ pattern.lastIndex = 0;
172
+ let m;
173
+ while ((m = pattern.exec(line)) !== null) {
174
+ const candidate = m[1] || m[0];
175
+ // 过滤显式占位符或纯哈希
176
+ if (/^(?:your[-_]?token|dummy[-_]?key|placeholder|test[-_]?secret)/i.test(candidate)) continue;
177
+ if (lineSeen.has(candidate)) continue;
178
+ lineSeen.add(candidate);
179
+ findings.push({
180
+ file: f,
181
+ line: i + 1,
182
+ match: m[0],
183
+ candidate,
184
+ });
185
+ }
186
+ }
187
+ }
188
+ }
189
+
190
+ return findings;
191
+ }
192
+ }