@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
package/src/fix-engine.js CHANGED
@@ -1,783 +1,783 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const readline = require('readline');
4
-
5
- const { ProjectContext } = require('./context');
6
- const { TECHNIQUES, STACKS } = require('./techniques');
7
- const { TEMPLATES, setup } = require('./setup');
8
- const { detectProjectMetadata, detectScripts } = require('./setup/analysis');
9
- const { writeRollbackArtifact } = require('./activity');
10
- const { recordPattern } = require('./usage-patterns');
11
- const { audit } = require('./audit');
12
- const {
13
- hasDocumentedVerificationGuidance,
14
- hasDocumentedTestCommand,
15
- hasDocumentedLintCommand,
16
- hasDocumentedBuildCommand,
17
- } = require('./instruction-surfaces');
18
-
19
- const IMPACT_ORDER = {
20
- critical: 3,
21
- high: 2,
22
- medium: 1,
23
- low: 0,
24
- };
25
-
26
- const CUSTOM_FIXER_KEYS = new Set([
27
- 'claudeMd',
28
- 'verificationLoop',
29
- 'testCommand',
30
- 'lintCommand',
31
- 'buildCommand',
32
- 'license',
33
- 'changelog',
34
- 'contributing',
35
- 'gitIgnoreEnv',
36
- 'secretsProtection',
37
- ]);
38
-
39
- const AUDIT_FIX_KEYS = new Set([
40
- 'claudeMd',
41
- 'verificationLoop',
42
- 'testCommand',
43
- 'lintCommand',
44
- 'buildCommand',
45
- 'license',
46
- 'changelog',
47
- 'contributing',
48
- ]);
49
-
50
- const INSTRUCTION_KEYS = new Set([
51
- 'claudeMd',
52
- 'verificationLoop',
53
- 'testCommand',
54
- 'lintCommand',
55
- 'buildCommand',
56
- ]);
57
-
58
- const QUALITY_COMMAND_KEYS = new Set([
59
- 'verificationLoop',
60
- 'testCommand',
61
- 'lintCommand',
62
- 'buildCommand',
63
- ]);
64
-
65
- function normalizeNewlines(content) {
66
- return String(content || '').replace(/\r\n/g, '\n');
67
- }
68
-
69
- function ensureTrailingNewline(content) {
70
- const normalized = normalizeNewlines(content);
71
- return normalized.endsWith('\n') ? normalized : `${normalized}\n`;
72
- }
73
-
74
- function normalizeForCompare(content) {
75
- return ensureTrailingNewline(content || '');
76
- }
77
-
78
- function unique(values) {
79
- return [...new Set(values.filter(Boolean))];
80
- }
81
-
82
- function sortFailedResults(a, b) {
83
- const impactDiff = (IMPACT_ORDER[b.impact] || 0) - (IMPACT_ORDER[a.impact] || 0);
84
- if (impactDiff !== 0) return impactDiff;
85
- return String(a.key || '').localeCompare(String(b.key || ''));
86
- }
87
-
88
- function highestImpact(keys, failedByKey) {
89
- const impacts = keys.map((key) => (failedByKey.get(key) || TECHNIQUES[key] || {}).impact);
90
- return impacts.sort((a, b) => (IMPACT_ORDER[b] || 0) - (IMPACT_ORDER[a] || 0))[0] || 'medium';
91
- }
92
-
93
- function isFixableKey(key, { mode = 'fix' } = {}) {
94
- if (mode === 'audit') {
95
- return AUDIT_FIX_KEYS.has(key);
96
- }
97
- return Boolean(TECHNIQUES[key] && TECHNIQUES[key].template) || CUSTOM_FIXER_KEYS.has(key);
98
- }
99
-
100
- function getFixableFailedResults(failedResults, { mode = 'fix', criticalOnly = false } = {}) {
101
- return [...(failedResults || [])]
102
- .filter((item) => item && item.passed === false)
103
- .filter((item) => isFixableKey(item.key, { mode }))
104
- .filter((item) => !criticalOnly || item.impact === 'critical')
105
- .sort(sortFailedResults);
106
- }
107
-
108
- function resolveInstructionPath(ctx, platform = 'claude') {
109
- if (platform === 'codex') {
110
- if (ctx.fileContent('AGENTS.md') !== null) return 'AGENTS.md';
111
- if (ctx.fileContent('.codex/AGENTS.md') !== null) return '.codex/AGENTS.md';
112
- return 'AGENTS.md';
113
- }
114
-
115
- if (ctx.fileContent('CLAUDE.md') !== null) return 'CLAUDE.md';
116
- if (ctx.fileContent('.claude/CLAUDE.md') !== null) return '.claude/CLAUDE.md';
117
- if (ctx.fileContent('AGENTS.md') !== null) return 'AGENTS.md';
118
- return 'CLAUDE.md';
119
- }
120
-
121
- function stackKeys(stacks) {
122
- return new Set((stacks || []).map((item) => item.key));
123
- }
124
-
125
- function getVerificationCommands(ctx, stacks) {
126
- const scripts = detectScripts(ctx);
127
- const detected = stackKeys(stacks);
128
-
129
- if (scripts.test || scripts.lint || scripts.build) {
130
- return {
131
- test: scripts.test ? 'npm test' : 'npm test',
132
- lint: scripts.lint ? 'npm run lint' : 'npm run lint',
133
- build: scripts.build ? 'npm run build' : 'npm run build',
134
- };
135
- }
136
-
137
- if (detected.has('python') || detected.has('django') || detected.has('fastapi')) {
138
- return {
139
- test: 'python -m pytest',
140
- lint: 'ruff check .',
141
- build: 'python -m build',
142
- };
143
- }
144
-
145
- if (detected.has('go')) {
146
- return {
147
- test: 'go test ./...',
148
- lint: 'go vet ./...',
149
- build: 'go build ./...',
150
- };
151
- }
152
-
153
- if (detected.has('rust')) {
154
- return {
155
- test: 'cargo test',
156
- lint: 'cargo clippy --all-targets --all-features',
157
- build: 'cargo build',
158
- };
159
- }
160
-
161
- if (detected.has('dotnet')) {
162
- return {
163
- test: 'dotnet test',
164
- lint: 'dotnet format --verify-no-changes',
165
- build: 'dotnet build',
166
- };
167
- }
168
-
169
- if (detected.has('java') || detected.has('kotlin')) {
170
- return {
171
- test: './gradlew test',
172
- lint: './gradlew check',
173
- build: './gradlew build',
174
- };
175
- }
176
-
177
- if (detected.has('flutter')) {
178
- return {
179
- test: 'flutter test',
180
- lint: 'flutter analyze',
181
- build: 'flutter build apk',
182
- };
183
- }
184
-
185
- if (detected.has('swift')) {
186
- return {
187
- test: 'swift test',
188
- lint: 'swiftlint',
189
- build: 'swift build',
190
- };
191
- }
192
-
193
- return {
194
- test: 'npm test',
195
- lint: 'npm run lint',
196
- build: 'npm run build',
197
- };
198
- }
199
-
200
- function buildVerificationBlock(commands) {
201
- return [
202
- '## Verification',
203
- '- Run the repository checks before handoff:',
204
- `- Test: \`${commands.test}\``,
205
- `- Lint: \`${commands.lint}\``,
206
- `- Build: \`${commands.build}\``,
207
- ].join('\n');
208
- }
209
-
210
- function upsertManagedBlock(content, id, block) {
211
- const start = `<!-- nerviq:${id}:start -->`;
212
- const end = `<!-- nerviq:${id}:end -->`;
213
- const wrapped = `${start}\n${block.trim()}\n${end}`;
214
- const pattern = new RegExp(`${start}[\\s\\S]*?${end}`);
215
- if (pattern.test(content)) {
216
- return {
217
- changed: true,
218
- content: content.replace(pattern, wrapped),
219
- };
220
- }
221
-
222
- return {
223
- changed: true,
224
- content: `${content.trimEnd()}\n\n${wrapped}\n`,
225
- };
226
- }
227
-
228
- function buildAgentsTemplate(ctx, commands) {
229
- const meta = detectProjectMetadata(ctx);
230
- const title = meta.name || path.basename(ctx.dir);
231
-
232
- return [
233
- `# ${title}`,
234
- '',
235
- '## Scope',
236
- '- Work inside the existing project boundaries and preserve established patterns.',
237
- '- Keep changes scoped to the requested task unless the repo clearly requires more.',
238
- '',
239
- buildVerificationBlock(commands),
240
- '',
241
- '## Working Agreement',
242
- '- Prefer editing existing files over introducing parallel abstractions.',
243
- '- Call out assumptions before taking repo-wide actions.',
244
- ].join('\n');
245
- }
246
-
247
- function buildLicenseTemplate(ctx) {
248
- const meta = detectProjectMetadata(ctx);
249
- const pkg = ctx.jsonFile('package.json') || {};
250
- const year = new Date().getFullYear();
251
- const name = meta.name || path.basename(ctx.dir);
252
- const declaredLicense = pkg.license ? `Declared license: ${pkg.license}` : 'Declared license: choose the approved license for this repository.';
253
-
254
- return [
255
- `${name} License Placeholder`,
256
- '',
257
- `Copyright (c) ${year} ${name}`,
258
- '',
259
- declaredLicense,
260
- 'Replace this placeholder with the full, approved license text before publishing or distribution.',
261
- ].join('\n');
262
- }
263
-
264
- function buildChangelogTemplate() {
265
- return [
266
- '# Changelog',
267
- '',
268
- 'All notable changes to this project will be documented in this file.',
269
- '',
270
- '## [Unreleased]',
271
- '',
272
- '### Added',
273
- '',
274
- '### Changed',
275
- '',
276
- '### Fixed',
277
- '',
278
- '### Security',
279
- ].join('\n');
280
- }
281
-
282
- function buildContributingTemplate(ctx, commands) {
283
- const meta = detectProjectMetadata(ctx);
284
- return [
285
- '# Contributing',
286
- '',
287
- `Thanks for contributing to ${meta.name || path.basename(ctx.dir)}.`,
288
- '',
289
- '## Local Setup',
290
- '- Install dependencies with the project-standard package manager.',
291
- '- Read the repository instructions before making changes.',
292
- '',
293
- '## Verification',
294
- `- Test: \`${commands.test}\``,
295
- `- Lint: \`${commands.lint}\``,
296
- `- Build: \`${commands.build}\``,
297
- '',
298
- '## Pull Requests',
299
- '- Keep changes focused and explain the user-facing impact.',
300
- '- Update docs and tests when behavior changes.',
301
- ].join('\n');
302
- }
303
-
304
- function buildInstructionOperation({ ctx, stacks, failedByKey, platform, targetKeys }) {
305
- const keys = targetKeys.filter((key) => INSTRUCTION_KEYS.has(key));
306
- if (keys.length === 0) return null;
307
-
308
- const targetPath = resolveInstructionPath(ctx, platform);
309
- const existing = ctx.fileContent(targetPath);
310
- const commands = getVerificationCommands(ctx, stacks);
311
- let content = existing === null
312
- ? (
313
- targetPath.toLowerCase().includes('agents')
314
- ? buildAgentsTemplate(ctx, commands)
315
- : TEMPLATES['claude-md'](stacks, ctx)
316
- )
317
- : normalizeNewlines(existing);
318
-
319
- if (keys.some((key) => QUALITY_COMMAND_KEYS.has(key))) {
320
- const needsVerification = !hasDocumentedVerificationGuidance(content);
321
- const needsTest = !hasDocumentedTestCommand(content);
322
- const needsLint = !hasDocumentedLintCommand(content);
323
- const needsBuild = !hasDocumentedBuildCommand(content);
324
-
325
- if (needsVerification || needsTest || needsLint || needsBuild) {
326
- const merged = upsertManagedBlock(content, 'audit-fix-verification', buildVerificationBlock(commands));
327
- content = merged.content;
328
- }
329
- }
330
-
331
- const after = ensureTrailingNewline(content);
332
- if (existing !== null && normalizeForCompare(existing) === normalizeForCompare(after)) {
333
- return null;
334
- }
335
-
336
- return {
337
- type: 'file',
338
- path: targetPath,
339
- action: existing === null ? 'create' : 'patch',
340
- before: existing,
341
- after,
342
- keys,
343
- impact: highestImpact(keys, failedByKey),
344
- };
345
- }
346
-
347
- function buildSimpleCreateOperation(filePath, content, keys, failedByKey) {
348
- return {
349
- type: 'file',
350
- path: filePath,
351
- action: 'create',
352
- before: null,
353
- after: ensureTrailingNewline(content),
354
- keys,
355
- impact: highestImpact(keys, failedByKey),
356
- };
357
- }
358
-
359
- function buildGitIgnoreOperation(ctx, failedByKey) {
360
- const existing = ctx.fileContent('.gitignore');
361
- const normalized = normalizeNewlines(existing || '');
362
- if (/(^|\n)\.env(\n|$)/.test(normalized) || normalized.includes('.env.*')) {
363
- return null;
364
- }
365
-
366
- const prefix = normalized && !normalized.endsWith('\n') ? '\n' : '';
367
- return {
368
- type: 'file',
369
- path: '.gitignore',
370
- action: existing === null ? 'create' : 'patch',
371
- before: existing,
372
- after: ensureTrailingNewline(`${normalized}${prefix}.env\n.env.*\n`),
373
- keys: ['gitIgnoreEnv'],
374
- impact: highestImpact(['gitIgnoreEnv'], failedByKey),
375
- };
376
- }
377
-
378
- function buildSecretsProtectionOperation(ctx, failedByKey) {
379
- const settingsPath = '.claude/settings.json';
380
- const existing = ctx.fileContent(settingsPath);
381
- let settings = {};
382
- if (existing) {
383
- try {
384
- settings = JSON.parse(existing);
385
- } catch {
386
- settings = {};
387
- }
388
- }
389
-
390
- settings.permissions = settings.permissions || {};
391
- settings.permissions.deny = Array.isArray(settings.permissions.deny) ? settings.permissions.deny : [];
392
- const denyEntries = ['.env', '.env.*', '**/.env', '**/*.pem', '**/secrets/**'];
393
- for (const entry of denyEntries) {
394
- if (!settings.permissions.deny.includes(entry)) {
395
- settings.permissions.deny.push(entry);
396
- }
397
- }
398
- if (Array.isArray(settings.permissions.allow) && settings.permissions.allow.includes('*')) {
399
- settings.permissions.allow = settings.permissions.allow.filter((item) => item !== '*');
400
- if (settings.permissions.allow.length === 0) {
401
- delete settings.permissions.allow;
402
- }
403
- }
404
-
405
- const after = `${JSON.stringify(settings, null, 2)}\n`;
406
- if (existing !== null && normalizeForCompare(existing) === normalizeForCompare(after)) {
407
- return null;
408
- }
409
-
410
- return {
411
- type: 'file',
412
- path: settingsPath,
413
- action: existing === null ? 'create' : 'patch',
414
- before: existing,
415
- after,
416
- keys: ['secretsProtection'],
417
- impact: highestImpact(['secretsProtection'], failedByKey),
418
- };
419
- }
420
-
421
- function buildFixPlan({ dir, platform, auditResult, targetKeys }) {
422
- const ctx = new ProjectContext(dir);
423
- const stacks = ctx.detectStacks(STACKS);
424
- const failedByKey = new Map(
425
- ((auditResult && auditResult.results) || [])
426
- .filter((item) => item && item.passed === false)
427
- .map((item) => [item.key, item]),
428
- );
429
-
430
- const normalizedKeys = unique(targetKeys);
431
- const customKeys = normalizedKeys.filter((key) => CUSTOM_FIXER_KEYS.has(key));
432
- const templateKeys = normalizedKeys.filter((key) => !CUSTOM_FIXER_KEYS.has(key) && TECHNIQUES[key] && TECHNIQUES[key].template);
433
- const operations = [];
434
-
435
- const instructionOperation = buildInstructionOperation({
436
- ctx,
437
- stacks,
438
- failedByKey,
439
- platform,
440
- targetKeys: customKeys,
441
- });
442
- if (instructionOperation) {
443
- operations.push(instructionOperation);
444
- }
445
-
446
- if (customKeys.includes('license') && ctx.fileContent('LICENSE') === null) {
447
- operations.push(buildSimpleCreateOperation('LICENSE', buildLicenseTemplate(ctx), ['license'], failedByKey));
448
- }
449
- if (customKeys.includes('changelog') && ctx.fileContent('CHANGELOG.md') === null) {
450
- operations.push(buildSimpleCreateOperation('CHANGELOG.md', buildChangelogTemplate(), ['changelog'], failedByKey));
451
- }
452
- if (customKeys.includes('contributing') && ctx.fileContent('CONTRIBUTING.md') === null) {
453
- operations.push(buildSimpleCreateOperation(
454
- 'CONTRIBUTING.md',
455
- buildContributingTemplate(ctx, getVerificationCommands(ctx, stacks)),
456
- ['contributing'],
457
- failedByKey,
458
- ));
459
- }
460
- if (customKeys.includes('gitIgnoreEnv')) {
461
- const gitIgnoreOperation = buildGitIgnoreOperation(ctx, failedByKey);
462
- if (gitIgnoreOperation) {
463
- operations.push(gitIgnoreOperation);
464
- }
465
- }
466
- if (customKeys.includes('secretsProtection')) {
467
- const secretsOperation = buildSecretsProtectionOperation(ctx, failedByKey);
468
- if (secretsOperation) {
469
- operations.push(secretsOperation);
470
- }
471
- }
472
-
473
- for (const key of templateKeys) {
474
- operations.push({
475
- type: 'template',
476
- key,
477
- keys: [key],
478
- impact: highestImpact([key], failedByKey),
479
- });
480
- }
481
-
482
- return operations.sort((a, b) => {
483
- const impactDiff = (IMPACT_ORDER[b.impact] || 0) - (IMPACT_ORDER[a.impact] || 0);
484
- if (impactDiff !== 0) return impactDiff;
485
- return String(a.path || a.key).localeCompare(String(b.path || b.key));
486
- });
487
- }
488
-
489
- function formatDiff(filePath, before, after) {
490
- const beforeLines = before === null ? [] : normalizeNewlines(before).split('\n');
491
- const afterLines = normalizeNewlines(after).split('\n');
492
-
493
- if (before === null) {
494
- return [
495
- '--- /dev/null',
496
- `+++ ${filePath}`,
497
- '@@',
498
- ...afterLines.map((line) => `+${line}`),
499
- ].join('\n');
500
- }
501
-
502
- let start = 0;
503
- while (
504
- start < beforeLines.length &&
505
- start < afterLines.length &&
506
- beforeLines[start] === afterLines[start]
507
- ) {
508
- start += 1;
509
- }
510
-
511
- let endBefore = beforeLines.length - 1;
512
- let endAfter = afterLines.length - 1;
513
- while (
514
- endBefore >= start &&
515
- endAfter >= start &&
516
- beforeLines[endBefore] === afterLines[endAfter]
517
- ) {
518
- endBefore -= 1;
519
- endAfter -= 1;
520
- }
521
-
522
- const removed = beforeLines.slice(start, endBefore + 1);
523
- const added = afterLines.slice(start, endAfter + 1);
524
-
525
- return [
526
- `--- ${filePath}`,
527
- `+++ ${filePath}`,
528
- '@@',
529
- ...removed.map((line) => `-${line}`),
530
- ...added.map((line) => `+${line}`),
531
- ].join('\n');
532
- }
533
-
534
- function hasDoNotAutoEditMarker(content) {
535
- return typeof content === 'string' && content.includes('DO NOT AUTOEDIT');
536
- }
537
-
538
- async function confirmOperation(operation, logger) {
539
- logger.log('');
540
- logger.log(` קובץ: ${operation.path}`);
541
- logger.log(formatDiff(operation.path, operation.before, operation.after));
542
- logger.log('');
543
-
544
- const rl = readline.createInterface({
545
- input: process.stdin,
546
- output: process.stdout,
547
- });
548
-
549
- const answer = await new Promise((resolve) => {
550
- rl.question(' להחיל את השינוי הזה? (Y/n) ', resolve);
551
- });
552
- rl.close();
553
-
554
- const normalized = String(answer || '').trim().toLowerCase();
555
- return normalized === '' || normalized === 'y' || normalized === 'yes';
556
- }
557
-
558
- function createRollbackArtifact(dir, createdFiles, patchedFiles, sourceLabel) {
559
- if (createdFiles.length === 0 && patchedFiles.length === 0) {
560
- return null;
561
- }
562
-
563
- return writeRollbackArtifact(dir, {
564
- sourcePlan: sourceLabel,
565
- createdFiles,
566
- patchedFiles,
567
- rollbackInstructions: [
568
- ...createdFiles.map((file) => `Delete ${file}`),
569
- ...patchedFiles.map((file) => `Restore previous content for ${file.path} from this manifest`),
570
- ],
571
- });
572
- }
573
-
574
- function describeTemplateOperation(operation) {
575
- const technique = TECHNIQUES[operation.key] || {};
576
- return `${operation.key} (${technique.name || 'template fix'})`;
577
- }
578
-
579
- async function applyFixes({
580
- dir,
581
- platform,
582
- auditResult,
583
- targetKeys,
584
- auto = false,
585
- dryRun = false,
586
- mode = 'fix',
587
- logger = console,
588
- recordOutcomes = false,
589
- }) {
590
- const plan = buildFixPlan({ dir, platform, auditResult, targetKeys });
591
- const createdFiles = [];
592
- const patchedFiles = [];
593
- const keyStatus = new Map();
594
- const warnings = [];
595
- let rollbackArtifact = null;
596
-
597
- if (plan.length === 0) {
598
- return {
599
- exitCode: 2,
600
- plan,
601
- warnings,
602
- rollbackArtifact: null,
603
- keyStatus,
604
- reAudit: auditResult,
605
- targetedKeys: unique(targetKeys),
606
- };
607
- }
608
-
609
- if (!dryRun && !auto && (!process.stdin.isTTY || !process.stdout.isTTY)) {
610
- logger.error('\n שגיאה: `audit --fix` בלי `--auto` דורש טרמינל אינטראקטיבי.\n');
611
- return {
612
- exitCode: 2,
613
- plan,
614
- warnings,
615
- rollbackArtifact: null,
616
- keyStatus,
617
- reAudit: auditResult,
618
- targetedKeys: unique(targetKeys),
619
- };
620
- }
621
-
622
- logger.log('');
623
- logger.log(` תוכנית autofix: ${plan.length} פריט(ים), ${unique(targetKeys).length} בדיקות יעד`);
624
-
625
- if (dryRun) {
626
- for (const operation of plan) {
627
- logger.log('');
628
- if (operation.type === 'file') {
629
- logger.log(` שינוי מוצע: ${operation.path}`);
630
- logger.log(formatDiff(operation.path, operation.before, operation.after));
631
- } else {
632
- logger.log(` תיקון תבנית מוצע: ${describeTemplateOperation(operation)}`);
633
- }
634
- for (const key of operation.keys) {
635
- keyStatus.set(key, 'dry-run');
636
- }
637
- }
638
- logger.log('\n Dry-run הושלם. לא נכתבו קבצים.\n');
639
- return {
640
- exitCode: 0,
641
- plan,
642
- warnings,
643
- rollbackArtifact: null,
644
- keyStatus,
645
- reAudit: auditResult,
646
- targetedKeys: unique(targetKeys),
647
- };
648
- }
649
-
650
- try {
651
- for (const operation of plan) {
652
- if (operation.type === 'file' && hasDoNotAutoEditMarker(operation.before)) {
653
- const warning = `Skipped ${operation.path}: DO NOT AUTOEDIT marker found.`;
654
- warnings.push(warning);
655
- logger.warn(` Warning: ${warning}`);
656
- for (const key of operation.keys) {
657
- keyStatus.set(key, 'skipped-do-not-autoedit');
658
- }
659
- continue;
660
- }
661
-
662
- if (!auto) {
663
- const confirmed = await confirmOperation(operation, logger);
664
- if (!confirmed) {
665
- logger.log(` דולג: ${operation.path}`);
666
- for (const key of operation.keys) {
667
- keyStatus.set(key, 'skipped');
668
- }
669
- continue;
670
- }
671
- }
672
-
673
- if (operation.type === 'template') {
674
- const result = await setup({
675
- dir,
676
- platform,
677
- only: [operation.key],
678
- silent: true,
679
- });
680
- const didWrite = Array.isArray(result.writtenFiles) && result.writtenFiles.length > 0;
681
- for (const key of operation.keys) {
682
- keyStatus.set(key, didWrite ? 'applied' : 'skipped');
683
- }
684
- logger.log(` ${didWrite ? 'הוחל' : 'דולג'} תיקון תבנית: ${describeTemplateOperation(operation)}`);
685
- continue;
686
- }
687
-
688
- const fullPath = path.join(dir, operation.path);
689
- fs.mkdirSync(path.dirname(fullPath), { recursive: true });
690
- fs.writeFileSync(fullPath, operation.after, 'utf8');
691
- if (operation.action === 'create') {
692
- createdFiles.push(operation.path);
693
- } else {
694
- patchedFiles.push({ path: operation.path, previousContent: operation.before });
695
- }
696
- for (const key of operation.keys) {
697
- keyStatus.set(key, 'applied');
698
- }
699
- logger.log(` הוחל: ${operation.path}`);
700
- }
701
- } catch (error) {
702
- rollbackArtifact = createRollbackArtifact(dir, createdFiles, patchedFiles, mode === 'audit' ? 'audit-fix' : 'fix-command');
703
- logger.error(`\n Error: ${error.message}`);
704
- if (rollbackArtifact) {
705
- logger.error(` נשמר rollback: ${rollbackArtifact.relativePath}`);
706
- }
707
- return {
708
- exitCode: 1,
709
- plan,
710
- warnings,
711
- rollbackArtifact,
712
- keyStatus,
713
- reAudit: auditResult,
714
- targetedKeys: unique(targetKeys),
715
- error,
716
- };
717
- }
718
-
719
- rollbackArtifact = createRollbackArtifact(dir, createdFiles, patchedFiles, mode === 'audit' ? 'audit-fix' : 'fix-command');
720
- const reAudit = await audit({ dir, platform, silent: true });
721
- const targetedKeys = unique(targetKeys);
722
- const unresolvedKeys = targetedKeys.filter((key) => {
723
- const check = (reAudit.results || []).find((item) => item.key === key);
724
- return !check || check.passed !== true;
725
- });
726
-
727
- for (const key of targetedKeys) {
728
- const previous = keyStatus.get(key);
729
- if (!previous || previous.startsWith('skipped') || previous === 'failed') {
730
- continue;
731
- }
732
- keyStatus.set(key, unresolvedKeys.includes(key) ? 'failed-verification' : 'verified');
733
- }
734
-
735
- if (recordOutcomes) {
736
- for (const key of targetedKeys) {
737
- const status = keyStatus.get(key);
738
- recordPattern(dir, key, status === 'verified' ? 'accepted' : 'rejected');
739
- }
740
- }
741
-
742
- logger.log('');
743
- logger.log(` ציון לאחר audit חוזר: ${auditResult.score} -> ${reAudit.score}`);
744
- if (rollbackArtifact) {
745
- logger.log(` נשמר rollback: ${rollbackArtifact.relativePath}`);
746
- }
747
- if (unresolvedKeys.length > 0) {
748
- logger.log(` בדיקות שלא נפתרו: ${unresolvedKeys.join(', ')}`);
749
- logger.log('');
750
- return {
751
- exitCode: 1,
752
- plan,
753
- warnings,
754
- rollbackArtifact,
755
- keyStatus,
756
- reAudit,
757
- targetedKeys,
758
- unresolvedKeys,
759
- };
760
- }
761
-
762
- logger.log(' התיקון האוטומטי הושלם בהצלחה.');
763
- logger.log('');
764
- return {
765
- exitCode: 0,
766
- plan,
767
- warnings,
768
- rollbackArtifact,
769
- keyStatus,
770
- reAudit,
771
- targetedKeys,
772
- unresolvedKeys: [],
773
- };
774
- }
775
-
776
- module.exports = {
777
- AUDIT_FIX_KEYS,
778
- CUSTOM_FIXER_KEYS,
779
- applyFixes,
780
- buildFixPlan,
781
- getFixableFailedResults,
782
- isFixableKey,
783
- };
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const readline = require('readline');
4
+
5
+ const { ProjectContext } = require('./context');
6
+ const { TECHNIQUES, STACKS } = require('./techniques');
7
+ const { TEMPLATES, setup } = require('./setup');
8
+ const { detectProjectMetadata, detectScripts } = require('./setup/analysis');
9
+ const { writeRollbackArtifact } = require('./activity');
10
+ const { recordPattern } = require('./usage-patterns');
11
+ const { audit } = require('./audit');
12
+ const {
13
+ hasDocumentedVerificationGuidance,
14
+ hasDocumentedTestCommand,
15
+ hasDocumentedLintCommand,
16
+ hasDocumentedBuildCommand,
17
+ } = require('./instruction-surfaces');
18
+
19
+ const IMPACT_ORDER = {
20
+ critical: 3,
21
+ high: 2,
22
+ medium: 1,
23
+ low: 0,
24
+ };
25
+
26
+ const CUSTOM_FIXER_KEYS = new Set([
27
+ 'claudeMd',
28
+ 'verificationLoop',
29
+ 'testCommand',
30
+ 'lintCommand',
31
+ 'buildCommand',
32
+ 'license',
33
+ 'changelog',
34
+ 'contributing',
35
+ 'gitIgnoreEnv',
36
+ 'secretsProtection',
37
+ ]);
38
+
39
+ const AUDIT_FIX_KEYS = new Set([
40
+ 'claudeMd',
41
+ 'verificationLoop',
42
+ 'testCommand',
43
+ 'lintCommand',
44
+ 'buildCommand',
45
+ 'license',
46
+ 'changelog',
47
+ 'contributing',
48
+ ]);
49
+
50
+ const INSTRUCTION_KEYS = new Set([
51
+ 'claudeMd',
52
+ 'verificationLoop',
53
+ 'testCommand',
54
+ 'lintCommand',
55
+ 'buildCommand',
56
+ ]);
57
+
58
+ const QUALITY_COMMAND_KEYS = new Set([
59
+ 'verificationLoop',
60
+ 'testCommand',
61
+ 'lintCommand',
62
+ 'buildCommand',
63
+ ]);
64
+
65
+ function normalizeNewlines(content) {
66
+ return String(content || '').replace(/\r\n/g, '\n');
67
+ }
68
+
69
+ function ensureTrailingNewline(content) {
70
+ const normalized = normalizeNewlines(content);
71
+ return normalized.endsWith('\n') ? normalized : `${normalized}\n`;
72
+ }
73
+
74
+ function normalizeForCompare(content) {
75
+ return ensureTrailingNewline(content || '');
76
+ }
77
+
78
+ function unique(values) {
79
+ return [...new Set(values.filter(Boolean))];
80
+ }
81
+
82
+ function sortFailedResults(a, b) {
83
+ const impactDiff = (IMPACT_ORDER[b.impact] || 0) - (IMPACT_ORDER[a.impact] || 0);
84
+ if (impactDiff !== 0) return impactDiff;
85
+ return String(a.key || '').localeCompare(String(b.key || ''));
86
+ }
87
+
88
+ function highestImpact(keys, failedByKey) {
89
+ const impacts = keys.map((key) => (failedByKey.get(key) || TECHNIQUES[key] || {}).impact);
90
+ return impacts.sort((a, b) => (IMPACT_ORDER[b] || 0) - (IMPACT_ORDER[a] || 0))[0] || 'medium';
91
+ }
92
+
93
+ function isFixableKey(key, { mode = 'fix' } = {}) {
94
+ if (mode === 'audit') {
95
+ return AUDIT_FIX_KEYS.has(key);
96
+ }
97
+ return Boolean(TECHNIQUES[key] && TECHNIQUES[key].template) || CUSTOM_FIXER_KEYS.has(key);
98
+ }
99
+
100
+ function getFixableFailedResults(failedResults, { mode = 'fix', criticalOnly = false } = {}) {
101
+ return [...(failedResults || [])]
102
+ .filter((item) => item && item.passed === false)
103
+ .filter((item) => isFixableKey(item.key, { mode }))
104
+ .filter((item) => !criticalOnly || item.impact === 'critical')
105
+ .sort(sortFailedResults);
106
+ }
107
+
108
+ function resolveInstructionPath(ctx, platform = 'claude') {
109
+ if (platform === 'codex') {
110
+ if (ctx.fileContent('AGENTS.md') !== null) return 'AGENTS.md';
111
+ if (ctx.fileContent('.codex/AGENTS.md') !== null) return '.codex/AGENTS.md';
112
+ return 'AGENTS.md';
113
+ }
114
+
115
+ if (ctx.fileContent('CLAUDE.md') !== null) return 'CLAUDE.md';
116
+ if (ctx.fileContent('.claude/CLAUDE.md') !== null) return '.claude/CLAUDE.md';
117
+ if (ctx.fileContent('AGENTS.md') !== null) return 'AGENTS.md';
118
+ return 'CLAUDE.md';
119
+ }
120
+
121
+ function stackKeys(stacks) {
122
+ return new Set((stacks || []).map((item) => item.key));
123
+ }
124
+
125
+ function getVerificationCommands(ctx, stacks) {
126
+ const scripts = detectScripts(ctx);
127
+ const detected = stackKeys(stacks);
128
+
129
+ if (scripts.test || scripts.lint || scripts.build) {
130
+ return {
131
+ test: scripts.test ? 'npm test' : 'npm test',
132
+ lint: scripts.lint ? 'npm run lint' : 'npm run lint',
133
+ build: scripts.build ? 'npm run build' : 'npm run build',
134
+ };
135
+ }
136
+
137
+ if (detected.has('python') || detected.has('django') || detected.has('fastapi')) {
138
+ return {
139
+ test: 'python -m pytest',
140
+ lint: 'ruff check .',
141
+ build: 'python -m build',
142
+ };
143
+ }
144
+
145
+ if (detected.has('go')) {
146
+ return {
147
+ test: 'go test ./...',
148
+ lint: 'go vet ./...',
149
+ build: 'go build ./...',
150
+ };
151
+ }
152
+
153
+ if (detected.has('rust')) {
154
+ return {
155
+ test: 'cargo test',
156
+ lint: 'cargo clippy --all-targets --all-features',
157
+ build: 'cargo build',
158
+ };
159
+ }
160
+
161
+ if (detected.has('dotnet')) {
162
+ return {
163
+ test: 'dotnet test',
164
+ lint: 'dotnet format --verify-no-changes',
165
+ build: 'dotnet build',
166
+ };
167
+ }
168
+
169
+ if (detected.has('java') || detected.has('kotlin')) {
170
+ return {
171
+ test: './gradlew test',
172
+ lint: './gradlew check',
173
+ build: './gradlew build',
174
+ };
175
+ }
176
+
177
+ if (detected.has('flutter')) {
178
+ return {
179
+ test: 'flutter test',
180
+ lint: 'flutter analyze',
181
+ build: 'flutter build apk',
182
+ };
183
+ }
184
+
185
+ if (detected.has('swift')) {
186
+ return {
187
+ test: 'swift test',
188
+ lint: 'swiftlint',
189
+ build: 'swift build',
190
+ };
191
+ }
192
+
193
+ return {
194
+ test: 'npm test',
195
+ lint: 'npm run lint',
196
+ build: 'npm run build',
197
+ };
198
+ }
199
+
200
+ function buildVerificationBlock(commands) {
201
+ return [
202
+ '## Verification',
203
+ '- Run the repository checks before handoff:',
204
+ `- Test: \`${commands.test}\``,
205
+ `- Lint: \`${commands.lint}\``,
206
+ `- Build: \`${commands.build}\``,
207
+ ].join('\n');
208
+ }
209
+
210
+ function upsertManagedBlock(content, id, block) {
211
+ const start = `<!-- nerviq:${id}:start -->`;
212
+ const end = `<!-- nerviq:${id}:end -->`;
213
+ const wrapped = `${start}\n${block.trim()}\n${end}`;
214
+ const pattern = new RegExp(`${start}[\\s\\S]*?${end}`);
215
+ if (pattern.test(content)) {
216
+ return {
217
+ changed: true,
218
+ content: content.replace(pattern, wrapped),
219
+ };
220
+ }
221
+
222
+ return {
223
+ changed: true,
224
+ content: `${content.trimEnd()}\n\n${wrapped}\n`,
225
+ };
226
+ }
227
+
228
+ function buildAgentsTemplate(ctx, commands) {
229
+ const meta = detectProjectMetadata(ctx);
230
+ const title = meta.name || path.basename(ctx.dir);
231
+
232
+ return [
233
+ `# ${title}`,
234
+ '',
235
+ '## Scope',
236
+ '- Work inside the existing project boundaries and preserve established patterns.',
237
+ '- Keep changes scoped to the requested task unless the repo clearly requires more.',
238
+ '',
239
+ buildVerificationBlock(commands),
240
+ '',
241
+ '## Working Agreement',
242
+ '- Prefer editing existing files over introducing parallel abstractions.',
243
+ '- Call out assumptions before taking repo-wide actions.',
244
+ ].join('\n');
245
+ }
246
+
247
+ function buildLicenseTemplate(ctx) {
248
+ const meta = detectProjectMetadata(ctx);
249
+ const pkg = ctx.jsonFile('package.json') || {};
250
+ const year = new Date().getFullYear();
251
+ const name = meta.name || path.basename(ctx.dir);
252
+ const declaredLicense = pkg.license ? `Declared license: ${pkg.license}` : 'Declared license: choose the approved license for this repository.';
253
+
254
+ return [
255
+ `${name} License Placeholder`,
256
+ '',
257
+ `Copyright (c) ${year} ${name}`,
258
+ '',
259
+ declaredLicense,
260
+ 'Replace this placeholder with the full, approved license text before publishing or distribution.',
261
+ ].join('\n');
262
+ }
263
+
264
+ function buildChangelogTemplate() {
265
+ return [
266
+ '# Changelog',
267
+ '',
268
+ 'All notable changes to this project will be documented in this file.',
269
+ '',
270
+ '## [Unreleased]',
271
+ '',
272
+ '### Added',
273
+ '',
274
+ '### Changed',
275
+ '',
276
+ '### Fixed',
277
+ '',
278
+ '### Security',
279
+ ].join('\n');
280
+ }
281
+
282
+ function buildContributingTemplate(ctx, commands) {
283
+ const meta = detectProjectMetadata(ctx);
284
+ return [
285
+ '# Contributing',
286
+ '',
287
+ `Thanks for contributing to ${meta.name || path.basename(ctx.dir)}.`,
288
+ '',
289
+ '## Local Setup',
290
+ '- Install dependencies with the project-standard package manager.',
291
+ '- Read the repository instructions before making changes.',
292
+ '',
293
+ '## Verification',
294
+ `- Test: \`${commands.test}\``,
295
+ `- Lint: \`${commands.lint}\``,
296
+ `- Build: \`${commands.build}\``,
297
+ '',
298
+ '## Pull Requests',
299
+ '- Keep changes focused and explain the user-facing impact.',
300
+ '- Update docs and tests when behavior changes.',
301
+ ].join('\n');
302
+ }
303
+
304
+ function buildInstructionOperation({ ctx, stacks, failedByKey, platform, targetKeys }) {
305
+ const keys = targetKeys.filter((key) => INSTRUCTION_KEYS.has(key));
306
+ if (keys.length === 0) return null;
307
+
308
+ const targetPath = resolveInstructionPath(ctx, platform);
309
+ const existing = ctx.fileContent(targetPath);
310
+ const commands = getVerificationCommands(ctx, stacks);
311
+ let content = existing === null
312
+ ? (
313
+ targetPath.toLowerCase().includes('agents')
314
+ ? buildAgentsTemplate(ctx, commands)
315
+ : TEMPLATES['claude-md'](stacks, ctx)
316
+ )
317
+ : normalizeNewlines(existing);
318
+
319
+ if (keys.some((key) => QUALITY_COMMAND_KEYS.has(key))) {
320
+ const needsVerification = !hasDocumentedVerificationGuidance(content);
321
+ const needsTest = !hasDocumentedTestCommand(content);
322
+ const needsLint = !hasDocumentedLintCommand(content);
323
+ const needsBuild = !hasDocumentedBuildCommand(content);
324
+
325
+ if (needsVerification || needsTest || needsLint || needsBuild) {
326
+ const merged = upsertManagedBlock(content, 'audit-fix-verification', buildVerificationBlock(commands));
327
+ content = merged.content;
328
+ }
329
+ }
330
+
331
+ const after = ensureTrailingNewline(content);
332
+ if (existing !== null && normalizeForCompare(existing) === normalizeForCompare(after)) {
333
+ return null;
334
+ }
335
+
336
+ return {
337
+ type: 'file',
338
+ path: targetPath,
339
+ action: existing === null ? 'create' : 'patch',
340
+ before: existing,
341
+ after,
342
+ keys,
343
+ impact: highestImpact(keys, failedByKey),
344
+ };
345
+ }
346
+
347
+ function buildSimpleCreateOperation(filePath, content, keys, failedByKey) {
348
+ return {
349
+ type: 'file',
350
+ path: filePath,
351
+ action: 'create',
352
+ before: null,
353
+ after: ensureTrailingNewline(content),
354
+ keys,
355
+ impact: highestImpact(keys, failedByKey),
356
+ };
357
+ }
358
+
359
+ function buildGitIgnoreOperation(ctx, failedByKey) {
360
+ const existing = ctx.fileContent('.gitignore');
361
+ const normalized = normalizeNewlines(existing || '');
362
+ if (/(^|\n)\.env(\n|$)/.test(normalized) || normalized.includes('.env.*')) {
363
+ return null;
364
+ }
365
+
366
+ const prefix = normalized && !normalized.endsWith('\n') ? '\n' : '';
367
+ return {
368
+ type: 'file',
369
+ path: '.gitignore',
370
+ action: existing === null ? 'create' : 'patch',
371
+ before: existing,
372
+ after: ensureTrailingNewline(`${normalized}${prefix}.env\n.env.*\n`),
373
+ keys: ['gitIgnoreEnv'],
374
+ impact: highestImpact(['gitIgnoreEnv'], failedByKey),
375
+ };
376
+ }
377
+
378
+ function buildSecretsProtectionOperation(ctx, failedByKey) {
379
+ const settingsPath = '.claude/settings.json';
380
+ const existing = ctx.fileContent(settingsPath);
381
+ let settings = {};
382
+ if (existing) {
383
+ try {
384
+ settings = JSON.parse(existing);
385
+ } catch {
386
+ settings = {};
387
+ }
388
+ }
389
+
390
+ settings.permissions = settings.permissions || {};
391
+ settings.permissions.deny = Array.isArray(settings.permissions.deny) ? settings.permissions.deny : [];
392
+ const denyEntries = ['.env', '.env.*', '**/.env', '**/*.pem', '**/secrets/**'];
393
+ for (const entry of denyEntries) {
394
+ if (!settings.permissions.deny.includes(entry)) {
395
+ settings.permissions.deny.push(entry);
396
+ }
397
+ }
398
+ if (Array.isArray(settings.permissions.allow) && settings.permissions.allow.includes('*')) {
399
+ settings.permissions.allow = settings.permissions.allow.filter((item) => item !== '*');
400
+ if (settings.permissions.allow.length === 0) {
401
+ delete settings.permissions.allow;
402
+ }
403
+ }
404
+
405
+ const after = `${JSON.stringify(settings, null, 2)}\n`;
406
+ if (existing !== null && normalizeForCompare(existing) === normalizeForCompare(after)) {
407
+ return null;
408
+ }
409
+
410
+ return {
411
+ type: 'file',
412
+ path: settingsPath,
413
+ action: existing === null ? 'create' : 'patch',
414
+ before: existing,
415
+ after,
416
+ keys: ['secretsProtection'],
417
+ impact: highestImpact(['secretsProtection'], failedByKey),
418
+ };
419
+ }
420
+
421
+ function buildFixPlan({ dir, platform, auditResult, targetKeys }) {
422
+ const ctx = new ProjectContext(dir);
423
+ const stacks = ctx.detectStacks(STACKS);
424
+ const failedByKey = new Map(
425
+ ((auditResult && auditResult.results) || [])
426
+ .filter((item) => item && item.passed === false)
427
+ .map((item) => [item.key, item]),
428
+ );
429
+
430
+ const normalizedKeys = unique(targetKeys);
431
+ const customKeys = normalizedKeys.filter((key) => CUSTOM_FIXER_KEYS.has(key));
432
+ const templateKeys = normalizedKeys.filter((key) => !CUSTOM_FIXER_KEYS.has(key) && TECHNIQUES[key] && TECHNIQUES[key].template);
433
+ const operations = [];
434
+
435
+ const instructionOperation = buildInstructionOperation({
436
+ ctx,
437
+ stacks,
438
+ failedByKey,
439
+ platform,
440
+ targetKeys: customKeys,
441
+ });
442
+ if (instructionOperation) {
443
+ operations.push(instructionOperation);
444
+ }
445
+
446
+ if (customKeys.includes('license') && ctx.fileContent('LICENSE') === null) {
447
+ operations.push(buildSimpleCreateOperation('LICENSE', buildLicenseTemplate(ctx), ['license'], failedByKey));
448
+ }
449
+ if (customKeys.includes('changelog') && ctx.fileContent('CHANGELOG.md') === null) {
450
+ operations.push(buildSimpleCreateOperation('CHANGELOG.md', buildChangelogTemplate(), ['changelog'], failedByKey));
451
+ }
452
+ if (customKeys.includes('contributing') && ctx.fileContent('CONTRIBUTING.md') === null) {
453
+ operations.push(buildSimpleCreateOperation(
454
+ 'CONTRIBUTING.md',
455
+ buildContributingTemplate(ctx, getVerificationCommands(ctx, stacks)),
456
+ ['contributing'],
457
+ failedByKey,
458
+ ));
459
+ }
460
+ if (customKeys.includes('gitIgnoreEnv')) {
461
+ const gitIgnoreOperation = buildGitIgnoreOperation(ctx, failedByKey);
462
+ if (gitIgnoreOperation) {
463
+ operations.push(gitIgnoreOperation);
464
+ }
465
+ }
466
+ if (customKeys.includes('secretsProtection')) {
467
+ const secretsOperation = buildSecretsProtectionOperation(ctx, failedByKey);
468
+ if (secretsOperation) {
469
+ operations.push(secretsOperation);
470
+ }
471
+ }
472
+
473
+ for (const key of templateKeys) {
474
+ operations.push({
475
+ type: 'template',
476
+ key,
477
+ keys: [key],
478
+ impact: highestImpact([key], failedByKey),
479
+ });
480
+ }
481
+
482
+ return operations.sort((a, b) => {
483
+ const impactDiff = (IMPACT_ORDER[b.impact] || 0) - (IMPACT_ORDER[a.impact] || 0);
484
+ if (impactDiff !== 0) return impactDiff;
485
+ return String(a.path || a.key).localeCompare(String(b.path || b.key));
486
+ });
487
+ }
488
+
489
+ function formatDiff(filePath, before, after) {
490
+ const beforeLines = before === null ? [] : normalizeNewlines(before).split('\n');
491
+ const afterLines = normalizeNewlines(after).split('\n');
492
+
493
+ if (before === null) {
494
+ return [
495
+ '--- /dev/null',
496
+ `+++ ${filePath}`,
497
+ '@@',
498
+ ...afterLines.map((line) => `+${line}`),
499
+ ].join('\n');
500
+ }
501
+
502
+ let start = 0;
503
+ while (
504
+ start < beforeLines.length &&
505
+ start < afterLines.length &&
506
+ beforeLines[start] === afterLines[start]
507
+ ) {
508
+ start += 1;
509
+ }
510
+
511
+ let endBefore = beforeLines.length - 1;
512
+ let endAfter = afterLines.length - 1;
513
+ while (
514
+ endBefore >= start &&
515
+ endAfter >= start &&
516
+ beforeLines[endBefore] === afterLines[endAfter]
517
+ ) {
518
+ endBefore -= 1;
519
+ endAfter -= 1;
520
+ }
521
+
522
+ const removed = beforeLines.slice(start, endBefore + 1);
523
+ const added = afterLines.slice(start, endAfter + 1);
524
+
525
+ return [
526
+ `--- ${filePath}`,
527
+ `+++ ${filePath}`,
528
+ '@@',
529
+ ...removed.map((line) => `-${line}`),
530
+ ...added.map((line) => `+${line}`),
531
+ ].join('\n');
532
+ }
533
+
534
+ function hasDoNotAutoEditMarker(content) {
535
+ return typeof content === 'string' && content.includes('DO NOT AUTOEDIT');
536
+ }
537
+
538
+ async function confirmOperation(operation, logger) {
539
+ logger.log('');
540
+ logger.log(` קובץ: ${operation.path}`);
541
+ logger.log(formatDiff(operation.path, operation.before, operation.after));
542
+ logger.log('');
543
+
544
+ const rl = readline.createInterface({
545
+ input: process.stdin,
546
+ output: process.stdout,
547
+ });
548
+
549
+ const answer = await new Promise((resolve) => {
550
+ rl.question(' להחיל את השינוי הזה? (Y/n) ', resolve);
551
+ });
552
+ rl.close();
553
+
554
+ const normalized = String(answer || '').trim().toLowerCase();
555
+ return normalized === '' || normalized === 'y' || normalized === 'yes';
556
+ }
557
+
558
+ function createRollbackArtifact(dir, createdFiles, patchedFiles, sourceLabel) {
559
+ if (createdFiles.length === 0 && patchedFiles.length === 0) {
560
+ return null;
561
+ }
562
+
563
+ return writeRollbackArtifact(dir, {
564
+ sourcePlan: sourceLabel,
565
+ createdFiles,
566
+ patchedFiles,
567
+ rollbackInstructions: [
568
+ ...createdFiles.map((file) => `Delete ${file}`),
569
+ ...patchedFiles.map((file) => `Restore previous content for ${file.path} from this manifest`),
570
+ ],
571
+ });
572
+ }
573
+
574
+ function describeTemplateOperation(operation) {
575
+ const technique = TECHNIQUES[operation.key] || {};
576
+ return `${operation.key} (${technique.name || 'template fix'})`;
577
+ }
578
+
579
+ async function applyFixes({
580
+ dir,
581
+ platform,
582
+ auditResult,
583
+ targetKeys,
584
+ auto = false,
585
+ dryRun = false,
586
+ mode = 'fix',
587
+ logger = console,
588
+ recordOutcomes = false,
589
+ }) {
590
+ const plan = buildFixPlan({ dir, platform, auditResult, targetKeys });
591
+ const createdFiles = [];
592
+ const patchedFiles = [];
593
+ const keyStatus = new Map();
594
+ const warnings = [];
595
+ let rollbackArtifact = null;
596
+
597
+ if (plan.length === 0) {
598
+ return {
599
+ exitCode: 2,
600
+ plan,
601
+ warnings,
602
+ rollbackArtifact: null,
603
+ keyStatus,
604
+ reAudit: auditResult,
605
+ targetedKeys: unique(targetKeys),
606
+ };
607
+ }
608
+
609
+ if (!dryRun && !auto && (!process.stdin.isTTY || !process.stdout.isTTY)) {
610
+ logger.error('\n שגיאה: `audit --fix` בלי `--auto` דורש טרמינל אינטראקטיבי.\n');
611
+ return {
612
+ exitCode: 2,
613
+ plan,
614
+ warnings,
615
+ rollbackArtifact: null,
616
+ keyStatus,
617
+ reAudit: auditResult,
618
+ targetedKeys: unique(targetKeys),
619
+ };
620
+ }
621
+
622
+ logger.log('');
623
+ logger.log(` תוכנית autofix: ${plan.length} פריט(ים), ${unique(targetKeys).length} בדיקות יעד`);
624
+
625
+ if (dryRun) {
626
+ for (const operation of plan) {
627
+ logger.log('');
628
+ if (operation.type === 'file') {
629
+ logger.log(` שינוי מוצע: ${operation.path}`);
630
+ logger.log(formatDiff(operation.path, operation.before, operation.after));
631
+ } else {
632
+ logger.log(` תיקון תבנית מוצע: ${describeTemplateOperation(operation)}`);
633
+ }
634
+ for (const key of operation.keys) {
635
+ keyStatus.set(key, 'dry-run');
636
+ }
637
+ }
638
+ logger.log('\n Dry-run הושלם. לא נכתבו קבצים.\n');
639
+ return {
640
+ exitCode: 0,
641
+ plan,
642
+ warnings,
643
+ rollbackArtifact: null,
644
+ keyStatus,
645
+ reAudit: auditResult,
646
+ targetedKeys: unique(targetKeys),
647
+ };
648
+ }
649
+
650
+ try {
651
+ for (const operation of plan) {
652
+ if (operation.type === 'file' && hasDoNotAutoEditMarker(operation.before)) {
653
+ const warning = `Skipped ${operation.path}: DO NOT AUTOEDIT marker found.`;
654
+ warnings.push(warning);
655
+ logger.warn(` Warning: ${warning}`);
656
+ for (const key of operation.keys) {
657
+ keyStatus.set(key, 'skipped-do-not-autoedit');
658
+ }
659
+ continue;
660
+ }
661
+
662
+ if (!auto) {
663
+ const confirmed = await confirmOperation(operation, logger);
664
+ if (!confirmed) {
665
+ logger.log(` דולג: ${operation.path}`);
666
+ for (const key of operation.keys) {
667
+ keyStatus.set(key, 'skipped');
668
+ }
669
+ continue;
670
+ }
671
+ }
672
+
673
+ if (operation.type === 'template') {
674
+ const result = await setup({
675
+ dir,
676
+ platform,
677
+ only: [operation.key],
678
+ silent: true,
679
+ });
680
+ const didWrite = Array.isArray(result.writtenFiles) && result.writtenFiles.length > 0;
681
+ for (const key of operation.keys) {
682
+ keyStatus.set(key, didWrite ? 'applied' : 'skipped');
683
+ }
684
+ logger.log(` ${didWrite ? 'הוחל' : 'דולג'} תיקון תבנית: ${describeTemplateOperation(operation)}`);
685
+ continue;
686
+ }
687
+
688
+ const fullPath = path.join(dir, operation.path);
689
+ fs.mkdirSync(path.dirname(fullPath), { recursive: true });
690
+ fs.writeFileSync(fullPath, operation.after, 'utf8');
691
+ if (operation.action === 'create') {
692
+ createdFiles.push(operation.path);
693
+ } else {
694
+ patchedFiles.push({ path: operation.path, previousContent: operation.before });
695
+ }
696
+ for (const key of operation.keys) {
697
+ keyStatus.set(key, 'applied');
698
+ }
699
+ logger.log(` הוחל: ${operation.path}`);
700
+ }
701
+ } catch (error) {
702
+ rollbackArtifact = createRollbackArtifact(dir, createdFiles, patchedFiles, mode === 'audit' ? 'audit-fix' : 'fix-command');
703
+ logger.error(`\n Error: ${error.message}`);
704
+ if (rollbackArtifact) {
705
+ logger.error(` נשמר rollback: ${rollbackArtifact.relativePath}`);
706
+ }
707
+ return {
708
+ exitCode: 1,
709
+ plan,
710
+ warnings,
711
+ rollbackArtifact,
712
+ keyStatus,
713
+ reAudit: auditResult,
714
+ targetedKeys: unique(targetKeys),
715
+ error,
716
+ };
717
+ }
718
+
719
+ rollbackArtifact = createRollbackArtifact(dir, createdFiles, patchedFiles, mode === 'audit' ? 'audit-fix' : 'fix-command');
720
+ const reAudit = await audit({ dir, platform, silent: true });
721
+ const targetedKeys = unique(targetKeys);
722
+ const unresolvedKeys = targetedKeys.filter((key) => {
723
+ const check = (reAudit.results || []).find((item) => item.key === key);
724
+ return !check || check.passed !== true;
725
+ });
726
+
727
+ for (const key of targetedKeys) {
728
+ const previous = keyStatus.get(key);
729
+ if (!previous || previous.startsWith('skipped') || previous === 'failed') {
730
+ continue;
731
+ }
732
+ keyStatus.set(key, unresolvedKeys.includes(key) ? 'failed-verification' : 'verified');
733
+ }
734
+
735
+ if (recordOutcomes) {
736
+ for (const key of targetedKeys) {
737
+ const status = keyStatus.get(key);
738
+ recordPattern(dir, key, status === 'verified' ? 'accepted' : 'rejected');
739
+ }
740
+ }
741
+
742
+ logger.log('');
743
+ logger.log(` ציון לאחר audit חוזר: ${auditResult.score} -> ${reAudit.score}`);
744
+ if (rollbackArtifact) {
745
+ logger.log(` נשמר rollback: ${rollbackArtifact.relativePath}`);
746
+ }
747
+ if (unresolvedKeys.length > 0) {
748
+ logger.log(` בדיקות שלא נפתרו: ${unresolvedKeys.join(', ')}`);
749
+ logger.log('');
750
+ return {
751
+ exitCode: 1,
752
+ plan,
753
+ warnings,
754
+ rollbackArtifact,
755
+ keyStatus,
756
+ reAudit,
757
+ targetedKeys,
758
+ unresolvedKeys,
759
+ };
760
+ }
761
+
762
+ logger.log(' התיקון האוטומטי הושלם בהצלחה.');
763
+ logger.log('');
764
+ return {
765
+ exitCode: 0,
766
+ plan,
767
+ warnings,
768
+ rollbackArtifact,
769
+ keyStatus,
770
+ reAudit,
771
+ targetedKeys,
772
+ unresolvedKeys: [],
773
+ };
774
+ }
775
+
776
+ module.exports = {
777
+ AUDIT_FIX_KEYS,
778
+ CUSTOM_FIXER_KEYS,
779
+ applyFixes,
780
+ buildFixPlan,
781
+ getFixableFailedResults,
782
+ isFixableKey,
783
+ };