@nerviq/cli 1.18.0 → 1.19.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 (187) hide show
  1. package/LICENSE +23 -23
  2. package/README.md +2 -2
  3. package/bin/cli.js +130 -130
  4. package/package.json +1 -1
  5. package/src/activity.js +1039 -1039
  6. package/src/adoption-advisor.js +299 -299
  7. package/src/aider/config-parser.js +166 -166
  8. package/src/aider/context.js +158 -158
  9. package/src/aider/deep-review.js +316 -316
  10. package/src/aider/domain-packs.js +303 -303
  11. package/src/aider/freshness.js +93 -93
  12. package/src/aider/governance.js +253 -253
  13. package/src/aider/interactive.js +334 -334
  14. package/src/aider/mcp-packs.js +329 -329
  15. package/src/aider/patch.js +214 -214
  16. package/src/aider/plans.js +186 -186
  17. package/src/aider/premium.js +360 -360
  18. package/src/aider/setup.js +404 -404
  19. package/src/aider/techniques.js +16 -16
  20. package/src/analyze.js +951 -951
  21. package/src/anti-patterns.js +485 -485
  22. package/src/audit/instruction-files.js +180 -180
  23. package/src/audit/recommendations.js +577 -577
  24. package/src/auto-suggest.js +154 -154
  25. package/src/badge.js +13 -13
  26. package/src/behavioral-drift.js +801 -801
  27. package/src/benchmark.js +67 -67
  28. package/src/catalog.js +103 -103
  29. package/src/certification.js +128 -128
  30. package/src/codex/config-parser.js +183 -183
  31. package/src/codex/context.js +223 -223
  32. package/src/codex/deep-review.js +493 -493
  33. package/src/codex/domain-packs.js +394 -394
  34. package/src/codex/freshness.js +84 -84
  35. package/src/codex/governance.js +192 -192
  36. package/src/codex/interactive.js +618 -618
  37. package/src/codex/mcp-packs.js +914 -914
  38. package/src/codex/patch.js +209 -209
  39. package/src/codex/plans.js +251 -251
  40. package/src/codex/premium.js +614 -614
  41. package/src/codex/setup.js +591 -591
  42. package/src/context.js +320 -320
  43. package/src/continuous-ops.js +681 -681
  44. package/src/copilot/activity.js +309 -309
  45. package/src/copilot/deep-review.js +346 -346
  46. package/src/copilot/domain-packs.js +372 -372
  47. package/src/copilot/freshness.js +57 -57
  48. package/src/copilot/governance.js +222 -222
  49. package/src/copilot/interactive.js +406 -406
  50. package/src/copilot/mcp-packs.js +826 -826
  51. package/src/copilot/plans.js +253 -253
  52. package/src/copilot/premium.js +451 -451
  53. package/src/copilot/setup.js +488 -488
  54. package/src/cost-tracking.js +61 -61
  55. package/src/cursor/activity.js +301 -301
  56. package/src/cursor/config-parser.js +265 -265
  57. package/src/cursor/context.js +256 -256
  58. package/src/cursor/deep-review.js +334 -334
  59. package/src/cursor/domain-packs.js +368 -368
  60. package/src/cursor/freshness.js +65 -65
  61. package/src/cursor/governance.js +229 -229
  62. package/src/cursor/interactive.js +391 -391
  63. package/src/cursor/mcp-packs.js +828 -828
  64. package/src/cursor/plans.js +254 -254
  65. package/src/cursor/premium.js +469 -469
  66. package/src/cursor/setup.js +488 -488
  67. package/src/dashboard.js +493 -493
  68. package/src/deep-review.js +428 -428
  69. package/src/deprecation.js +98 -98
  70. package/src/diff-only.js +280 -280
  71. package/src/doctor.js +119 -119
  72. package/src/domain-pack-expansion.js +1033 -1033
  73. package/src/domain-packs.js +387 -387
  74. package/src/feedback.js +178 -178
  75. package/src/fix-engine.js +783 -783
  76. package/src/fix-prompts.js +122 -122
  77. package/src/formatters/sarif.js +115 -115
  78. package/src/freshness.js +74 -74
  79. package/src/gemini/config-parser.js +275 -275
  80. package/src/gemini/context.js +221 -221
  81. package/src/gemini/deep-review.js +559 -559
  82. package/src/gemini/domain-packs.js +393 -393
  83. package/src/gemini/freshness.js +66 -66
  84. package/src/gemini/governance.js +201 -201
  85. package/src/gemini/interactive.js +860 -860
  86. package/src/gemini/mcp-packs.js +915 -915
  87. package/src/gemini/plans.js +269 -269
  88. package/src/gemini/premium.js +760 -760
  89. package/src/gemini/setup.js +692 -692
  90. package/src/gemini/techniques.js +14 -14
  91. package/src/governance.js +72 -72
  92. package/src/harmony/add.js +68 -68
  93. package/src/harmony/advisor.js +333 -333
  94. package/src/harmony/canon.js +565 -565
  95. package/src/harmony/cli.js +591 -591
  96. package/src/harmony/drift.js +401 -401
  97. package/src/harmony/governance.js +313 -313
  98. package/src/harmony/memory.js +239 -239
  99. package/src/harmony/sync.js +475 -475
  100. package/src/harmony/watch.js +370 -370
  101. package/src/hook-validation.js +342 -342
  102. package/src/index.js +271 -271
  103. package/src/init.js +184 -184
  104. package/src/instruction-surfaces.js +185 -185
  105. package/src/integrations.js +144 -144
  106. package/src/interactive.js +118 -118
  107. package/src/locales/en.json +1 -1
  108. package/src/locales/es.json +1 -1
  109. package/src/mcp-packs.js +830 -830
  110. package/src/mcp-server.js +726 -726
  111. package/src/mcp-validation.js +337 -337
  112. package/src/nerviq-sync.json +7 -7
  113. package/src/opencode/config-parser.js +109 -109
  114. package/src/opencode/context.js +247 -247
  115. package/src/opencode/deep-review.js +313 -313
  116. package/src/opencode/domain-packs.js +262 -262
  117. package/src/opencode/freshness.js +66 -66
  118. package/src/opencode/governance.js +159 -159
  119. package/src/opencode/interactive.js +392 -392
  120. package/src/opencode/mcp-packs.js +705 -705
  121. package/src/opencode/patch.js +184 -184
  122. package/src/opencode/plans.js +231 -231
  123. package/src/opencode/premium.js +413 -413
  124. package/src/opencode/setup.js +449 -449
  125. package/src/opencode/techniques.js +27 -27
  126. package/src/operating-profile.js +574 -574
  127. package/src/org.js +152 -152
  128. package/src/permission-rules.js +218 -218
  129. package/src/plans.js +839 -839
  130. package/src/platform-change-manifest.js +86 -86
  131. package/src/plugins.js +110 -110
  132. package/src/policy-layers.js +210 -210
  133. package/src/profiles.js +124 -124
  134. package/src/prompt-injection.js +74 -74
  135. package/src/public-api.js +173 -173
  136. package/src/recommendation-rules.js +84 -84
  137. package/src/repo-archetype.js +386 -386
  138. package/src/secret-patterns.js +39 -39
  139. package/src/server.js +527 -527
  140. package/src/setup/analysis.js +607 -607
  141. package/src/setup/runtime.js +172 -172
  142. package/src/setup.js +677 -677
  143. package/src/shared/capabilities.js +194 -194
  144. package/src/source-urls.js +132 -132
  145. package/src/stack-checks.js +565 -565
  146. package/src/supplemental-checks.js +13 -13
  147. package/src/synergy/adaptive.js +261 -261
  148. package/src/synergy/compensation.js +137 -137
  149. package/src/synergy/evidence.js +193 -193
  150. package/src/synergy/learning.js +199 -199
  151. package/src/synergy/patterns.js +227 -227
  152. package/src/synergy/ranking.js +83 -83
  153. package/src/synergy/report.js +165 -165
  154. package/src/synergy/routing.js +146 -146
  155. package/src/techniques/api.js +407 -407
  156. package/src/techniques/automation.js +316 -316
  157. package/src/techniques/compliance.js +257 -257
  158. package/src/techniques/hygiene.js +294 -294
  159. package/src/techniques/instructions.js +243 -243
  160. package/src/techniques/observability.js +226 -226
  161. package/src/techniques/optimization.js +142 -142
  162. package/src/techniques/quality.js +318 -318
  163. package/src/techniques/security.js +237 -237
  164. package/src/techniques/shared.js +443 -443
  165. package/src/techniques/stacks.js +2294 -2294
  166. package/src/techniques/tools.js +106 -106
  167. package/src/techniques/workflow.js +413 -413
  168. package/src/techniques.js +81 -81
  169. package/src/terminology.js +73 -73
  170. package/src/token-estimate.js +35 -35
  171. package/src/usage-patterns.js +99 -99
  172. package/src/verification-metadata.js +145 -145
  173. package/src/watch.js +247 -247
  174. package/src/windsurf/activity.js +302 -302
  175. package/src/windsurf/config-parser.js +267 -267
  176. package/src/windsurf/context.js +249 -249
  177. package/src/windsurf/deep-review.js +337 -337
  178. package/src/windsurf/domain-packs.js +370 -370
  179. package/src/windsurf/freshness.js +36 -36
  180. package/src/windsurf/governance.js +231 -231
  181. package/src/windsurf/interactive.js +388 -388
  182. package/src/windsurf/mcp-packs.js +792 -792
  183. package/src/windsurf/plans.js +247 -247
  184. package/src/windsurf/premium.js +468 -468
  185. package/src/windsurf/setup.js +471 -471
  186. package/src/windsurf/techniques.js +17 -17
  187. package/src/workspace.js +375 -375
package/src/plans.js CHANGED
@@ -1,839 +1,839 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
-
4
- const { version } = require('../package.json');
5
- const { analyzeProject } = require('./analyze');
6
- const { ProjectContext } = require('./context');
7
- const { TECHNIQUES, STACKS } = require('./techniques');
8
- const { TEMPLATES } = require('./setup');
9
- const { buildSettingsForProfile } = require('./governance');
10
- const { getMcpPackPreflight } = require('./mcp-packs');
11
- const { writeActivityArtifact, writeRollbackArtifact } = require('./activity');
12
- const { buildCodexProposalBundle } = require('./codex/plans');
13
-
14
- const TEMPLATE_DIR_MAP = {
15
- hooks: '.claude/hooks',
16
- commands: '.claude/commands',
17
- skills: '.claude/skills',
18
- rules: '.claude/rules',
19
- agents: '.claude/agents',
20
- };
21
-
22
- const TEMPLATE_LABELS = {
23
- 'claude-md': 'CLAUDE.md baseline',
24
- hooks: 'Hooks bundle',
25
- commands: 'Slash commands',
26
- skills: 'Skills pack',
27
- rules: 'Rules pack',
28
- agents: 'Specialized agents',
29
- };
30
-
31
- const TEMPLATE_MODULES = {
32
- 'claude-md': 'CLAUDE.md',
33
- hooks: 'hooks',
34
- commands: 'commands',
35
- skills: 'skills',
36
- rules: 'rules',
37
- agents: 'agents',
38
- };
39
-
40
- const IMPACT_ORDER = { critical: 3, high: 2, medium: 1, low: 0 };
41
- const FALLBACK_TEMPLATE_BY_KEY = {
42
- importSyntax: 'claude-md',
43
- verificationLoop: 'claude-md',
44
- testCommand: 'claude-md',
45
- lintCommand: 'claude-md',
46
- buildCommand: 'claude-md',
47
- securityReview: 'claude-md',
48
- compactionAwareness: 'claude-md',
49
- contextManagement: 'claude-md',
50
- xmlTags: 'claude-md',
51
- roleDefinition: 'claude-md',
52
- constraintBlocks: 'claude-md',
53
- claudeMdFreshness: 'claude-md',
54
- permissionDeny: 'hooks',
55
- secretsProtection: 'hooks',
56
- preToolUseHook: 'hooks',
57
- postToolUseHook: 'hooks',
58
- sessionStartHook: 'hooks',
59
- agentsHaveMaxTurns: 'agents',
60
- };
61
-
62
- const VERIFICATION_TRIGGER_KEYS = new Set([
63
- 'verificationLoop',
64
- 'testCommand',
65
- 'lintCommand',
66
- 'buildCommand',
67
- ]);
68
-
69
- const GOVERNANCE_TRIGGER_KEYS = new Set([
70
- 'permissionDeny',
71
- 'secretsProtection',
72
- 'preToolUseHook',
73
- 'postToolUseHook',
74
- 'sessionStartHook',
75
- 'hooksInSettings',
76
- 'settingsPermissions',
77
- 'securityReview',
78
- ]);
79
-
80
- const AUTOMATION_TRIGGER_KEYS = new Set([
81
- 'customCommands',
82
- 'skills',
83
- 'agents',
84
- 'multipleAgents',
85
- 'multipleMcpServers',
86
- ]);
87
-
88
- function previewContent(content) {
89
- return content.split('\n').slice(0, 12).join('\n');
90
- }
91
-
92
- function riskFromImpact(impact) {
93
- if (impact === 'critical') return 'high';
94
- if (impact === 'high') return 'medium';
95
- return 'low';
96
- }
97
-
98
- function normalizeNewlines(content) {
99
- return (content || '').replace(/\r\n/g, '\n');
100
- }
101
-
102
- function ensureTrailingNewline(content) {
103
- const normalized = normalizeNewlines(content);
104
- return normalized.endsWith('\n') ? normalized : `${normalized}\n`;
105
- }
106
-
107
- function upsertManagedBlock(content, id, block) {
108
- const start = `<!-- nerviq:${id}:start -->`;
109
- const end = `<!-- nerviq:${id}:end -->`;
110
- const wrapped = `${start}\n${block.trim()}\n${end}`;
111
- const pattern = new RegExp(`${start}[\\s\\S]*?${end}`);
112
-
113
- if (pattern.test(content)) {
114
- return {
115
- changed: true,
116
- content: content.replace(pattern, wrapped),
117
- };
118
- }
119
-
120
- return {
121
- changed: true,
122
- content: `${content.trimEnd()}\n\n${wrapped}\n`,
123
- };
124
- }
125
-
126
- function extractGeneratedBuildSection(content) {
127
- const match = content.match(/## Build & Test\n([\s\S]*?)\n\n## Working Notes/);
128
- return match ? `## Build & Test\n${match[1].trim()}` : null;
129
- }
130
-
131
- function extractGeneratedVerificationBlock(content) {
132
- const match = content.match(/<verification>\n([\s\S]*?)\n<\/verification>/);
133
- return match ? `<verification>\n${match[1].trim()}\n</verification>` : null;
134
- }
135
-
136
- function extractGeneratedWorkingNotes(content) {
137
- const match = content.match(/## Working Notes\n([\s\S]*?)\n\n<constraints>/);
138
- return match ? `## Working Notes\n${match[1].trim()}` : null;
139
- }
140
-
141
- function extractGeneratedConstraintsBlock(content) {
142
- const match = content.match(/<constraints>\n([\s\S]*?)\n<\/constraints>/);
143
- return match ? `<constraints>\n${match[1].trim()}\n</constraints>` : null;
144
- }
145
-
146
- function extractGeneratedContextSection(content) {
147
- const match = content.match(/## Context Management\n([\s\S]*?)\n\n---/);
148
- return match ? `## Context Management\n${match[1].trim()}` : null;
149
- }
150
-
151
- function getFailedTemplateGroups(ctx, only = []) {
152
- const groups = new Map();
153
- for (const [key, technique] of Object.entries(TECHNIQUES)) {
154
- const passed = technique.check(ctx);
155
- const templateKey = technique.template || FALLBACK_TEMPLATE_BY_KEY[key];
156
- if (passed !== false || !templateKey) continue;
157
- if (templateKey === 'mermaid') continue;
158
- if (only.length > 0 && !only.includes(key) && !only.includes(templateKey)) continue;
159
- if (!groups.has(templateKey)) {
160
- groups.set(templateKey, []);
161
- }
162
- groups.get(templateKey).push({ key, ...technique });
163
- }
164
- return groups;
165
- }
166
-
167
- function buildClaudeMdPatchFile(ctx, stacks) {
168
- const claudePath = ctx.fileContent('CLAUDE.md') !== null
169
- ? 'CLAUDE.md'
170
- : (ctx.fileContent('.claude/CLAUDE.md') !== null ? '.claude/CLAUDE.md' : null);
171
- if (!claudePath) return null;
172
-
173
- const existing = normalizeNewlines(ctx.fileContent(claudePath));
174
- const generated = TEMPLATES['claude-md'](stacks, ctx);
175
- const buildSection = extractGeneratedBuildSection(generated);
176
- const verificationBlock = extractGeneratedVerificationBlock(generated);
177
- const workingNotes = extractGeneratedWorkingNotes(generated);
178
- const constraintsBlock = extractGeneratedConstraintsBlock(generated);
179
- const contextSection = extractGeneratedContextSection(generated);
180
- let merged = existing;
181
- let changed = false;
182
-
183
- const hasTest = /npm test|pytest|jest|vitest|cargo test|go test|mix test|rspec/.test(merged);
184
- const hasLint = /eslint|prettier|ruff|black|clippy|golangci-lint|rubocop/.test(merged);
185
- const hasBuild = /npm run build|cargo build|go build|make|tsc|gradle build|mvn compile/.test(merged);
186
- const hasVerification = merged.includes('<verification>');
187
- const hasSecurityWorkflow = merged.toLowerCase().includes('security') || merged.includes('/security-review');
188
- const hasImportGuidance = merged.includes('@import');
189
- const hasRoleDefinition = /you are|your role|act as|persona|behave as/i.test(merged);
190
- const hasConstraintBlock = /<constraints|<rules|<requirements|<boundaries/i.test(merged);
191
- const hasCompaction = /\/compact|compaction/i.test(merged);
192
- const hasContextManagement = /context.*(manage|window|limit|budget|token)/i.test(merged);
193
- const modernFeatures = ['hook', 'skill', 'agent', 'subagent', 'mcp', 'worktree'];
194
- const hasFreshness = modernFeatures.filter(feature => merged.toLowerCase().includes(feature)).length >= 2;
195
-
196
- if ((!hasTest || !hasLint || !hasBuild) && buildSection) {
197
- const result = upsertManagedBlock(merged, 'build-test', buildSection);
198
- merged = result.content;
199
- changed = true;
200
- }
201
-
202
- if (!hasRoleDefinition && workingNotes) {
203
- const result = upsertManagedBlock(merged, 'working-style', workingNotes);
204
- merged = result.content;
205
- changed = true;
206
- }
207
-
208
- if (!hasConstraintBlock && constraintsBlock) {
209
- const result = upsertManagedBlock(merged, 'constraints', constraintsBlock);
210
- merged = result.content;
211
- changed = true;
212
- }
213
-
214
- if (!hasVerification && verificationBlock) {
215
- const result = upsertManagedBlock(merged, 'verification', verificationBlock);
216
- merged = result.content;
217
- changed = true;
218
- }
219
-
220
- if (!hasSecurityWorkflow) {
221
- const result = upsertManagedBlock(merged, 'security-workflow', [
222
- '## Security Workflow',
223
- '- Run `/security-review` when touching authentication, permissions, secrets, or customer data.',
224
- '- Treat secret access, shell commands, and risky file operations as review-worthy changes.',
225
- ].join('\n'));
226
- merged = result.content;
227
- changed = true;
228
- }
229
-
230
- if (!hasImportGuidance) {
231
- const result = upsertManagedBlock(merged, 'modularity', [
232
- '## Modularity',
233
- '- If this file grows, split it with `@import ./docs/...` so the base instructions stay concise.',
234
- ].join('\n'));
235
- merged = result.content;
236
- changed = true;
237
- }
238
-
239
- if ((!hasCompaction || !hasContextManagement || !hasFreshness) && contextSection) {
240
- const result = upsertManagedBlock(merged, 'context-management', contextSection);
241
- merged = result.content;
242
- changed = true;
243
- }
244
-
245
- if (!changed) {
246
- return null;
247
- }
248
-
249
- return {
250
- path: claudePath,
251
- action: 'patch',
252
- currentState: 'existing CLAUDE.md is missing recommended verification or security sections',
253
- proposedState: 'append managed sections for verification, security workflow, and modularity',
254
- content: ensureTrailingNewline(merged),
255
- };
256
- }
257
-
258
- function buildAgentPatchFiles(ctx) {
259
- if (!ctx.hasDir('.claude/agents')) {
260
- return [];
261
- }
262
-
263
- return ctx.dirFiles('.claude/agents')
264
- .filter(file => file.endsWith('.md'))
265
- .map((file) => {
266
- const relativePath = `.claude/agents/${file}`;
267
- const content = normalizeNewlines(ctx.fileContent(relativePath) || '');
268
- if (!content.startsWith('---\n') || content.includes('\nmaxTurns:')) {
269
- return null;
270
- }
271
-
272
- const updated = content.replace(/^---\n([\s\S]*?)\n---/, (match, frontmatter) => `---\n${frontmatter}\nmaxTurns: 50\n---`);
273
- if (updated === content) {
274
- return null;
275
- }
276
-
277
- return {
278
- path: relativePath,
279
- action: 'patch',
280
- currentState: 'existing agent is missing a maxTurns safety limit',
281
- proposedState: 'add maxTurns: 50 to the agent frontmatter',
282
- content: ensureTrailingNewline(updated),
283
- };
284
- })
285
- .filter(Boolean);
286
- }
287
-
288
- function buildHookSettings(ctx, plannedHookFiles, options = {}) {
289
- const existing = ctx.hasDir('.claude/hooks')
290
- ? ctx.dirFiles('.claude/hooks').filter(file => file.endsWith('.sh') || file.endsWith('.js'))
291
- : [];
292
- const hookFiles = [...new Set([...existing, ...plannedHookFiles])].sort();
293
- if (hookFiles.length === 0) {
294
- return null;
295
- }
296
- const settingsPath = '.claude/settings.json';
297
- const existingSettings = ctx.jsonFile(settingsPath);
298
- const settings = buildSettingsForProfile({
299
- profileKey: options.profile || 'safe-write',
300
- hookFiles,
301
- existingSettings,
302
- mcpPackKeys: options.mcpPacks || [],
303
- });
304
- const content = `${JSON.stringify(settings, null, 2)}\n`;
305
- const existingContent = existingSettings ? `${JSON.stringify(existingSettings, null, 2)}\n` : null;
306
-
307
- if (existingContent === content) {
308
- return null;
309
- }
310
-
311
- return {
312
- path: settingsPath,
313
- action: existingSettings ? 'patch' : 'create',
314
- currentState: existingSettings
315
- ? 'existing settings are missing selected profile protections or hook registrations'
316
- : 'settings file is missing',
317
- proposedState: existingSettings
318
- ? `merge ${options.profile || 'safe-write'} profile protections into existing settings`
319
- : `create settings for ${options.profile || 'safe-write'} profile and register hooks`,
320
- content,
321
- };
322
- }
323
-
324
- function buildTemplateFiles(templateKey, stacks, ctx, triggers, options = {}) {
325
- const patchFiles = templateKey === 'agents' ? buildAgentPatchFiles(ctx) : [];
326
-
327
- if (templateKey === 'claude-md') {
328
- const patchFile = buildClaudeMdPatchFile(ctx, stacks);
329
- if (patchFile) {
330
- return [patchFile];
331
- }
332
- }
333
-
334
- const template = TEMPLATES[templateKey];
335
- if (!template) return [];
336
-
337
- const result = template(stacks, ctx);
338
- if (typeof result === 'string') {
339
- return [{ path: 'CLAUDE.md', content: result }];
340
- }
341
-
342
- const targetDir = TEMPLATE_DIR_MAP[templateKey];
343
- if (!targetDir) return [];
344
-
345
- const generatedFiles = Object.entries(result).map(([fileName, content]) => ({
346
- path: path.posix.join(targetDir.replace(/\\/g, '/'), fileName),
347
- content,
348
- }));
349
-
350
- const patchedPaths = new Set(patchFiles.map(file => file.path));
351
- return [...patchFiles, ...generatedFiles.filter(file => !patchedPaths.has(file.path))];
352
- }
353
-
354
- function toProposal(templateKey, triggers, templateFiles, ctx) {
355
- const sortedTriggers = [...triggers].sort((a, b) => {
356
- const impactA = IMPACT_ORDER[a.impact] ?? 0;
357
- const impactB = IMPACT_ORDER[b.impact] ?? 0;
358
- return impactB - impactA;
359
- });
360
- const highestImpact = sortedTriggers[0]?.impact || 'medium';
361
- const files = templateFiles.map(file => {
362
- const exists = ctx.fileContent(file.path) !== null || ctx.hasDir(file.path);
363
- const action = file.action || (exists ? 'manual-review' : 'create');
364
- const currentState = file.currentState || (exists ? 'file already exists and will be preserved' : 'missing');
365
- const proposedState = file.proposedState || (exists ? 'generated baseline available for manual merge' : 'create new file');
366
- const diffPreview = [
367
- `--- ${exists ? file.path : 'missing'}`,
368
- `+++ ${file.path}`,
369
- ...previewContent(file.content).split('\n').map(line => `+${line}`),
370
- ].join('\n');
371
- return {
372
- path: file.path,
373
- action,
374
- currentState,
375
- proposedState,
376
- bytes: Buffer.byteLength(file.content, 'utf8'),
377
- content: file.content,
378
- preview: previewContent(file.content),
379
- diffPreview,
380
- };
381
- });
382
-
383
- return {
384
- id: templateKey,
385
- title: TEMPLATE_LABELS[templateKey] || templateKey,
386
- module: TEMPLATE_MODULES[templateKey] || templateKey,
387
- risk: riskFromImpact(highestImpact),
388
- confidence: sortedTriggers.length >= 2 ? 'high' : 'medium',
389
- triggers: sortedTriggers.map(trigger => ({
390
- key: trigger.key,
391
- name: trigger.name,
392
- impact: trigger.impact,
393
- fix: trigger.fix,
394
- })),
395
- rationale: sortedTriggers.map(trigger => trigger.fix),
396
- files,
397
- readyToApply: files.some(file => ['create', 'patch'].includes(file.action)),
398
- };
399
- }
400
-
401
- function proposalMatchesTriggerKeys(proposal, keySet) {
402
- return (proposal.triggers || []).some((trigger) => keySet.has(trigger.key));
403
- }
404
-
405
- function collectCampaignProposals(proposals, predicate) {
406
- return proposals.filter((proposal) => proposal.readyToApply && predicate(proposal));
407
- }
408
-
409
- function buildCampaigns(bundle) {
410
- const proposals = Array.isArray(bundle?.proposals) ? bundle.proposals : [];
411
- const campaigns = [];
412
- const maturity = bundle?.projectSummary?.maturity || 'unknown';
413
-
414
- const starterBaseline = collectCampaignProposals(
415
- proposals,
416
- (proposal) => ['claude-md', 'commands', 'rules', 'hooks', 'agents'].includes(proposal.id),
417
- );
418
- if (starterBaseline.length > 0) {
419
- campaigns.push({
420
- key: 'starter-baseline',
421
- label: 'Starter baseline',
422
- summary: 'Establish the managed baseline surfaces Nerviq expects before deeper upgrades.',
423
- proposalIds: starterBaseline.map((proposal) => proposal.id),
424
- milestone: maturity === 'mature' ? 'pre-upgrade' : 'baseline',
425
- focusAreas: ['config-drift', 'maturity-opportunity'],
426
- });
427
- }
428
-
429
- const verificationClosure = collectCampaignProposals(
430
- proposals,
431
- (proposal) => proposalMatchesTriggerKeys(proposal, VERIFICATION_TRIGGER_KEYS),
432
- );
433
- if (verificationClosure.length > 0) {
434
- campaigns.push({
435
- key: 'verification-closure',
436
- label: 'Verification closure',
437
- summary: 'Close missing test/lint/build loops so audits can be verified continuously.',
438
- proposalIds: verificationClosure.map((proposal) => proposal.id),
439
- milestone: 'post-fix',
440
- focusAreas: ['config-drift', 'maturity-opportunity'],
441
- });
442
- }
443
-
444
- const governanceHardening = collectCampaignProposals(
445
- proposals,
446
- (proposal) => proposal.id === 'hooks' || proposalMatchesTriggerKeys(proposal, GOVERNANCE_TRIGGER_KEYS),
447
- );
448
- if (governanceHardening.length > 0) {
449
- campaigns.push({
450
- key: 'governance-hardening',
451
- label: 'Governance hardening',
452
- summary: 'Tighten permissions, hooks, secret protection, and reviewable safety defaults.',
453
- proposalIds: governanceHardening.map((proposal) => proposal.id),
454
- milestone: 'pre-upgrade',
455
- focusAreas: ['policy-drift', 'config-drift'],
456
- });
457
- }
458
-
459
- const reviewableAutomation = collectCampaignProposals(
460
- proposals,
461
- (proposal) => proposal.id === 'agents' || proposal.id === 'commands' || proposalMatchesTriggerKeys(proposal, AUTOMATION_TRIGGER_KEYS),
462
- );
463
- if (reviewableAutomation.length > 0) {
464
- campaigns.push({
465
- key: 'reviewable-automation',
466
- label: 'Reviewable automation',
467
- summary: 'Add automation surfaces that keep upgrades inspectable instead of ad-hoc.',
468
- proposalIds: reviewableAutomation.map((proposal) => proposal.id),
469
- milestone: 'pre-upgrade',
470
- focusAreas: ['maturity-opportunity', 'config-drift'],
471
- });
472
- }
473
-
474
- return campaigns.filter((campaign, index, all) =>
475
- all.findIndex((item) => item.key === campaign.key) === index,
476
- );
477
- }
478
-
479
- function filterBundleByCampaigns(bundle, campaignKeys = []) {
480
- if (!Array.isArray(campaignKeys) || campaignKeys.length === 0) {
481
- return bundle;
482
- }
483
-
484
- const available = new Map((bundle.campaigns || []).map((campaign) => [campaign.key, campaign]));
485
- const missing = campaignKeys.filter((key) => !available.has(key));
486
- if (missing.length > 0) {
487
- throw new Error(`unknown campaign(s): ${missing.join(', ')}`);
488
- }
489
-
490
- const selectedIds = new Set();
491
- for (const key of campaignKeys) {
492
- for (const proposalId of available.get(key).proposalIds || []) {
493
- selectedIds.add(proposalId);
494
- }
495
- }
496
-
497
- return {
498
- ...bundle,
499
- selectedCampaigns: campaignKeys,
500
- proposals: bundle.proposals.filter((proposal) => selectedIds.has(proposal.id)),
501
- campaigns: (bundle.campaigns || []).filter((campaign) => campaignKeys.includes(campaign.key)),
502
- };
503
- }
504
-
505
- function resolveSelectionSet(bundle, options = {}) {
506
- const proposalIds = new Set((bundle.proposals || []).map((proposal) => proposal.id));
507
- const onlySet = options.only && options.only.length > 0 ? new Set(options.only) : null;
508
- const campaignSet = options.campaigns && options.campaigns.length > 0
509
- ? new Set((bundle.campaigns || []).flatMap((campaign) => {
510
- if (!options.campaigns.includes(campaign.key)) return [];
511
- return campaign.proposalIds || [];
512
- }))
513
- : null;
514
-
515
- if (onlySet && campaignSet) {
516
- return new Set([...onlySet].filter((proposalId) => campaignSet.has(proposalId) && proposalIds.has(proposalId)));
517
- }
518
- if (onlySet) {
519
- return new Set([...onlySet].filter((proposalId) => proposalIds.has(proposalId)));
520
- }
521
- if (campaignSet) {
522
- return new Set([...campaignSet].filter((proposalId) => proposalIds.has(proposalId)));
523
- }
524
-
525
- return null;
526
- }
527
-
528
- async function buildProposalBundle(options) {
529
- if (options.platform === 'codex') {
530
- const bundle = await buildCodexProposalBundle(options);
531
- return filterBundleByCampaigns({
532
- ...bundle,
533
- campaigns: buildCampaigns(bundle),
534
- }, options.campaigns);
535
- }
536
-
537
- const ctx = new ProjectContext(options.dir);
538
- const stacks = ctx.detectStacks(STACKS);
539
- const report = await analyzeProject({ ...options, mode: 'augment' });
540
- const mcpPreflightWarnings = getMcpPackPreflight(options.mcpPacks || [])
541
- .filter(item => item.missingEnvVars.length > 0);
542
- const groups = getFailedTemplateGroups(ctx, options.only || []);
543
- const proposals = [];
544
-
545
- for (const [templateKey, triggers] of groups.entries()) {
546
- const templateFiles = buildTemplateFiles(templateKey, stacks, ctx, triggers, options);
547
- if (templateKey === 'hooks') {
548
- const plannedHookFiles = templateFiles
549
- .map(file => path.basename(file.path))
550
- .filter(file => file.endsWith('.sh') || file.endsWith('.js'));
551
- const settingsFile = buildHookSettings(ctx, plannedHookFiles, options);
552
- if (settingsFile) {
553
- templateFiles.push(settingsFile);
554
- }
555
- }
556
- proposals.push(toProposal(templateKey, triggers, templateFiles, ctx));
557
- }
558
-
559
- proposals.sort((a, b) => {
560
- const impactA = IMPACT_ORDER[a.triggers[0]?.impact] ?? 0;
561
- const impactB = IMPACT_ORDER[b.triggers[0]?.impact] ?? 0;
562
- return impactB - impactA;
563
- });
564
-
565
- return filterBundleByCampaigns({
566
- schemaVersion: 1,
567
- generatedBy: `nerviq@${version}`,
568
- createdAt: new Date().toISOString(),
569
- directory: options.dir,
570
- projectSummary: report.projectSummary,
571
- strengthsPreserved: report.strengthsPreserved,
572
- topNextActions: report.topNextActions,
573
- riskNotes: report.riskNotes,
574
- mcpPreflightWarnings,
575
- proposals,
576
- campaigns: buildCampaigns({ proposals, projectSummary: report.projectSummary }),
577
- }, options.campaigns);
578
- }
579
-
580
- function printProposalBundle(bundle, options = {}) {
581
- if (options.json) {
582
- console.log(JSON.stringify(bundle, null, 2));
583
- return;
584
- }
585
-
586
- console.log('');
587
- console.log(' nerviq plan');
588
- console.log(' ═══════════════════════════════════════');
589
- console.log(` ${bundle.projectSummary.name} | maturity=${bundle.projectSummary.maturity} | score=${bundle.projectSummary.score}/100`);
590
- if (bundle.projectSummary.archetype) {
591
- console.log(` archetype=${bundle.projectSummary.archetype} | workflow=${bundle.projectSummary.workflow || 'unknown'} | risk=${bundle.projectSummary.riskLevel || 'unknown'}`);
592
- }
593
- if (bundle.projectSummary.operatingProfile) {
594
- console.log(` operating-profile=${bundle.projectSummary.operatingProfile}`);
595
- }
596
- console.log('');
597
-
598
- if (bundle.selectedCampaigns && bundle.selectedCampaigns.length > 0) {
599
- console.log(` Selected campaigns: ${bundle.selectedCampaigns.join(', ')}`);
600
- console.log('');
601
- }
602
-
603
- if (bundle.mcpPreflightWarnings && bundle.mcpPreflightWarnings.length > 0) {
604
- console.log(' MCP Preflight Warnings');
605
- for (const warning of bundle.mcpPreflightWarnings) {
606
- console.log(` - ${warning.label}: missing ${warning.missingEnvVars.join(', ')}`);
607
- }
608
- console.log('');
609
- }
610
-
611
- if (bundle.proposals.length === 0) {
612
- console.log(' No templated proposals are needed right now.');
613
- console.log('');
614
- return;
615
- }
616
-
617
- if (bundle.campaigns && bundle.campaigns.length > 0) {
618
- console.log(' Upgrade campaigns');
619
- for (const campaign of bundle.campaigns) {
620
- console.log(` - ${campaign.key} (${campaign.milestone})`);
621
- console.log(` ${campaign.label} — ${campaign.summary}`);
622
- console.log(` proposals: ${campaign.proposalIds.join(', ')}`);
623
- }
624
- console.log('');
625
- }
626
-
627
- console.log(' Proposal Bundles');
628
- for (const proposal of bundle.proposals) {
629
- const applyState = proposal.readyToApply ? 'ready' : 'manual-review';
630
- console.log(` - ${proposal.id} [${applyState}]`);
631
- console.log(` ${proposal.title} | risk=${proposal.risk} | confidence=${proposal.confidence}`);
632
- console.log(` triggers: ${proposal.triggers.map(item => item.name).join(', ')}`);
633
- console.log(` files: ${proposal.files.map(file => `${file.path} (${file.action})`).join(', ')}`);
634
- }
635
- console.log('');
636
- }
637
-
638
- function writePlanFile(bundle, outFile) {
639
- fs.mkdirSync(path.dirname(outFile), { recursive: true });
640
- fs.writeFileSync(outFile, JSON.stringify(bundle, null, 2), 'utf8');
641
- return writeActivityArtifact(bundle.directory, 'plan-export', {
642
- exportedPlan: outFile,
643
- proposalIds: bundle.proposals.map(proposal => proposal.id),
644
- proposalCount: bundle.proposals.length,
645
- });
646
- }
647
-
648
- function tryParseJson(content) {
649
- try {
650
- return JSON.parse(content);
651
- } catch {
652
- return null;
653
- }
654
- }
655
-
656
- function applyRuntimeSettingsOverlays(bundle, options) {
657
- if (options.platform === 'codex') {
658
- return bundle;
659
- }
660
-
661
- if (!bundle || !Array.isArray(bundle.proposals)) {
662
- return bundle;
663
- }
664
-
665
- const ctx = new ProjectContext(options.dir);
666
- const existingHooks = ctx.hasDir('.claude/hooks')
667
- ? ctx.dirFiles('.claude/hooks').filter(file => file.endsWith('.sh') || file.endsWith('.js'))
668
- : [];
669
-
670
- const proposals = bundle.proposals.map((proposal) => {
671
- const settingsIndex = proposal.files.findIndex(file => file.path === '.claude/settings.json');
672
- if (settingsIndex === -1) {
673
- return proposal;
674
- }
675
-
676
- const plannedHookFiles = proposal.files
677
- .filter(file => file.path.startsWith('.claude/hooks/') && file.path.endsWith('.sh'))
678
- .map(file => path.basename(file.path));
679
- const hookFiles = [...new Set([...existingHooks, ...plannedHookFiles])].sort();
680
- const currentSettings = tryParseJson(proposal.files[settingsIndex].content) || ctx.jsonFile('.claude/settings.json') || null;
681
- const mergedSettings = buildSettingsForProfile({
682
- profileKey: options.profile || 'safe-write',
683
- hookFiles,
684
- existingSettings: currentSettings,
685
- mcpPackKeys: options.mcpPacks || [],
686
- });
687
- const updatedContent = `${JSON.stringify(mergedSettings, null, 2)}\n`;
688
- const currentFile = proposal.files[settingsIndex];
689
-
690
- const files = [...proposal.files];
691
- files[settingsIndex] = {
692
- ...currentFile,
693
- content: updatedContent,
694
- preview: previewContent(updatedContent),
695
- diffPreview: [
696
- `--- ${ctx.fileContent(currentFile.path) !== null ? currentFile.path : 'missing'}`,
697
- `+++ ${currentFile.path}`,
698
- ...previewContent(updatedContent).split('\n').map(line => `+${line}`),
699
- ].join('\n'),
700
- currentState: currentFile.currentState || 'existing settings are missing runtime-selected protections or MCP packs',
701
- proposedState: `merge ${options.profile || 'safe-write'} profile protections and requested MCP packs into settings`,
702
- };
703
-
704
- return {
705
- ...proposal,
706
- files,
707
- };
708
- });
709
-
710
- return {
711
- ...bundle,
712
- proposals,
713
- };
714
- }
715
-
716
- function resolvePlan(bundle, options) {
717
- if (options.planFile) {
718
- return filterBundleByCampaigns(
719
- applyRuntimeSettingsOverlays(JSON.parse(fs.readFileSync(options.planFile, 'utf8')), options),
720
- options.campaigns,
721
- );
722
- }
723
- return filterBundleByCampaigns(applyRuntimeSettingsOverlays(bundle, options), options.campaigns);
724
- }
725
-
726
- async function applyProposalBundle(options) {
727
- const liveBundle = options.planFile ? null : await buildProposalBundle(options);
728
- const bundle = resolvePlan(liveBundle, options);
729
- const mcpPreflightWarnings = getMcpPackPreflight(options.mcpPacks || [])
730
- .filter(item => item.missingEnvVars.length > 0);
731
- const selectedIds = resolveSelectionSet(bundle, options);
732
- const selected = bundle.proposals.filter(proposal => {
733
- if (selectedIds && !selectedIds.has(proposal.id)) return false;
734
- return proposal.readyToApply;
735
- });
736
-
737
- const createdFiles = [];
738
- const patchedFiles = [];
739
- const skippedFiles = [];
740
- for (const proposal of selected) {
741
- for (const file of proposal.files) {
742
- if (!['create', 'patch'].includes(file.action)) {
743
- skippedFiles.push(file.path);
744
- continue;
745
- }
746
- const fullPath = path.join(options.dir, file.path);
747
- if (file.action === 'create' && fs.existsSync(fullPath)) {
748
- skippedFiles.push(file.path);
749
- continue;
750
- }
751
- const previousContent = fs.existsSync(fullPath) ? fs.readFileSync(fullPath, 'utf8') : null;
752
- if (!options.dryRun) {
753
- fs.mkdirSync(path.dirname(fullPath), { recursive: true });
754
- fs.writeFileSync(fullPath, file.content, 'utf8');
755
- }
756
- if (file.action === 'create') {
757
- createdFiles.push(file.path);
758
- } else {
759
- patchedFiles.push({ path: file.path, previousContent });
760
- }
761
- }
762
- }
763
-
764
- let rollback = null;
765
- let activity = null;
766
- if (!options.dryRun && (createdFiles.length > 0 || patchedFiles.length > 0)) {
767
- rollback = writeRollbackArtifact(options.dir, {
768
- sourcePlan: options.planFile ? path.basename(options.planFile) : 'live-plan',
769
- createdFiles,
770
- patchedFiles,
771
- rollbackInstructions: [
772
- ...createdFiles.map(file => `Delete ${file}`),
773
- ...patchedFiles.map(file => `Restore previous content for ${file.path} from this manifest`),
774
- ],
775
- });
776
- activity = writeActivityArtifact(options.dir, 'apply', {
777
- sourcePlan: options.planFile ? path.basename(options.planFile) : 'live-plan',
778
- appliedProposalIds: selected.map(item => item.id),
779
- createdFiles,
780
- patchedFiles: patchedFiles.map(file => file.path),
781
- skippedFiles,
782
- rollbackArtifact: rollback.relativePath,
783
- });
784
- }
785
-
786
- return {
787
- proposalCount: bundle.proposals.length,
788
- appliedProposalIds: selected.map(item => item.id),
789
- selectedCampaigns: bundle.selectedCampaigns || options.campaigns || [],
790
- createdFiles,
791
- patchedFiles: patchedFiles.map(file => file.path),
792
- skippedFiles,
793
- dryRun: options.dryRun === true,
794
- rollbackArtifact: rollback ? rollback.relativePath : null,
795
- activityArtifact: activity ? activity.relativePath : null,
796
- mcpPreflightWarnings,
797
- };
798
- }
799
-
800
- function printApplyResult(result, options = {}) {
801
- if (options.json) {
802
- console.log(JSON.stringify(result, null, 2));
803
- return;
804
- }
805
-
806
- console.log('');
807
- console.log(' nerviq apply');
808
- console.log(' ═══════════════════════════════════════');
809
- if (result.dryRun) {
810
- console.log(' Dry-run only. No files were written.');
811
- }
812
- console.log(` Applied proposal bundles: ${result.appliedProposalIds.join(', ') || 'none'}`);
813
- if (result.selectedCampaigns && result.selectedCampaigns.length > 0) {
814
- console.log(` Campaigns: ${result.selectedCampaigns.join(', ')}`);
815
- }
816
- console.log(` Created files: ${result.createdFiles.join(', ') || 'none'}`);
817
- console.log(` Patched files: ${result.patchedFiles.join(', ') || 'none'}`);
818
- if (result.mcpPreflightWarnings && result.mcpPreflightWarnings.length > 0) {
819
- console.log(' MCP preflight warnings:');
820
- for (const warning of result.mcpPreflightWarnings) {
821
- console.log(` - ${warning.label}: missing ${warning.missingEnvVars.join(', ')}`);
822
- }
823
- }
824
- if (result.rollbackArtifact) {
825
- console.log(` Rollback: ${result.rollbackArtifact}`);
826
- }
827
- if (result.activityArtifact) {
828
- console.log(` Activity log: ${result.activityArtifact}`);
829
- }
830
- console.log('');
831
- }
832
-
833
- module.exports = {
834
- buildProposalBundle,
835
- printProposalBundle,
836
- writePlanFile,
837
- applyProposalBundle,
838
- printApplyResult,
839
- };
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+
4
+ const { version } = require('../package.json');
5
+ const { analyzeProject } = require('./analyze');
6
+ const { ProjectContext } = require('./context');
7
+ const { TECHNIQUES, STACKS } = require('./techniques');
8
+ const { TEMPLATES } = require('./setup');
9
+ const { buildSettingsForProfile } = require('./governance');
10
+ const { getMcpPackPreflight } = require('./mcp-packs');
11
+ const { writeActivityArtifact, writeRollbackArtifact } = require('./activity');
12
+ const { buildCodexProposalBundle } = require('./codex/plans');
13
+
14
+ const TEMPLATE_DIR_MAP = {
15
+ hooks: '.claude/hooks',
16
+ commands: '.claude/commands',
17
+ skills: '.claude/skills',
18
+ rules: '.claude/rules',
19
+ agents: '.claude/agents',
20
+ };
21
+
22
+ const TEMPLATE_LABELS = {
23
+ 'claude-md': 'CLAUDE.md baseline',
24
+ hooks: 'Hooks bundle',
25
+ commands: 'Slash commands',
26
+ skills: 'Skills pack',
27
+ rules: 'Rules pack',
28
+ agents: 'Specialized agents',
29
+ };
30
+
31
+ const TEMPLATE_MODULES = {
32
+ 'claude-md': 'CLAUDE.md',
33
+ hooks: 'hooks',
34
+ commands: 'commands',
35
+ skills: 'skills',
36
+ rules: 'rules',
37
+ agents: 'agents',
38
+ };
39
+
40
+ const IMPACT_ORDER = { critical: 3, high: 2, medium: 1, low: 0 };
41
+ const FALLBACK_TEMPLATE_BY_KEY = {
42
+ importSyntax: 'claude-md',
43
+ verificationLoop: 'claude-md',
44
+ testCommand: 'claude-md',
45
+ lintCommand: 'claude-md',
46
+ buildCommand: 'claude-md',
47
+ securityReview: 'claude-md',
48
+ compactionAwareness: 'claude-md',
49
+ contextManagement: 'claude-md',
50
+ xmlTags: 'claude-md',
51
+ roleDefinition: 'claude-md',
52
+ constraintBlocks: 'claude-md',
53
+ claudeMdFreshness: 'claude-md',
54
+ permissionDeny: 'hooks',
55
+ secretsProtection: 'hooks',
56
+ preToolUseHook: 'hooks',
57
+ postToolUseHook: 'hooks',
58
+ sessionStartHook: 'hooks',
59
+ agentsHaveMaxTurns: 'agents',
60
+ };
61
+
62
+ const VERIFICATION_TRIGGER_KEYS = new Set([
63
+ 'verificationLoop',
64
+ 'testCommand',
65
+ 'lintCommand',
66
+ 'buildCommand',
67
+ ]);
68
+
69
+ const GOVERNANCE_TRIGGER_KEYS = new Set([
70
+ 'permissionDeny',
71
+ 'secretsProtection',
72
+ 'preToolUseHook',
73
+ 'postToolUseHook',
74
+ 'sessionStartHook',
75
+ 'hooksInSettings',
76
+ 'settingsPermissions',
77
+ 'securityReview',
78
+ ]);
79
+
80
+ const AUTOMATION_TRIGGER_KEYS = new Set([
81
+ 'customCommands',
82
+ 'skills',
83
+ 'agents',
84
+ 'multipleAgents',
85
+ 'multipleMcpServers',
86
+ ]);
87
+
88
+ function previewContent(content) {
89
+ return content.split('\n').slice(0, 12).join('\n');
90
+ }
91
+
92
+ function riskFromImpact(impact) {
93
+ if (impact === 'critical') return 'high';
94
+ if (impact === 'high') return 'medium';
95
+ return 'low';
96
+ }
97
+
98
+ function normalizeNewlines(content) {
99
+ return (content || '').replace(/\r\n/g, '\n');
100
+ }
101
+
102
+ function ensureTrailingNewline(content) {
103
+ const normalized = normalizeNewlines(content);
104
+ return normalized.endsWith('\n') ? normalized : `${normalized}\n`;
105
+ }
106
+
107
+ function upsertManagedBlock(content, id, block) {
108
+ const start = `<!-- nerviq:${id}:start -->`;
109
+ const end = `<!-- nerviq:${id}:end -->`;
110
+ const wrapped = `${start}\n${block.trim()}\n${end}`;
111
+ const pattern = new RegExp(`${start}[\\s\\S]*?${end}`);
112
+
113
+ if (pattern.test(content)) {
114
+ return {
115
+ changed: true,
116
+ content: content.replace(pattern, wrapped),
117
+ };
118
+ }
119
+
120
+ return {
121
+ changed: true,
122
+ content: `${content.trimEnd()}\n\n${wrapped}\n`,
123
+ };
124
+ }
125
+
126
+ function extractGeneratedBuildSection(content) {
127
+ const match = content.match(/## Build & Test\n([\s\S]*?)\n\n## Working Notes/);
128
+ return match ? `## Build & Test\n${match[1].trim()}` : null;
129
+ }
130
+
131
+ function extractGeneratedVerificationBlock(content) {
132
+ const match = content.match(/<verification>\n([\s\S]*?)\n<\/verification>/);
133
+ return match ? `<verification>\n${match[1].trim()}\n</verification>` : null;
134
+ }
135
+
136
+ function extractGeneratedWorkingNotes(content) {
137
+ const match = content.match(/## Working Notes\n([\s\S]*?)\n\n<constraints>/);
138
+ return match ? `## Working Notes\n${match[1].trim()}` : null;
139
+ }
140
+
141
+ function extractGeneratedConstraintsBlock(content) {
142
+ const match = content.match(/<constraints>\n([\s\S]*?)\n<\/constraints>/);
143
+ return match ? `<constraints>\n${match[1].trim()}\n</constraints>` : null;
144
+ }
145
+
146
+ function extractGeneratedContextSection(content) {
147
+ const match = content.match(/## Context Management\n([\s\S]*?)\n\n---/);
148
+ return match ? `## Context Management\n${match[1].trim()}` : null;
149
+ }
150
+
151
+ function getFailedTemplateGroups(ctx, only = []) {
152
+ const groups = new Map();
153
+ for (const [key, technique] of Object.entries(TECHNIQUES)) {
154
+ const passed = technique.check(ctx);
155
+ const templateKey = technique.template || FALLBACK_TEMPLATE_BY_KEY[key];
156
+ if (passed !== false || !templateKey) continue;
157
+ if (templateKey === 'mermaid') continue;
158
+ if (only.length > 0 && !only.includes(key) && !only.includes(templateKey)) continue;
159
+ if (!groups.has(templateKey)) {
160
+ groups.set(templateKey, []);
161
+ }
162
+ groups.get(templateKey).push({ key, ...technique });
163
+ }
164
+ return groups;
165
+ }
166
+
167
+ function buildClaudeMdPatchFile(ctx, stacks) {
168
+ const claudePath = ctx.fileContent('CLAUDE.md') !== null
169
+ ? 'CLAUDE.md'
170
+ : (ctx.fileContent('.claude/CLAUDE.md') !== null ? '.claude/CLAUDE.md' : null);
171
+ if (!claudePath) return null;
172
+
173
+ const existing = normalizeNewlines(ctx.fileContent(claudePath));
174
+ const generated = TEMPLATES['claude-md'](stacks, ctx);
175
+ const buildSection = extractGeneratedBuildSection(generated);
176
+ const verificationBlock = extractGeneratedVerificationBlock(generated);
177
+ const workingNotes = extractGeneratedWorkingNotes(generated);
178
+ const constraintsBlock = extractGeneratedConstraintsBlock(generated);
179
+ const contextSection = extractGeneratedContextSection(generated);
180
+ let merged = existing;
181
+ let changed = false;
182
+
183
+ const hasTest = /npm test|pytest|jest|vitest|cargo test|go test|mix test|rspec/.test(merged);
184
+ const hasLint = /eslint|prettier|ruff|black|clippy|golangci-lint|rubocop/.test(merged);
185
+ const hasBuild = /npm run build|cargo build|go build|make|tsc|gradle build|mvn compile/.test(merged);
186
+ const hasVerification = merged.includes('<verification>');
187
+ const hasSecurityWorkflow = merged.toLowerCase().includes('security') || merged.includes('/security-review');
188
+ const hasImportGuidance = merged.includes('@import');
189
+ const hasRoleDefinition = /you are|your role|act as|persona|behave as/i.test(merged);
190
+ const hasConstraintBlock = /<constraints|<rules|<requirements|<boundaries/i.test(merged);
191
+ const hasCompaction = /\/compact|compaction/i.test(merged);
192
+ const hasContextManagement = /context.*(manage|window|limit|budget|token)/i.test(merged);
193
+ const modernFeatures = ['hook', 'skill', 'agent', 'subagent', 'mcp', 'worktree'];
194
+ const hasFreshness = modernFeatures.filter(feature => merged.toLowerCase().includes(feature)).length >= 2;
195
+
196
+ if ((!hasTest || !hasLint || !hasBuild) && buildSection) {
197
+ const result = upsertManagedBlock(merged, 'build-test', buildSection);
198
+ merged = result.content;
199
+ changed = true;
200
+ }
201
+
202
+ if (!hasRoleDefinition && workingNotes) {
203
+ const result = upsertManagedBlock(merged, 'working-style', workingNotes);
204
+ merged = result.content;
205
+ changed = true;
206
+ }
207
+
208
+ if (!hasConstraintBlock && constraintsBlock) {
209
+ const result = upsertManagedBlock(merged, 'constraints', constraintsBlock);
210
+ merged = result.content;
211
+ changed = true;
212
+ }
213
+
214
+ if (!hasVerification && verificationBlock) {
215
+ const result = upsertManagedBlock(merged, 'verification', verificationBlock);
216
+ merged = result.content;
217
+ changed = true;
218
+ }
219
+
220
+ if (!hasSecurityWorkflow) {
221
+ const result = upsertManagedBlock(merged, 'security-workflow', [
222
+ '## Security Workflow',
223
+ '- Run `/security-review` when touching authentication, permissions, secrets, or customer data.',
224
+ '- Treat secret access, shell commands, and risky file operations as review-worthy changes.',
225
+ ].join('\n'));
226
+ merged = result.content;
227
+ changed = true;
228
+ }
229
+
230
+ if (!hasImportGuidance) {
231
+ const result = upsertManagedBlock(merged, 'modularity', [
232
+ '## Modularity',
233
+ '- If this file grows, split it with `@import ./docs/...` so the base instructions stay concise.',
234
+ ].join('\n'));
235
+ merged = result.content;
236
+ changed = true;
237
+ }
238
+
239
+ if ((!hasCompaction || !hasContextManagement || !hasFreshness) && contextSection) {
240
+ const result = upsertManagedBlock(merged, 'context-management', contextSection);
241
+ merged = result.content;
242
+ changed = true;
243
+ }
244
+
245
+ if (!changed) {
246
+ return null;
247
+ }
248
+
249
+ return {
250
+ path: claudePath,
251
+ action: 'patch',
252
+ currentState: 'existing CLAUDE.md is missing recommended verification or security sections',
253
+ proposedState: 'append managed sections for verification, security workflow, and modularity',
254
+ content: ensureTrailingNewline(merged),
255
+ };
256
+ }
257
+
258
+ function buildAgentPatchFiles(ctx) {
259
+ if (!ctx.hasDir('.claude/agents')) {
260
+ return [];
261
+ }
262
+
263
+ return ctx.dirFiles('.claude/agents')
264
+ .filter(file => file.endsWith('.md'))
265
+ .map((file) => {
266
+ const relativePath = `.claude/agents/${file}`;
267
+ const content = normalizeNewlines(ctx.fileContent(relativePath) || '');
268
+ if (!content.startsWith('---\n') || content.includes('\nmaxTurns:')) {
269
+ return null;
270
+ }
271
+
272
+ const updated = content.replace(/^---\n([\s\S]*?)\n---/, (match, frontmatter) => `---\n${frontmatter}\nmaxTurns: 50\n---`);
273
+ if (updated === content) {
274
+ return null;
275
+ }
276
+
277
+ return {
278
+ path: relativePath,
279
+ action: 'patch',
280
+ currentState: 'existing agent is missing a maxTurns safety limit',
281
+ proposedState: 'add maxTurns: 50 to the agent frontmatter',
282
+ content: ensureTrailingNewline(updated),
283
+ };
284
+ })
285
+ .filter(Boolean);
286
+ }
287
+
288
+ function buildHookSettings(ctx, plannedHookFiles, options = {}) {
289
+ const existing = ctx.hasDir('.claude/hooks')
290
+ ? ctx.dirFiles('.claude/hooks').filter(file => file.endsWith('.sh') || file.endsWith('.js'))
291
+ : [];
292
+ const hookFiles = [...new Set([...existing, ...plannedHookFiles])].sort();
293
+ if (hookFiles.length === 0) {
294
+ return null;
295
+ }
296
+ const settingsPath = '.claude/settings.json';
297
+ const existingSettings = ctx.jsonFile(settingsPath);
298
+ const settings = buildSettingsForProfile({
299
+ profileKey: options.profile || 'safe-write',
300
+ hookFiles,
301
+ existingSettings,
302
+ mcpPackKeys: options.mcpPacks || [],
303
+ });
304
+ const content = `${JSON.stringify(settings, null, 2)}\n`;
305
+ const existingContent = existingSettings ? `${JSON.stringify(existingSettings, null, 2)}\n` : null;
306
+
307
+ if (existingContent === content) {
308
+ return null;
309
+ }
310
+
311
+ return {
312
+ path: settingsPath,
313
+ action: existingSettings ? 'patch' : 'create',
314
+ currentState: existingSettings
315
+ ? 'existing settings are missing selected profile protections or hook registrations'
316
+ : 'settings file is missing',
317
+ proposedState: existingSettings
318
+ ? `merge ${options.profile || 'safe-write'} profile protections into existing settings`
319
+ : `create settings for ${options.profile || 'safe-write'} profile and register hooks`,
320
+ content,
321
+ };
322
+ }
323
+
324
+ function buildTemplateFiles(templateKey, stacks, ctx, triggers, options = {}) {
325
+ const patchFiles = templateKey === 'agents' ? buildAgentPatchFiles(ctx) : [];
326
+
327
+ if (templateKey === 'claude-md') {
328
+ const patchFile = buildClaudeMdPatchFile(ctx, stacks);
329
+ if (patchFile) {
330
+ return [patchFile];
331
+ }
332
+ }
333
+
334
+ const template = TEMPLATES[templateKey];
335
+ if (!template) return [];
336
+
337
+ const result = template(stacks, ctx);
338
+ if (typeof result === 'string') {
339
+ return [{ path: 'CLAUDE.md', content: result }];
340
+ }
341
+
342
+ const targetDir = TEMPLATE_DIR_MAP[templateKey];
343
+ if (!targetDir) return [];
344
+
345
+ const generatedFiles = Object.entries(result).map(([fileName, content]) => ({
346
+ path: path.posix.join(targetDir.replace(/\\/g, '/'), fileName),
347
+ content,
348
+ }));
349
+
350
+ const patchedPaths = new Set(patchFiles.map(file => file.path));
351
+ return [...patchFiles, ...generatedFiles.filter(file => !patchedPaths.has(file.path))];
352
+ }
353
+
354
+ function toProposal(templateKey, triggers, templateFiles, ctx) {
355
+ const sortedTriggers = [...triggers].sort((a, b) => {
356
+ const impactA = IMPACT_ORDER[a.impact] ?? 0;
357
+ const impactB = IMPACT_ORDER[b.impact] ?? 0;
358
+ return impactB - impactA;
359
+ });
360
+ const highestImpact = sortedTriggers[0]?.impact || 'medium';
361
+ const files = templateFiles.map(file => {
362
+ const exists = ctx.fileContent(file.path) !== null || ctx.hasDir(file.path);
363
+ const action = file.action || (exists ? 'manual-review' : 'create');
364
+ const currentState = file.currentState || (exists ? 'file already exists and will be preserved' : 'missing');
365
+ const proposedState = file.proposedState || (exists ? 'generated baseline available for manual merge' : 'create new file');
366
+ const diffPreview = [
367
+ `--- ${exists ? file.path : 'missing'}`,
368
+ `+++ ${file.path}`,
369
+ ...previewContent(file.content).split('\n').map(line => `+${line}`),
370
+ ].join('\n');
371
+ return {
372
+ path: file.path,
373
+ action,
374
+ currentState,
375
+ proposedState,
376
+ bytes: Buffer.byteLength(file.content, 'utf8'),
377
+ content: file.content,
378
+ preview: previewContent(file.content),
379
+ diffPreview,
380
+ };
381
+ });
382
+
383
+ return {
384
+ id: templateKey,
385
+ title: TEMPLATE_LABELS[templateKey] || templateKey,
386
+ module: TEMPLATE_MODULES[templateKey] || templateKey,
387
+ risk: riskFromImpact(highestImpact),
388
+ confidence: sortedTriggers.length >= 2 ? 'high' : 'medium',
389
+ triggers: sortedTriggers.map(trigger => ({
390
+ key: trigger.key,
391
+ name: trigger.name,
392
+ impact: trigger.impact,
393
+ fix: trigger.fix,
394
+ })),
395
+ rationale: sortedTriggers.map(trigger => trigger.fix),
396
+ files,
397
+ readyToApply: files.some(file => ['create', 'patch'].includes(file.action)),
398
+ };
399
+ }
400
+
401
+ function proposalMatchesTriggerKeys(proposal, keySet) {
402
+ return (proposal.triggers || []).some((trigger) => keySet.has(trigger.key));
403
+ }
404
+
405
+ function collectCampaignProposals(proposals, predicate) {
406
+ return proposals.filter((proposal) => proposal.readyToApply && predicate(proposal));
407
+ }
408
+
409
+ function buildCampaigns(bundle) {
410
+ const proposals = Array.isArray(bundle?.proposals) ? bundle.proposals : [];
411
+ const campaigns = [];
412
+ const maturity = bundle?.projectSummary?.maturity || 'unknown';
413
+
414
+ const starterBaseline = collectCampaignProposals(
415
+ proposals,
416
+ (proposal) => ['claude-md', 'commands', 'rules', 'hooks', 'agents'].includes(proposal.id),
417
+ );
418
+ if (starterBaseline.length > 0) {
419
+ campaigns.push({
420
+ key: 'starter-baseline',
421
+ label: 'Starter baseline',
422
+ summary: 'Establish the managed baseline surfaces Nerviq expects before deeper upgrades.',
423
+ proposalIds: starterBaseline.map((proposal) => proposal.id),
424
+ milestone: maturity === 'mature' ? 'pre-upgrade' : 'baseline',
425
+ focusAreas: ['config-drift', 'maturity-opportunity'],
426
+ });
427
+ }
428
+
429
+ const verificationClosure = collectCampaignProposals(
430
+ proposals,
431
+ (proposal) => proposalMatchesTriggerKeys(proposal, VERIFICATION_TRIGGER_KEYS),
432
+ );
433
+ if (verificationClosure.length > 0) {
434
+ campaigns.push({
435
+ key: 'verification-closure',
436
+ label: 'Verification closure',
437
+ summary: 'Close missing test/lint/build loops so audits can be verified continuously.',
438
+ proposalIds: verificationClosure.map((proposal) => proposal.id),
439
+ milestone: 'post-fix',
440
+ focusAreas: ['config-drift', 'maturity-opportunity'],
441
+ });
442
+ }
443
+
444
+ const governanceHardening = collectCampaignProposals(
445
+ proposals,
446
+ (proposal) => proposal.id === 'hooks' || proposalMatchesTriggerKeys(proposal, GOVERNANCE_TRIGGER_KEYS),
447
+ );
448
+ if (governanceHardening.length > 0) {
449
+ campaigns.push({
450
+ key: 'governance-hardening',
451
+ label: 'Governance hardening',
452
+ summary: 'Tighten permissions, hooks, secret protection, and reviewable safety defaults.',
453
+ proposalIds: governanceHardening.map((proposal) => proposal.id),
454
+ milestone: 'pre-upgrade',
455
+ focusAreas: ['policy-drift', 'config-drift'],
456
+ });
457
+ }
458
+
459
+ const reviewableAutomation = collectCampaignProposals(
460
+ proposals,
461
+ (proposal) => proposal.id === 'agents' || proposal.id === 'commands' || proposalMatchesTriggerKeys(proposal, AUTOMATION_TRIGGER_KEYS),
462
+ );
463
+ if (reviewableAutomation.length > 0) {
464
+ campaigns.push({
465
+ key: 'reviewable-automation',
466
+ label: 'Reviewable automation',
467
+ summary: 'Add automation surfaces that keep upgrades inspectable instead of ad-hoc.',
468
+ proposalIds: reviewableAutomation.map((proposal) => proposal.id),
469
+ milestone: 'pre-upgrade',
470
+ focusAreas: ['maturity-opportunity', 'config-drift'],
471
+ });
472
+ }
473
+
474
+ return campaigns.filter((campaign, index, all) =>
475
+ all.findIndex((item) => item.key === campaign.key) === index,
476
+ );
477
+ }
478
+
479
+ function filterBundleByCampaigns(bundle, campaignKeys = []) {
480
+ if (!Array.isArray(campaignKeys) || campaignKeys.length === 0) {
481
+ return bundle;
482
+ }
483
+
484
+ const available = new Map((bundle.campaigns || []).map((campaign) => [campaign.key, campaign]));
485
+ const missing = campaignKeys.filter((key) => !available.has(key));
486
+ if (missing.length > 0) {
487
+ throw new Error(`unknown campaign(s): ${missing.join(', ')}`);
488
+ }
489
+
490
+ const selectedIds = new Set();
491
+ for (const key of campaignKeys) {
492
+ for (const proposalId of available.get(key).proposalIds || []) {
493
+ selectedIds.add(proposalId);
494
+ }
495
+ }
496
+
497
+ return {
498
+ ...bundle,
499
+ selectedCampaigns: campaignKeys,
500
+ proposals: bundle.proposals.filter((proposal) => selectedIds.has(proposal.id)),
501
+ campaigns: (bundle.campaigns || []).filter((campaign) => campaignKeys.includes(campaign.key)),
502
+ };
503
+ }
504
+
505
+ function resolveSelectionSet(bundle, options = {}) {
506
+ const proposalIds = new Set((bundle.proposals || []).map((proposal) => proposal.id));
507
+ const onlySet = options.only && options.only.length > 0 ? new Set(options.only) : null;
508
+ const campaignSet = options.campaigns && options.campaigns.length > 0
509
+ ? new Set((bundle.campaigns || []).flatMap((campaign) => {
510
+ if (!options.campaigns.includes(campaign.key)) return [];
511
+ return campaign.proposalIds || [];
512
+ }))
513
+ : null;
514
+
515
+ if (onlySet && campaignSet) {
516
+ return new Set([...onlySet].filter((proposalId) => campaignSet.has(proposalId) && proposalIds.has(proposalId)));
517
+ }
518
+ if (onlySet) {
519
+ return new Set([...onlySet].filter((proposalId) => proposalIds.has(proposalId)));
520
+ }
521
+ if (campaignSet) {
522
+ return new Set([...campaignSet].filter((proposalId) => proposalIds.has(proposalId)));
523
+ }
524
+
525
+ return null;
526
+ }
527
+
528
+ async function buildProposalBundle(options) {
529
+ if (options.platform === 'codex') {
530
+ const bundle = await buildCodexProposalBundle(options);
531
+ return filterBundleByCampaigns({
532
+ ...bundle,
533
+ campaigns: buildCampaigns(bundle),
534
+ }, options.campaigns);
535
+ }
536
+
537
+ const ctx = new ProjectContext(options.dir);
538
+ const stacks = ctx.detectStacks(STACKS);
539
+ const report = await analyzeProject({ ...options, mode: 'augment' });
540
+ const mcpPreflightWarnings = getMcpPackPreflight(options.mcpPacks || [])
541
+ .filter(item => item.missingEnvVars.length > 0);
542
+ const groups = getFailedTemplateGroups(ctx, options.only || []);
543
+ const proposals = [];
544
+
545
+ for (const [templateKey, triggers] of groups.entries()) {
546
+ const templateFiles = buildTemplateFiles(templateKey, stacks, ctx, triggers, options);
547
+ if (templateKey === 'hooks') {
548
+ const plannedHookFiles = templateFiles
549
+ .map(file => path.basename(file.path))
550
+ .filter(file => file.endsWith('.sh') || file.endsWith('.js'));
551
+ const settingsFile = buildHookSettings(ctx, plannedHookFiles, options);
552
+ if (settingsFile) {
553
+ templateFiles.push(settingsFile);
554
+ }
555
+ }
556
+ proposals.push(toProposal(templateKey, triggers, templateFiles, ctx));
557
+ }
558
+
559
+ proposals.sort((a, b) => {
560
+ const impactA = IMPACT_ORDER[a.triggers[0]?.impact] ?? 0;
561
+ const impactB = IMPACT_ORDER[b.triggers[0]?.impact] ?? 0;
562
+ return impactB - impactA;
563
+ });
564
+
565
+ return filterBundleByCampaigns({
566
+ schemaVersion: 1,
567
+ generatedBy: `nerviq@${version}`,
568
+ createdAt: new Date().toISOString(),
569
+ directory: options.dir,
570
+ projectSummary: report.projectSummary,
571
+ strengthsPreserved: report.strengthsPreserved,
572
+ topNextActions: report.topNextActions,
573
+ riskNotes: report.riskNotes,
574
+ mcpPreflightWarnings,
575
+ proposals,
576
+ campaigns: buildCampaigns({ proposals, projectSummary: report.projectSummary }),
577
+ }, options.campaigns);
578
+ }
579
+
580
+ function printProposalBundle(bundle, options = {}) {
581
+ if (options.json) {
582
+ console.log(JSON.stringify(bundle, null, 2));
583
+ return;
584
+ }
585
+
586
+ console.log('');
587
+ console.log(' nerviq plan');
588
+ console.log(' ═══════════════════════════════════════');
589
+ console.log(` ${bundle.projectSummary.name} | maturity=${bundle.projectSummary.maturity} | score=${bundle.projectSummary.score}/100`);
590
+ if (bundle.projectSummary.archetype) {
591
+ console.log(` archetype=${bundle.projectSummary.archetype} | workflow=${bundle.projectSummary.workflow || 'unknown'} | risk=${bundle.projectSummary.riskLevel || 'unknown'}`);
592
+ }
593
+ if (bundle.projectSummary.operatingProfile) {
594
+ console.log(` operating-profile=${bundle.projectSummary.operatingProfile}`);
595
+ }
596
+ console.log('');
597
+
598
+ if (bundle.selectedCampaigns && bundle.selectedCampaigns.length > 0) {
599
+ console.log(` Selected campaigns: ${bundle.selectedCampaigns.join(', ')}`);
600
+ console.log('');
601
+ }
602
+
603
+ if (bundle.mcpPreflightWarnings && bundle.mcpPreflightWarnings.length > 0) {
604
+ console.log(' MCP Preflight Warnings');
605
+ for (const warning of bundle.mcpPreflightWarnings) {
606
+ console.log(` - ${warning.label}: missing ${warning.missingEnvVars.join(', ')}`);
607
+ }
608
+ console.log('');
609
+ }
610
+
611
+ if (bundle.proposals.length === 0) {
612
+ console.log(' No templated proposals are needed right now.');
613
+ console.log('');
614
+ return;
615
+ }
616
+
617
+ if (bundle.campaigns && bundle.campaigns.length > 0) {
618
+ console.log(' Upgrade campaigns');
619
+ for (const campaign of bundle.campaigns) {
620
+ console.log(` - ${campaign.key} (${campaign.milestone})`);
621
+ console.log(` ${campaign.label} — ${campaign.summary}`);
622
+ console.log(` proposals: ${campaign.proposalIds.join(', ')}`);
623
+ }
624
+ console.log('');
625
+ }
626
+
627
+ console.log(' Proposal Bundles');
628
+ for (const proposal of bundle.proposals) {
629
+ const applyState = proposal.readyToApply ? 'ready' : 'manual-review';
630
+ console.log(` - ${proposal.id} [${applyState}]`);
631
+ console.log(` ${proposal.title} | risk=${proposal.risk} | confidence=${proposal.confidence}`);
632
+ console.log(` triggers: ${proposal.triggers.map(item => item.name).join(', ')}`);
633
+ console.log(` files: ${proposal.files.map(file => `${file.path} (${file.action})`).join(', ')}`);
634
+ }
635
+ console.log('');
636
+ }
637
+
638
+ function writePlanFile(bundle, outFile) {
639
+ fs.mkdirSync(path.dirname(outFile), { recursive: true });
640
+ fs.writeFileSync(outFile, JSON.stringify(bundle, null, 2), 'utf8');
641
+ return writeActivityArtifact(bundle.directory, 'plan-export', {
642
+ exportedPlan: outFile,
643
+ proposalIds: bundle.proposals.map(proposal => proposal.id),
644
+ proposalCount: bundle.proposals.length,
645
+ });
646
+ }
647
+
648
+ function tryParseJson(content) {
649
+ try {
650
+ return JSON.parse(content);
651
+ } catch {
652
+ return null;
653
+ }
654
+ }
655
+
656
+ function applyRuntimeSettingsOverlays(bundle, options) {
657
+ if (options.platform === 'codex') {
658
+ return bundle;
659
+ }
660
+
661
+ if (!bundle || !Array.isArray(bundle.proposals)) {
662
+ return bundle;
663
+ }
664
+
665
+ const ctx = new ProjectContext(options.dir);
666
+ const existingHooks = ctx.hasDir('.claude/hooks')
667
+ ? ctx.dirFiles('.claude/hooks').filter(file => file.endsWith('.sh') || file.endsWith('.js'))
668
+ : [];
669
+
670
+ const proposals = bundle.proposals.map((proposal) => {
671
+ const settingsIndex = proposal.files.findIndex(file => file.path === '.claude/settings.json');
672
+ if (settingsIndex === -1) {
673
+ return proposal;
674
+ }
675
+
676
+ const plannedHookFiles = proposal.files
677
+ .filter(file => file.path.startsWith('.claude/hooks/') && file.path.endsWith('.sh'))
678
+ .map(file => path.basename(file.path));
679
+ const hookFiles = [...new Set([...existingHooks, ...plannedHookFiles])].sort();
680
+ const currentSettings = tryParseJson(proposal.files[settingsIndex].content) || ctx.jsonFile('.claude/settings.json') || null;
681
+ const mergedSettings = buildSettingsForProfile({
682
+ profileKey: options.profile || 'safe-write',
683
+ hookFiles,
684
+ existingSettings: currentSettings,
685
+ mcpPackKeys: options.mcpPacks || [],
686
+ });
687
+ const updatedContent = `${JSON.stringify(mergedSettings, null, 2)}\n`;
688
+ const currentFile = proposal.files[settingsIndex];
689
+
690
+ const files = [...proposal.files];
691
+ files[settingsIndex] = {
692
+ ...currentFile,
693
+ content: updatedContent,
694
+ preview: previewContent(updatedContent),
695
+ diffPreview: [
696
+ `--- ${ctx.fileContent(currentFile.path) !== null ? currentFile.path : 'missing'}`,
697
+ `+++ ${currentFile.path}`,
698
+ ...previewContent(updatedContent).split('\n').map(line => `+${line}`),
699
+ ].join('\n'),
700
+ currentState: currentFile.currentState || 'existing settings are missing runtime-selected protections or MCP packs',
701
+ proposedState: `merge ${options.profile || 'safe-write'} profile protections and requested MCP packs into settings`,
702
+ };
703
+
704
+ return {
705
+ ...proposal,
706
+ files,
707
+ };
708
+ });
709
+
710
+ return {
711
+ ...bundle,
712
+ proposals,
713
+ };
714
+ }
715
+
716
+ function resolvePlan(bundle, options) {
717
+ if (options.planFile) {
718
+ return filterBundleByCampaigns(
719
+ applyRuntimeSettingsOverlays(JSON.parse(fs.readFileSync(options.planFile, 'utf8')), options),
720
+ options.campaigns,
721
+ );
722
+ }
723
+ return filterBundleByCampaigns(applyRuntimeSettingsOverlays(bundle, options), options.campaigns);
724
+ }
725
+
726
+ async function applyProposalBundle(options) {
727
+ const liveBundle = options.planFile ? null : await buildProposalBundle(options);
728
+ const bundle = resolvePlan(liveBundle, options);
729
+ const mcpPreflightWarnings = getMcpPackPreflight(options.mcpPacks || [])
730
+ .filter(item => item.missingEnvVars.length > 0);
731
+ const selectedIds = resolveSelectionSet(bundle, options);
732
+ const selected = bundle.proposals.filter(proposal => {
733
+ if (selectedIds && !selectedIds.has(proposal.id)) return false;
734
+ return proposal.readyToApply;
735
+ });
736
+
737
+ const createdFiles = [];
738
+ const patchedFiles = [];
739
+ const skippedFiles = [];
740
+ for (const proposal of selected) {
741
+ for (const file of proposal.files) {
742
+ if (!['create', 'patch'].includes(file.action)) {
743
+ skippedFiles.push(file.path);
744
+ continue;
745
+ }
746
+ const fullPath = path.join(options.dir, file.path);
747
+ if (file.action === 'create' && fs.existsSync(fullPath)) {
748
+ skippedFiles.push(file.path);
749
+ continue;
750
+ }
751
+ const previousContent = fs.existsSync(fullPath) ? fs.readFileSync(fullPath, 'utf8') : null;
752
+ if (!options.dryRun) {
753
+ fs.mkdirSync(path.dirname(fullPath), { recursive: true });
754
+ fs.writeFileSync(fullPath, file.content, 'utf8');
755
+ }
756
+ if (file.action === 'create') {
757
+ createdFiles.push(file.path);
758
+ } else {
759
+ patchedFiles.push({ path: file.path, previousContent });
760
+ }
761
+ }
762
+ }
763
+
764
+ let rollback = null;
765
+ let activity = null;
766
+ if (!options.dryRun && (createdFiles.length > 0 || patchedFiles.length > 0)) {
767
+ rollback = writeRollbackArtifact(options.dir, {
768
+ sourcePlan: options.planFile ? path.basename(options.planFile) : 'live-plan',
769
+ createdFiles,
770
+ patchedFiles,
771
+ rollbackInstructions: [
772
+ ...createdFiles.map(file => `Delete ${file}`),
773
+ ...patchedFiles.map(file => `Restore previous content for ${file.path} from this manifest`),
774
+ ],
775
+ });
776
+ activity = writeActivityArtifact(options.dir, 'apply', {
777
+ sourcePlan: options.planFile ? path.basename(options.planFile) : 'live-plan',
778
+ appliedProposalIds: selected.map(item => item.id),
779
+ createdFiles,
780
+ patchedFiles: patchedFiles.map(file => file.path),
781
+ skippedFiles,
782
+ rollbackArtifact: rollback.relativePath,
783
+ });
784
+ }
785
+
786
+ return {
787
+ proposalCount: bundle.proposals.length,
788
+ appliedProposalIds: selected.map(item => item.id),
789
+ selectedCampaigns: bundle.selectedCampaigns || options.campaigns || [],
790
+ createdFiles,
791
+ patchedFiles: patchedFiles.map(file => file.path),
792
+ skippedFiles,
793
+ dryRun: options.dryRun === true,
794
+ rollbackArtifact: rollback ? rollback.relativePath : null,
795
+ activityArtifact: activity ? activity.relativePath : null,
796
+ mcpPreflightWarnings,
797
+ };
798
+ }
799
+
800
+ function printApplyResult(result, options = {}) {
801
+ if (options.json) {
802
+ console.log(JSON.stringify(result, null, 2));
803
+ return;
804
+ }
805
+
806
+ console.log('');
807
+ console.log(' nerviq apply');
808
+ console.log(' ═══════════════════════════════════════');
809
+ if (result.dryRun) {
810
+ console.log(' Dry-run only. No files were written.');
811
+ }
812
+ console.log(` Applied proposal bundles: ${result.appliedProposalIds.join(', ') || 'none'}`);
813
+ if (result.selectedCampaigns && result.selectedCampaigns.length > 0) {
814
+ console.log(` Campaigns: ${result.selectedCampaigns.join(', ')}`);
815
+ }
816
+ console.log(` Created files: ${result.createdFiles.join(', ') || 'none'}`);
817
+ console.log(` Patched files: ${result.patchedFiles.join(', ') || 'none'}`);
818
+ if (result.mcpPreflightWarnings && result.mcpPreflightWarnings.length > 0) {
819
+ console.log(' MCP preflight warnings:');
820
+ for (const warning of result.mcpPreflightWarnings) {
821
+ console.log(` - ${warning.label}: missing ${warning.missingEnvVars.join(', ')}`);
822
+ }
823
+ }
824
+ if (result.rollbackArtifact) {
825
+ console.log(` Rollback: ${result.rollbackArtifact}`);
826
+ }
827
+ if (result.activityArtifact) {
828
+ console.log(` Activity log: ${result.activityArtifact}`);
829
+ }
830
+ console.log('');
831
+ }
832
+
833
+ module.exports = {
834
+ buildProposalBundle,
835
+ printProposalBundle,
836
+ writePlanFile,
837
+ applyProposalBundle,
838
+ printApplyResult,
839
+ };