@nerviq/cli 1.20.1 → 1.21.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 (181) hide show
  1. package/LICENSE +23 -23
  2. package/README.md +2 -2
  3. package/package.json +1 -1
  4. package/src/activity.js +1039 -1039
  5. package/src/adoption-advisor.js +299 -299
  6. package/src/aider/config-parser.js +166 -166
  7. package/src/aider/context.js +4 -1
  8. package/src/aider/deep-review.js +316 -316
  9. package/src/aider/domain-packs.js +303 -303
  10. package/src/aider/freshness.js +93 -93
  11. package/src/aider/governance.js +253 -253
  12. package/src/aider/interactive.js +334 -334
  13. package/src/aider/mcp-packs.js +329 -329
  14. package/src/aider/patch.js +214 -214
  15. package/src/aider/plans.js +186 -186
  16. package/src/aider/premium.js +360 -360
  17. package/src/aider/setup.js +404 -404
  18. package/src/aider/techniques.js +312 -67
  19. package/src/analyze.js +951 -951
  20. package/src/anti-patterns.js +485 -485
  21. package/src/audit/instruction-files.js +180 -180
  22. package/src/audit/recommendations.js +577 -577
  23. package/src/auto-suggest.js +154 -154
  24. package/src/badge.js +13 -13
  25. package/src/behavioral-drift.js +801 -801
  26. package/src/benchmark.js +67 -67
  27. package/src/catalog.js +103 -103
  28. package/src/certification.js +128 -128
  29. package/src/codex/config-parser.js +183 -183
  30. package/src/codex/context.js +223 -223
  31. package/src/codex/deep-review.js +493 -493
  32. package/src/codex/domain-packs.js +394 -394
  33. package/src/codex/freshness.js +84 -84
  34. package/src/codex/governance.js +192 -192
  35. package/src/codex/interactive.js +618 -618
  36. package/src/codex/mcp-packs.js +914 -914
  37. package/src/codex/patch.js +209 -209
  38. package/src/codex/plans.js +251 -251
  39. package/src/codex/premium.js +614 -614
  40. package/src/codex/setup.js +591 -591
  41. package/src/continuous-ops.js +681 -681
  42. package/src/copilot/activity.js +309 -309
  43. package/src/copilot/deep-review.js +346 -346
  44. package/src/copilot/domain-packs.js +372 -372
  45. package/src/copilot/freshness.js +57 -57
  46. package/src/copilot/governance.js +222 -222
  47. package/src/copilot/interactive.js +406 -406
  48. package/src/copilot/mcp-packs.js +826 -826
  49. package/src/copilot/plans.js +253 -253
  50. package/src/copilot/premium.js +451 -451
  51. package/src/copilot/setup.js +488 -488
  52. package/src/cost-tracking.js +61 -61
  53. package/src/cursor/activity.js +301 -301
  54. package/src/cursor/config-parser.js +265 -265
  55. package/src/cursor/context.js +256 -256
  56. package/src/cursor/deep-review.js +334 -334
  57. package/src/cursor/domain-packs.js +368 -368
  58. package/src/cursor/freshness.js +65 -65
  59. package/src/cursor/governance.js +229 -229
  60. package/src/cursor/interactive.js +391 -391
  61. package/src/cursor/mcp-packs.js +828 -828
  62. package/src/cursor/plans.js +254 -254
  63. package/src/cursor/premium.js +469 -469
  64. package/src/cursor/setup.js +488 -488
  65. package/src/dashboard.js +493 -493
  66. package/src/deep-review.js +428 -428
  67. package/src/deprecation.js +98 -98
  68. package/src/diff-only.js +280 -280
  69. package/src/doctor.js +119 -119
  70. package/src/domain-pack-expansion.js +1033 -1033
  71. package/src/domain-packs.js +387 -387
  72. package/src/feedback.js +178 -178
  73. package/src/fix-engine.js +783 -783
  74. package/src/fix-prompts.js +122 -122
  75. package/src/formatters/sarif.js +115 -115
  76. package/src/freshness.js +74 -74
  77. package/src/gemini/config-parser.js +275 -275
  78. package/src/gemini/deep-review.js +559 -559
  79. package/src/gemini/domain-packs.js +393 -393
  80. package/src/gemini/freshness.js +66 -66
  81. package/src/gemini/governance.js +201 -201
  82. package/src/gemini/interactive.js +860 -860
  83. package/src/gemini/mcp-packs.js +915 -915
  84. package/src/gemini/plans.js +269 -269
  85. package/src/gemini/premium.js +760 -760
  86. package/src/gemini/setup.js +692 -692
  87. package/src/governance.js +72 -72
  88. package/src/harmony/add.js +68 -68
  89. package/src/harmony/advisor.js +333 -333
  90. package/src/harmony/canon.js +565 -565
  91. package/src/harmony/cli.js +591 -591
  92. package/src/harmony/drift.js +401 -401
  93. package/src/harmony/governance.js +313 -313
  94. package/src/harmony/memory.js +239 -239
  95. package/src/harmony/sync.js +475 -475
  96. package/src/harmony/watch.js +370 -370
  97. package/src/hook-validation.js +342 -342
  98. package/src/index.js +271 -271
  99. package/src/init.js +184 -184
  100. package/src/instruction-surfaces.js +185 -185
  101. package/src/integrations.js +144 -144
  102. package/src/interactive.js +118 -118
  103. package/src/locales/en.json +1 -1
  104. package/src/locales/es.json +1 -1
  105. package/src/mcp-packs.js +830 -830
  106. package/src/mcp-server.js +726 -726
  107. package/src/mcp-validation.js +337 -337
  108. package/src/nerviq-sync.json +7 -7
  109. package/src/opencode/config-parser.js +109 -109
  110. package/src/opencode/context.js +247 -247
  111. package/src/opencode/deep-review.js +313 -313
  112. package/src/opencode/domain-packs.js +262 -262
  113. package/src/opencode/freshness.js +66 -66
  114. package/src/opencode/governance.js +159 -159
  115. package/src/opencode/interactive.js +392 -392
  116. package/src/opencode/mcp-packs.js +705 -705
  117. package/src/opencode/patch.js +184 -184
  118. package/src/opencode/plans.js +231 -231
  119. package/src/opencode/premium.js +413 -413
  120. package/src/opencode/setup.js +449 -449
  121. package/src/opencode/techniques.js +27 -27
  122. package/src/operating-profile.js +574 -574
  123. package/src/org.js +152 -152
  124. package/src/permission-rules.js +218 -218
  125. package/src/plans.js +839 -839
  126. package/src/platform-change-manifest.js +86 -86
  127. package/src/plugins.js +110 -110
  128. package/src/policy-layers.js +210 -210
  129. package/src/profiles.js +124 -124
  130. package/src/prompt-injection.js +74 -74
  131. package/src/public-api.js +173 -173
  132. package/src/recommendation-rules.js +84 -84
  133. package/src/repo-archetype.js +386 -386
  134. package/src/secret-patterns.js +39 -39
  135. package/src/server.js +527 -527
  136. package/src/setup/analysis.js +607 -607
  137. package/src/setup/runtime.js +172 -172
  138. package/src/setup.js +677 -677
  139. package/src/shared/capabilities.js +194 -194
  140. package/src/source-urls.js +132 -132
  141. package/src/stack-checks.js +565 -565
  142. package/src/supplemental-checks.js +13 -13
  143. package/src/synergy/adaptive.js +261 -261
  144. package/src/synergy/compensation.js +137 -137
  145. package/src/synergy/evidence.js +193 -193
  146. package/src/synergy/learning.js +199 -199
  147. package/src/synergy/patterns.js +227 -227
  148. package/src/synergy/ranking.js +83 -83
  149. package/src/synergy/report.js +165 -165
  150. package/src/synergy/routing.js +146 -146
  151. package/src/techniques/api.js +407 -407
  152. package/src/techniques/automation.js +316 -316
  153. package/src/techniques/compliance.js +257 -257
  154. package/src/techniques/hygiene.js +294 -294
  155. package/src/techniques/instructions.js +243 -243
  156. package/src/techniques/observability.js +226 -226
  157. package/src/techniques/optimization.js +142 -142
  158. package/src/techniques/quality.js +318 -318
  159. package/src/techniques/security.js +237 -237
  160. package/src/techniques/shared.js +443 -443
  161. package/src/techniques/stacks.js +2294 -2294
  162. package/src/techniques/tools.js +106 -106
  163. package/src/techniques/workflow.js +413 -413
  164. package/src/techniques.js +81 -81
  165. package/src/terminology.js +73 -73
  166. package/src/token-estimate.js +35 -35
  167. package/src/usage-patterns.js +99 -99
  168. package/src/verification-metadata.js +145 -145
  169. package/src/watch.js +247 -247
  170. package/src/windsurf/activity.js +302 -302
  171. package/src/windsurf/config-parser.js +267 -267
  172. package/src/windsurf/deep-review.js +337 -337
  173. package/src/windsurf/domain-packs.js +370 -370
  174. package/src/windsurf/freshness.js +36 -36
  175. package/src/windsurf/governance.js +231 -231
  176. package/src/windsurf/interactive.js +388 -388
  177. package/src/windsurf/mcp-packs.js +792 -792
  178. package/src/windsurf/plans.js +247 -247
  179. package/src/windsurf/premium.js +468 -468
  180. package/src/windsurf/setup.js +471 -471
  181. package/src/workspace.js +375 -375
@@ -1,475 +1,475 @@
1
- /**
2
- * Harmony Sync — Unified Setup / Sync Engine
3
- *
4
- * Generates aligned configs for ALL active platforms from a shared canonical
5
- * understanding. Ensures instructions, MCP servers, and trust posture are
6
- * consistent across Claude, Codex, Gemini, Copilot, Cursor, Windsurf,
7
- * Aider, and OpenCode.
8
- *
9
- * Uses managed blocks from each platform's patch module so hand-authored
10
- * content is always preserved.
11
- */
12
-
13
- const fs = require('fs');
14
- const path = require('path');
15
- const { buildCanonicalModel, PLATFORM_SIGNATURES } = require('./canon');
16
-
17
- // ─── Managed block markers (imported from platform patch modules) ───────────
18
-
19
- const MANAGED_MARKERS = {
20
- claude: {
21
- start: '<!-- nerviq:managed:start -->',
22
- end: '<!-- nerviq:managed:end -->',
23
- },
24
- codex: {
25
- start: '<!-- nerviq:managed:start -->',
26
- end: '<!-- nerviq:managed:end -->',
27
- },
28
- gemini: {
29
- start: '<!-- nerviq:managed:start -->',
30
- end: '<!-- nerviq:managed:end -->',
31
- },
32
- copilot: {
33
- start: '<!-- nerviq:managed:start -->',
34
- end: '<!-- nerviq:managed:end -->',
35
- },
36
- cursor: {
37
- // Cursor uses MDC format but managed blocks are still HTML-comment-based for .mdc
38
- start: '<!-- nerviq:managed:start -->',
39
- end: '<!-- nerviq:managed:end -->',
40
- },
41
- windsurf: {
42
- start: '<!-- nerviq:managed:start -->',
43
- end: '<!-- nerviq:managed:end -->',
44
- },
45
- // aider: uses .aider.conf.yml (YAML) — managed HTML-comment blocks not supported
46
- // opencode: uses opencode.json (JSON) — managed HTML-comment blocks not supported
47
- };
48
-
49
- // ─── Helpers ────────────────────────────────────────────────────────────────
50
-
51
- function safeReadFile(filePath) {
52
- try {
53
- return fs.readFileSync(filePath, 'utf8');
54
- } catch {
55
- return null;
56
- }
57
- }
58
-
59
- function ensureDir(dirPath) {
60
- try {
61
- fs.mkdirSync(dirPath, { recursive: true });
62
- } catch {
63
- // Already exists or not writable
64
- }
65
- }
66
-
67
- /**
68
- * Extract managed block from content.
69
- */
70
- function extractManagedBlock(content, startMarker, endMarker) {
71
- const startIdx = content.indexOf(startMarker);
72
- const endIdx = content.indexOf(endMarker);
73
-
74
- if (startIdx === -1 || endIdx === -1 || endIdx <= startIdx) {
75
- return { before: content, managed: null, after: '' };
76
- }
77
-
78
- return {
79
- before: content.substring(0, startIdx),
80
- managed: content.substring(startIdx + startMarker.length, endIdx).trim(),
81
- after: content.substring(endIdx + endMarker.length),
82
- };
83
- }
84
-
85
- /**
86
- * Upsert a managed block within content.
87
- */
88
- function upsertManagedBlock(content, newManaged, startMarker, endMarker) {
89
- const { before, managed, after } = extractManagedBlock(content, startMarker, endMarker);
90
-
91
- if (managed !== null) {
92
- return `${before}${startMarker}\n${newManaged}\n${endMarker}${after}`;
93
- }
94
-
95
- const separator = content.endsWith('\n') ? '\n' : '\n\n';
96
- return `${content}${separator}${startMarker}\n${newManaged}\n${endMarker}\n`;
97
- }
98
-
99
- // ─── Instruction content builders ───────────────────────────────────────────
100
-
101
- /**
102
- * Build a shared instruction block that should appear on every platform.
103
- * Derived from the canonical model's shared understanding.
104
- */
105
- function buildSharedInstructionBlock(model) {
106
- const lines = [];
107
-
108
- lines.push(`## Harmony-Managed Instructions`);
109
- lines.push(`<!-- Synced by nerviq harmony. Do not edit this block manually. -->`);
110
- lines.push('');
111
-
112
- // Project identity
113
- lines.push(`Project: ${model.projectName}`);
114
- if (model.stacks.length > 0) {
115
- lines.push(`Stacks: ${model.stacks.join(', ')}`);
116
- }
117
- lines.push('');
118
-
119
- // Shared instructions (if any were found across platforms)
120
- if (model.sharedInstructions.length > 0) {
121
- lines.push('### Shared Guidelines');
122
- for (const instruction of model.sharedInstructions.slice(0, 20)) {
123
- lines.push(instruction);
124
- }
125
- lines.push('');
126
- }
127
-
128
- // MCP servers (unified list)
129
- const mcpNames = Object.keys(model.mcpServers);
130
- if (mcpNames.length > 0) {
131
- lines.push('### Available MCP Servers');
132
- for (const name of mcpNames) {
133
- const server = model.mcpServers[name];
134
- lines.push(`- ${name} (on: ${server.platforms.join(', ')})`);
135
- }
136
- lines.push('');
137
- }
138
-
139
- return lines.join('\n');
140
- }
141
-
142
- // ─── Platform-specific file generators ──────────────────────────────────────
143
-
144
- /**
145
- * Generate the instruction file path for a platform.
146
- */
147
- function getInstructionPath(platform) {
148
- switch (platform) {
149
- case 'claude': return 'CLAUDE.md';
150
- case 'codex': return 'AGENTS.md';
151
- case 'gemini': return 'GEMINI.md';
152
- case 'copilot': return '.github/copilot-instructions.md';
153
- case 'cursor': return '.cursorrules';
154
- case 'windsurf': return '.windsurfrules';
155
- // aider: .aider.conf.yml is YAML config — no managed block support, skip instruction sync
156
- // opencode: opencode.json is JSON config — no managed block support, skip instruction sync
157
- default: return null;
158
- }
159
- }
160
-
161
- /**
162
- * Generate MCP config content for a platform based on the unified MCP server list.
163
- */
164
- function buildMcpConfig(platform, mcpServers) {
165
- // Filter to servers that should be on this platform
166
- const servers = {};
167
- for (const [name, server] of Object.entries(mcpServers)) {
168
- servers[name] = {
169
- command: server.command || 'npx',
170
- args: server.args || [],
171
- };
172
- }
173
-
174
- if (Object.keys(servers).length === 0) return null;
175
-
176
- if (platform === 'claude') {
177
- // Claude settings.json format
178
- return { mcpServers: servers };
179
- }
180
-
181
- if (platform === 'cursor' || platform === 'copilot') {
182
- // mcp.json format
183
- return { mcpServers: servers };
184
- }
185
-
186
- if (platform === 'gemini') {
187
- // Gemini settings.json format
188
- return { mcpServers: servers };
189
- }
190
-
191
- if (platform === 'windsurf') {
192
- // Windsurf mcp.json format
193
- return { mcpServers: servers };
194
- }
195
-
196
- return null;
197
- }
198
-
199
- /**
200
- * Get the MCP config file path for a platform.
201
- */
202
- function getMcpConfigPath(platform) {
203
- switch (platform) {
204
- case 'claude': return '.claude/settings.json';
205
- case 'gemini': return '.gemini/settings.json';
206
- case 'copilot': return '.vscode/mcp.json';
207
- case 'cursor': return '.cursor/mcp.json';
208
- case 'windsurf': return '.windsurf/mcp.json';
209
- // aider & opencode: no MCP config support
210
- default: return null;
211
- }
212
- }
213
-
214
- // ─── Trust alignment recommendations ────────────────────────────────────────
215
-
216
- /**
217
- * Recommend a unified trust posture across all platforms.
218
- * Strategy: use the most restrictive trust level present.
219
- */
220
- function recommendTrustPosture(model) {
221
- const TRUST_LEVELS = {
222
- 'locked-down': 0,
223
- 'default': 1,
224
- 'unknown': 1,
225
- 'safe-write': 2,
226
- 'standard': 2,
227
- 'no-sandbox': 3,
228
- 'full-auto': 4,
229
- 'bypass': 4,
230
- 'unrestricted': 5,
231
- };
232
-
233
- const postures = Object.values(model.trustPosture);
234
- if (postures.length === 0) return 'safe-write';
235
-
236
- // Find the most restrictive (lowest) trust level
237
- let minLevel = Infinity;
238
- let minPosture = 'default';
239
- for (const posture of postures) {
240
- const level = TRUST_LEVELS[posture] ?? 1;
241
- if (level < minLevel) {
242
- minLevel = level;
243
- minPosture = posture;
244
- }
245
- }
246
-
247
- return minPosture;
248
- }
249
-
250
- // ─── Main sync functions ────────────────────────────────────────────────────
251
-
252
- /**
253
- * Generate harmony sync operations from a canonical model.
254
- *
255
- * For each active platform:
256
- * - Generate/update instruction file with shared managed block
257
- * - Ensure shared MCP servers exist on all platforms that support MCP
258
- * - Report trust posture alignment recommendations
259
- *
260
- * @param {object} canonicalModel - Output of buildCanonicalModel()
261
- * @param {object} [options] - { syncMcp: true, syncInstructions: true, dryRun: false }
262
- * @returns {object} { files, summary, warnings }
263
- */
264
- function generateHarmonySync(canonicalModel, options = {}) {
265
- const {
266
- syncMcp = true,
267
- syncInstructions = true,
268
- } = options;
269
-
270
- const model = canonicalModel;
271
- const files = [];
272
- const warnings = [];
273
-
274
- const sharedBlock = buildSharedInstructionBlock(model);
275
- const recommendedTrust = recommendTrustPosture(model);
276
-
277
- for (const ap of model.activePlatforms) {
278
- const platform = ap.platform;
279
-
280
- // ── Instruction file sync ──
281
- if (syncInstructions) {
282
- const instrPath = getInstructionPath(platform);
283
- if (instrPath) {
284
- const fullPath = path.join(model.dir, instrPath);
285
- const existingContent = safeReadFile(fullPath);
286
- const markers = MANAGED_MARKERS[platform];
287
-
288
- if (existingContent) {
289
- // Patch existing file with managed block
290
- const updated = upsertManagedBlock(
291
- existingContent,
292
- sharedBlock,
293
- markers.start,
294
- markers.end,
295
- );
296
-
297
- if (updated !== existingContent) {
298
- files.push({
299
- platform,
300
- path: instrPath,
301
- action: 'patch',
302
- content: updated,
303
- preview: `Update managed block in ${instrPath}`,
304
- });
305
- }
306
- } else {
307
- // Create new instruction file with managed block
308
- const newContent = `# ${platform === 'codex' ? 'AGENTS' : platform.charAt(0).toUpperCase() + platform.slice(1)} Instructions\n\n` +
309
- `${markers.start}\n${sharedBlock}\n${markers.end}\n`;
310
-
311
- files.push({
312
- platform,
313
- path: instrPath,
314
- action: 'create',
315
- content: newContent,
316
- preview: `Create ${instrPath} with harmony-managed content`,
317
- });
318
- }
319
- }
320
- }
321
-
322
- // ── MCP server sync ──
323
- if (syncMcp && Object.keys(model.mcpServers).length > 0) {
324
- const mcpPath = getMcpConfigPath(platform);
325
- if (!mcpPath) continue; // Codex doesn't support MCP config
326
-
327
- const fullMcpPath = path.join(model.dir, mcpPath);
328
- const existingMcp = safeReadFile(fullMcpPath);
329
- const mcpConfig = buildMcpConfig(platform, model.mcpServers);
330
-
331
- if (!mcpConfig) continue;
332
-
333
- if (existingMcp) {
334
- // Merge: add missing servers, don't overwrite existing
335
- let existingJson;
336
- try {
337
- existingJson = JSON.parse(existingMcp);
338
- } catch {
339
- warnings.push(`Cannot parse ${mcpPath} — skipping MCP sync for ${platform}`);
340
- continue;
341
- }
342
-
343
- const existingServers = existingJson.mcpServers || existingJson.servers || {};
344
- const newServers = mcpConfig.mcpServers || {};
345
- let added = 0;
346
-
347
- for (const [name, config] of Object.entries(newServers)) {
348
- if (!existingServers[name]) {
349
- existingServers[name] = config;
350
- added++;
351
- }
352
- }
353
-
354
- if (added > 0) {
355
- // Preserve the original key name (mcpServers or servers)
356
- const serverKey = existingJson.servers ? 'servers' : 'mcpServers';
357
- existingJson[serverKey] = existingServers;
358
-
359
- files.push({
360
- platform,
361
- path: mcpPath,
362
- action: 'patch',
363
- content: JSON.stringify(existingJson, null, 2) + '\n',
364
- preview: `Add ${added} MCP server(s) to ${mcpPath}`,
365
- });
366
- }
367
- } else {
368
- // Create new MCP config
369
- files.push({
370
- platform,
371
- path: mcpPath,
372
- action: 'create',
373
- content: JSON.stringify(mcpConfig, null, 2) + '\n',
374
- preview: `Create ${mcpPath} with ${Object.keys(mcpConfig.mcpServers || {}).length} MCP server(s)`,
375
- });
376
- }
377
- }
378
- }
379
-
380
- // Trust posture warnings
381
- const trustValues = Object.values(model.trustPosture);
382
- const uniqueTrust = new Set(trustValues);
383
- if (uniqueTrust.size > 1) {
384
- warnings.push(
385
- `Trust posture varies across platforms. Recommended baseline: "${recommendedTrust}". ` +
386
- `Current: ${Object.entries(model.trustPosture).map(([p, t]) => `${p}=${t}`).join(', ')}. ` +
387
- `Trust alignment must be applied manually per platform.`
388
- );
389
- }
390
-
391
- // Summary
392
- const creates = files.filter(f => f.action === 'create').length;
393
- const patches = files.filter(f => f.action === 'patch').length;
394
- const summary = {
395
- totalFiles: files.length,
396
- creates,
397
- patches,
398
- platforms: [...new Set(files.map(f => f.platform))],
399
- recommendedTrust,
400
- };
401
-
402
- return { files, summary, warnings };
403
- }
404
-
405
- /**
406
- * Preview sync operations without writing.
407
- *
408
- * @param {string} dir - Project root directory
409
- * @param {object} [options] - Same as generateHarmonySync options
410
- * @returns {object} Sync plan (files, summary, warnings)
411
- */
412
- function previewHarmonySync(dir, options = {}) {
413
- const model = buildCanonicalModel(dir);
414
- return generateHarmonySync(model, options);
415
- }
416
-
417
- /**
418
- * Apply harmony sync — write all generated files to disk.
419
- *
420
- * @param {string} dir - Project root directory
421
- * @param {object} [options] - { syncMcp, syncInstructions, dryRun }
422
- * @returns {object} { applied, skipped, warnings }
423
- */
424
- function applyHarmonySync(dir, options = {}) {
425
- const { dryRun = false } = options;
426
- const model = buildCanonicalModel(dir);
427
- const sync = generateHarmonySync(model, options);
428
-
429
- if (dryRun) {
430
- return {
431
- applied: [],
432
- skipped: sync.files.map(f => f.path),
433
- warnings: sync.warnings,
434
- plan: sync,
435
- };
436
- }
437
-
438
- const applied = [];
439
- const skipped = [];
440
-
441
- for (const file of sync.files) {
442
- const fullPath = path.join(dir, file.path);
443
-
444
- try {
445
- // Ensure parent directory exists
446
- ensureDir(path.dirname(fullPath));
447
-
448
- fs.writeFileSync(fullPath, file.content, 'utf8');
449
- applied.push({
450
- platform: file.platform,
451
- path: file.path,
452
- action: file.action,
453
- });
454
- } catch (err) {
455
- skipped.push({
456
- platform: file.platform,
457
- path: file.path,
458
- reason: err.message,
459
- });
460
- }
461
- }
462
-
463
- return {
464
- applied,
465
- skipped,
466
- warnings: sync.warnings,
467
- summary: sync.summary,
468
- };
469
- }
470
-
471
- module.exports = {
472
- generateHarmonySync,
473
- applyHarmonySync,
474
- previewHarmonySync,
475
- };
1
+ /**
2
+ * Harmony Sync — Unified Setup / Sync Engine
3
+ *
4
+ * Generates aligned configs for ALL active platforms from a shared canonical
5
+ * understanding. Ensures instructions, MCP servers, and trust posture are
6
+ * consistent across Claude, Codex, Gemini, Copilot, Cursor, Windsurf,
7
+ * Aider, and OpenCode.
8
+ *
9
+ * Uses managed blocks from each platform's patch module so hand-authored
10
+ * content is always preserved.
11
+ */
12
+
13
+ const fs = require('fs');
14
+ const path = require('path');
15
+ const { buildCanonicalModel, PLATFORM_SIGNATURES } = require('./canon');
16
+
17
+ // ─── Managed block markers (imported from platform patch modules) ───────────
18
+
19
+ const MANAGED_MARKERS = {
20
+ claude: {
21
+ start: '<!-- nerviq:managed:start -->',
22
+ end: '<!-- nerviq:managed:end -->',
23
+ },
24
+ codex: {
25
+ start: '<!-- nerviq:managed:start -->',
26
+ end: '<!-- nerviq:managed:end -->',
27
+ },
28
+ gemini: {
29
+ start: '<!-- nerviq:managed:start -->',
30
+ end: '<!-- nerviq:managed:end -->',
31
+ },
32
+ copilot: {
33
+ start: '<!-- nerviq:managed:start -->',
34
+ end: '<!-- nerviq:managed:end -->',
35
+ },
36
+ cursor: {
37
+ // Cursor uses MDC format but managed blocks are still HTML-comment-based for .mdc
38
+ start: '<!-- nerviq:managed:start -->',
39
+ end: '<!-- nerviq:managed:end -->',
40
+ },
41
+ windsurf: {
42
+ start: '<!-- nerviq:managed:start -->',
43
+ end: '<!-- nerviq:managed:end -->',
44
+ },
45
+ // aider: uses .aider.conf.yml (YAML) — managed HTML-comment blocks not supported
46
+ // opencode: uses opencode.json (JSON) — managed HTML-comment blocks not supported
47
+ };
48
+
49
+ // ─── Helpers ────────────────────────────────────────────────────────────────
50
+
51
+ function safeReadFile(filePath) {
52
+ try {
53
+ return fs.readFileSync(filePath, 'utf8');
54
+ } catch {
55
+ return null;
56
+ }
57
+ }
58
+
59
+ function ensureDir(dirPath) {
60
+ try {
61
+ fs.mkdirSync(dirPath, { recursive: true });
62
+ } catch {
63
+ // Already exists or not writable
64
+ }
65
+ }
66
+
67
+ /**
68
+ * Extract managed block from content.
69
+ */
70
+ function extractManagedBlock(content, startMarker, endMarker) {
71
+ const startIdx = content.indexOf(startMarker);
72
+ const endIdx = content.indexOf(endMarker);
73
+
74
+ if (startIdx === -1 || endIdx === -1 || endIdx <= startIdx) {
75
+ return { before: content, managed: null, after: '' };
76
+ }
77
+
78
+ return {
79
+ before: content.substring(0, startIdx),
80
+ managed: content.substring(startIdx + startMarker.length, endIdx).trim(),
81
+ after: content.substring(endIdx + endMarker.length),
82
+ };
83
+ }
84
+
85
+ /**
86
+ * Upsert a managed block within content.
87
+ */
88
+ function upsertManagedBlock(content, newManaged, startMarker, endMarker) {
89
+ const { before, managed, after } = extractManagedBlock(content, startMarker, endMarker);
90
+
91
+ if (managed !== null) {
92
+ return `${before}${startMarker}\n${newManaged}\n${endMarker}${after}`;
93
+ }
94
+
95
+ const separator = content.endsWith('\n') ? '\n' : '\n\n';
96
+ return `${content}${separator}${startMarker}\n${newManaged}\n${endMarker}\n`;
97
+ }
98
+
99
+ // ─── Instruction content builders ───────────────────────────────────────────
100
+
101
+ /**
102
+ * Build a shared instruction block that should appear on every platform.
103
+ * Derived from the canonical model's shared understanding.
104
+ */
105
+ function buildSharedInstructionBlock(model) {
106
+ const lines = [];
107
+
108
+ lines.push(`## Harmony-Managed Instructions`);
109
+ lines.push(`<!-- Synced by nerviq harmony. Do not edit this block manually. -->`);
110
+ lines.push('');
111
+
112
+ // Project identity
113
+ lines.push(`Project: ${model.projectName}`);
114
+ if (model.stacks.length > 0) {
115
+ lines.push(`Stacks: ${model.stacks.join(', ')}`);
116
+ }
117
+ lines.push('');
118
+
119
+ // Shared instructions (if any were found across platforms)
120
+ if (model.sharedInstructions.length > 0) {
121
+ lines.push('### Shared Guidelines');
122
+ for (const instruction of model.sharedInstructions.slice(0, 20)) {
123
+ lines.push(instruction);
124
+ }
125
+ lines.push('');
126
+ }
127
+
128
+ // MCP servers (unified list)
129
+ const mcpNames = Object.keys(model.mcpServers);
130
+ if (mcpNames.length > 0) {
131
+ lines.push('### Available MCP Servers');
132
+ for (const name of mcpNames) {
133
+ const server = model.mcpServers[name];
134
+ lines.push(`- ${name} (on: ${server.platforms.join(', ')})`);
135
+ }
136
+ lines.push('');
137
+ }
138
+
139
+ return lines.join('\n');
140
+ }
141
+
142
+ // ─── Platform-specific file generators ──────────────────────────────────────
143
+
144
+ /**
145
+ * Generate the instruction file path for a platform.
146
+ */
147
+ function getInstructionPath(platform) {
148
+ switch (platform) {
149
+ case 'claude': return 'CLAUDE.md';
150
+ case 'codex': return 'AGENTS.md';
151
+ case 'gemini': return 'GEMINI.md';
152
+ case 'copilot': return '.github/copilot-instructions.md';
153
+ case 'cursor': return '.cursorrules';
154
+ case 'windsurf': return '.windsurfrules';
155
+ // aider: .aider.conf.yml is YAML config — no managed block support, skip instruction sync
156
+ // opencode: opencode.json is JSON config — no managed block support, skip instruction sync
157
+ default: return null;
158
+ }
159
+ }
160
+
161
+ /**
162
+ * Generate MCP config content for a platform based on the unified MCP server list.
163
+ */
164
+ function buildMcpConfig(platform, mcpServers) {
165
+ // Filter to servers that should be on this platform
166
+ const servers = {};
167
+ for (const [name, server] of Object.entries(mcpServers)) {
168
+ servers[name] = {
169
+ command: server.command || 'npx',
170
+ args: server.args || [],
171
+ };
172
+ }
173
+
174
+ if (Object.keys(servers).length === 0) return null;
175
+
176
+ if (platform === 'claude') {
177
+ // Claude settings.json format
178
+ return { mcpServers: servers };
179
+ }
180
+
181
+ if (platform === 'cursor' || platform === 'copilot') {
182
+ // mcp.json format
183
+ return { mcpServers: servers };
184
+ }
185
+
186
+ if (platform === 'gemini') {
187
+ // Gemini settings.json format
188
+ return { mcpServers: servers };
189
+ }
190
+
191
+ if (platform === 'windsurf') {
192
+ // Windsurf mcp.json format
193
+ return { mcpServers: servers };
194
+ }
195
+
196
+ return null;
197
+ }
198
+
199
+ /**
200
+ * Get the MCP config file path for a platform.
201
+ */
202
+ function getMcpConfigPath(platform) {
203
+ switch (platform) {
204
+ case 'claude': return '.claude/settings.json';
205
+ case 'gemini': return '.gemini/settings.json';
206
+ case 'copilot': return '.vscode/mcp.json';
207
+ case 'cursor': return '.cursor/mcp.json';
208
+ case 'windsurf': return '.windsurf/mcp.json';
209
+ // aider & opencode: no MCP config support
210
+ default: return null;
211
+ }
212
+ }
213
+
214
+ // ─── Trust alignment recommendations ────────────────────────────────────────
215
+
216
+ /**
217
+ * Recommend a unified trust posture across all platforms.
218
+ * Strategy: use the most restrictive trust level present.
219
+ */
220
+ function recommendTrustPosture(model) {
221
+ const TRUST_LEVELS = {
222
+ 'locked-down': 0,
223
+ 'default': 1,
224
+ 'unknown': 1,
225
+ 'safe-write': 2,
226
+ 'standard': 2,
227
+ 'no-sandbox': 3,
228
+ 'full-auto': 4,
229
+ 'bypass': 4,
230
+ 'unrestricted': 5,
231
+ };
232
+
233
+ const postures = Object.values(model.trustPosture);
234
+ if (postures.length === 0) return 'safe-write';
235
+
236
+ // Find the most restrictive (lowest) trust level
237
+ let minLevel = Infinity;
238
+ let minPosture = 'default';
239
+ for (const posture of postures) {
240
+ const level = TRUST_LEVELS[posture] ?? 1;
241
+ if (level < minLevel) {
242
+ minLevel = level;
243
+ minPosture = posture;
244
+ }
245
+ }
246
+
247
+ return minPosture;
248
+ }
249
+
250
+ // ─── Main sync functions ────────────────────────────────────────────────────
251
+
252
+ /**
253
+ * Generate harmony sync operations from a canonical model.
254
+ *
255
+ * For each active platform:
256
+ * - Generate/update instruction file with shared managed block
257
+ * - Ensure shared MCP servers exist on all platforms that support MCP
258
+ * - Report trust posture alignment recommendations
259
+ *
260
+ * @param {object} canonicalModel - Output of buildCanonicalModel()
261
+ * @param {object} [options] - { syncMcp: true, syncInstructions: true, dryRun: false }
262
+ * @returns {object} { files, summary, warnings }
263
+ */
264
+ function generateHarmonySync(canonicalModel, options = {}) {
265
+ const {
266
+ syncMcp = true,
267
+ syncInstructions = true,
268
+ } = options;
269
+
270
+ const model = canonicalModel;
271
+ const files = [];
272
+ const warnings = [];
273
+
274
+ const sharedBlock = buildSharedInstructionBlock(model);
275
+ const recommendedTrust = recommendTrustPosture(model);
276
+
277
+ for (const ap of model.activePlatforms) {
278
+ const platform = ap.platform;
279
+
280
+ // ── Instruction file sync ──
281
+ if (syncInstructions) {
282
+ const instrPath = getInstructionPath(platform);
283
+ if (instrPath) {
284
+ const fullPath = path.join(model.dir, instrPath);
285
+ const existingContent = safeReadFile(fullPath);
286
+ const markers = MANAGED_MARKERS[platform];
287
+
288
+ if (existingContent) {
289
+ // Patch existing file with managed block
290
+ const updated = upsertManagedBlock(
291
+ existingContent,
292
+ sharedBlock,
293
+ markers.start,
294
+ markers.end,
295
+ );
296
+
297
+ if (updated !== existingContent) {
298
+ files.push({
299
+ platform,
300
+ path: instrPath,
301
+ action: 'patch',
302
+ content: updated,
303
+ preview: `Update managed block in ${instrPath}`,
304
+ });
305
+ }
306
+ } else {
307
+ // Create new instruction file with managed block
308
+ const newContent = `# ${platform === 'codex' ? 'AGENTS' : platform.charAt(0).toUpperCase() + platform.slice(1)} Instructions\n\n` +
309
+ `${markers.start}\n${sharedBlock}\n${markers.end}\n`;
310
+
311
+ files.push({
312
+ platform,
313
+ path: instrPath,
314
+ action: 'create',
315
+ content: newContent,
316
+ preview: `Create ${instrPath} with harmony-managed content`,
317
+ });
318
+ }
319
+ }
320
+ }
321
+
322
+ // ── MCP server sync ──
323
+ if (syncMcp && Object.keys(model.mcpServers).length > 0) {
324
+ const mcpPath = getMcpConfigPath(platform);
325
+ if (!mcpPath) continue; // Codex doesn't support MCP config
326
+
327
+ const fullMcpPath = path.join(model.dir, mcpPath);
328
+ const existingMcp = safeReadFile(fullMcpPath);
329
+ const mcpConfig = buildMcpConfig(platform, model.mcpServers);
330
+
331
+ if (!mcpConfig) continue;
332
+
333
+ if (existingMcp) {
334
+ // Merge: add missing servers, don't overwrite existing
335
+ let existingJson;
336
+ try {
337
+ existingJson = JSON.parse(existingMcp);
338
+ } catch {
339
+ warnings.push(`Cannot parse ${mcpPath} — skipping MCP sync for ${platform}`);
340
+ continue;
341
+ }
342
+
343
+ const existingServers = existingJson.mcpServers || existingJson.servers || {};
344
+ const newServers = mcpConfig.mcpServers || {};
345
+ let added = 0;
346
+
347
+ for (const [name, config] of Object.entries(newServers)) {
348
+ if (!existingServers[name]) {
349
+ existingServers[name] = config;
350
+ added++;
351
+ }
352
+ }
353
+
354
+ if (added > 0) {
355
+ // Preserve the original key name (mcpServers or servers)
356
+ const serverKey = existingJson.servers ? 'servers' : 'mcpServers';
357
+ existingJson[serverKey] = existingServers;
358
+
359
+ files.push({
360
+ platform,
361
+ path: mcpPath,
362
+ action: 'patch',
363
+ content: JSON.stringify(existingJson, null, 2) + '\n',
364
+ preview: `Add ${added} MCP server(s) to ${mcpPath}`,
365
+ });
366
+ }
367
+ } else {
368
+ // Create new MCP config
369
+ files.push({
370
+ platform,
371
+ path: mcpPath,
372
+ action: 'create',
373
+ content: JSON.stringify(mcpConfig, null, 2) + '\n',
374
+ preview: `Create ${mcpPath} with ${Object.keys(mcpConfig.mcpServers || {}).length} MCP server(s)`,
375
+ });
376
+ }
377
+ }
378
+ }
379
+
380
+ // Trust posture warnings
381
+ const trustValues = Object.values(model.trustPosture);
382
+ const uniqueTrust = new Set(trustValues);
383
+ if (uniqueTrust.size > 1) {
384
+ warnings.push(
385
+ `Trust posture varies across platforms. Recommended baseline: "${recommendedTrust}". ` +
386
+ `Current: ${Object.entries(model.trustPosture).map(([p, t]) => `${p}=${t}`).join(', ')}. ` +
387
+ `Trust alignment must be applied manually per platform.`
388
+ );
389
+ }
390
+
391
+ // Summary
392
+ const creates = files.filter(f => f.action === 'create').length;
393
+ const patches = files.filter(f => f.action === 'patch').length;
394
+ const summary = {
395
+ totalFiles: files.length,
396
+ creates,
397
+ patches,
398
+ platforms: [...new Set(files.map(f => f.platform))],
399
+ recommendedTrust,
400
+ };
401
+
402
+ return { files, summary, warnings };
403
+ }
404
+
405
+ /**
406
+ * Preview sync operations without writing.
407
+ *
408
+ * @param {string} dir - Project root directory
409
+ * @param {object} [options] - Same as generateHarmonySync options
410
+ * @returns {object} Sync plan (files, summary, warnings)
411
+ */
412
+ function previewHarmonySync(dir, options = {}) {
413
+ const model = buildCanonicalModel(dir);
414
+ return generateHarmonySync(model, options);
415
+ }
416
+
417
+ /**
418
+ * Apply harmony sync — write all generated files to disk.
419
+ *
420
+ * @param {string} dir - Project root directory
421
+ * @param {object} [options] - { syncMcp, syncInstructions, dryRun }
422
+ * @returns {object} { applied, skipped, warnings }
423
+ */
424
+ function applyHarmonySync(dir, options = {}) {
425
+ const { dryRun = false } = options;
426
+ const model = buildCanonicalModel(dir);
427
+ const sync = generateHarmonySync(model, options);
428
+
429
+ if (dryRun) {
430
+ return {
431
+ applied: [],
432
+ skipped: sync.files.map(f => f.path),
433
+ warnings: sync.warnings,
434
+ plan: sync,
435
+ };
436
+ }
437
+
438
+ const applied = [];
439
+ const skipped = [];
440
+
441
+ for (const file of sync.files) {
442
+ const fullPath = path.join(dir, file.path);
443
+
444
+ try {
445
+ // Ensure parent directory exists
446
+ ensureDir(path.dirname(fullPath));
447
+
448
+ fs.writeFileSync(fullPath, file.content, 'utf8');
449
+ applied.push({
450
+ platform: file.platform,
451
+ path: file.path,
452
+ action: file.action,
453
+ });
454
+ } catch (err) {
455
+ skipped.push({
456
+ platform: file.platform,
457
+ path: file.path,
458
+ reason: err.message,
459
+ });
460
+ }
461
+ }
462
+
463
+ return {
464
+ applied,
465
+ skipped,
466
+ warnings: sync.warnings,
467
+ summary: sync.summary,
468
+ };
469
+ }
470
+
471
+ module.exports = {
472
+ generateHarmonySync,
473
+ applyHarmonySync,
474
+ previewHarmonySync,
475
+ };