claude-flow-guidance-implementation 0.1.0

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 (275) hide show
  1. package/.agents/README.md +38 -0
  2. package/.agents/config.toml +298 -0
  3. package/.agents/skills/memory-management/SKILL.md +126 -0
  4. package/.agents/skills/memory-management/scripts/memory-backup.sh +16 -0
  5. package/.agents/skills/memory-management/scripts/memory-consolidate.sh +11 -0
  6. package/.agents/skills/security-audit/SKILL.md +135 -0
  7. package/.agents/skills/security-audit/scripts/cve-remediate.sh +16 -0
  8. package/.agents/skills/security-audit/scripts/security-scan.sh +33 -0
  9. package/.agents/skills/sparc-methodology/SKILL.md +118 -0
  10. package/.agents/skills/sparc-methodology/scripts/sparc-init.sh +21 -0
  11. package/.agents/skills/sparc-methodology/scripts/sparc-review.sh +18 -0
  12. package/.agents/skills/swarm-orchestration/SKILL.md +114 -0
  13. package/.agents/skills/swarm-orchestration/scripts/swarm-monitor.sh +8 -0
  14. package/.agents/skills/swarm-orchestration/scripts/swarm-start.sh +14 -0
  15. package/.claude/agents/analysis/analyze-code-quality.md +179 -0
  16. package/.claude/agents/analysis/code-analyzer.md +210 -0
  17. package/.claude/agents/analysis/code-review/analyze-code-quality.md +179 -0
  18. package/.claude/agents/architecture/system-design/arch-system-design.md +155 -0
  19. package/.claude/agents/consensus/README.md +253 -0
  20. package/.claude/agents/consensus/byzantine-coordinator.md +63 -0
  21. package/.claude/agents/consensus/crdt-synchronizer.md +997 -0
  22. package/.claude/agents/consensus/gossip-coordinator.md +63 -0
  23. package/.claude/agents/consensus/performance-benchmarker.md +851 -0
  24. package/.claude/agents/consensus/quorum-manager.md +823 -0
  25. package/.claude/agents/consensus/raft-manager.md +63 -0
  26. package/.claude/agents/consensus/security-manager.md +622 -0
  27. package/.claude/agents/core/coder.md +266 -0
  28. package/.claude/agents/core/planner.md +168 -0
  29. package/.claude/agents/core/researcher.md +190 -0
  30. package/.claude/agents/core/reviewer.md +326 -0
  31. package/.claude/agents/core/tester.md +319 -0
  32. package/.claude/agents/custom/test-long-runner.md +44 -0
  33. package/.claude/agents/data/ml/data-ml-model.md +193 -0
  34. package/.claude/agents/development/backend/dev-backend-api.md +142 -0
  35. package/.claude/agents/development/dev-backend-api.md +345 -0
  36. package/.claude/agents/devops/ci-cd/ops-cicd-github.md +164 -0
  37. package/.claude/agents/documentation/api-docs/docs-api-openapi.md +174 -0
  38. package/.claude/agents/dual-mode/README.md +94 -0
  39. package/.claude/agents/dual-mode/codex-coordinator.md +224 -0
  40. package/.claude/agents/dual-mode/codex-worker.md +211 -0
  41. package/.claude/agents/dual-mode/dual-orchestrator.md +291 -0
  42. package/.claude/agents/flow-nexus/app-store.md +88 -0
  43. package/.claude/agents/flow-nexus/authentication.md +69 -0
  44. package/.claude/agents/flow-nexus/challenges.md +81 -0
  45. package/.claude/agents/flow-nexus/neural-network.md +88 -0
  46. package/.claude/agents/flow-nexus/payments.md +83 -0
  47. package/.claude/agents/flow-nexus/sandbox.md +76 -0
  48. package/.claude/agents/flow-nexus/swarm.md +76 -0
  49. package/.claude/agents/flow-nexus/user-tools.md +96 -0
  50. package/.claude/agents/flow-nexus/workflow.md +84 -0
  51. package/.claude/agents/github/code-review-swarm.md +538 -0
  52. package/.claude/agents/github/github-modes.md +173 -0
  53. package/.claude/agents/github/issue-tracker.md +319 -0
  54. package/.claude/agents/github/multi-repo-swarm.md +553 -0
  55. package/.claude/agents/github/pr-manager.md +191 -0
  56. package/.claude/agents/github/project-board-sync.md +509 -0
  57. package/.claude/agents/github/release-manager.md +367 -0
  58. package/.claude/agents/github/release-swarm.md +583 -0
  59. package/.claude/agents/github/repo-architect.md +398 -0
  60. package/.claude/agents/github/swarm-issue.md +573 -0
  61. package/.claude/agents/github/swarm-pr.md +428 -0
  62. package/.claude/agents/github/sync-coordinator.md +452 -0
  63. package/.claude/agents/github/workflow-automation.md +635 -0
  64. package/.claude/agents/goal/agent.md +816 -0
  65. package/.claude/agents/goal/code-goal-planner.md +446 -0
  66. package/.claude/agents/goal/goal-planner.md +168 -0
  67. package/.claude/agents/hive-mind/collective-intelligence-coordinator.md +130 -0
  68. package/.claude/agents/hive-mind/queen-coordinator.md +203 -0
  69. package/.claude/agents/hive-mind/scout-explorer.md +242 -0
  70. package/.claude/agents/hive-mind/swarm-memory-manager.md +193 -0
  71. package/.claude/agents/hive-mind/worker-specialist.md +217 -0
  72. package/.claude/agents/optimization/README.md +250 -0
  73. package/.claude/agents/optimization/benchmark-suite.md +665 -0
  74. package/.claude/agents/optimization/load-balancer.md +431 -0
  75. package/.claude/agents/optimization/performance-monitor.md +672 -0
  76. package/.claude/agents/optimization/resource-allocator.md +674 -0
  77. package/.claude/agents/optimization/topology-optimizer.md +808 -0
  78. package/.claude/agents/payments/agentic-payments.md +126 -0
  79. package/.claude/agents/sona/sona-learning-optimizer.md +74 -0
  80. package/.claude/agents/sparc/architecture.md +472 -0
  81. package/.claude/agents/sparc/pseudocode.md +318 -0
  82. package/.claude/agents/sparc/refinement.md +525 -0
  83. package/.claude/agents/sparc/specification.md +276 -0
  84. package/.claude/agents/specialized/mobile/spec-mobile-react-native.md +225 -0
  85. package/.claude/agents/sublinear/consensus-coordinator.md +338 -0
  86. package/.claude/agents/sublinear/matrix-optimizer.md +185 -0
  87. package/.claude/agents/sublinear/pagerank-analyzer.md +299 -0
  88. package/.claude/agents/sublinear/performance-optimizer.md +368 -0
  89. package/.claude/agents/sublinear/trading-predictor.md +246 -0
  90. package/.claude/agents/swarm/README.md +190 -0
  91. package/.claude/agents/swarm/adaptive-coordinator.md +396 -0
  92. package/.claude/agents/swarm/hierarchical-coordinator.md +327 -0
  93. package/.claude/agents/swarm/mesh-coordinator.md +392 -0
  94. package/.claude/agents/templates/automation-smart-agent.md +205 -0
  95. package/.claude/agents/templates/coordinator-swarm-init.md +105 -0
  96. package/.claude/agents/templates/github-pr-manager.md +177 -0
  97. package/.claude/agents/templates/implementer-sparc-coder.md +259 -0
  98. package/.claude/agents/templates/memory-coordinator.md +187 -0
  99. package/.claude/agents/templates/migration-plan.md +746 -0
  100. package/.claude/agents/templates/orchestrator-task.md +139 -0
  101. package/.claude/agents/templates/performance-analyzer.md +199 -0
  102. package/.claude/agents/templates/sparc-coordinator.md +183 -0
  103. package/.claude/agents/testing/production-validator.md +395 -0
  104. package/.claude/agents/testing/tdd-london-swarm.md +244 -0
  105. package/.claude/agents/testing/unit/tdd-london-swarm.md +244 -0
  106. package/.claude/agents/testing/validation/production-validator.md +395 -0
  107. package/.claude/agents/v3/database-specialist.yaml +21 -0
  108. package/.claude/agents/v3/index.yaml +17 -0
  109. package/.claude/agents/v3/project-coordinator.yaml +15 -0
  110. package/.claude/agents/v3/python-specialist.yaml +21 -0
  111. package/.claude/agents/v3/test-architect.yaml +20 -0
  112. package/.claude/agents/v3/typescript-specialist.yaml +21 -0
  113. package/.claude/agents/v3/v3-integration-architect.md +346 -0
  114. package/.claude/agents/v3/v3-memory-specialist.md +318 -0
  115. package/.claude/agents/v3/v3-performance-engineer.md +397 -0
  116. package/.claude/agents/v3/v3-queen-coordinator.md +98 -0
  117. package/.claude/agents/v3/v3-security-architect.md +174 -0
  118. package/.claude/commands/analysis/COMMAND_COMPLIANCE_REPORT.md +54 -0
  119. package/.claude/commands/analysis/README.md +9 -0
  120. package/.claude/commands/analysis/bottleneck-detect.md +162 -0
  121. package/.claude/commands/analysis/performance-bottlenecks.md +59 -0
  122. package/.claude/commands/analysis/performance-report.md +25 -0
  123. package/.claude/commands/analysis/token-efficiency.md +45 -0
  124. package/.claude/commands/analysis/token-usage.md +25 -0
  125. package/.claude/commands/automation/README.md +9 -0
  126. package/.claude/commands/automation/auto-agent.md +122 -0
  127. package/.claude/commands/automation/self-healing.md +106 -0
  128. package/.claude/commands/automation/session-memory.md +90 -0
  129. package/.claude/commands/automation/smart-agents.md +73 -0
  130. package/.claude/commands/automation/smart-spawn.md +25 -0
  131. package/.claude/commands/automation/workflow-select.md +25 -0
  132. package/.claude/commands/claude-flow-help.md +103 -0
  133. package/.claude/commands/claude-flow-memory.md +107 -0
  134. package/.claude/commands/claude-flow-swarm.md +205 -0
  135. package/.claude/commands/github/README.md +11 -0
  136. package/.claude/commands/github/code-review-swarm.md +514 -0
  137. package/.claude/commands/github/code-review.md +25 -0
  138. package/.claude/commands/github/github-modes.md +147 -0
  139. package/.claude/commands/github/github-swarm.md +121 -0
  140. package/.claude/commands/github/issue-tracker.md +292 -0
  141. package/.claude/commands/github/issue-triage.md +25 -0
  142. package/.claude/commands/github/multi-repo-swarm.md +519 -0
  143. package/.claude/commands/github/pr-enhance.md +26 -0
  144. package/.claude/commands/github/pr-manager.md +170 -0
  145. package/.claude/commands/github/project-board-sync.md +471 -0
  146. package/.claude/commands/github/release-manager.md +338 -0
  147. package/.claude/commands/github/release-swarm.md +544 -0
  148. package/.claude/commands/github/repo-analyze.md +25 -0
  149. package/.claude/commands/github/repo-architect.md +367 -0
  150. package/.claude/commands/github/swarm-issue.md +482 -0
  151. package/.claude/commands/github/swarm-pr.md +285 -0
  152. package/.claude/commands/github/sync-coordinator.md +301 -0
  153. package/.claude/commands/github/workflow-automation.md +442 -0
  154. package/.claude/commands/hooks/README.md +11 -0
  155. package/.claude/commands/hooks/overview.md +58 -0
  156. package/.claude/commands/hooks/post-edit.md +117 -0
  157. package/.claude/commands/hooks/post-task.md +112 -0
  158. package/.claude/commands/hooks/pre-edit.md +113 -0
  159. package/.claude/commands/hooks/pre-task.md +111 -0
  160. package/.claude/commands/hooks/session-end.md +118 -0
  161. package/.claude/commands/hooks/setup.md +103 -0
  162. package/.claude/commands/monitoring/README.md +9 -0
  163. package/.claude/commands/monitoring/agent-metrics.md +25 -0
  164. package/.claude/commands/monitoring/agents.md +44 -0
  165. package/.claude/commands/monitoring/real-time-view.md +25 -0
  166. package/.claude/commands/monitoring/status.md +46 -0
  167. package/.claude/commands/monitoring/swarm-monitor.md +25 -0
  168. package/.claude/commands/optimization/README.md +9 -0
  169. package/.claude/commands/optimization/auto-topology.md +62 -0
  170. package/.claude/commands/optimization/cache-manage.md +25 -0
  171. package/.claude/commands/optimization/parallel-execute.md +25 -0
  172. package/.claude/commands/optimization/parallel-execution.md +50 -0
  173. package/.claude/commands/optimization/topology-optimize.md +25 -0
  174. package/.claude/commands/sparc/analyzer.md +52 -0
  175. package/.claude/commands/sparc/architect.md +53 -0
  176. package/.claude/commands/sparc/ask.md +97 -0
  177. package/.claude/commands/sparc/batch-executor.md +54 -0
  178. package/.claude/commands/sparc/code.md +89 -0
  179. package/.claude/commands/sparc/coder.md +54 -0
  180. package/.claude/commands/sparc/debug.md +83 -0
  181. package/.claude/commands/sparc/debugger.md +54 -0
  182. package/.claude/commands/sparc/designer.md +53 -0
  183. package/.claude/commands/sparc/devops.md +109 -0
  184. package/.claude/commands/sparc/docs-writer.md +80 -0
  185. package/.claude/commands/sparc/documenter.md +54 -0
  186. package/.claude/commands/sparc/innovator.md +54 -0
  187. package/.claude/commands/sparc/integration.md +83 -0
  188. package/.claude/commands/sparc/mcp.md +117 -0
  189. package/.claude/commands/sparc/memory-manager.md +54 -0
  190. package/.claude/commands/sparc/optimizer.md +54 -0
  191. package/.claude/commands/sparc/orchestrator.md +132 -0
  192. package/.claude/commands/sparc/post-deployment-monitoring-mode.md +83 -0
  193. package/.claude/commands/sparc/refinement-optimization-mode.md +83 -0
  194. package/.claude/commands/sparc/researcher.md +54 -0
  195. package/.claude/commands/sparc/reviewer.md +54 -0
  196. package/.claude/commands/sparc/security-review.md +80 -0
  197. package/.claude/commands/sparc/sparc-modes.md +174 -0
  198. package/.claude/commands/sparc/sparc.md +111 -0
  199. package/.claude/commands/sparc/spec-pseudocode.md +80 -0
  200. package/.claude/commands/sparc/supabase-admin.md +348 -0
  201. package/.claude/commands/sparc/swarm-coordinator.md +54 -0
  202. package/.claude/commands/sparc/tdd.md +54 -0
  203. package/.claude/commands/sparc/tester.md +54 -0
  204. package/.claude/commands/sparc/tutorial.md +79 -0
  205. package/.claude/commands/sparc/workflow-manager.md +54 -0
  206. package/.claude/helpers/hook-handler.cjs +168 -0
  207. package/.claude/helpers/intelligence.cjs +197 -0
  208. package/.claude/helpers/memory.js +83 -0
  209. package/.claude/helpers/post-commit +16 -0
  210. package/.claude/helpers/pre-commit +26 -0
  211. package/.claude/helpers/router.js +66 -0
  212. package/.claude/helpers/session.js +127 -0
  213. package/.claude/settings.json +250 -0
  214. package/.claude/skills/agentdb-advanced/SKILL.md +550 -0
  215. package/.claude/skills/agentdb-learning/SKILL.md +545 -0
  216. package/.claude/skills/agentdb-memory-patterns/SKILL.md +339 -0
  217. package/.claude/skills/agentdb-optimization/SKILL.md +509 -0
  218. package/.claude/skills/agentdb-vector-search/SKILL.md +339 -0
  219. package/.claude/skills/github-code-review/SKILL.md +1140 -0
  220. package/.claude/skills/github-multi-repo/SKILL.md +874 -0
  221. package/.claude/skills/github-project-management/SKILL.md +1277 -0
  222. package/.claude/skills/github-release-management/SKILL.md +1081 -0
  223. package/.claude/skills/github-workflow-automation/SKILL.md +1065 -0
  224. package/.claude/skills/hooks-automation/SKILL.md +1201 -0
  225. package/.claude/skills/pair-programming/SKILL.md +1202 -0
  226. package/.claude/skills/reasoningbank-agentdb/SKILL.md +446 -0
  227. package/.claude/skills/reasoningbank-intelligence/SKILL.md +201 -0
  228. package/.claude/skills/skill-builder/.claude-flow/metrics/agent-metrics.json +1 -0
  229. package/.claude/skills/skill-builder/.claude-flow/metrics/performance.json +87 -0
  230. package/.claude/skills/skill-builder/.claude-flow/metrics/task-metrics.json +10 -0
  231. package/.claude/skills/skill-builder/SKILL.md +910 -0
  232. package/.claude/skills/sparc-methodology/SKILL.md +1115 -0
  233. package/.claude/skills/stream-chain/SKILL.md +563 -0
  234. package/.claude/skills/swarm-advanced/SKILL.md +973 -0
  235. package/.claude/skills/swarm-orchestration/SKILL.md +179 -0
  236. package/.claude/skills/v3-cli-modernization/SKILL.md +872 -0
  237. package/.claude/skills/v3-core-implementation/SKILL.md +797 -0
  238. package/.claude/skills/v3-ddd-architecture/SKILL.md +442 -0
  239. package/.claude/skills/v3-integration-deep/SKILL.md +241 -0
  240. package/.claude/skills/v3-mcp-optimization/SKILL.md +777 -0
  241. package/.claude/skills/v3-memory-unification/SKILL.md +174 -0
  242. package/.claude/skills/v3-performance-optimization/SKILL.md +390 -0
  243. package/.claude/skills/v3-security-overhaul/SKILL.md +82 -0
  244. package/.claude/skills/v3-swarm-coordination/SKILL.md +340 -0
  245. package/.claude/skills/verification-quality/SKILL.md +649 -0
  246. package/.claude/statusline.mjs +109 -0
  247. package/.claude/statusline.sh +375 -0
  248. package/.claude-flow/CAPABILITIES.md +403 -0
  249. package/.claude-flow/config.yaml +43 -0
  250. package/.claude-flow/metrics/learning.json +17 -0
  251. package/.claude-flow/metrics/swarm-activity.json +18 -0
  252. package/.claude-flow/metrics/v3-progress.json +26 -0
  253. package/.claude-flow/security/audit-status.json +8 -0
  254. package/.mcp.json +20 -0
  255. package/AGENTS.md +145 -0
  256. package/CLAUDE.md +188 -0
  257. package/LICENSE +21 -0
  258. package/README.md +115 -0
  259. package/bin/cf-guidance-impl.mjs +74 -0
  260. package/package.json +23 -0
  261. package/scaffold/.claude/helpers/hook-handler.cjs +576 -0
  262. package/scaffold/docs/guidance-control-plane.md +441 -0
  263. package/scaffold/docs/guidance-implementation-guide.md +424 -0
  264. package/scaffold/scripts/analyze-guidance.js +176 -0
  265. package/scaffold/scripts/guidance-ab-benchmark.js +40 -0
  266. package/scaffold/scripts/guidance-autopilot.js +473 -0
  267. package/scaffold/scripts/guidance-codex-bridge.js +337 -0
  268. package/scaffold/scripts/guidance-integrations.js +587 -0
  269. package/scaffold/scripts/guidance-runtime.js +133 -0
  270. package/scaffold/scripts/scaffold-guidance.js +122 -0
  271. package/scaffold/src/guidance/advanced-runtime.js +658 -0
  272. package/scaffold/src/guidance/content-aware-executor.js +70 -0
  273. package/scaffold/src/guidance/phase1-runtime.js +151 -0
  274. package/src/default-settings.mjs +111 -0
  275. package/src/installer.mjs +415 -0
@@ -0,0 +1,473 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ appendFileSync,
4
+ existsSync,
5
+ mkdirSync,
6
+ openSync,
7
+ closeSync,
8
+ readFileSync,
9
+ readdirSync,
10
+ unlinkSync,
11
+ writeFileSync,
12
+ } from 'node:fs';
13
+ import { createHash } from 'node:crypto';
14
+ import { dirname, resolve } from 'node:path';
15
+ import { fileURLToPath } from 'node:url';
16
+
17
+ import { analyze, benchmark, abBenchmark } from '@claude-flow/guidance/analyzer';
18
+ import { createCompiler } from '@claude-flow/guidance/compiler';
19
+ import { createSyntheticContentAwareExecutor } from '../src/guidance/content-aware-executor.js';
20
+
21
+ const __dirname = dirname(fileURLToPath(import.meta.url));
22
+ const rootDir = resolve(__dirname, '..');
23
+
24
+ const DEFAULTS = {
25
+ mode: 'once',
26
+ apply: false,
27
+ minDelta: 0.5,
28
+ maxPromotions: 12,
29
+ intervalMs: 30 * 60 * 1000,
30
+ runAB: false,
31
+ minABGain: 0.05,
32
+ source: 'manual',
33
+ };
34
+
35
+ function parseArgs() {
36
+ const options = { ...DEFAULTS };
37
+ const args = process.argv.slice(2);
38
+
39
+ const readNumber = (value, fallback) => {
40
+ const parsed = Number(value);
41
+ return Number.isFinite(parsed) ? parsed : fallback;
42
+ };
43
+
44
+ const readString = (value, fallback) => {
45
+ if (value == null) return fallback;
46
+ return String(value);
47
+ };
48
+
49
+ for (let i = 0; i < args.length; i += 1) {
50
+ const arg = args[i];
51
+ switch (arg) {
52
+ case '--once':
53
+ options.mode = 'once';
54
+ break;
55
+ case '--daemon':
56
+ options.mode = 'daemon';
57
+ break;
58
+ case '--apply':
59
+ options.apply = true;
60
+ break;
61
+ case '--ab':
62
+ options.runAB = true;
63
+ break;
64
+ case '--no-ab':
65
+ options.runAB = false;
66
+ break;
67
+ case '--min-delta':
68
+ options.minDelta = readNumber(args[i + 1], options.minDelta);
69
+ i += 1;
70
+ break;
71
+ case '--max-promotions':
72
+ options.maxPromotions = readNumber(args[i + 1], options.maxPromotions);
73
+ i += 1;
74
+ break;
75
+ case '--interval-ms':
76
+ options.intervalMs = readNumber(args[i + 1], options.intervalMs);
77
+ i += 1;
78
+ break;
79
+ case '--min-ab-gain':
80
+ options.minABGain = readNumber(args[i + 1], options.minABGain);
81
+ i += 1;
82
+ break;
83
+ case '--source':
84
+ options.source = readString(args[i + 1], options.source);
85
+ i += 1;
86
+ break;
87
+ default:
88
+ break;
89
+ }
90
+ }
91
+ return options;
92
+ }
93
+
94
+ function nowIso() {
95
+ return new Date().toISOString();
96
+ }
97
+
98
+ function shortHash(input) {
99
+ return createHash('sha256').update(input).digest('hex').slice(0, 16);
100
+ }
101
+
102
+ function ensureDir(path) {
103
+ mkdirSync(path, { recursive: true });
104
+ }
105
+
106
+ function loadJson(path, fallback = {}) {
107
+ if (!existsSync(path)) return fallback;
108
+ try {
109
+ return JSON.parse(readFileSync(path, 'utf-8'));
110
+ } catch {
111
+ return fallback;
112
+ }
113
+ }
114
+
115
+ function writeJson(path, value) {
116
+ ensureDir(dirname(path));
117
+ writeFileSync(path, JSON.stringify(value, null, 2));
118
+ }
119
+
120
+ function loadGuidanceFiles() {
121
+ const rootPath = resolve(rootDir, 'CLAUDE.md');
122
+ const localPath = resolve(rootDir, 'CLAUDE.local.md');
123
+ if (!existsSync(rootPath)) {
124
+ throw new Error(`Missing root guidance file: ${rootPath}`);
125
+ }
126
+ const rootContent = readFileSync(rootPath, 'utf-8');
127
+ const localContent = existsSync(localPath) ? readFileSync(localPath, 'utf-8') : null;
128
+ return { rootPath, localPath, rootContent, localContent };
129
+ }
130
+
131
+ function getAllRules(bundle) {
132
+ return [
133
+ ...bundle.constitution.rules,
134
+ ...bundle.shards.map((entry) => entry.rule),
135
+ ];
136
+ }
137
+
138
+ function getPromotableLocalRules(rootContent, localContent) {
139
+ if (!localContent) return [];
140
+ const compiler = createCompiler();
141
+ const rootBundle = compiler.compile(rootContent);
142
+ const mergedBundle = compiler.compile(rootContent, localContent);
143
+
144
+ const rootRules = new Map(getAllRules(rootBundle).map((rule) => [rule.id, rule]));
145
+ const mergedRules = getAllRules(mergedBundle);
146
+ const seen = new Set();
147
+ const candidates = [];
148
+
149
+ for (const rule of mergedRules) {
150
+ if (rule.source !== 'local') continue;
151
+ if (seen.has(rule.id)) continue;
152
+ seen.add(rule.id);
153
+
154
+ const rootRule = rootRules.get(rule.id);
155
+ if (!rootRule) {
156
+ candidates.push(rule);
157
+ continue;
158
+ }
159
+
160
+ const changed =
161
+ rootRule.text !== rule.text ||
162
+ rootRule.riskClass !== rule.riskClass ||
163
+ rootRule.priority !== rule.priority ||
164
+ JSON.stringify(rootRule.intents) !== JSON.stringify(rule.intents) ||
165
+ JSON.stringify(rootRule.domains) !== JSON.stringify(rule.domains) ||
166
+ JSON.stringify(rootRule.toolClasses) !== JSON.stringify(rule.toolClasses);
167
+
168
+ if (changed) candidates.push(rule);
169
+ }
170
+
171
+ return candidates.sort((a, b) => b.priority - a.priority);
172
+ }
173
+
174
+ function ruleToLine(rule) {
175
+ const tags = [];
176
+ if (rule.riskClass) tags.push(`(${rule.riskClass})`);
177
+ for (const domain of rule.domains ?? []) tags.push(`@${domain}`);
178
+ for (const intent of rule.intents ?? []) tags.push(`#${intent}`);
179
+ for (const toolClass of rule.toolClasses ?? []) {
180
+ if (toolClass !== 'all') tags.push(`[${toolClass}]`);
181
+ }
182
+ tags.push(`priority:${rule.priority}`);
183
+ return `- [${rule.id}] ${rule.text} ${tags.join(' ')}`.replace(/\s+/g, ' ').trim();
184
+ }
185
+
186
+ function buildPromotionSection(rules, metadata) {
187
+ const lines = rules.map(ruleToLine);
188
+ return [
189
+ '## Guidance Auto-Promotions',
190
+ '',
191
+ '<!-- guidance-autopilot:start -->',
192
+ `<!-- source:${metadata.source} generated:${metadata.generatedAt} -->`,
193
+ ...lines,
194
+ '<!-- guidance-autopilot:end -->',
195
+ '',
196
+ ].join('\n');
197
+ }
198
+
199
+ function buildCandidateRoot(rootContent, rules, metadata) {
200
+ const section = buildPromotionSection(rules, metadata);
201
+ const markerPattern = /## Guidance Auto-Promotions[\s\S]*?<!-- guidance-autopilot:end -->\n?/m;
202
+ if (markerPattern.test(rootContent)) {
203
+ return rootContent.replace(markerPattern, section);
204
+ }
205
+ const trimmed = rootContent.trimEnd();
206
+ return `${trimmed}\n\n${section}`;
207
+ }
208
+
209
+ function getNextAdrNumber(adrDir) {
210
+ if (!existsSync(adrDir)) return 1;
211
+ const files = readdirSync(adrDir);
212
+ let max = 0;
213
+ for (const file of files) {
214
+ const match = file.match(/^ADR-(\d{3})-/);
215
+ if (match) max = Math.max(max, Number(match[1]));
216
+ }
217
+ return max + 1;
218
+ }
219
+
220
+ function formatAdrNumber(value) {
221
+ return String(value).padStart(3, '0');
222
+ }
223
+
224
+ function writePromotionAdr({ promotedRules, metrics, benchmarkSummary, adrDir }) {
225
+ ensureDir(adrDir);
226
+ const number = getNextAdrNumber(adrDir);
227
+ const id = `ADR-${formatAdrNumber(number)}`;
228
+ const fileName = `${id}-guidance-local-rule-promotion.md`;
229
+ const filePath = resolve(adrDir, fileName);
230
+
231
+ const lines = [];
232
+ lines.push(`# ${id}: Promote High-Value Local Guidance Rules`);
233
+ lines.push('');
234
+ lines.push(`- Date: ${new Date().toISOString().slice(0, 10)}`);
235
+ lines.push('- Status: Accepted');
236
+ lines.push('');
237
+ lines.push('## Context');
238
+ lines.push('Local guidance rules in `CLAUDE.local.md` are useful for experimentation, but successful patterns should move into shared `CLAUDE.md` to improve team-wide behavior.');
239
+ lines.push('');
240
+ lines.push('## Decision');
241
+ lines.push(`Promote ${promotedRules.length} local rule(s) into the auto-promotion section in \`CLAUDE.md\`.`);
242
+ lines.push('');
243
+ lines.push('Promoted rules:');
244
+ for (const rule of promotedRules) {
245
+ lines.push(`- [${rule.id}] ${rule.text}`);
246
+ }
247
+ lines.push('');
248
+ lines.push('## Measured Effect');
249
+ lines.push(`- Composite score before: ${metrics.beforeComposite}`);
250
+ lines.push(`- Composite score after: ${metrics.afterComposite}`);
251
+ lines.push(`- Composite delta: ${metrics.delta}`);
252
+ lines.push(`- Promotion threshold: ${metrics.threshold}`);
253
+ if (benchmarkSummary) {
254
+ lines.push(`- A/B delta gain: ${benchmarkSummary.deltaGain}`);
255
+ lines.push(`- A/B baseline delta: ${benchmarkSummary.baseDelta}`);
256
+ lines.push(`- A/B candidate delta: ${benchmarkSummary.candidateDelta}`);
257
+ }
258
+ lines.push('');
259
+ lines.push('## Consequences');
260
+ lines.push('- Shared guidance receives proven local improvements.');
261
+ lines.push('- Future sessions apply these rules without requiring local overrides.');
262
+ lines.push('- Further local experiments can be promoted by the same autopilot loop.');
263
+ lines.push('');
264
+
265
+ writeFileSync(filePath, lines.join('\n'));
266
+ return filePath;
267
+ }
268
+
269
+ function acquireLock(lockPath) {
270
+ ensureDir(dirname(lockPath));
271
+ try {
272
+ const fd = openSync(lockPath, 'wx');
273
+ return fd;
274
+ } catch {
275
+ return null;
276
+ }
277
+ }
278
+
279
+ function releaseLock(fd, lockPath) {
280
+ if (fd != null) closeSync(fd);
281
+ if (existsSync(lockPath)) unlinkSync(lockPath);
282
+ }
283
+
284
+ function appendLog(logPath, line) {
285
+ ensureDir(dirname(logPath));
286
+ appendFileSync(logPath, `[${nowIso()}] ${line}\n`);
287
+ }
288
+
289
+ async function runCycle(options) {
290
+ const guidanceDir = resolve(rootDir, '.claude-flow', 'guidance');
291
+ const backupDir = resolve(guidanceDir, 'backups');
292
+ const proposalDir = resolve(guidanceDir, 'proposals');
293
+ const reportPath = resolve(guidanceDir, 'autopilot-report.json');
294
+ const statePath = resolve(guidanceDir, 'autopilot-state.json');
295
+ const logPath = resolve(guidanceDir, 'autopilot.log');
296
+ const lockPath = resolve(guidanceDir, 'autopilot.lock');
297
+ const adrDir = resolve(rootDir, 'docs', 'adr');
298
+
299
+ const lockFd = acquireLock(lockPath);
300
+ if (lockFd == null) {
301
+ appendLog(logPath, 'skip: another autopilot process is already active');
302
+ return { skipped: true, reason: 'locked' };
303
+ }
304
+
305
+ try {
306
+ const { rootPath, rootContent, localContent } = loadGuidanceFiles();
307
+ const state = loadJson(statePath, {});
308
+ const candidates = getPromotableLocalRules(rootContent, localContent).slice(0, options.maxPromotions);
309
+
310
+ if (candidates.length === 0) {
311
+ const report = {
312
+ timestamp: nowIso(),
313
+ source: options.source,
314
+ applied: false,
315
+ reason: 'no-promotable-local-rules',
316
+ };
317
+ writeJson(reportPath, report);
318
+ writeJson(statePath, {
319
+ ...state,
320
+ lastRunAt: report.timestamp,
321
+ lastDecision: report.reason,
322
+ });
323
+ appendLog(logPath, 'no promotable local rules found');
324
+ return report;
325
+ }
326
+
327
+ const metadata = { source: options.source, generatedAt: nowIso() };
328
+ const candidateContent = buildCandidateRoot(rootContent, candidates, metadata);
329
+ const candidateHash = shortHash(candidateContent);
330
+
331
+ if (state.lastCandidateHash === candidateHash && state.lastDecision === 'below-threshold') {
332
+ const report = {
333
+ timestamp: metadata.generatedAt,
334
+ source: options.source,
335
+ applied: false,
336
+ reason: 'unchanged-below-threshold',
337
+ candidateHash,
338
+ };
339
+ writeJson(reportPath, report);
340
+ appendLog(logPath, `skip unchanged candidate hash=${candidateHash}`);
341
+ return report;
342
+ }
343
+
344
+ const scoreBefore = analyze(rootContent);
345
+ const scoreAfter = analyze(candidateContent);
346
+ const bench = benchmark(rootContent, candidateContent);
347
+
348
+ let abSummary = null;
349
+ let abGatePass = true;
350
+ if (options.runAB) {
351
+ const baseAB = await abBenchmark(rootContent, {
352
+ executor: createSyntheticContentAwareExecutor(),
353
+ });
354
+ const candidateAB = await abBenchmark(candidateContent, {
355
+ executor: createSyntheticContentAwareExecutor(),
356
+ });
357
+ const deltaGain = candidateAB.compositeDelta - baseAB.compositeDelta;
358
+ abSummary = {
359
+ baseDelta: baseAB.compositeDelta,
360
+ candidateDelta: candidateAB.compositeDelta,
361
+ deltaGain: Number(deltaGain.toFixed(3)),
362
+ };
363
+ abGatePass = deltaGain >= options.minABGain;
364
+ }
365
+
366
+ const thresholdPass = bench.delta >= options.minDelta;
367
+ const shouldApply = Boolean(options.apply && thresholdPass && abGatePass);
368
+
369
+ const report = {
370
+ timestamp: metadata.generatedAt,
371
+ source: options.source,
372
+ applied: shouldApply,
373
+ candidateHash,
374
+ promotedRuleCount: candidates.length,
375
+ promotedRuleIds: candidates.map((rule) => rule.id),
376
+ metrics: {
377
+ beforeComposite: scoreBefore.compositeScore,
378
+ afterComposite: scoreAfter.compositeScore,
379
+ delta: bench.delta,
380
+ threshold: options.minDelta,
381
+ },
382
+ ab: abSummary,
383
+ reasons: {
384
+ thresholdPass,
385
+ abGatePass,
386
+ applyFlag: options.apply,
387
+ },
388
+ };
389
+
390
+ if (!shouldApply) {
391
+ ensureDir(proposalDir);
392
+ const proposalPath = resolve(proposalDir, `CLAUDE.promoted.${Date.now()}.md`);
393
+ writeFileSync(proposalPath, candidateContent);
394
+ report.proposalPath = proposalPath;
395
+ report.decision = 'below-threshold';
396
+ appendLog(
397
+ logPath,
398
+ `proposal only: delta=${bench.delta.toFixed(2)} threshold=${options.minDelta} file=${proposalPath}`
399
+ );
400
+ } else {
401
+ ensureDir(backupDir);
402
+ const backupPath = resolve(backupDir, `CLAUDE.md.${Date.now()}.bak`);
403
+ writeFileSync(backupPath, rootContent);
404
+ writeFileSync(rootPath, candidateContent);
405
+
406
+ const adrPath = writePromotionAdr({
407
+ promotedRules: candidates,
408
+ metrics: {
409
+ beforeComposite: scoreBefore.compositeScore,
410
+ afterComposite: scoreAfter.compositeScore,
411
+ delta: bench.delta,
412
+ threshold: options.minDelta,
413
+ },
414
+ benchmarkSummary: abSummary,
415
+ adrDir,
416
+ });
417
+ report.backupPath = backupPath;
418
+ report.adrPath = adrPath;
419
+ report.decision = 'applied';
420
+ appendLog(
421
+ logPath,
422
+ `applied: promoted=${candidates.length} delta=${bench.delta.toFixed(2)} adr=${adrPath}`
423
+ );
424
+ }
425
+
426
+ writeJson(reportPath, report);
427
+ writeJson(statePath, {
428
+ ...state,
429
+ lastRunAt: report.timestamp,
430
+ lastCandidateHash: candidateHash,
431
+ lastDecision: report.decision,
432
+ lastApplied: report.applied,
433
+ lastDelta: report.metrics.delta,
434
+ });
435
+
436
+ return report;
437
+ } finally {
438
+ releaseLock(lockFd, lockPath);
439
+ }
440
+ }
441
+
442
+ async function runDaemon(options) {
443
+ const run = async () => {
444
+ try {
445
+ const report = await runCycle(options);
446
+ if (!report?.skipped) {
447
+ console.log(JSON.stringify(report, null, 2));
448
+ }
449
+ } catch (error) {
450
+ const message = error instanceof Error ? error.message : String(error);
451
+ console.error(message);
452
+ }
453
+ };
454
+
455
+ await run();
456
+ setInterval(run, options.intervalMs);
457
+ }
458
+
459
+ async function main() {
460
+ const options = parseArgs();
461
+ if (options.mode === 'daemon') {
462
+ await runDaemon(options);
463
+ return;
464
+ }
465
+ const report = await runCycle(options);
466
+ console.log(JSON.stringify(report, null, 2));
467
+ }
468
+
469
+ main().catch((error) => {
470
+ const message = error instanceof Error ? error.message : String(error);
471
+ console.error(message);
472
+ process.exit(1);
473
+ });