@chongyan/autospec 1.0.1

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 (243) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +472 -0
  3. package/README.md +476 -0
  4. package/bin/autospec.js +3 -0
  5. package/knowledge/README.md +144 -0
  6. package/knowledge/checklists/code.md +182 -0
  7. package/knowledge/checklists/design.md +196 -0
  8. package/knowledge/checklists/release.md +70 -0
  9. package/knowledge/checklists/requirement.md +169 -0
  10. package/knowledge/checklists/test.md +46 -0
  11. package/knowledge/config/README.en.md +44 -0
  12. package/knowledge/config/README.md +44 -0
  13. package/knowledge/config/role-composition.yaml +98 -0
  14. package/knowledge/config/role-extensions.yaml +140 -0
  15. package/knowledge/config/skill-compositions.yaml +142 -0
  16. package/knowledge/config/team-stage.yaml +95 -0
  17. package/knowledge/config/team-tasks.yaml +139 -0
  18. package/knowledge/config/team-triggers.yaml +198 -0
  19. package/knowledge/config/validation-patterns.yaml +137 -0
  20. package/knowledge/domain/README.md +115 -0
  21. package/knowledge/domain/flows/README.md +194 -0
  22. package/knowledge/domain/glossary.md +143 -0
  23. package/knowledge/domain/rules.md +138 -0
  24. package/knowledge/environment/README.en.md +36 -0
  25. package/knowledge/environment/README.md +87 -0
  26. package/knowledge/environment/component-knowledge.md +316 -0
  27. package/knowledge/environment/detection-patterns.yaml +502 -0
  28. package/knowledge/environment/middleware-knowledge.md +237 -0
  29. package/knowledge/environment/template-registry.md +321 -0
  30. package/knowledge/guides/domain-driven-design.md +345 -0
  31. package/knowledge/guides/knowledge-management.md +369 -0
  32. package/knowledge/guides/requirement-engineering.md +329 -0
  33. package/knowledge/guides/stages/ai-effect-evaluator.md +93 -0
  34. package/knowledge/guides/stages/code-implementer.md +205 -0
  35. package/knowledge/guides/stages/code-reviewer.md +111 -0
  36. package/knowledge/guides/stages/consistency-checker.md +177 -0
  37. package/knowledge/guides/stages/design-planner.md +401 -0
  38. package/knowledge/guides/stages/design-reviewer.md +83 -0
  39. package/knowledge/guides/stages/integration-test-runner.md +105 -0
  40. package/knowledge/guides/stages/release-checker.md +205 -0
  41. package/knowledge/guides/stages/requirement-analyzer.md +195 -0
  42. package/knowledge/guides/stages/requirement-reviewer.md +83 -0
  43. package/knowledge/guides/stages/security-reviewer.md +89 -0
  44. package/knowledge/guides/stages/test-context-analyzer.md +250 -0
  45. package/knowledge/guides/stages/test-generator.md +241 -0
  46. package/knowledge/guides/stages/test-planner.md +183 -0
  47. package/knowledge/guides/stages/test-reviewer.md +76 -0
  48. package/knowledge/guides/stages/unit-test-runner.md +83 -0
  49. package/knowledge/guides/support/ai-agent-analyzer.md +362 -0
  50. package/knowledge/guides/support/ai-anomaly-analyzer.md +213 -0
  51. package/knowledge/guides/support/ai-artifact-evaluator.md +192 -0
  52. package/knowledge/guides/support/ai-capability-analyzer.md +193 -0
  53. package/knowledge/guides/support/ai-component-analyzer.md +169 -0
  54. package/knowledge/guides/support/ai-data-validator.md +276 -0
  55. package/knowledge/guides/support/ai-evaluation-planner.md +374 -0
  56. package/knowledge/guides/support/ai-path-evaluator.md +274 -0
  57. package/knowledge/guides/support/ai-pipeline-evaluator.md +219 -0
  58. package/knowledge/guides/support/ai-rag-analyzer.md +339 -0
  59. package/knowledge/guides/support/ai-task-assessor.md +418 -0
  60. package/knowledge/guides/support/ai-test-diagnostics.md +133 -0
  61. package/knowledge/guides/support/complexity-assessor.md +268 -0
  62. package/knowledge/guides/support/component-discovery.md +183 -0
  63. package/knowledge/guides/support/environment-scanner.md +207 -0
  64. package/knowledge/guides/support/environment-validator.md +207 -0
  65. package/knowledge/guides/support/knowledge-generator.md +234 -0
  66. package/knowledge/guides/support/methodology-extractor.md +55 -0
  67. package/knowledge/guides/support/pipeline-protocol.md +438 -0
  68. package/knowledge/guides/support/practice-logger.md +359 -0
  69. package/knowledge/guides/support/scope-inference.md +174 -0
  70. package/knowledge/guides/support/skill-distiller.md +91 -0
  71. package/knowledge/guides/support/skill-updater.md +45 -0
  72. package/knowledge/guides/support/skill-validator.md +72 -0
  73. package/knowledge/guides/support/team-orchestrator.md +323 -0
  74. package/knowledge/guides/support/tech-stack-analyzer.md +139 -0
  75. package/knowledge/guides/support/test-runner.md +254 -0
  76. package/knowledge/guides/system-design.md +352 -0
  77. package/knowledge/organization/ai-native-team.md +318 -0
  78. package/knowledge/organization/team-metrics.md +228 -0
  79. package/knowledge/principles/constitution.md +134 -0
  80. package/knowledge/principles/core-principles.md +368 -0
  81. package/knowledge/principles/design-philosophy.md +877 -0
  82. package/knowledge/principles/evolution.md +553 -0
  83. package/knowledge/process/01-requirement.md +113 -0
  84. package/knowledge/process/02-design.md +123 -0
  85. package/knowledge/process/03-implementation.md +90 -0
  86. package/knowledge/process/04-review.md +80 -0
  87. package/knowledge/process/05-testing.md +90 -0
  88. package/knowledge/process/06-delivery.md +88 -0
  89. package/knowledge/process/README.en.md +38 -0
  90. package/knowledge/process/README.md +48 -0
  91. package/knowledge/process/ai-sdlc.md +475 -0
  92. package/knowledge/process/overview.md +319 -0
  93. package/knowledge/standards/code-review.md +876 -0
  94. package/knowledge/standards/coding-style.md +940 -0
  95. package/knowledge/standards/data-consistency.md +1085 -0
  96. package/knowledge/standards/document-versioning.md +210 -0
  97. package/knowledge/standards/risk-detection.md +186 -0
  98. package/knowledge/templates/ai-evaluation.md +150 -0
  99. package/knowledge/templates/api-design.md +117 -0
  100. package/knowledge/templates/database-design.md +132 -0
  101. package/knowledge/templates/domain-driven-design.md +321 -0
  102. package/knowledge/templates/product-proposal.md +201 -0
  103. package/knowledge/templates/system-design.md +227 -0
  104. package/knowledge/templates/task-breakdown.md +107 -0
  105. package/knowledge/templates/test-case.md +170 -0
  106. package/package.json +53 -0
  107. package/plugins/.claude-plugin/plugin.json +134 -0
  108. package/plugins/agents/roles/ai-engineer.md +129 -0
  109. package/plugins/agents/roles/backend-engineer.md +165 -0
  110. package/plugins/agents/roles/ceo.md +94 -0
  111. package/plugins/agents/roles/data-engineer.md +135 -0
  112. package/plugins/agents/roles/devops-engineer.md +181 -0
  113. package/plugins/agents/roles/frontend-engineer.md +129 -0
  114. package/plugins/agents/roles/product-owner.md +98 -0
  115. package/plugins/agents/roles/quality-engineer.md +129 -0
  116. package/plugins/agents/roles/security-engineer.md +180 -0
  117. package/plugins/agents/roles/tech-lead.md +97 -0
  118. package/plugins/agents/support/blind-comparator.md +88 -0
  119. package/plugins/agents/support/consistency-checker.md +103 -0
  120. package/plugins/agents/support/failure-diagnostician.md +141 -0
  121. package/plugins/agents/support/independent-reviewer.md +80 -0
  122. package/plugins/agents/support/safety-auditor.md +121 -0
  123. package/plugins/agents/support/skill-benchmarker.md +86 -0
  124. package/plugins/agents/support/skill-forger.md +105 -0
  125. package/plugins/agents/support/stage-gate-evaluator.md +121 -0
  126. package/plugins/agents/support/test-coverage-reviewer.md +73 -0
  127. package/plugins/benchmarks/templates/README.md +44 -0
  128. package/plugins/benchmarks/templates/commands/explore-template.yaml +48 -0
  129. package/plugins/benchmarks/templates/pipeline/agile-template.yaml +84 -0
  130. package/plugins/benchmarks/templates/pipeline/waterfall-template.yaml +106 -0
  131. package/plugins/benchmarks/templates/skills/requirement-analyzer-template.yaml +48 -0
  132. package/plugins/commands/README.en.md +96 -0
  133. package/plugins/commands/README.md +96 -0
  134. package/plugins/commands/apply.md +191 -0
  135. package/plugins/commands/archive.md +76 -0
  136. package/plugins/commands/env-export.md +79 -0
  137. package/plugins/commands/env-sync.md +640 -0
  138. package/plugins/commands/env-template.md +223 -0
  139. package/plugins/commands/env-update.md +264 -0
  140. package/plugins/commands/env-validate.md +176 -0
  141. package/plugins/commands/env.md +79 -0
  142. package/plugins/commands/explore.md +76 -0
  143. package/plugins/commands/field-evolve.md +536 -0
  144. package/plugins/commands/memory.md +249 -0
  145. package/plugins/commands/project-evolve.md +821 -0
  146. package/plugins/commands/propose.md +93 -0
  147. package/plugins/commands/review.md +140 -0
  148. package/plugins/commands/run.md +224 -0
  149. package/plugins/commands/status.md +62 -0
  150. package/plugins/commands/validate.md +108 -0
  151. package/plugins/hooks/README.en.md +56 -0
  152. package/plugins/hooks/README.md +56 -0
  153. package/plugins/hooks/ai-project-guard.js +329 -0
  154. package/plugins/hooks/artifact-evaluation-hook.js +237 -0
  155. package/plugins/hooks/constitution-guard.js +211 -0
  156. package/plugins/hooks/environment-autocommit.js +264 -0
  157. package/plugins/hooks/environment-manager.js +778 -0
  158. package/plugins/hooks/execution-tracker.js +354 -0
  159. package/plugins/hooks/frozen-zone-guard.js +140 -0
  160. package/plugins/hooks/layer1-validator.js +423 -0
  161. package/plugins/hooks/lib/artifact-evaluator.js +414 -0
  162. package/plugins/hooks/lib/benchmarks/change-detector.js +390 -0
  163. package/plugins/hooks/lib/benchmarks/evaluator.js +605 -0
  164. package/plugins/hooks/lib/benchmarks/integration-example.js +169 -0
  165. package/plugins/hooks/lib/data-and-ai-detector.js +275 -0
  166. package/plugins/hooks/lib/detection-pattern-loader.js +865 -0
  167. package/plugins/hooks/lib/directory-discovery.js +395 -0
  168. package/plugins/hooks/lib/environment-config-loader.js +341 -0
  169. package/plugins/hooks/lib/environment-detector.js +553 -0
  170. package/plugins/hooks/lib/environment-evolver.js +564 -0
  171. package/plugins/hooks/lib/environment-registry.js +813 -0
  172. package/plugins/hooks/lib/execution-path.js +427 -0
  173. package/plugins/hooks/lib/hook-error-recorder.js +245 -0
  174. package/plugins/hooks/lib/hook-logger.js +538 -0
  175. package/plugins/hooks/lib/hook-runner.js +97 -0
  176. package/plugins/hooks/lib/hook-runner.sh +44 -0
  177. package/plugins/hooks/lib/hook-state-manager.js +480 -0
  178. package/plugins/hooks/lib/memory-extractor.js +377 -0
  179. package/plugins/hooks/lib/memory-manager.js +673 -0
  180. package/plugins/hooks/lib/metrics-analyzer.js +489 -0
  181. package/plugins/hooks/lib/project-evolution/auto-fixer.js +511 -0
  182. package/plugins/hooks/lib/project-evolution/memory-manager.js +346 -0
  183. package/plugins/hooks/lib/project-evolution/pattern-detector.js +476 -0
  184. package/plugins/hooks/lib/project-evolution/semantic-indexer.js +480 -0
  185. package/plugins/hooks/lib/project-structure-detector.js +326 -0
  186. package/plugins/hooks/lib/rollback-tracker.js +346 -0
  187. package/plugins/hooks/lib/source-code-scanner.js +596 -0
  188. package/plugins/hooks/lib/technology-stack-detector.js +374 -0
  189. package/plugins/hooks/lib/test-failure-analyzer.js +375 -0
  190. package/plugins/hooks/lib/test-failure-fixer.js +268 -0
  191. package/plugins/hooks/lib/trace-context.js +277 -0
  192. package/plugins/hooks/lib/validation-patterns.js +415 -0
  193. package/plugins/hooks/memory-sync.js +171 -0
  194. package/plugins/hooks/pipeline-observer.js +413 -0
  195. package/plugins/hooks/scope-sentinel.js +204 -0
  196. package/plugins/hooks/trace-initialization.js +169 -0
  197. package/plugins/memory/templates/code-quality.yaml +149 -0
  198. package/plugins/memory/templates/multi-system.yaml +155 -0
  199. package/plugins/memory/templates/team-habits.yaml +119 -0
  200. package/plugins/memory/templates/testing.yaml +121 -0
  201. package/plugins/skills/README.en.md +47 -0
  202. package/plugins/skills/README.md +104 -0
  203. package/plugins/skills/benchmark-executor/README.md +93 -0
  204. package/plugins/skills/benchmark-executor/SKILL.md +647 -0
  205. package/plugins/skills/benchmark-generator/SKILL.md +349 -0
  206. package/plugins/skills/delivery-stage/SKILL.md +203 -0
  207. package/plugins/skills/design-stage/SKILL.md +216 -0
  208. package/plugins/skills/evolution-process/SKILL.md +291 -0
  209. package/plugins/skills/exploration-phase/SKILL.md +133 -0
  210. package/plugins/skills/implementation-stage/SKILL.md +179 -0
  211. package/plugins/skills/layer1-validation/SKILL.md +79 -0
  212. package/plugins/skills/pending-dashboard/SKILL.md +109 -0
  213. package/plugins/skills/project-evolution/SKILL.md +847 -0
  214. package/plugins/skills/requirement-stage/SKILL.md +183 -0
  215. package/plugins/skills/skill-forge/SKILL.md +223 -0
  216. package/plugins/skills/skill-forge/references/description-guide.md +92 -0
  217. package/plugins/skills/skill-forge/references/quality-rubric.md +104 -0
  218. package/plugins/skills/skill-forge/references/skill-template.md +106 -0
  219. package/plugins/skills/startup-guard/SKILL.md +38 -0
  220. package/plugins/skills/testing-stage/SKILL.md +195 -0
  221. package/scripts/cli/global-init.js +288 -0
  222. package/scripts/cli/global.js +324 -0
  223. package/scripts/cli/index.js +55 -0
  224. package/scripts/cli/init.js +382 -0
  225. package/scripts/cli/list.js +69 -0
  226. package/scripts/cli/org.js +340 -0
  227. package/scripts/cli/update.js +44 -0
  228. package/scripts/config/commands.config.js +145 -0
  229. package/scripts/config/hooks.config.js +197 -0
  230. package/scripts/evolution/evolution-router.js +273 -0
  231. package/scripts/evolution/evolution-signal-collector.js +307 -0
  232. package/scripts/evolution/knowledge-loader.js +346 -0
  233. package/scripts/evolution/marketplace.js +317 -0
  234. package/scripts/evolution/version-manager.js +371 -0
  235. package/scripts/install/agents.js +106 -0
  236. package/scripts/install/commands.js +133 -0
  237. package/scripts/install/constants.js +424 -0
  238. package/scripts/install/hook-logger.js +536 -0
  239. package/scripts/install/hooks.js +110 -0
  240. package/scripts/install/index.js +39 -0
  241. package/scripts/install/skills.js +95 -0
  242. package/scripts/postinstall.js +25 -0
  243. package/scripts/state.js +376 -0
@@ -0,0 +1,204 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * AutoSpec PreToolUse Hook: Scope Sentinel
5
+ *
6
+ * During implementation stage (Stage 03), monitors Write/Edit operations
7
+ * to detect scope creep — modifying files outside the planned scope.
8
+ *
9
+ * Detection strategy:
10
+ * 1. If .autospec/state.json shows currentStage is 03 (implementation)
11
+ * 2. Check if the target file path is reasonable for the current task
12
+ * 3. Warn (not block) if editing framework/config files or unrelated modules
13
+ *
14
+ * This hook WARNS but never BLOCKS — it's a cognitive nudge, not a gate.
15
+ *
16
+ * 优化点:
17
+ * 1. 使用共享工具函数
18
+ * 2. 统一错误处理和日志
19
+ * 3. 缓存状态避免重复读取
20
+ */
21
+
22
+ import { createHookLogger, safeJsonParse, handleHookError, readStdin, findProjectRootAsync, fileExists, globalHookCache } from './lib/hook-logger.js';
23
+
24
+ const logger = createHookLogger('scope-sentinel');
25
+ const stateCache = globalHookCache; // 使用全局单例缓存
26
+
27
+ // 缓存键前缀
28
+ const CACHE_KEY_PREFIX = 'scope-check:';
29
+
30
+ async function main() {
31
+ let input;
32
+ try {
33
+ const rawInput = await readStdin(1000);
34
+ input = safeJsonParse(rawInput, null, 'hook input');
35
+
36
+ if (!input) {
37
+ logger.debug('Empty or invalid input, skipping');
38
+ process.exit(0);
39
+ }
40
+ } catch (err) {
41
+ logger.error('Failed to parse input', { error: err.message });
42
+ process.exit(0);
43
+ }
44
+
45
+ const toolName = input.tool_name;
46
+ if (toolName !== 'Write' && toolName !== 'Edit') {
47
+ logger.debug('Not a write/edit operation, skipping', { toolName });
48
+ process.exit(0);
49
+ }
50
+
51
+ const fs = await import('fs');
52
+ const path = await import('path');
53
+
54
+ // Find project root
55
+ const cwd = input.cwd || process.cwd();
56
+ const projectRoot = await findProjectRootAsync(cwd);
57
+
58
+ if (!projectRoot) {
59
+ logger.debug('No .autospec directory found, skipping');
60
+ process.exit(0);
61
+ }
62
+
63
+ const statePath = path.join(projectRoot, '.autospec', 'state.json');
64
+
65
+ // Check if we should skip based on cached stage check
66
+ const stageCacheKey = `${CACHE_KEY_PREFIX}${projectRoot}:stage`;
67
+ let isImplementationStage = stateCache.get(stageCacheKey);
68
+
69
+ if (isImplementationStage === undefined) {
70
+ isImplementationStage = await checkImplementationStage(statePath, fs);
71
+ stateCache.set(stageCacheKey, isImplementationStage, 30000); // 30s cache
72
+ logger.debug('Stage checked', { isImplementationStage });
73
+ } else {
74
+ logger.debug('Using cached stage check', { isImplementationStage });
75
+ }
76
+
77
+ if (!isImplementationStage) {
78
+ process.exit(0);
79
+ }
80
+
81
+ const filePath = (input.tool_input?.file_path || '').replace(/\\/g, '/');
82
+
83
+ // Skip autospec internal files (specs, state, metrics — those are expected)
84
+ if (filePath.includes('.autospec/') || filePath.includes('.claude/')) {
85
+ logger.debug('Skipping autospec internal file', { filePath });
86
+ process.exit(0);
87
+ }
88
+
89
+ // Detect potentially risky modifications
90
+ const warnings = [];
91
+
92
+ // 1. Modifying package.json / config files (potential scope creep)
93
+ const configPatterns = [
94
+ /package\.json$/,
95
+ /tsconfig.*\.json$/,
96
+ /\.eslintrc/,
97
+ /webpack|vite|rollup.*config/,
98
+ /docker/i,
99
+ /\.env/
100
+ ];
101
+ for (const pattern of configPatterns) {
102
+ if (pattern.test(filePath)) {
103
+ warnings.push(
104
+ `Modifying config file: ${path.basename(filePath)}. ` +
105
+ `Verify this change is required by the current task scope.`
106
+ );
107
+ logger.info('Config file modification detected', { filePath });
108
+ break;
109
+ }
110
+ }
111
+
112
+ // 2. Creating new directories (potential feature creep)
113
+ if (toolName === 'Write') {
114
+ const dir = path.dirname(filePath);
115
+ const relDir = path.relative(cwd, dir).replace(/\\/g, '/');
116
+ // Count directory depth — creating deeply nested new structures may signal scope creep
117
+ const parts = relDir.split('/').filter(Boolean);
118
+ if (parts.length > 4) {
119
+ warnings.push(
120
+ `Creating file in deeply nested path (${parts.length} levels). ` +
121
+ `Check if this aligns with the technical design.`
122
+ );
123
+ logger.info('Deep nesting detected', { depth: parts.length, path: relDir });
124
+ }
125
+ }
126
+
127
+ // Load metrics to track scope warnings count
128
+ const metricsPath = path.join(projectRoot, '.autospec', 'metrics.json');
129
+ let metrics;
130
+ try {
131
+ metrics = JSON.parse(fs.readFileSync(metricsPath, 'utf-8'));
132
+ } catch {
133
+ metrics = { totals: { scopeWarnings: 0 } };
134
+ }
135
+
136
+ if (warnings.length > 0) {
137
+ if (!metrics.totals.scopeWarnings) metrics.totals.scopeWarnings = 0;
138
+ metrics.totals.scopeWarnings++;
139
+
140
+ try {
141
+ fs.writeFileSync(metricsPath, JSON.stringify(metrics, null, 2));
142
+ } catch (err) {
143
+ logger.debug('Failed to write metrics', { error: err.message });
144
+ }
145
+
146
+ // Graduated response (CP8 三级偏航提醒)
147
+ let level = '';
148
+ const count = metrics.totals.scopeWarnings;
149
+ if (count <= 2) {
150
+ level = '(scope check — informational)';
151
+ } else if (count <= 5) {
152
+ level = '⚠️ (scope check — repeated, please verify)';
153
+ } else {
154
+ level = '🚨 (scope check — frequent deviations detected, review needed)';
155
+ }
156
+
157
+ logger.info('Scope warning generated', { level, warningCount: count });
158
+
159
+ const output = {
160
+ hookSpecificOutput: {
161
+ hookEventName: 'PreToolUse',
162
+ additionalContext:
163
+ `[AutoSpec Scope Sentinel] ${level}\n` +
164
+ warnings.join('\n') + '\n' +
165
+ `Verify this change is within the scope defined in .autospec/specs/*/design.md`
166
+ }
167
+ };
168
+ process.stdout.write(JSON.stringify(output));
169
+ }
170
+
171
+ process.exit(0);
172
+ }
173
+
174
+ /**
175
+ * Check if current stage is implementation (Stage 3)
176
+ */
177
+ async function checkImplementationStage(statePath, fs) {
178
+ if (!(await fileExists(statePath))) {
179
+ return false;
180
+ }
181
+
182
+ try {
183
+ const content = await fs.promises.readFile(statePath, 'utf-8');
184
+ const state = safeJsonParse(content, null, 'state.json');
185
+
186
+ if (!state) {
187
+ return false;
188
+ }
189
+
190
+ const stage = String(state.currentStage);
191
+ return stage === '3' || stage === '03';
192
+ } catch (err) {
193
+ logger.debug('Failed to read state', { error: err.message });
194
+ return false;
195
+ }
196
+ }
197
+
198
+ main().catch((err) => {
199
+ const result = handleHookError('scope-sentinel', err, {
200
+ eventName: 'PreToolUse'
201
+ });
202
+ process.stdout.write(JSON.stringify(result.hookSpecificOutput));
203
+ process.exit(0);
204
+ });
@@ -0,0 +1,169 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * AutoSpec PreToolUse Hook: Trace Init
5
+ *
6
+ * 流程启动时初始化 Trace ID
7
+ * - 检测到新流程启动(state.json 创建或重置)时生成 traceId
8
+ * - 记录用户输入用于调试和评测
9
+ * - 优先级:200(最高)
10
+ */
11
+
12
+ import { createHookLogger, safeJsonParse, handleHookError, readStdin, findProjectRootAsync } from './lib/hook-logger.js';
13
+ import { getState, updateState } from './lib/hook-state-manager.js';
14
+ import { generateTraceId, getTraceId, appendTraceEvent } from './lib/trace-context.js';
15
+ import fs from 'fs';
16
+ import path from 'path';
17
+
18
+ const logger = createHookLogger('trace-initialization');
19
+
20
+ /**
21
+ * 检测是否为新流程启动
22
+ * @param {Object} input - Hook 输入
23
+ * @param {string} projectRoot - 项目根目录
24
+ * @returns {boolean} 是否为新流程
25
+ */
26
+ function isNewPipelineStart(input, projectRoot) {
27
+ const filePath = input.tool_input?.file_path || '';
28
+
29
+ // 检测 state.json 创建
30
+ if (filePath.includes('state.json')) {
31
+ const statePath = path.join(projectRoot, '.autospec', 'runtime', 'state.json');
32
+
33
+ // 如果 state.json 不存在,说明是新流程
34
+ if (!fs.existsSync(statePath)) {
35
+ return true;
36
+ }
37
+
38
+ // 如果正在重置 state.json(写入新的 taskName),也是新流程
39
+ const content = input.tool_input?.content || '';
40
+ if (content && (content.includes('"taskName"') || content.includes('"currentStage": "01"'))) {
41
+ // 检查现有 state 是否有 traceId
42
+ const existingState = getState(projectRoot);
43
+ if (!existingState?.traceId) {
44
+ return true;
45
+ }
46
+ }
47
+ }
48
+
49
+ return false;
50
+ }
51
+
52
+ /**
53
+ * 检测是否为流程结束
54
+ * @param {Object} input - Hook 输入
55
+ * @param {string} projectRoot - 项目根目录
56
+ * @returns {boolean} 是否为流程结束
57
+ */
58
+ function isPipelineEnd(input, projectRoot) {
59
+ const filePath = input.tool_input?.file_path || '';
60
+
61
+ // 检测归档操作
62
+ if (filePath.includes('archives/') && filePath.includes('state.json')) {
63
+ return true;
64
+ }
65
+
66
+ return false;
67
+ }
68
+
69
+ async function main() {
70
+ let input;
71
+ try {
72
+ const rawInput = await readStdin(1000);
73
+ input = safeJsonParse(rawInput, null, 'hook input');
74
+
75
+ if (!input) {
76
+ logger.debug('Empty or invalid input, skipping');
77
+ process.exit(0);
78
+ }
79
+ } catch (err) {
80
+ logger.error('Failed to parse input', { error: err.message });
81
+ process.exit(0);
82
+ }
83
+
84
+ const toolName = input.tool_name;
85
+
86
+ // 只处理 Write 操作
87
+ if (toolName !== 'Write') {
88
+ process.exit(0);
89
+ }
90
+
91
+ const cwd = input.cwd || process.cwd();
92
+ const projectRoot = await findProjectRootAsync(cwd);
93
+
94
+ if (!projectRoot) {
95
+ logger.debug('No .autospec directory found, skipping');
96
+ process.exit(0);
97
+ }
98
+
99
+ // 检测新流程启动
100
+ if (isNewPipelineStart(input, projectRoot)) {
101
+ const traceId = generateTraceId();
102
+ logger.info('New pipeline detected, initializing Trace ID', { traceId });
103
+
104
+ // 提取用户输入(从 state.json 内容中)
105
+ const content = input.tool_input?.content || '';
106
+ let userInput = '';
107
+ try {
108
+ const stateData = JSON.parse(content);
109
+ userInput = stateData.taskName || stateData.userInput || '';
110
+ } catch (e) {
111
+ // 忽略解析错误
112
+ }
113
+
114
+ // 增强:记录用户输入到 trace 日志
115
+ if (userInput) {
116
+ const traceEvent = {
117
+ eventId: `init-${Date.now()}`,
118
+ traceId,
119
+ timestamp: new Date().toISOString(),
120
+ type: 'pipeline_started',
121
+ source: 'trace-initialization',
122
+ data: {
123
+ userInput,
124
+ workflow: input.tool_input?.content?.includes('"workflow"')
125
+ ? JSON.parse(input.tool_input.content).workflow
126
+ : 'unknown'
127
+ }
128
+ };
129
+ appendTraceEvent(projectRoot, traceEvent);
130
+ logger.info('User input recorded', { userInput: userInput.substring(0, 100) });
131
+ }
132
+
133
+ // 不在这里更新 state.json,因为 Write 操作还未完成
134
+ // 而是输出提示,让后续的 execution-tracker 来处理
135
+ process.stdout.write(JSON.stringify({
136
+ hookSpecificOutput: {
137
+ hookEventName: 'PreToolUse',
138
+ additionalContext: `[trace-initialization] 新流程启动,Trace ID: ${traceId},用户输入: ${userInput.substring(0, 50)}...`
139
+ }
140
+ }));
141
+ process.exit(0);
142
+ }
143
+
144
+ // 检测流程结束
145
+ if (isPipelineEnd(input, projectRoot)) {
146
+ const traceId = getTraceId(projectRoot);
147
+ if (traceId) {
148
+ logger.info('Pipeline ending, archiving Trace', { traceId });
149
+
150
+ process.stdout.write(JSON.stringify({
151
+ hookSpecificOutput: {
152
+ hookEventName: 'PreToolUse',
153
+ additionalContext: `[trace-initialization] 流程结束,Trace ID: ${traceId} 正在归档。`
154
+ }
155
+ }));
156
+ }
157
+ process.exit(0);
158
+ }
159
+
160
+ process.exit(0);
161
+ }
162
+
163
+ main().catch((err) => {
164
+ const result = handleHookError('trace-initialization', err, {
165
+ eventName: 'PreToolUse'
166
+ });
167
+ process.stdout.write(JSON.stringify(result.hookSpecificOutput));
168
+ process.exit(0);
169
+ });
@@ -0,0 +1,149 @@
1
+ # AutoSpec Memory Template - Code Quality
2
+ # 代码质量评测记忆模板
3
+ # 复制到 .autospec/autospec:memory/discovered/ 后按需调整
4
+
5
+ version: "1.0"
6
+ memory:
7
+ id: "template-code-quality"
8
+ name: "代码质量评测模板"
9
+ description: "通用的代码质量评测规则模板"
10
+ category: "code-quality"
11
+
12
+ # 适用条件
13
+ applicability:
14
+ tech_stacks: ["*"] # 适用于所有技术栈
15
+ file_patterns: ["*"]
16
+ min_confidence: 0.7
17
+
18
+ # 评测规则集合
19
+ rules:
20
+ # 规则1: 代码复杂度
21
+ - id: "complexity-check"
22
+ name: "代码复杂度检查"
23
+ description: "检测高复杂度函数和类"
24
+ severity: "warning"
25
+
26
+ detection:
27
+ type: "metric"
28
+ metrics:
29
+ - name: "cyclomatic-complexity"
30
+ threshold: 10
31
+ message: "圈复杂度过高,建议拆分为小函数"
32
+ - name: "cognitive-complexity"
33
+ threshold: 15
34
+ message: "认知复杂度过高,建议简化逻辑"
35
+ - name: "function-length"
36
+ threshold: 50
37
+ message: "函数过长,建议拆分"
38
+ - name: "class-length"
39
+ threshold: 300
40
+ message: "类过大,建议拆分职责"
41
+
42
+ fixes:
43
+ - type: "suggest"
44
+ description: "提供重构建议"
45
+ action: "generate-refactoring-plan"
46
+
47
+ # 规则2: 重复代码
48
+ - id: "duplicate-code"
49
+ name: "重复代码检测"
50
+ description: "检测3行以上的重复代码"
51
+ severity: "warning"
52
+
53
+ detection:
54
+ type: "similarity"
55
+ min_lines: 3
56
+ similarity_threshold: 0.8
57
+
58
+ fixes:
59
+ - type: "suggest"
60
+ description: "建议提取公共函数"
61
+ action: "extract-common-function"
62
+
63
+ # 规则3: 死代码
64
+ - id: "dead-code"
65
+ name: "死代码清理"
66
+ description: "检测未使用的变量、函数、导入"
67
+ severity: "info"
68
+
69
+ detection:
70
+ type: "static-analysis"
71
+ checks:
72
+ - "unused-variables"
73
+ - "unused-functions"
74
+ - "unused-imports"
75
+ - "unreachable-code"
76
+
77
+ fixes:
78
+ - type: "auto"
79
+ description: "自动移除死代码"
80
+ action: "remove-dead-code"
81
+ validation: "compile-pass"
82
+
83
+ # 规则4: 命名规范
84
+ - id: "naming-convention"
85
+ name: "命名规范检查"
86
+ description: "检查变量、函数、类命名是否符合规范"
87
+ severity: "info"
88
+
89
+ detection:
90
+ type: "pattern"
91
+ patterns:
92
+ - name: "camelCase"
93
+ apply_to: ["variable", "function"]
94
+ regex: "^[a-z][a-zA-Z0-9]*$"
95
+ - name: "PascalCase"
96
+ apply_to: ["class", "interface", "type"]
97
+ regex: "^[A-Z][a-zA-Z0-9]*$"
98
+ - name: "SCREAMING_SNAKE_CASE"
99
+ apply_to: ["constant"]
100
+ regex: "^[A-Z][A-Z0-9_]*$"
101
+
102
+ fixes:
103
+ - type: "auto"
104
+ description: "自动重命名"
105
+ action: "rename-symbol"
106
+ validation: "compile-pass"
107
+
108
+ # 规则5: 代码注释
109
+ - id: "code-comments"
110
+ name: "代码注释检查"
111
+ description: "检查公共API是否有文档注释"
112
+ severity: "info"
113
+
114
+ detection:
115
+ type: "ast-pattern"
116
+ patterns:
117
+ - "public-function-without-doc"
118
+ - "public-class-without-doc"
119
+ - "complex-logic-without-comment"
120
+
121
+ fixes:
122
+ - type: "suggest"
123
+ description: "生成文档注释模板"
124
+ action: "generate-doc-template"
125
+
126
+ # 执行配置
127
+ execution:
128
+ # 执行顺序
129
+ order:
130
+ - "dead-code" # 先清理死代码
131
+ - "naming-convention" # 再修复命名
132
+ - "code-comments" # 再补注释
133
+ - "complexity-check" # 最后处理复杂度
134
+ - "duplicate-code"
135
+
136
+ # 执行条件
137
+ conditions:
138
+ - "compile-pass" # 编译通过
139
+ - "test-pass" # 测试通过
140
+
141
+ # 失败处理
142
+ on_failure:
143
+ action: "rollback" # 失败回滚
144
+ notify: true # 通知用户
145
+
146
+ # 统计和反馈
147
+ statistics:
148
+ track: true # 追踪执行统计
149
+ feedback: true # 收集反馈
@@ -0,0 +1,155 @@
1
+ # AutoSpec Memory Template - Multi-System
2
+ # 多系统项目评测记忆模板
3
+
4
+ version: "1.0"
5
+ memory:
6
+ id: "template-multi-system"
7
+ name: "多系统项目评测模板"
8
+ description: "针对多系统项目的专项评测"
9
+ category: "multi-system"
10
+
11
+ # 适用条件
12
+ applicability:
13
+ project_types: ["multi-system"]
14
+ min_subsystems: 2
15
+
16
+ rules:
17
+ # 规则1: 接口契约一致性
18
+ - id: "contract-consistency"
19
+ name: "接口契约一致性"
20
+ description: "检查前后端接口契约是否一致"
21
+ severity: "error"
22
+
23
+ detection:
24
+ type: "contract-analysis"
25
+ checks:
26
+ - "api-definition-vs-implementation"
27
+ - "request-schema-match"
28
+ - "response-schema-match"
29
+ - "type-compatibility"
30
+
31
+ sources:
32
+ - "contracts/api.yaml" # 契约定义
33
+ - "frontend/src/api/" # 前端调用
34
+ - "backend/src/controller/" # 后端实现
35
+
36
+ fixes:
37
+ - type: "suggest"
38
+ description: "同步接口定义"
39
+ action: "sync-contract"
40
+
41
+ # 规则2: 共享逻辑识别
42
+ - id: "shared-logic"
43
+ name: "共享逻辑抽离"
44
+ description: "识别跨系统重复代码,建议抽离"
45
+ severity: "warning"
46
+
47
+ detection:
48
+ type: "cross-system-similarity"
49
+ min_similarity: 0.8
50
+ min_lines: 10
51
+
52
+ scopes:
53
+ - "data-models"
54
+ - "utility-functions"
55
+ - "validation-logic"
56
+ - "constants"
57
+
58
+ fixes:
59
+ - type: "suggest"
60
+ description: "建议创建共享库"
61
+ action: "suggest-shared-library"
62
+
63
+ # 规则3: 依赖循环检测
64
+ - id: "dependency-cycle"
65
+ name: "依赖循环检测"
66
+ description: "检测子系统间的循环依赖"
67
+ severity: "error"
68
+
69
+ detection:
70
+ type: "dependency-graph"
71
+ algorithm: "tarjan-cycle-detection"
72
+
73
+ scope:
74
+ - "import-statements"
75
+ - "service-calls"
76
+ - "event-subscriptions"
77
+
78
+ fixes:
79
+ - type: "suggest"
80
+ description: "建议解耦方案"
81
+ action: "suggest-decoupling"
82
+
83
+ # 规则4: 构建顺序优化
84
+ - id: "build-order"
85
+ name: "构建顺序优化"
86
+ description: "分析并优化子系统构建顺序"
87
+ severity: "info"
88
+
89
+ detection:
90
+ type: "build-analysis"
91
+ analyze:
92
+ - "current-build-time"
93
+ - "dependency-graph"
94
+ - "parallel-opportunities"
95
+
96
+ fixes:
97
+ - type: "suggest"
98
+ description: "优化构建配置"
99
+ action: "optimize-build-config"
100
+
101
+ # 规则5: 数据模型对齐
102
+ - id: "data-model-alignment"
103
+ name: "数据模型对齐"
104
+ description: "检查跨系统数据模型一致性"
105
+ severity: "warning"
106
+
107
+ detection:
108
+ type: "schema-comparison"
109
+ compare:
110
+ - "backend/entities/" vs "frontend/src/types/"
111
+ - "backend/dto/" vs "frontend/src/api/types/"
112
+
113
+ checks:
114
+ - "field-name-consistency"
115
+ - "type-compatibility"
116
+ - "nullability-match"
117
+
118
+ fixes:
119
+ - type: "suggest"
120
+ description: "同步数据模型"
121
+ action: "sync-data-models"
122
+
123
+ # 规则6: 错误处理统一
124
+ - id: "error-handling"
125
+ name: "错误处理统一"
126
+ description: "检查跨系统错误处理是否统一"
127
+ severity: "warning"
128
+
129
+ detection:
130
+ type: "error-pattern-analysis"
131
+ checks:
132
+ - "error-code-consistency"
133
+ - "error-message-format"
134
+ - "error-response-structure"
135
+
136
+ fixes:
137
+ - type: "suggest"
138
+ description: "统一错误处理规范"
139
+ action: "unify-error-handling"
140
+
141
+ execution:
142
+ order:
143
+ - "dependency-cycle" # 优先处理架构问题
144
+ - "contract-consistency"
145
+ - "data-model-alignment"
146
+ - "shared-logic"
147
+ - "error-handling"
148
+ - "build-order"
149
+
150
+ conditions:
151
+ - "all-subsystems-compile"
152
+
153
+ on_failure:
154
+ action: "report"
155
+ notify: true