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,142 @@
1
+ /**
2
+ * Git Blob Reader (Read-Only Invariant Core)
3
+ *
4
+ * 遵循「只读第一 (Read-Only Invariant)」原则:
5
+ * 1. 恒基于 Git HEAD blob 流式加载,严禁依赖脏工作树;
6
+ * 2. 读取过程绝对零污染工作树,严禁在被测仓库生成任何临时文件。
7
+ */
8
+
9
+ import { execSync, execFileSync } from 'node:child_process';
10
+ import path from 'node:path';
11
+
12
+ export class BlobReader {
13
+ /**
14
+ * @param {string} [repoDir=process.cwd()] 仓库根目录
15
+ * @param {string} [ref='HEAD'] 目标 Git 引用或提交哈希
16
+ */
17
+ constructor(repoDir = process.cwd(), ref = 'HEAD') {
18
+ this.repoDir = path.resolve(repoDir);
19
+ this.ref = ref;
20
+ this._blobList = null;
21
+ this._headCommit = null;
22
+ this._cache = new Map();
23
+ }
24
+
25
+ /**
26
+ * 获取当前引用的完整 Commit SHA
27
+ * @returns {string}
28
+ */
29
+ getHeadCommit() {
30
+ if (this._headCommit) return this._headCommit;
31
+ try {
32
+ this._headCommit = execSync(`git rev-parse ${this.ref}`, {
33
+ cwd: this.repoDir,
34
+ encoding: 'utf8',
35
+ stdio: ['pipe', 'pipe', 'ignore'],
36
+ }).trim();
37
+ } catch {
38
+ this._headCommit = '0000000000000000000000000000000000000000';
39
+ }
40
+ return this._headCommit;
41
+ }
42
+
43
+ /**
44
+ * 列出所有被 Git 跟踪的 Blob 列表 (基于 HEAD)
45
+ * @param {function(string): boolean} [filterFn] 路径过滤条件
46
+ * @returns {Array<{ path: string, mode: string, type: string, oid: string }>}
47
+ */
48
+ listBlobs(filterFn = null) {
49
+ if (this._blobList) {
50
+ if (filterFn) return this._blobList.filter(b => filterFn(b.path));
51
+ return this._blobList;
52
+ }
53
+
54
+ try {
55
+ const raw = execSync(`git ls-tree -r -z ${this.ref}`, {
56
+ cwd: this.repoDir,
57
+ maxBuffer: 64 * 1024 * 1024,
58
+ stdio: ['pipe', 'pipe', 'ignore'],
59
+ });
60
+
61
+ const entries = [];
62
+ let start = 0;
63
+ for (let i = 0; i < raw.length; i++) {
64
+ if (raw[i] === 0) { // NUL byte delimiter
65
+ const slice = raw.subarray(start, i).toString('utf8');
66
+ start = i + 1;
67
+ if (!slice) continue;
68
+
69
+ const tabIndex = slice.indexOf('\t');
70
+ if (tabIndex === -1) continue;
71
+ const meta = slice.slice(0, tabIndex).trim();
72
+ const filePath = slice.slice(tabIndex + 1);
73
+
74
+ const parts = meta.split(/\s+/);
75
+ if (parts.length >= 3 && parts[1] === 'blob') {
76
+ entries.push({
77
+ mode: parts[0],
78
+ type: parts[1],
79
+ oid: parts[2],
80
+ path: filePath,
81
+ });
82
+ }
83
+ }
84
+ }
85
+
86
+ this._blobList = entries;
87
+ if (filterFn) return this._blobList.filter(b => filterFn(b.path));
88
+ return this._blobList;
89
+ } catch (err) {
90
+ // 非 git 仓库或异常时降级返回空
91
+ this._blobList = [];
92
+ return this._blobList;
93
+ }
94
+ }
95
+
96
+ /**
97
+ * 读取单个 Blob 的文本内容(基于 oid 或 path)
98
+ * @param {string} filePath 文件相对路径
99
+ * @param {string} [oid] Blob OID
100
+ * @returns {string}
101
+ */
102
+ readBlobText(filePath, oid = null) {
103
+ if (this._cache.has(filePath)) {
104
+ return this._cache.get(filePath);
105
+ }
106
+
107
+ let targetOid = oid;
108
+ if (!targetOid) {
109
+ const found = this.listBlobs().find(b => b.path === filePath);
110
+ if (!found) return '';
111
+ targetOid = found.oid;
112
+ }
113
+
114
+ try {
115
+ const content = execFileSync('git', ['cat-file', '-p', targetOid], {
116
+ cwd: this.repoDir,
117
+ maxBuffer: 32 * 1024 * 1024,
118
+ encoding: 'utf8',
119
+ stdio: ['pipe', 'pipe', 'ignore'],
120
+ });
121
+ this._cache.set(filePath, content);
122
+ return content;
123
+ } catch {
124
+ return '';
125
+ }
126
+ }
127
+
128
+ /**
129
+ * 批量加载并填充所有过滤后的 Blob 内容至内存
130
+ * @param {function(string): boolean} [filterFn] 过滤器
131
+ * @returns {Map<string, string>} filePath -> content
132
+ */
133
+ loadAllTextBlobs(filterFn = null) {
134
+ const blobs = this.listBlobs(filterFn);
135
+ const map = new Map();
136
+ for (const b of blobs) {
137
+ const text = this.readBlobText(b.path, b.oid);
138
+ map.set(b.path, text);
139
+ }
140
+ return map;
141
+ }
142
+ }
@@ -0,0 +1,261 @@
1
+ /**
2
+ * Reference Classifier (引用三分类器)
3
+ *
4
+ * 将行级命中细分为:
5
+ * 1. Code 引用 (STRONG_CODE) - 代码符号、import、方法调用、类继承等强绑定;
6
+ * 2. Resource 引用 (MEDIUM_RESOURCE) - 布局绑定、XML/JSON 资产引用、路由表;
7
+ * 3. Doc/Comment 引用 (WEAK_DOC) - Markdown、文本说明、行内注释等弱引用。
8
+ */
9
+
10
+ import path from 'node:path';
11
+
12
+ export const ReferenceKind = {
13
+ STRONG_CODE: 'STRONG_CODE',
14
+ MEDIUM_RESOURCE: 'MEDIUM_RESOURCE',
15
+ WEAK_DOC: 'WEAK_DOC',
16
+ };
17
+
18
+ export const CallerKind = {
19
+ PRODUCTION_CALLER: 'PRODUCTION_CALLER',
20
+ TEST_CALLER: 'TEST_CALLER',
21
+ DOC_CALLER: 'DOC_CALLER',
22
+ };
23
+
24
+ export const TEST_PATH_PATTERNS = [
25
+ /(?:^|[\\/])(?:src[\\/])?test(?:s)?[\\/]/i,
26
+ /(?:^|[\\/])androidTest[\\/]/i,
27
+ /__tests__[\\/]/i,
28
+ /_test\.go$/i,
29
+ /\.(?:test|spec)\.[jt]sx?$/i,
30
+ /^test_.*\.py$/i,
31
+ /.*_test\.py$/i,
32
+ ];
33
+
34
+ /**
35
+ * 判断路径是否属于测试范围
36
+ * @param {string} filePath 相对或绝对路径
37
+ * @returns {boolean}
38
+ */
39
+ export function isTestPath(filePath) {
40
+ if (!filePath) return false;
41
+ const normalized = filePath.replace(/\\/g, '/');
42
+ return TEST_PATH_PATTERNS.some((pattern) => pattern.test(normalized));
43
+ }
44
+
45
+ const DOC_EXTS = new Set([
46
+ '.md', '.markdown', '.txt', '.rst', '.adoc', '.doc', '.docx'
47
+ ]);
48
+
49
+ const RESOURCE_EXTS = new Set([
50
+ '.xml', '.json', '.yaml', '.yml', '.html', '.htm', '.css', '.scss', '.toml', '.properties'
51
+ ]);
52
+
53
+ const CODE_EXTS = new Set([
54
+ '.js', '.mjs', '.cjs', '.ts', '.tsx', '.jsx',
55
+ '.kt', '.java', '.py', '.rs', '.go', '.swift',
56
+ '.c', '.cpp', '.cc', '.h', '.hpp', '.m', '.mm'
57
+ ]);
58
+
59
+ export class Classifier {
60
+ /**
61
+ * 判定单条引用的类型
62
+ * @param {{ path: string, lineNo: number, lineText: string }} ref
63
+ * @returns {string} ReferenceKind
64
+ */
65
+ static classifySingle(ref) {
66
+ const ext = path.extname(ref.path).toLowerCase();
67
+ const text = ref.lineText.trim();
68
+
69
+ // 1. 文档文件一律归为弱引用
70
+ if (DOC_EXTS.has(ext) || ref.path.includes('/docs/') || ref.path.includes('/doc/')) {
71
+ return ReferenceKind.WEAK_DOC;
72
+ }
73
+
74
+ // 2. 检查是否为纯注释行
75
+ if (
76
+ text.startsWith('//') ||
77
+ text.startsWith('#') ||
78
+ text.startsWith('*') ||
79
+ text.startsWith('/*') ||
80
+ text.startsWith('<!--')
81
+ ) {
82
+ return ReferenceKind.WEAK_DOC;
83
+ }
84
+
85
+ // 3. 资源文件
86
+ if (RESOURCE_EXTS.has(ext)) {
87
+ return ReferenceKind.MEDIUM_RESOURCE;
88
+ }
89
+
90
+ // 4. 代码文件
91
+ if (CODE_EXTS.has(ext)) {
92
+ return ReferenceKind.STRONG_CODE;
93
+ }
94
+
95
+ // 默认降级为资源引用
96
+ return ReferenceKind.MEDIUM_RESOURCE;
97
+ }
98
+
99
+ /**
100
+ * 聚合分析某个候选符号的所有引用列表
101
+ * @param {Array<{ path: string, lineNo: number, lineText: string }>} references
102
+ * @returns {{
103
+ * isAlive: boolean,
104
+ * hasStrongCode: boolean,
105
+ * hasMediumResource: boolean,
106
+ * hasWeakDocOnly: boolean,
107
+ * strongCount: number,
108
+ * mediumCount: number,
109
+ * weakCount: number,
110
+ * classified: Array<{ path: string, lineNo: number, lineText: string, kind: string }>
111
+ * }}
112
+ */
113
+ static evaluate(references) {
114
+ const classified = references.map(ref => ({
115
+ ...ref,
116
+ kind: Classifier.classifySingle(ref),
117
+ }));
118
+
119
+ let strongCount = 0;
120
+ let mediumCount = 0;
121
+ let weakCount = 0;
122
+
123
+ for (const item of classified) {
124
+ if (item.kind === ReferenceKind.STRONG_CODE) strongCount++;
125
+ else if (item.kind === ReferenceKind.MEDIUM_RESOURCE) mediumCount++;
126
+ else if (item.kind === ReferenceKind.WEAK_DOC) weakCount++;
127
+ }
128
+
129
+ const hasStrongCode = strongCount > 0;
130
+ const hasMediumResource = mediumCount > 0;
131
+ const isAlive = hasStrongCode || hasMediumResource;
132
+ const hasWeakDocOnly = !isAlive && weakCount > 0;
133
+
134
+ return {
135
+ isAlive,
136
+ hasStrongCode,
137
+ hasMediumResource,
138
+ hasWeakDocOnly,
139
+ strongCount,
140
+ mediumCount,
141
+ weakCount,
142
+ classified,
143
+ };
144
+ }
145
+
146
+ /**
147
+ * 判定路径是否属于测试范围
148
+ * @param {string} filePath
149
+ * @returns {boolean}
150
+ */
151
+ static isTestPath(filePath) {
152
+ return isTestPath(filePath);
153
+ }
154
+
155
+ /**
156
+ * 判定引用是否来自生产代码
157
+ * @param {{ path: string, lineNo: number, lineText: string }} ref
158
+ * @returns {boolean}
159
+ */
160
+ static isProductionCaller(ref) {
161
+ const kind = Classifier.classifySingle(ref);
162
+ if (kind === ReferenceKind.WEAK_DOC) return false;
163
+ return !isTestPath(ref.path);
164
+ }
165
+
166
+ /**
167
+ * 判定引用是否来自测试代码
168
+ * @param {{ path: string, lineNo: number, lineText: string }} ref
169
+ * @returns {boolean}
170
+ */
171
+ static isTestCaller(ref) {
172
+ const kind = Classifier.classifySingle(ref);
173
+ if (kind === ReferenceKind.WEAK_DOC) return false;
174
+ return isTestPath(ref.path);
175
+ }
176
+
177
+ /**
178
+ * 将引用精准分类为 PRODUCTION_CALLER | TEST_CALLER | DOC_CALLER
179
+ * @param {{ path: string, lineNo: number, lineText: string }} ref
180
+ * @returns {string} CallerKind
181
+ */
182
+ static classifyCaller(ref) {
183
+ const kind = Classifier.classifySingle(ref);
184
+ if (kind === ReferenceKind.WEAK_DOC) return CallerKind.DOC_CALLER;
185
+ return isTestPath(ref.path) ? CallerKind.TEST_CALLER : CallerKind.PRODUCTION_CALLER;
186
+ }
187
+
188
+ /**
189
+ * 聚合评估某个符号的所有调用者分布(区分生产接线与单测自测)
190
+ * @param {Array<{ path: string, lineNo: number, lineText: string }>} references
191
+ * @param {object} [opts]
192
+ * @param {Array<string>} [opts.excludePaths=[]] 排除的文件路径列表
193
+ * @param {string} [opts.symbolName=''] 符号名称(用于过滤自身声明行)
194
+ * @returns {{
195
+ * productionCallerCount: number,
196
+ * testCallerCount: number,
197
+ * docReferenceCount: number,
198
+ * productionCallers: Array<{ path: string, lineNo: number, lineText: string }>,
199
+ * testCallers: Array<{ path: string, lineNo: number, lineText: string }>,
200
+ * docReferences: Array<{ path: string, lineNo: number, lineText: string }>,
201
+ * wiringStatus: 'wired' | 'test_only' | 'unwired',
202
+ * isWiredInProduction: boolean,
203
+ * isTestOnly: boolean,
204
+ * isCompletelyOrphan: boolean,
205
+ * }}
206
+ */
207
+ static evaluateCallers(references, { excludePaths = [], symbolName = '' } = {}) {
208
+ const excludeSet = new Set(excludePaths.map((p) => p.replace(/\\/g, '/')));
209
+ const escapedSymbol = symbolName ? symbolName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') : '';
210
+ const declRegex = escapedSymbol
211
+ ? new RegExp(`(?:fun|def|func|function|fn)\\s+(?:[A-Za-z0-9_.]+\\.)?${escapedSymbol}\\b|(?:val|var|const|let)\\s+${escapedSymbol}\\s*[:=]`)
212
+ : null;
213
+
214
+ const productionCallers = [];
215
+ const testCallers = [];
216
+ const docReferences = [];
217
+
218
+ for (const ref of references) {
219
+ const normPath = ref.path.replace(/\\/g, '/');
220
+ if (excludeSet.has(normPath)) continue;
221
+
222
+ // 排除符号声明行自身
223
+ if (declRegex && declRegex.test(ref.lineText)) {
224
+ continue;
225
+ }
226
+
227
+ const callerKind = Classifier.classifyCaller(ref);
228
+ if (callerKind === CallerKind.PRODUCTION_CALLER) {
229
+ productionCallers.push(ref);
230
+ } else if (callerKind === CallerKind.TEST_CALLER) {
231
+ testCallers.push(ref);
232
+ } else {
233
+ docReferences.push(ref);
234
+ }
235
+ }
236
+
237
+ const isWiredInProduction = productionCallers.length > 0;
238
+ const isTestOnly = productionCallers.length === 0 && testCallers.length > 0;
239
+ const isCompletelyOrphan = productionCallers.length === 0 && testCallers.length === 0;
240
+
241
+ let wiringStatus = 'unwired';
242
+ if (isWiredInProduction) {
243
+ wiringStatus = 'wired';
244
+ } else if (isTestOnly) {
245
+ wiringStatus = 'test_only';
246
+ }
247
+
248
+ return {
249
+ productionCallerCount: productionCallers.length,
250
+ testCallerCount: testCallers.length,
251
+ docReferenceCount: docReferences.length,
252
+ productionCallers,
253
+ testCallers,
254
+ docReferences,
255
+ wiringStatus,
256
+ isWiredInProduction,
257
+ isTestOnly,
258
+ isCompletelyOrphan,
259
+ };
260
+ }
261
+ }
@@ -0,0 +1,166 @@
1
+ /**
2
+ * Safe Pruner / Cleaner (安全修剪清理器)
3
+ *
4
+ * 遵循「只读演练(Dry-Run by Default)」与「精确 Diff 生成」原则:
5
+ * 1. 默认仅生成 patch / diff 预览,绝对零污染磁盘;
6
+ * 2. 仅对 CONFIRMED_ORPHAN 执行清理;
7
+ * 3. 支持整文件级孤儿资产删除与代码符号级精确剪枝。
8
+ */
9
+
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+
13
+ export class Cleaner {
14
+ /**
15
+ * @param {object} [options]
16
+ * @param {string} [options.repoDir=process.cwd()]
17
+ * @param {boolean} [options.dryRun=true]
18
+ */
19
+ constructor(options = {}) {
20
+ this.repoDir = path.resolve(options.repoDir || process.cwd());
21
+ this.dryRun = options.dryRun !== false; // 默认开启 dry-run
22
+ }
23
+
24
+ /**
25
+ * 为整文件孤儿生成 patch diff
26
+ * @param {string} relPath
27
+ * @returns {string}
28
+ */
29
+ _generateFileDeletionDiff(relPath) {
30
+ return [
31
+ `diff --git a/${relPath} b/${relPath}`,
32
+ `deleted file mode 100644`,
33
+ `--- a/${relPath}`,
34
+ `+++ /dev/null`,
35
+ `@@ -1 +0,0 @@`,
36
+ `-<binary/text content deleted>`,
37
+ ].join('\n');
38
+ }
39
+
40
+ /**
41
+ * 为代码符号级孤儿生成行级删除 diff
42
+ * @param {string} relPath
43
+ * @param {string} symbolName
44
+ * @param {number} [lineNo=1]
45
+ * @param {boolean} [apply=false]
46
+ * @returns {{ diff: string, removedLines: number }}
47
+ */
48
+ _generateSymbolPruneDiff(relPath, symbolName, lineNo = 1, apply = false) {
49
+ const absPath = path.join(this.repoDir, relPath);
50
+ if (!fs.existsSync(absPath)) return { diff: '', removedLines: 0 };
51
+
52
+ const content = fs.readFileSync(absPath, 'utf8');
53
+ const lines = content.split(/\r?\n/);
54
+
55
+ // 找到定义起始行
56
+ let startIdx = -1;
57
+ for (let i = 0; i < lines.length; i++) {
58
+ if (lines[i].includes(symbolName) && (
59
+ lines[i].match(new RegExp(`(?:def|class|export|const|let|var|function)\\s+${symbolName}\\b`)) ||
60
+ lines[i].match(new RegExp(`\\b${symbolName}\\s*[:=]`))
61
+ )) {
62
+ startIdx = i;
63
+ break;
64
+ }
65
+ }
66
+
67
+ if (startIdx === -1) return { diff: '', removedLines: 0 };
68
+
69
+ // 寻找缩进或花括号界限估算函数/类体结束
70
+ let endIdx = startIdx;
71
+ const baseIndent = lines[startIdx].match(/^\s*/)[0].length;
72
+
73
+ // 探测块结束
74
+ for (let i = startIdx + 1; i < lines.length; i++) {
75
+ const line = lines[i];
76
+ if (!line.trim()) continue;
77
+ const currentIndent = line.match(/^\s*/)[0].length;
78
+ if (currentIndent <= baseIndent && !line.trim().startsWith('}') && !line.trim().startsWith(')')) {
79
+ break;
80
+ }
81
+ endIdx = i;
82
+ if (line.trim() === '}' && currentIndent === baseIndent) break;
83
+ }
84
+
85
+ const removedHunk = lines.slice(startIdx, endIdx + 1);
86
+ const diffLines = [
87
+ `diff --git a/${relPath} b/${relPath}`,
88
+ `--- a/${relPath}`,
89
+ `+++ b/${relPath}`,
90
+ `@@ -${startIdx + 1},${removedHunk.length} +${startIdx + 1},0 @@`,
91
+ ...removedHunk.map(l => `-${l}`),
92
+ ];
93
+
94
+ if (apply && !this.dryRun) {
95
+ lines.splice(startIdx, removedHunk.length);
96
+ fs.writeFileSync(absPath, lines.join('\n'), 'utf8');
97
+ }
98
+
99
+ return {
100
+ diff: diffLines.join('\n'),
101
+ removedLines: removedHunk.length,
102
+ };
103
+ }
104
+
105
+ /**
106
+ * 执行安全清理演练或应用
107
+ * @param {Array<any>} candidates 候选孤儿列表 (candidates.json)
108
+ * @returns {{
109
+ * dryRun: boolean,
110
+ * totalCandidates: number,
111
+ * cleanedCount: number,
112
+ * patches: Array<{ path: string, type: string, diff: string }>,
113
+ * unifiedDiff: string
114
+ * }}
115
+ */
116
+ clean(candidates) {
117
+ const confirmed = (candidates || []).filter(c => c.status === 'CONFIRMED_ORPHAN');
118
+ const patches = [];
119
+ let cleanedCount = 0;
120
+
121
+ for (const item of confirmed) {
122
+ const relPath = item.path;
123
+ const absPath = path.join(this.repoDir, relPath);
124
+
125
+ // 1. 整文件资产孤儿 (asset_resource / asset_resource_family)
126
+ if (item.type === 'asset_resource' || item.type === 'asset_resource_family') {
127
+ const pathsToDelete = item.qualifier_paths || [relPath];
128
+ for (const p of pathsToDelete) {
129
+ const diff = this._generateFileDeletionDiff(p);
130
+ patches.push({
131
+ path: p,
132
+ type: 'file_deletion',
133
+ diff,
134
+ });
135
+ cleanedCount++;
136
+ if (!this.dryRun) {
137
+ const abs = path.join(this.repoDir, p);
138
+ if (fs.existsSync(abs)) fs.unlinkSync(abs);
139
+ }
140
+ }
141
+ continue;
142
+ }
143
+
144
+ // 2. 代码符号孤儿 (function / class / export_*)
145
+ const pruneResult = this._generateSymbolPruneDiff(relPath, item.name, item.line_no || 1, !this.dryRun);
146
+ if (pruneResult.diff) {
147
+ patches.push({
148
+ path: relPath,
149
+ type: 'symbol_prune',
150
+ diff: pruneResult.diff,
151
+ });
152
+ cleanedCount++;
153
+ }
154
+ }
155
+
156
+ const unifiedDiff = patches.map(p => p.diff).join('\n\n');
157
+
158
+ return {
159
+ dryRun: this.dryRun,
160
+ totalCandidates: confirmed.length,
161
+ cleanedCount,
162
+ patches,
163
+ unifiedDiff,
164
+ };
165
+ }
166
+ }