@nerviq/cli 0.0.1 → 0.9.0-beta.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 (148) hide show
  1. package/CHANGELOG.md +181 -0
  2. package/LICENSE +21 -0
  3. package/README.md +447 -0
  4. package/bin/cli.js +749 -0
  5. package/content/case-study-template.md +91 -0
  6. package/content/claims-governance.md +37 -0
  7. package/content/claude-code/audit-repo/SKILL.md +20 -0
  8. package/content/claude-native-integration.md +60 -0
  9. package/content/devto-article.json +9 -0
  10. package/content/launch-posts.md +226 -0
  11. package/content/pilot-rollout-kit.md +30 -0
  12. package/content/release-checklist.md +31 -0
  13. package/package.json +53 -4
  14. package/src/activity.js +529 -0
  15. package/src/aider/activity.js +226 -0
  16. package/src/aider/config-parser.js +166 -0
  17. package/src/aider/context.js +158 -0
  18. package/src/aider/deep-review.js +316 -0
  19. package/src/aider/domain-packs.js +278 -0
  20. package/src/aider/freshness.js +168 -0
  21. package/src/aider/governance.js +253 -0
  22. package/src/aider/interactive.js +334 -0
  23. package/src/aider/mcp-packs.js +98 -0
  24. package/src/aider/patch.js +214 -0
  25. package/src/aider/plans.js +186 -0
  26. package/src/aider/premium.js +360 -0
  27. package/src/aider/setup.js +404 -0
  28. package/src/aider/techniques.js +1323 -0
  29. package/src/analyze.js +821 -0
  30. package/src/audit.js +1003 -0
  31. package/src/badge.js +13 -0
  32. package/src/benchmark.js +339 -0
  33. package/src/claudex-sync.json +7 -0
  34. package/src/codex/activity.js +324 -0
  35. package/src/codex/config-parser.js +183 -0
  36. package/src/codex/context.js +221 -0
  37. package/src/codex/deep-review.js +493 -0
  38. package/src/codex/domain-packs.js +372 -0
  39. package/src/codex/freshness.js +167 -0
  40. package/src/codex/governance.js +192 -0
  41. package/src/codex/interactive.js +618 -0
  42. package/src/codex/mcp-packs.js +660 -0
  43. package/src/codex/patch.js +209 -0
  44. package/src/codex/plans.js +251 -0
  45. package/src/codex/premium.js +614 -0
  46. package/src/codex/setup.js +603 -0
  47. package/src/codex/techniques.js +2649 -0
  48. package/src/context.js +272 -0
  49. package/src/copilot/activity.js +309 -0
  50. package/src/copilot/config-parser.js +226 -0
  51. package/src/copilot/context.js +197 -0
  52. package/src/copilot/deep-review.js +346 -0
  53. package/src/copilot/domain-packs.js +350 -0
  54. package/src/copilot/freshness.js +197 -0
  55. package/src/copilot/governance.js +222 -0
  56. package/src/copilot/interactive.js +406 -0
  57. package/src/copilot/mcp-packs.js +572 -0
  58. package/src/copilot/patch.js +238 -0
  59. package/src/copilot/plans.js +253 -0
  60. package/src/copilot/premium.js +450 -0
  61. package/src/copilot/setup.js +488 -0
  62. package/src/copilot/techniques.js +1822 -0
  63. package/src/cursor/activity.js +301 -0
  64. package/src/cursor/config-parser.js +265 -0
  65. package/src/cursor/context.js +236 -0
  66. package/src/cursor/deep-review.js +334 -0
  67. package/src/cursor/domain-packs.js +346 -0
  68. package/src/cursor/freshness.js +214 -0
  69. package/src/cursor/governance.js +229 -0
  70. package/src/cursor/interactive.js +391 -0
  71. package/src/cursor/mcp-packs.js +571 -0
  72. package/src/cursor/patch.js +243 -0
  73. package/src/cursor/plans.js +254 -0
  74. package/src/cursor/premium.js +468 -0
  75. package/src/cursor/setup.js +488 -0
  76. package/src/cursor/techniques.js +1786 -0
  77. package/src/deep-review.js +345 -0
  78. package/src/domain-packs.js +364 -0
  79. package/src/formatters/sarif.js +115 -0
  80. package/src/gemini/activity.js +402 -0
  81. package/src/gemini/config-parser.js +275 -0
  82. package/src/gemini/context.js +221 -0
  83. package/src/gemini/deep-review.js +559 -0
  84. package/src/gemini/domain-packs.js +371 -0
  85. package/src/gemini/freshness.js +204 -0
  86. package/src/gemini/governance.js +201 -0
  87. package/src/gemini/interactive.js +860 -0
  88. package/src/gemini/mcp-packs.js +658 -0
  89. package/src/gemini/patch.js +229 -0
  90. package/src/gemini/plans.js +269 -0
  91. package/src/gemini/premium.js +759 -0
  92. package/src/gemini/setup.js +692 -0
  93. package/src/gemini/techniques.js +2084 -0
  94. package/src/governance.js +523 -0
  95. package/src/harmony/advisor.js +383 -0
  96. package/src/harmony/audit.js +303 -0
  97. package/src/harmony/canon.js +444 -0
  98. package/src/harmony/cli.js +331 -0
  99. package/src/harmony/drift.js +401 -0
  100. package/src/harmony/governance.js +313 -0
  101. package/src/harmony/memory.js +238 -0
  102. package/src/harmony/sync.js +458 -0
  103. package/src/harmony/watch.js +336 -0
  104. package/src/index.js +256 -0
  105. package/src/insights.js +119 -0
  106. package/src/interactive.js +118 -0
  107. package/src/mcp-packs.js +597 -0
  108. package/src/opencode/activity.js +286 -0
  109. package/src/opencode/config-parser.js +109 -0
  110. package/src/opencode/context.js +247 -0
  111. package/src/opencode/deep-review.js +313 -0
  112. package/src/opencode/domain-packs.js +240 -0
  113. package/src/opencode/freshness.js +158 -0
  114. package/src/opencode/governance.js +159 -0
  115. package/src/opencode/interactive.js +392 -0
  116. package/src/opencode/mcp-packs.js +474 -0
  117. package/src/opencode/patch.js +184 -0
  118. package/src/opencode/plans.js +231 -0
  119. package/src/opencode/premium.js +413 -0
  120. package/src/opencode/setup.js +449 -0
  121. package/src/opencode/techniques.js +1713 -0
  122. package/src/plans.js +655 -0
  123. package/src/secret-patterns.js +30 -0
  124. package/src/setup.js +1274 -0
  125. package/src/synergy/adaptive.js +261 -0
  126. package/src/synergy/compensation.js +156 -0
  127. package/src/synergy/evidence.js +193 -0
  128. package/src/synergy/learning.js +184 -0
  129. package/src/synergy/patterns.js +227 -0
  130. package/src/synergy/ranking.js +83 -0
  131. package/src/synergy/report.js +163 -0
  132. package/src/synergy/routing.js +152 -0
  133. package/src/techniques.js +1354 -0
  134. package/src/watch.js +229 -0
  135. package/src/windsurf/activity.js +302 -0
  136. package/src/windsurf/config-parser.js +267 -0
  137. package/src/windsurf/context.js +249 -0
  138. package/src/windsurf/deep-review.js +337 -0
  139. package/src/windsurf/domain-packs.js +348 -0
  140. package/src/windsurf/freshness.js +215 -0
  141. package/src/windsurf/governance.js +231 -0
  142. package/src/windsurf/interactive.js +388 -0
  143. package/src/windsurf/mcp-packs.js +535 -0
  144. package/src/windsurf/patch.js +231 -0
  145. package/src/windsurf/plans.js +247 -0
  146. package/src/windsurf/premium.js +467 -0
  147. package/src/windsurf/setup.js +471 -0
  148. package/src/windsurf/techniques.js +1758 -0
@@ -0,0 +1,184 @@
1
+ /**
2
+ * S1. Cross-Platform Learning Engine
3
+ *
4
+ * When a recommendation succeeds on one platform, propagate to others.
5
+ * Translates recommendations into each platform's native semantics
6
+ * rather than blindly copying.
7
+ */
8
+
9
+ const fs = require('fs');
10
+ const path = require('path');
11
+
12
+ const PLATFORM_SEMANTICS = {
13
+ claude: { configFile: 'CLAUDE.md', format: 'markdown', instructionStyle: 'prose' },
14
+ codex: { configFile: 'AGENTS.md', format: 'markdown', instructionStyle: 'directive' },
15
+ gemini: { configFile: 'GEMINI.md', format: 'markdown', instructionStyle: 'structured' },
16
+ copilot: { configFile: '.github/copilot-instructions.md', format: 'markdown', instructionStyle: 'concise' },
17
+ cursor: { configFile: '.cursor/rules', format: 'mdc', instructionStyle: 'rule-based' },
18
+ };
19
+
20
+ const TRANSLATION_MAP = {
21
+ 'verification-command': {
22
+ claude: (rec) => `Add to CLAUDE.md: \`## Verification\` section with \`${rec.command}\``,
23
+ codex: (rec) => `Add to AGENTS.md verification block: \`${rec.command}\``,
24
+ gemini: (rec) => `Add to GEMINI.md: verification command \`${rec.command}\``,
25
+ copilot: (rec) => `Document in copilot-instructions.md: always run \`${rec.command}\` before completing`,
26
+ cursor: (rec) => `Add rule: "Always run \`${rec.command}\` before completing tasks"`,
27
+ },
28
+ 'architecture-doc': {
29
+ claude: (rec) => `Add Mermaid architecture diagram to CLAUDE.md`,
30
+ codex: (rec) => `Add architecture overview to AGENTS.md`,
31
+ gemini: (rec) => `Add architecture context to GEMINI.md`,
32
+ copilot: (rec) => `Add architecture reference in copilot-instructions.md`,
33
+ cursor: (rec) => `Add architecture context rule in .cursor/rules`,
34
+ },
35
+ 'permission-rule': {
36
+ claude: (rec) => `Configure in settings.json permissions: ${rec.description}`,
37
+ codex: (rec) => `Set sandbox policy in codex config: ${rec.description}`,
38
+ gemini: (rec) => `Configure Gemini sandbox settings: ${rec.description}`,
39
+ copilot: (rec) => `Note in instructions: ${rec.description}`,
40
+ cursor: (rec) => `Add safety rule: ${rec.description}`,
41
+ },
42
+ 'hook': {
43
+ claude: (rec) => `Add hook in settings.json: ${rec.description}`,
44
+ codex: (rec) => `Add pre/post task check: ${rec.description}`,
45
+ gemini: (rec) => `Add automated check: ${rec.description}`,
46
+ copilot: (rec) => `Add workflow step: ${rec.description}`,
47
+ cursor: (rec) => `Add background task rule: ${rec.description}`,
48
+ },
49
+ };
50
+
51
+ /**
52
+ * Adapt a recommendation from one platform's semantics to another.
53
+ */
54
+ function adaptRecommendation(recommendation, sourcePlatform, targetPlatform) {
55
+ const translator = TRANSLATION_MAP[recommendation.type];
56
+ if (translator && translator[targetPlatform]) {
57
+ return translator[targetPlatform](recommendation);
58
+ }
59
+ // Generic fallback: describe the recommendation in platform-neutral terms
60
+ const semantics = PLATFORM_SEMANTICS[targetPlatform];
61
+ if (!semantics) return recommendation.description || recommendation.recommendation;
62
+ return `[${semantics.configFile}] ${recommendation.description || recommendation.recommendation}`;
63
+ }
64
+
65
+ /**
66
+ * Calculate confidence for a propagated insight based on similarity
67
+ * between source and target platforms.
68
+ */
69
+ function calculatePropagationConfidence(insight, sourcePlatform, targetPlatform) {
70
+ // Base confidence from the original outcome
71
+ let confidence = Math.min(1, Math.max(0, (insight.score_delta || 0) / 20));
72
+
73
+ // Same instruction style = higher confidence
74
+ const sourceStyle = (PLATFORM_SEMANTICS[sourcePlatform] || {}).instructionStyle;
75
+ const targetStyle = (PLATFORM_SEMANTICS[targetPlatform] || {}).instructionStyle;
76
+ if (sourceStyle === targetStyle) confidence *= 1.2;
77
+
78
+ // Same format = slightly higher confidence
79
+ const sourceFormat = (PLATFORM_SEMANTICS[sourcePlatform] || {}).format;
80
+ const targetFormat = (PLATFORM_SEMANTICS[targetPlatform] || {}).format;
81
+ if (sourceFormat === targetFormat) confidence *= 1.1;
82
+
83
+ return Math.min(1, Math.round(confidence * 100) / 100);
84
+ }
85
+
86
+ /**
87
+ * Propagate an insight from one platform to others.
88
+ *
89
+ * @param {Object} insight - { type, recommendation, outcome, score_delta }
90
+ * @param {string} sourcePlatform - Platform where the insight originated
91
+ * @param {string[]} targetPlatforms - Platforms to propagate to
92
+ * @returns {Object[]} Adapted recommendations per target platform
93
+ */
94
+ function propagateInsight(insight, sourcePlatform, targetPlatforms) {
95
+ return targetPlatforms
96
+ .filter(p => p !== sourcePlatform)
97
+ .map(platform => ({
98
+ platform,
99
+ adaptedRecommendation: adaptRecommendation(insight, sourcePlatform, platform),
100
+ confidence: calculatePropagationConfidence(insight, sourcePlatform, platform),
101
+ sourceEvidence: {
102
+ platform: sourcePlatform,
103
+ outcome: insight.outcome,
104
+ score_delta: insight.score_delta,
105
+ },
106
+ }));
107
+ }
108
+
109
+ /**
110
+ * Read recommendation outcomes from all platforms and find cross-learning opportunities.
111
+ *
112
+ * @param {string} dir - Project directory
113
+ * @returns {Object[]} Cross-learning opportunities
114
+ */
115
+ function getCrossLearnings(dir) {
116
+ const learningsFile = path.join(dir, '.claude', 'synergy-learnings.json');
117
+ let learnings = [];
118
+ try {
119
+ learnings = JSON.parse(fs.readFileSync(learningsFile, 'utf8'));
120
+ } catch {
121
+ // No learnings file yet
122
+ }
123
+
124
+ // Group by recommendation type
125
+ const byType = {};
126
+ for (const learning of learnings) {
127
+ if (!byType[learning.type]) byType[learning.type] = [];
128
+ byType[learning.type].push(learning);
129
+ }
130
+
131
+ const opportunities = [];
132
+ for (const [type, items] of Object.entries(byType)) {
133
+ // Find successful outcomes
134
+ const successes = items.filter(i => i.outcome === 'applied' || i.outcome === 'helpful');
135
+ if (successes.length === 0) continue;
136
+
137
+ // Find platforms that haven't tried this yet
138
+ const triedPlatforms = new Set(items.map(i => i.platform));
139
+ const allPlatforms = Object.keys(PLATFORM_SEMANTICS);
140
+ const untried = allPlatforms.filter(p => !triedPlatforms.has(p));
141
+
142
+ if (untried.length > 0) {
143
+ const bestSuccess = successes.reduce((a, b) =>
144
+ (b.score_delta || 0) > (a.score_delta || 0) ? b : a
145
+ );
146
+ opportunities.push({
147
+ type,
148
+ successfulOn: successes.map(s => s.platform),
149
+ untestedOn: untried,
150
+ bestEvidence: bestSuccess,
151
+ propagations: propagateInsight(bestSuccess, bestSuccess.platform, untried),
152
+ });
153
+ }
154
+ }
155
+
156
+ return opportunities;
157
+ }
158
+
159
+ /**
160
+ * Record a learning outcome for later cross-platform propagation.
161
+ *
162
+ * @param {string} dir - Project directory
163
+ * @param {Object} outcome - { platform, type, recommendation, outcome, score_delta }
164
+ */
165
+ function recordLearningOutcome(dir, outcome) {
166
+ const learningsFile = path.join(dir, '.claude', 'synergy-learnings.json');
167
+ let learnings = [];
168
+ try {
169
+ learnings = JSON.parse(fs.readFileSync(learningsFile, 'utf8'));
170
+ } catch {
171
+ // Start fresh
172
+ }
173
+
174
+ learnings.push({
175
+ ...outcome,
176
+ timestamp: new Date().toISOString(),
177
+ });
178
+
179
+ const claudeDir = path.join(dir, '.claude');
180
+ if (!fs.existsSync(claudeDir)) fs.mkdirSync(claudeDir, { recursive: true });
181
+ fs.writeFileSync(learningsFile, JSON.stringify(learnings, null, 2));
182
+ }
183
+
184
+ module.exports = { propagateInsight, getCrossLearnings, recordLearningOutcome };
@@ -0,0 +1,227 @@
1
+ /**
2
+ * S5. Cross-Platform Pattern Discovery
3
+ *
4
+ * Finds patterns only visible from a cross-platform perspective:
5
+ * recurring failures, platform-specific successes, sequence effects,
6
+ * and diminishing returns.
7
+ */
8
+
9
+ const { PLATFORM_CAPABILITIES } = require('./routing');
10
+
11
+ /**
12
+ * Detect recurring failures across platforms (root cause is project, not platform).
13
+ */
14
+ function detectRecurringFailures(harmonyHistory) {
15
+ const patterns = [];
16
+ const failureCounts = {};
17
+
18
+ for (const entry of harmonyHistory) {
19
+ if (!entry.findings) continue;
20
+ for (const finding of entry.findings) {
21
+ if (finding.passed === false) {
22
+ const key = finding.key || finding.name;
23
+ if (!failureCounts[key]) {
24
+ failureCounts[key] = { key, name: finding.name, category: finding.category, platforms: new Set() };
25
+ }
26
+ failureCounts[key].platforms.add(entry.platform);
27
+ }
28
+ }
29
+ }
30
+
31
+ for (const [key, data] of Object.entries(failureCounts)) {
32
+ if (data.platforms.size >= 3) {
33
+ patterns.push({
34
+ type: 'recurring-failure',
35
+ description: `"${data.name || key}" fails on ${data.platforms.size} platforms — root cause is project-level, not platform-specific`,
36
+ key: data.key,
37
+ affectedPlatforms: [...data.platforms],
38
+ severity: data.platforms.size >= 4 ? 'high' : 'medium',
39
+ });
40
+ }
41
+ }
42
+
43
+ return patterns;
44
+ }
45
+
46
+ /**
47
+ * Detect platform-specific successes (recommendation only works on one platform).
48
+ */
49
+ function detectPlatformSpecificSuccess(harmonyHistory) {
50
+ const patterns = [];
51
+ const outcomesByKey = {};
52
+
53
+ for (const entry of harmonyHistory) {
54
+ if (!entry.findings) continue;
55
+ for (const finding of entry.findings) {
56
+ const key = finding.key || finding.name;
57
+ if (!outcomesByKey[key]) outcomesByKey[key] = {};
58
+ outcomesByKey[key][entry.platform] = finding.passed;
59
+ }
60
+ }
61
+
62
+ for (const [key, platforms] of Object.entries(outcomesByKey)) {
63
+ const entries = Object.entries(platforms);
64
+ if (entries.length < 2) continue;
65
+
66
+ const passed = entries.filter(([, v]) => v === true);
67
+ const failed = entries.filter(([, v]) => v === false);
68
+
69
+ if (passed.length === 1 && failed.length >= 2) {
70
+ patterns.push({
71
+ type: 'platform-specific-success',
72
+ description: `"${key}" only passes on ${passed[0][0]} — fails on ${failed.map(f => f[0]).join(', ')}`,
73
+ key,
74
+ successPlatform: passed[0][0],
75
+ failPlatforms: failed.map(f => f[0]),
76
+ });
77
+ }
78
+ }
79
+
80
+ return patterns;
81
+ }
82
+
83
+ /**
84
+ * Analyze sequence effects (order of platform setup matters).
85
+ */
86
+ function analyzeSequenceEffects(harmonyHistory) {
87
+ const patterns = [];
88
+ const sequenceScores = {};
89
+
90
+ // Group history entries by timestamp to detect sequences
91
+ const sorted = [...harmonyHistory].sort((a, b) =>
92
+ new Date(a.timestamp || 0) - new Date(b.timestamp || 0)
93
+ );
94
+
95
+ // Look at consecutive pairs
96
+ for (let i = 0; i < sorted.length - 1; i++) {
97
+ const first = sorted[i];
98
+ const second = sorted[i + 1];
99
+ if (!first.platform || !second.platform || first.platform === second.platform) continue;
100
+
101
+ const seqKey = `${first.platform}→${second.platform}`;
102
+ if (!sequenceScores[seqKey]) {
103
+ sequenceScores[seqKey] = { scores: [], firstScores: [], secondScores: [] };
104
+ }
105
+
106
+ if (second.score !== undefined) {
107
+ sequenceScores[seqKey].secondScores.push(second.score);
108
+ }
109
+ if (first.score !== undefined) {
110
+ sequenceScores[seqKey].firstScores.push(first.score);
111
+ }
112
+ }
113
+
114
+ for (const [seq, data] of Object.entries(sequenceScores)) {
115
+ if (data.secondScores.length < 2) continue;
116
+ const avgSecond = data.secondScores.reduce((a, b) => a + b, 0) / data.secondScores.length;
117
+
118
+ // Check if reverse sequence exists and compare
119
+ const [first, second] = seq.split('→');
120
+ const reverseKey = `${second}→${first}`;
121
+ const reverseData = sequenceScores[reverseKey];
122
+
123
+ if (reverseData && reverseData.secondScores.length >= 2) {
124
+ const avgReverse = reverseData.secondScores.reduce((a, b) => a + b, 0) / reverseData.secondScores.length;
125
+ if (Math.abs(avgSecond - avgReverse) > 5) {
126
+ const better = avgSecond > avgReverse ? seq : reverseKey;
127
+ patterns.push({
128
+ type: 'sequence-effect',
129
+ description: `Setup order "${better}" produces better results (${Math.round(Math.max(avgSecond, avgReverse))} vs ${Math.round(Math.min(avgSecond, avgReverse))})`,
130
+ bestSequence: better,
131
+ scoreDifference: Math.round(Math.abs(avgSecond - avgReverse)),
132
+ });
133
+ }
134
+ }
135
+ }
136
+
137
+ return patterns;
138
+ }
139
+
140
+ /**
141
+ * Detect diminishing returns from adding more platforms.
142
+ */
143
+ function detectDiminishingReturns(harmonyHistory) {
144
+ const patterns = [];
145
+
146
+ // Group by project (dir) and count platforms vs score improvement
147
+ const byProject = {};
148
+ for (const entry of harmonyHistory) {
149
+ const dir = entry.dir || 'unknown';
150
+ if (!byProject[dir]) byProject[dir] = [];
151
+ byProject[dir].push(entry);
152
+ }
153
+
154
+ for (const [dir, entries] of Object.entries(byProject)) {
155
+ const platformScores = {};
156
+ for (const entry of entries) {
157
+ if (entry.platform && entry.score !== undefined) {
158
+ platformScores[entry.platform] = entry.score;
159
+ }
160
+ }
161
+
162
+ const platforms = Object.keys(platformScores);
163
+ if (platforms.length < 3) continue;
164
+
165
+ // Sort by score descending to see marginal value of each addition
166
+ const sorted = Object.entries(platformScores).sort((a, b) => b[1] - a[1]);
167
+ const marginals = [];
168
+ let cumulative = 0;
169
+
170
+ for (let i = 0; i < sorted.length; i++) {
171
+ const marginal = i === 0 ? sorted[i][1] : Math.max(0, sorted[i][1] - cumulative / i);
172
+ marginals.push({ platform: sorted[i][0], score: sorted[i][1], marginalValue: Math.round(marginal) });
173
+ cumulative += sorted[i][1];
174
+ }
175
+
176
+ // Check if last platforms add significantly less
177
+ if (marginals.length >= 3) {
178
+ const firstMarginal = marginals[0].marginalValue;
179
+ const lastMarginal = marginals[marginals.length - 1].marginalValue;
180
+
181
+ if (firstMarginal > 0 && lastMarginal < firstMarginal * 0.3) {
182
+ patterns.push({
183
+ type: 'diminishing-returns',
184
+ description: `Platform #${marginals.length} (${marginals[marginals.length - 1].platform}) adds ${lastMarginal} marginal value vs ${firstMarginal} from #1 (${marginals[0].platform})`,
185
+ marginals,
186
+ dir,
187
+ });
188
+ }
189
+ }
190
+ }
191
+
192
+ return patterns;
193
+ }
194
+
195
+ /**
196
+ * Discover all cross-platform patterns from harmony history.
197
+ *
198
+ * @param {Object[]} harmonyHistory - Array of audit/harmony run entries
199
+ * @returns {Object} Discovered patterns by type
200
+ */
201
+ function discoverPatterns(harmonyHistory) {
202
+ if (!Array.isArray(harmonyHistory) || harmonyHistory.length === 0) {
203
+ return { patterns: [] };
204
+ }
205
+
206
+ const patterns = [
207
+ ...detectRecurringFailures(harmonyHistory),
208
+ ...detectPlatformSpecificSuccess(harmonyHistory),
209
+ ...analyzeSequenceEffects(harmonyHistory),
210
+ ...detectDiminishingReturns(harmonyHistory),
211
+ ];
212
+
213
+ return { patterns };
214
+ }
215
+
216
+ /**
217
+ * Focused analysis of sequence effects only.
218
+ *
219
+ * @param {Object[]} harmonyHistory - Array of audit/harmony run entries
220
+ * @returns {Object[]} Sequence effect patterns
221
+ */
222
+ function analyzeSequenceEffectsOnly(harmonyHistory) {
223
+ if (!Array.isArray(harmonyHistory)) return [];
224
+ return analyzeSequenceEffects(harmonyHistory);
225
+ }
226
+
227
+ module.exports = { discoverPatterns, analyzeSequenceEffects: analyzeSequenceEffectsOnly };
@@ -0,0 +1,83 @@
1
+ /**
2
+ * S6. Unified Recommendation Ranking
3
+ *
4
+ * Ranks recommendations by cross-platform impact, boosting those that
5
+ * apply broadly, have evidence from other platforms, or fill gaps.
6
+ */
7
+
8
+ /**
9
+ * Calculate synergy score for a single recommendation.
10
+ *
11
+ * @param {Object} recommendation - A recommendation object
12
+ * @param {string[]} activePlatforms - Currently active platforms
13
+ * @param {Object} [context] - Optional context with evidence and compensation data
14
+ * @returns {number} Synergy score
15
+ */
16
+ function calculateSynergyScore(recommendation, activePlatforms, context) {
17
+ let score = recommendation.baseScore || recommendation.score || 1;
18
+ const ctx = context || {};
19
+
20
+ // Cross-platform boost: applies to N platforms → x1.2 per additional
21
+ const applicablePlatforms = (recommendation.applicablePlatforms || [])
22
+ .filter(p => activePlatforms.includes(p));
23
+ if (applicablePlatforms.length > 1) {
24
+ score *= Math.pow(1.2, applicablePlatforms.length - 1);
25
+ }
26
+
27
+ // Evidence boost: validated on another platform → x1.3
28
+ if (recommendation.validatedOn && recommendation.validatedOn.length > 0) {
29
+ const externalValidations = recommendation.validatedOn.filter(
30
+ p => p !== recommendation.sourcePlatform
31
+ );
32
+ if (externalValidations.length > 0) {
33
+ score *= 1.3;
34
+ }
35
+ }
36
+
37
+ // Compensation boost: fills a gap → x1.5
38
+ if (recommendation.fillsGap || recommendation.isCompensation) {
39
+ score *= 1.5;
40
+ }
41
+
42
+ // Cross-learning boost: learned from another platform → x1.2
43
+ if (recommendation.crossLearningSource) {
44
+ score *= 1.2;
45
+ }
46
+
47
+ // Impact multiplier
48
+ const impactMultipliers = { critical: 2.0, high: 1.5, medium: 1.0, low: 0.7 };
49
+ const impactMult = impactMultipliers[recommendation.impact] || 1.0;
50
+ score *= impactMult;
51
+
52
+ // Historical success boost from context
53
+ if (ctx.successRate !== undefined && ctx.successRate > 0) {
54
+ score *= (1 + ctx.successRate * 0.3);
55
+ }
56
+
57
+ return Math.round(score * 100) / 100;
58
+ }
59
+
60
+ /**
61
+ * Rank recommendations by cross-platform synergy impact.
62
+ *
63
+ * @param {Object[]} recommendations - Array of recommendation objects
64
+ * @param {string[]} activePlatforms - Currently active platforms
65
+ * @param {Object} [context] - Optional context with evidence and compensation data
66
+ * @returns {Object[]} Sorted recommendations with synergyScore attached
67
+ */
68
+ function rankRecommendations(recommendations, activePlatforms, context) {
69
+ if (!Array.isArray(recommendations) || recommendations.length === 0) {
70
+ return [];
71
+ }
72
+
73
+ const platforms = activePlatforms || [];
74
+
75
+ return recommendations
76
+ .map(rec => ({
77
+ ...rec,
78
+ synergyScore: calculateSynergyScore(rec, platforms, context),
79
+ }))
80
+ .sort((a, b) => b.synergyScore - a.synergyScore);
81
+ }
82
+
83
+ module.exports = { rankRecommendations, calculateSynergyScore };
@@ -0,0 +1,163 @@
1
+ /**
2
+ * S7. Synergy Dashboard / Report
3
+ *
4
+ * Formats synergy analysis as CLI output showing amplification,
5
+ * per-platform contribution, active and untapped synergies, and trends.
6
+ */
7
+
8
+ const { compoundAudit, calculateAmplification } = require('./evidence');
9
+ const { analyzeCompensation } = require('./compensation');
10
+ const { discoverPatterns } = require('./patterns');
11
+ const { rankRecommendations } = require('./ranking');
12
+
13
+ const COLORS = {
14
+ reset: '\x1b[0m',
15
+ bold: '\x1b[1m',
16
+ dim: '\x1b[2m',
17
+ red: '\x1b[31m',
18
+ green: '\x1b[32m',
19
+ yellow: '\x1b[33m',
20
+ blue: '\x1b[36m',
21
+ magenta: '\x1b[35m',
22
+ white: '\x1b[37m',
23
+ };
24
+
25
+ function c(text, color) {
26
+ return `${COLORS[color] || ''}${text}${COLORS.reset}`;
27
+ }
28
+
29
+ function progressBar(score, max = 100, width = 20) {
30
+ const clamped = Math.min(max, Math.max(0, score));
31
+ const filled = Math.round((clamped / max) * width);
32
+ const empty = width - filled;
33
+ const color = score >= 70 ? 'green' : score >= 40 ? 'yellow' : 'red';
34
+ return c('\u2588'.repeat(filled), color) + c('\u2591'.repeat(empty), 'dim');
35
+ }
36
+
37
+ /**
38
+ * Format the synergy report for CLI output.
39
+ *
40
+ * @param {Object} options
41
+ * @param {Object} options.platformAudits - Audit results per platform
42
+ * @param {string[]} options.activePlatforms - Active platform names
43
+ * @param {Object[]} [options.harmonyHistory] - Historical harmony data
44
+ * @param {Object[]} [options.recommendations] - Aggregated recommendations
45
+ * @returns {string} Formatted CLI report
46
+ */
47
+ function formatSynergyReport(options) {
48
+ const { platformAudits, activePlatforms, harmonyHistory, recommendations } = options;
49
+ const lines = [];
50
+
51
+ // Header
52
+ lines.push('');
53
+ lines.push(c(' ╔══════════════════════════════════════════════════╗', 'blue'));
54
+ lines.push(c(' ║ SYNERGY DASHBOARD ║', 'blue'));
55
+ lines.push(c(' ╚══════════════════════════════════════════════════╝', 'blue'));
56
+ lines.push('');
57
+
58
+ // Compound audit
59
+ const compound = compoundAudit(platformAudits || {});
60
+ const amplification = calculateAmplification(platformAudits || {});
61
+
62
+ const ampColor = compound.amplification > 10 ? 'green'
63
+ : compound.amplification > 0 ? 'yellow' : 'red';
64
+
65
+ lines.push(c(' Synergy Score', 'bold'));
66
+ lines.push(` ${progressBar(compound.compoundScore, 150, 30)} ${c(compound.compoundScore + '/100', 'bold')}` +
67
+ (compound.amplification > 0
68
+ ? ` ${c(`(+${compound.amplification} amplification)`, ampColor)}`
69
+ : ''));
70
+ lines.push(` Best single platform: ${compound.bestSingleScore}/100`);
71
+ lines.push(` Cross-validated findings: ${compound.crossValidated.length}`);
72
+ lines.push(` Total unique findings: ${compound.totalFindings}`);
73
+ lines.push('');
74
+
75
+ // Per-platform contribution
76
+ lines.push(c(' Per-Platform Contribution', 'bold'));
77
+ for (const platform of (activePlatforms || [])) {
78
+ const audit = (platformAudits || {})[platform];
79
+ const score = audit ? audit.score : 0;
80
+ const coverage = compound.coverageMap[platform] || { found: 0, unique: 0, shared: 0 };
81
+ lines.push(` ${c(platform.padEnd(10), 'blue')} ${progressBar(score, 100, 15)} ${score}/100 ` +
82
+ `${c(`unique: ${coverage.unique}`, 'dim')} ${c(`shared: ${coverage.shared}`, 'dim')}`);
83
+ }
84
+ lines.push('');
85
+
86
+ // Active synergies (compensations)
87
+ const compensation = analyzeCompensation(activePlatforms || [], platformAudits);
88
+ if (compensation.compensations.length > 0) {
89
+ lines.push(c(' Active Synergies', 'bold'));
90
+ const shown = compensation.compensations.slice(0, 5);
91
+ for (const comp of shown) {
92
+ lines.push(` ${c('\u2713', 'green')} ${comp.compensatedBy.platform} covers ${comp.weakness.platform}'s weakness in ${comp.weakness.label} ` +
93
+ `${c(`(+${comp.netBenefit} net benefit)`, 'green')}`);
94
+ }
95
+ if (compensation.compensations.length > 5) {
96
+ lines.push(c(` ... and ${compensation.compensations.length - 5} more`, 'dim'));
97
+ }
98
+ lines.push('');
99
+ }
100
+
101
+ // Untapped synergies
102
+ if (compensation.uncoveredGaps.length > 0 || compensation.recommendedAdditions.length > 0) {
103
+ lines.push(c(' Untapped Synergies', 'bold'));
104
+
105
+ for (const gap of compensation.uncoveredGaps.slice(0, 3)) {
106
+ lines.push(` ${c('\u26A0', 'yellow')} No platform covers: ${gap.label}`);
107
+ }
108
+
109
+ for (const rec of compensation.recommendedAdditions.slice(0, 2)) {
110
+ const areas = rec.wouldCover.map(w => w.label).join(', ');
111
+ lines.push(` ${c('\u2192', 'blue')} Add ${c(rec.platform, 'bold')} to cover: ${areas}`);
112
+ }
113
+ lines.push('');
114
+ }
115
+
116
+ // Patterns (if history available)
117
+ if (Array.isArray(harmonyHistory) && harmonyHistory.length > 0) {
118
+ const { patterns } = discoverPatterns(harmonyHistory);
119
+ if (patterns.length > 0) {
120
+ lines.push(c(' Discovered Patterns', 'bold'));
121
+ for (const pattern of patterns.slice(0, 4)) {
122
+ const icon = pattern.type === 'recurring-failure' ? c('\u2717', 'red')
123
+ : pattern.type === 'sequence-effect' ? c('\u2194', 'blue')
124
+ : pattern.type === 'diminishing-returns' ? c('\u2193', 'yellow')
125
+ : c('\u2022', 'dim');
126
+ lines.push(` ${icon} ${pattern.description}`);
127
+ }
128
+ lines.push('');
129
+ }
130
+ }
131
+
132
+ // Top ranked recommendations
133
+ if (Array.isArray(recommendations) && recommendations.length > 0) {
134
+ const ranked = rankRecommendations(recommendations, activePlatforms || []);
135
+ if (ranked.length > 0) {
136
+ lines.push(c(' Top Synergy Recommendations', 'bold'));
137
+ for (const rec of ranked.slice(0, 5)) {
138
+ const platforms = (rec.applicablePlatforms || []).join(', ') || rec.platform || '?';
139
+ lines.push(` ${c(rec.synergyScore.toFixed(1).padStart(5), 'green')} ${rec.name || rec.description || rec.key} ${c(`[${platforms}]`, 'dim')}`);
140
+ }
141
+ lines.push('');
142
+ }
143
+ }
144
+
145
+ // Verdict
146
+ lines.push(c(` Verdict: ${amplification.verdict.replace(/-/g, ' ')}`, 'bold'));
147
+ lines.push('');
148
+
149
+ return lines.join('\n');
150
+ }
151
+
152
+ /**
153
+ * Generate a full synergy report for a project directory.
154
+ * High-level entry point that runs compound audit + compensation + patterns.
155
+ *
156
+ * @param {Object} options - Same as formatSynergyReport options
157
+ * @returns {string} Formatted CLI report string
158
+ */
159
+ function generateSynergyReport(options) {
160
+ return formatSynergyReport(options);
161
+ }
162
+
163
+ module.exports = { generateSynergyReport, formatSynergyReport };