@nerviq/cli 1.8.5 → 1.8.7

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.
package/src/audit.js CHANGED
@@ -1,1443 +1,1443 @@
1
- /**
2
- * Audit engine - evaluates project against CLAUDEX technique database.
3
- */
4
-
5
- const path = require('path');
6
- const { TECHNIQUES: CLAUDE_TECHNIQUES, STACKS, STACK_CATEGORY_DETECTORS } = require('./techniques');
7
- const { ProjectContext } = require('./context');
8
- const { CODEX_TECHNIQUES } = require('./codex/techniques');
9
- const { detectCodexDomainPacks } = require('./codex/domain-packs');
10
- const { CodexProjectContext, detectCodexVersion } = require('./codex/context');
11
- const { GEMINI_TECHNIQUES } = require('./gemini/techniques');
12
- const { detectGeminiDomainPacks } = require('./gemini/domain-packs');
13
- const { GeminiProjectContext, detectGeminiVersion } = require('./gemini/context');
14
- const { COPILOT_TECHNIQUES } = require('./copilot/techniques');
15
- const { detectCopilotDomainPacks } = require('./copilot/domain-packs');
16
- const { CopilotProjectContext } = require('./copilot/context');
17
- const { CURSOR_TECHNIQUES } = require('./cursor/techniques');
18
- const { detectCursorDomainPacks } = require('./cursor/domain-packs');
19
- const { CursorProjectContext } = require('./cursor/context');
20
- const { WINDSURF_TECHNIQUES } = require('./windsurf/techniques');
21
- const { WindsurfProjectContext } = require('./windsurf/context');
22
- const { AIDER_TECHNIQUES } = require('./aider/techniques');
23
- const { AiderProjectContext } = require('./aider/context');
24
- const { OPENCODE_TECHNIQUES } = require('./opencode/techniques');
25
- const { OpenCodeProjectContext } = require('./opencode/context');
26
- const { getBadgeMarkdown } = require('./badge');
27
- const { sendInsights, getLocalInsights } = require('./insights');
28
- const { getRecommendationOutcomeSummary, getRecommendationAdjustment } = require('./activity');
29
- const { getFeedbackSummary } = require('./feedback');
30
- const { formatSarif } = require('./formatters/sarif');
31
- const { formatOtelMetrics } = require('./formatters/otel');
32
- const { loadPlugins, mergePluginChecks } = require('./plugins');
33
- const { hasWorkspaceConfig, detectWorkspaceGlobs, detectWorkspaces } = require('./workspace');
34
- const { detectDeprecationWarnings } = require('./deprecation');
35
- const { version: packageVersion } = require('../package.json');
36
-
37
- const COLORS = {
38
- reset: '\x1b[0m',
39
- bold: '\x1b[1m',
40
- dim: '\x1b[2m',
41
- red: '\x1b[31m',
42
- green: '\x1b[32m',
43
- yellow: '\x1b[33m',
44
- blue: '\x1b[36m',
45
- magenta: '\x1b[35m',
46
- };
47
-
48
- function colorize(text, color) {
49
- return `${COLORS[color] || ''}${text}${COLORS.reset}`;
50
- }
51
-
52
- function progressBar(score, max = 100, width = 20) {
53
- const filled = Math.round((score / max) * width);
54
- const empty = width - filled;
55
- const color = score >= 70 ? 'green' : score >= 40 ? 'yellow' : 'red';
56
- return colorize('█'.repeat(filled), color) + colorize('░'.repeat(empty), 'dim');
57
- }
58
-
59
- function formatLocation(file, line) {
60
- if (!file) return null;
61
- return line ? `${file}:${line}` : file;
62
- }
63
-
64
- const IMPACT_ORDER = { critical: 3, high: 2, medium: 1, low: 0 };
65
- const WEIGHTS = { critical: 15, high: 10, medium: 5, low: 2 };
66
- const LARGE_INSTRUCTION_WARN_BYTES = 50 * 1024;
67
- const LARGE_INSTRUCTION_SKIP_BYTES = 1024 * 1024;
68
- const CATEGORY_MODULES = {
69
- memory: 'CLAUDE.md',
70
- quality: 'verification',
71
- git: 'safety',
72
- workflow: 'commands-agents-skills',
73
- security: 'permissions',
74
- automation: 'hooks',
75
- design: 'design-rules',
76
- devops: 'ci-devops',
77
- hygiene: 'project-hygiene',
78
- performance: 'context-management',
79
- tools: 'mcp-tools',
80
- prompting: 'prompt-structure',
81
- features: 'modern-claude-features',
82
- 'quality-deep': 'quality-deep',
83
- skills: 'skills',
84
- agents: 'subagents',
85
- review: 'review-workflow',
86
- local: 'local-environment',
87
- };
88
- const ACTION_RATIONALES = {
89
- noBypassPermissions: 'bypassPermissions skips the main safety layer. Explicit allow and deny rules create safer autonomy.',
90
- secretsProtection: 'Without secret protection, Claude can accidentally inspect sensitive files and leak them into outputs.',
91
- permissionDeny: 'Deny rules are the strongest way to prevent dangerous reads and destructive operations.',
92
- settingsPermissions: 'Explicit permission settings make the workflow safer, more governable, and easier to review.',
93
- testCommand: 'Without a test command, Claude cannot verify that its changes actually work before handoff.',
94
- lintCommand: 'Without a lint command, Claude will miss formatting and style regressions that teams expect to catch automatically.',
95
- buildCommand: 'Without a build command, compile and packaging failures stay invisible until later in the workflow.',
96
- ciPipeline: 'CI is what turns a local setup improvement into a repeatable team-wide standard.',
97
- securityReview: 'If you do not wire in security review guidance, high-risk changes are easier to ship without the right scrutiny.',
98
- skills: 'Skills package reusable expertise so Claude does not need the same context re-explained every session.',
99
- multipleAgents: 'Specialized agents unlock role-based work such as security review, implementation, and QA in parallel.',
100
- multipleMcpServers: 'A richer MCP surface gives Claude access to live tools and documentation instead of stale assumptions.',
101
- roleDefinition: 'A clear role definition calibrates how Claude thinks, explains, and validates work in this repo.',
102
- importSyntax: 'Imported modules keep CLAUDE.md maintainable as the workflow grows more sophisticated.',
103
- claudeMd: 'CLAUDE.md is the foundation of project-specific context. Without it, Claude starts every task half-blind.',
104
- hooks: 'Hooks enforce the rules programmatically, which is much more reliable than relying on instructions alone.',
105
- pathRules: 'Path-specific rules help Claude behave differently in different parts of the repo without global noise.',
106
- context7Mcp: 'Live documentation reduces version drift and cuts down on confident but outdated answers.',
107
- codexAgentsMd: 'AGENTS.md is the main Codex instruction surface. Without it, Codex starts without repo-specific guidance.',
108
- codexAgentsMdSubstantive: 'A thin AGENTS.md is almost as bad as no AGENTS.md because Codex still lacks the repo context it needs.',
109
- codexAgentsVerificationCommands: 'If AGENTS.md does not document how to verify work, Codex cannot reliably prove its own changes are safe.',
110
- codexAgentsArchitecture: 'A small architecture map reduces navigation drift and helps Codex change the right part of the repo first.',
111
- codexConfigExists: 'Without .codex/config.toml, trust and model behavior are implicit instead of explicit.',
112
- codexReasoningEffortExplicit: 'Reasoning depth should be intentional for cost and latency, not left to implicit defaults.',
113
- codexApprovalPolicyExplicit: 'Explicit approvals make Codex behavior predictable and reviewable across sessions.',
114
- codexNoDangerFullAccess: 'danger-full-access removes the main safety boundary and should be treated as a critical risk.',
115
- codexHistorySendToServerExplicit: 'History sync is a privacy and governance surface. Teams should decide it explicitly, not inherit it accidentally.',
116
- codexNoSecretsInAgents: 'Secrets in AGENTS.md can leak directly into agent context, outputs, and logs.',
117
- codexHooksWindowsCaveat: 'Windows does not support Codex hooks today, so relying on them there creates a false sense of runtime enforcement.',
118
- codexSkillsDirPresentWhenUsed: 'Versioned repo-local skills are the safest way to keep Codex expertise reviewable and consistent across contributors.',
119
- codexSkillsHaveMetadata: 'Without a usable SKILL.md, Codex cannot reliably decide when a skill should run or what it is for.',
120
- codexSkillNamesKebabCase: 'Consistent skill naming improves discoverability and avoids invocation drift.',
121
- codexSkillDescriptionsBounded: 'A bounded skill description helps Codex invoke the right skill without inflating prompt context.',
122
- codexSkillsNoAutoRunRisk: 'Skills should guide Codex, not silently authorize risky automation or destructive actions.',
123
- codexCustomAgentsRequiredFields: 'Custom agents need clear metadata and developer instructions so delegation stays predictable.',
124
- codexMaxThreadsExplicit: 'Explicit fanout limits make Codex delegation safer and easier to reason about.',
125
- codexMaxDepthExplicit: 'Nested delegation should be deliberate, not accidental.',
126
- codexPerAgentSandboxOverridesSafe: 'Per-agent overrides can quietly bypass the main trust model if they are not constrained.',
127
- codexExecUsageSafe: 'Unsafe Codex automation quickly turns small workflow mistakes into real repo damage.',
128
- codexGitHubActionSafeStrategy: 'CI safety posture should be visible and intentional, especially when Codex is acting in automation.',
129
- codexCiAuthUsesManagedKey: 'Managed secrets are the minimum trust boundary for Codex in CI.',
130
- codexAutomationManuallyTested: 'Manual dry-runs catch automation footguns before they become scheduled failures.',
131
- codexReviewWorkflowDocumented: 'A documented review path makes Codex safer to use on risky diffs and refactors.',
132
- codexReviewModelOverrideExplicit: 'Explicit review model selection keeps review quality and cost predictable when automation is involved.',
133
- codexWorkingTreeReviewExpectations: 'Codex reviews are much safer when the repo states how to treat staged, unstaged, and unrelated changes.',
134
- codexCostAwarenessDocumented: 'Heavy workflows should be intentional, not the invisible default.',
135
- codexArtifactsSharedIntentionally: 'If `.codex` is hidden from version control, the team loses a shared and reviewable Codex contract.',
136
- codexLifecycleScriptsPlatformSafe: 'Local setup/teardown scripts are part of the trust model and should not surprise contributors on other platforms.',
137
- codexActionsNotRedundant: 'Redundant automation expands the surface area without adding real value.',
138
- codexWorktreeLifecycleDocumented: 'Parallel worktree flows need explicit setup and cleanup expectations.',
139
- codexAgentsMentionModernFeatures: 'When the repo uses modern Codex surfaces, AGENTS.md should tell Codex they exist.',
140
- codexNoDeprecatedPatterns: 'Deprecated Codex patterns create silent drift and confusing behavior over time.',
141
- codexProfilesUsedWhenNeeded: 'Profiles become more important as Codex automation and delegation get more complex.',
142
- codexPluginConfigValid: 'Broken plugin metadata creates discoverability and tooling drift.',
143
- codexUndoExplicit: 'Undo is a user-facing safety feature and should be an explicit repo choice.',
144
- };
145
- const CODEX_HARD_FAIL_KEYS = new Set([
146
- 'codexAgentsMd',
147
- 'codexConfigValidToml',
148
- 'codexNoDangerFullAccess',
149
- 'codexApprovalPolicyExplicit',
150
- 'codexNoSecretsInAgents',
151
- 'codexHooksWindowsCaveat',
152
- ]);
153
- const CODEX_EVIDENCE_CLASSES = {
154
- 'CX-A01': 'runtime',
155
- 'CX-A02': 'derived',
156
- 'CX-A03': 'derived',
157
- 'CX-A04': 'derived',
158
- 'CX-A05': 'mixed',
159
- 'CX-A06': 'source',
160
- 'CX-A07': 'derived',
161
- 'CX-A08': 'derived',
162
- 'CX-B01': 'runtime',
163
- 'CX-B02': 'mixed',
164
- 'CX-B03': 'mixed',
165
- 'CX-B04': 'source',
166
- 'CX-B05': 'source',
167
- 'CX-B06': 'source',
168
- 'CX-B07': 'source',
169
- 'CX-B08': 'source',
170
- 'CX-B09': 'source',
171
- 'CX-C01': 'mixed',
172
- 'CX-C02': 'mixed',
173
- 'CX-C03': 'mixed',
174
- 'CX-C04': 'derived',
175
- 'CX-C05': 'source',
176
- 'CX-C06': 'source',
177
- 'CX-C07': 'mixed',
178
- 'CX-C08': 'source',
179
- 'CX-C09': 'mixed',
180
- 'CX-D01': 'runtime',
181
- 'CX-D02': 'mixed',
182
- 'CX-D03': 'source',
183
- 'CX-D04': 'mixed',
184
- 'CX-D05': 'mixed',
185
- 'CX-E01': 'mixed',
186
- 'CX-E02': 'runtime',
187
- 'CX-E03': 'mixed',
188
- 'CX-E04': 'mixed',
189
- 'CX-E05': 'source',
190
- 'CX-F01': 'mixed',
191
- 'CX-F02': 'mixed',
192
- 'CX-F03': 'source',
193
- 'CX-F04': 'mixed',
194
- 'CX-F05': 'source',
195
- 'CX-F06': 'source',
196
- 'CX-G01': 'mixed',
197
- 'CX-G02': 'source',
198
- 'CX-G03': 'source',
199
- 'CX-G04': 'derived',
200
- 'CX-G05': 'derived',
201
- 'CX-H01': 'source',
202
- 'CX-H02': 'runtime',
203
- 'CX-H03': 'runtime',
204
- 'CX-H04': 'source',
205
- 'CX-I01': 'mixed',
206
- 'CX-I02': 'mixed',
207
- 'CX-I03': 'source',
208
- 'CX-I04': 'source',
209
- 'CX-J01': 'source',
210
- 'CX-J02': 'source',
211
- 'CX-J03': 'source',
212
- 'CX-J04': 'source',
213
- 'CX-K01': 'source',
214
- 'CX-K02': 'source',
215
- 'CX-K03': 'source',
216
- 'CX-K04': 'source',
217
- 'CX-L01': 'derived',
218
- 'CX-L02': 'source',
219
- 'CX-L03': 'derived',
220
- 'CX-L04': 'source',
221
- 'CX-L05': 'source',
222
- };
223
- const CODEX_QUICKWIN_CONFIG_KEYS = new Set([
224
- 'codexConfigExists',
225
- 'codexModelExplicit',
226
- 'codexReasoningEffortExplicit',
227
- 'codexWeakModelExplicit',
228
- 'codexProfilesUsedAppropriately',
229
- 'codexFullAutoErrorModeExplicit',
230
- 'codexHistorySendToServerExplicit',
231
- 'codexNetworkAccessExplicit',
232
- 'codexHooksDeliberate',
233
- 'codexMcpStartupTimeoutReasonable',
234
- 'codexMaxThreadsExplicit',
235
- 'codexMaxDepthExplicit',
236
- ]);
237
- const CODEX_QUICKWIN_FILE_KEYS = new Set([
238
- 'codexAgentsMd',
239
- 'codexHooksJsonExistsWhenClaimed',
240
- 'codexSkillsDirPresentWhenUsed',
241
- ]);
242
- const CODEX_QUICKWIN_DOC_KEYS = new Set([
243
- 'codexAgentsArchitecture',
244
- 'codexOverrideDocumented',
245
- 'codexNoGenericFiller',
246
- 'codexNoInstructionContradictions',
247
- 'codexRulesExamplesPresent',
248
- 'codexRuleWrapperRiskDocumented',
249
- 'codexSkillsHaveMetadata',
250
- 'codexSkillNamesKebabCase',
251
- 'codexSkillDescriptionsBounded',
252
- 'codexAutomationManuallyTested',
253
- 'codexReviewWorkflowDocumented',
254
- 'codexWorkingTreeReviewExpectations',
255
- 'codexCostAwarenessDocumented',
256
- ]);
257
- const CODEX_QUICKWIN_POLICY_KEYS = new Set([
258
- 'codexRulesSpecificPatterns',
259
- 'codexNoBroadAllowAllRules',
260
- 'codexMcpWhitelistsExplicit',
261
- 'codexNoDeprecatedMcpTransport',
262
- 'codexGitHubActionSafeStrategy',
263
- 'codexProfilesUsedWhenNeeded',
264
- 'codexUndoExplicit',
265
- ]);
266
- const CODEX_QUICKWIN_AVOID_KEYS = new Set([
267
- 'codexNoDangerFullAccess',
268
- 'codexApprovalPolicyExplicit',
269
- 'codexGitHubActionUnsafeJustified',
270
- 'codexProjectScopedMcpTrusted',
271
- 'codexMcpAuthDocumented',
272
- 'codexHooksWindowsCaveat',
273
- 'codexNoSecretsInAgents',
274
- 'codexPerAgentSandboxOverridesSafe',
275
- 'codexExecUsageSafe',
276
- 'codexCiAuthUsesManagedKey',
277
- 'codexLifecycleScriptsPlatformSafe',
278
- ]);
279
-
280
- function getAuditSpec(platform = 'claude') {
281
- if (platform === 'codex') {
282
- return {
283
- platform: 'codex',
284
- platformLabel: 'Codex',
285
- techniques: CODEX_TECHNIQUES,
286
- ContextClass: CodexProjectContext,
287
- platformVersion: detectCodexVersion(),
288
- };
289
- }
290
-
291
- if (platform === 'gemini') {
292
- return {
293
- platform: 'gemini',
294
- platformLabel: 'Gemini CLI',
295
- techniques: GEMINI_TECHNIQUES,
296
- ContextClass: GeminiProjectContext,
297
- platformVersion: detectGeminiVersion(),
298
- };
299
- }
300
-
301
- if (platform === 'copilot') {
302
- return {
303
- platform: 'copilot',
304
- platformLabel: 'GitHub Copilot',
305
- techniques: COPILOT_TECHNIQUES,
306
- ContextClass: CopilotProjectContext,
307
- platformVersion: null,
308
- };
309
- }
310
-
311
- if (platform === 'cursor') {
312
- return {
313
- platform: 'cursor',
314
- platformLabel: 'Cursor',
315
- techniques: CURSOR_TECHNIQUES,
316
- ContextClass: CursorProjectContext,
317
- platformVersion: null,
318
- };
319
- }
320
-
321
- if (platform === 'windsurf') {
322
- return {
323
- platform: 'windsurf',
324
- platformLabel: 'Windsurf',
325
- techniques: WINDSURF_TECHNIQUES,
326
- ContextClass: WindsurfProjectContext,
327
- platformVersion: null,
328
- };
329
- }
330
-
331
- if (platform === 'aider') {
332
- return {
333
- platform: 'aider',
334
- platformLabel: 'Aider',
335
- techniques: AIDER_TECHNIQUES,
336
- ContextClass: AiderProjectContext,
337
- platformVersion: null,
338
- };
339
- }
340
-
341
- if (platform === 'opencode') {
342
- return {
343
- platform: 'opencode',
344
- platformLabel: 'OpenCode',
345
- techniques: OPENCODE_TECHNIQUES,
346
- ContextClass: OpenCodeProjectContext,
347
- platformVersion: null,
348
- };
349
- }
350
-
351
- return {
352
- platform: 'claude',
353
- platformLabel: 'Claude',
354
- techniques: CLAUDE_TECHNIQUES,
355
- ContextClass: ProjectContext,
356
- platformVersion: null,
357
- };
358
- }
359
-
360
- function normalizeRelativePath(filePath) {
361
- return String(filePath || '').replace(/\\/g, '/').replace(/^\.\//, '');
362
- }
363
-
364
- function addPath(target, filePath) {
365
- if (!filePath || typeof filePath !== 'string') return;
366
- target.add(normalizeRelativePath(filePath));
367
- }
368
-
369
- function addDirFiles(ctx, target, dirPath, filter) {
370
- if (typeof ctx.dirFiles !== 'function') return;
371
- for (const file of ctx.dirFiles(dirPath)) {
372
- if (filter && !filter.test(file)) continue;
373
- addPath(target, path.join(dirPath, file));
374
- }
375
- }
376
-
377
- function instructionFileCandidates(spec, ctx) {
378
- const candidates = new Set();
379
-
380
- if (spec.platform === 'claude') {
381
- addPath(candidates, 'CLAUDE.md');
382
- addPath(candidates, '.claude/CLAUDE.md');
383
- addDirFiles(ctx, candidates, '.claude/rules', /\.md$/i);
384
- addDirFiles(ctx, candidates, '.claude/commands', /\.md$/i);
385
- addDirFiles(ctx, candidates, '.claude/agents', /\.md$/i);
386
- if (typeof ctx.dirFiles === 'function') {
387
- for (const skillDir of ctx.dirFiles('.claude/skills')) {
388
- addPath(candidates, path.join('.claude', 'skills', skillDir, 'SKILL.md'));
389
- }
390
- }
391
- }
392
-
393
- if (spec.platform === 'codex') {
394
- addPath(candidates, 'AGENTS.md');
395
- addPath(candidates, 'AGENTS.override.md');
396
- addPath(candidates, typeof ctx.agentsMdPath === 'function' ? ctx.agentsMdPath() : null);
397
- addDirFiles(ctx, candidates, 'codex/rules');
398
- addDirFiles(ctx, candidates, '.codex/rules');
399
- if (typeof ctx.skillDirs === 'function') {
400
- for (const skillDir of ctx.skillDirs()) {
401
- addPath(candidates, path.join('.agents', 'skills', skillDir, 'SKILL.md'));
402
- }
403
- }
404
- }
405
-
406
- if (spec.platform === 'gemini') {
407
- addPath(candidates, 'GEMINI.md');
408
- addPath(candidates, '.gemini/GEMINI.md');
409
- addDirFiles(ctx, candidates, '.gemini/agents', /\.md$/i);
410
- if (typeof ctx.skillDirs === 'function') {
411
- for (const skillDir of ctx.skillDirs()) {
412
- addPath(candidates, path.join('.gemini', 'skills', skillDir, 'SKILL.md'));
413
- }
414
- }
415
- }
416
-
417
- if (spec.platform === 'copilot') {
418
- addPath(candidates, '.github/copilot-instructions.md');
419
- addDirFiles(ctx, candidates, '.github/instructions', /\.instructions\.md$/i);
420
- addDirFiles(ctx, candidates, '.github/prompts', /\.prompt\.md$/i);
421
- }
422
-
423
- if (spec.platform === 'cursor') {
424
- addPath(candidates, '.cursorrules');
425
- addDirFiles(ctx, candidates, '.cursor/rules', /\.mdc$/i);
426
- addDirFiles(ctx, candidates, '.cursor/commands', /\.md$/i);
427
- }
428
-
429
- if (spec.platform === 'windsurf') {
430
- addPath(candidates, '.windsurfrules');
431
- addDirFiles(ctx, candidates, '.windsurf/rules', /\.md$/i);
432
- addDirFiles(ctx, candidates, '.windsurf/workflows', /\.md$/i);
433
- addDirFiles(ctx, candidates, '.windsurf/memories', /\.(md|json)$/i);
434
- }
435
-
436
- if (spec.platform === 'aider' && typeof ctx.conventionFiles === 'function') {
437
- for (const file of ctx.conventionFiles()) {
438
- addPath(candidates, file);
439
- }
440
- }
441
-
442
- if (spec.platform === 'opencode') {
443
- addPath(candidates, 'AGENTS.md');
444
- addPath(candidates, 'CLAUDE.md');
445
- addDirFiles(ctx, candidates, '.opencode/commands', /\.(md|markdown|ya?ml)$/i);
446
- if (typeof ctx.skillDirs === 'function') {
447
- for (const skillDir of ctx.skillDirs()) {
448
- addPath(candidates, path.join('.opencode', 'commands', skillDir, 'SKILL.md'));
449
- }
450
- }
451
- }
452
-
453
- return [...candidates];
454
- }
455
-
456
- function inspectInstructionFiles(spec, ctx) {
457
- const warnings = [];
458
-
459
- for (const filePath of instructionFileCandidates(spec, ctx)) {
460
- const byteCount = typeof ctx.fileSizeBytes === 'function' ? ctx.fileSizeBytes(filePath) : null;
461
- if (!Number.isFinite(byteCount) || byteCount <= LARGE_INSTRUCTION_WARN_BYTES) continue;
462
-
463
- const content = typeof ctx.fileContent === 'function' ? ctx.fileContent(filePath) : null;
464
- warnings.push({
465
- file: normalizeRelativePath(filePath),
466
- byteCount,
467
- lineCount: typeof content === 'string' ? content.split(/\r?\n/).length : null,
468
- skipped: byteCount > LARGE_INSTRUCTION_SKIP_BYTES,
469
- severity: byteCount > LARGE_INSTRUCTION_SKIP_BYTES ? 'critical' : 'warning',
470
- message: byteCount > LARGE_INSTRUCTION_SKIP_BYTES
471
- ? 'Instruction file exceeds 1MB and will be skipped during audit.'
472
- : 'Instruction file exceeds 50KB. Audit will continue, but this file may reduce runtime clarity.',
473
- });
474
- }
475
-
476
- return warnings;
477
- }
478
-
479
- function guardSkippedInstructionFiles(ctx, warnings) {
480
- const skippedFiles = new Set(
481
- warnings.filter((item) => item.skipped).map((item) => normalizeRelativePath(item.file))
482
- );
483
-
484
- if (skippedFiles.size === 0) return;
485
-
486
- const originalFileContent = typeof ctx.fileContent === 'function' ? ctx.fileContent.bind(ctx) : null;
487
- const originalLineNumber = typeof ctx.lineNumber === 'function' ? ctx.lineNumber.bind(ctx) : null;
488
-
489
- if (originalFileContent) {
490
- ctx.fileContent = (filePath) => {
491
- if (skippedFiles.has(normalizeRelativePath(filePath))) return null;
492
- return originalFileContent(filePath);
493
- };
494
- }
495
-
496
- if (originalLineNumber) {
497
- ctx.lineNumber = (filePath, matcher) => {
498
- if (skippedFiles.has(normalizeRelativePath(filePath))) return null;
499
- return originalLineNumber(filePath, matcher);
500
- };
501
- }
502
- }
503
-
504
- function buildWorkspaceHint(dir) {
505
- if (!hasWorkspaceConfig(dir)) {
506
- return null;
507
- }
508
-
509
- const patterns = detectWorkspaceGlobs(dir);
510
- const workspaces = detectWorkspaces(dir);
511
- if (patterns.length === 0 && workspaces.length === 0) {
512
- return null;
513
- }
514
-
515
- return {
516
- detected: true,
517
- patterns,
518
- workspaces,
519
- suggestedCommand: patterns.length > 0
520
- ? `npx nerviq audit --workspace ${patterns.join(',')}`
521
- : `npx nerviq audit --workspace ${workspaces.join(',')}`,
522
- };
523
- }
524
-
525
- function riskFromImpact(impact) {
526
- if (impact === 'critical') return 'high';
527
- if (impact === 'high') return 'medium';
528
- return 'low';
529
- }
530
-
531
- function confidenceFromImpact(impact) {
532
- return impact === 'critical' || impact === 'high' ? 'high' : 'medium';
533
- }
534
-
535
- function confidenceLabel(confidence) {
536
- if (confidence >= 0.6) return 'HIGH';
537
- if (confidence >= 0.3) return 'MEDIUM';
538
- return 'HEURISTIC';
539
- }
540
-
541
- function getPrioritizedFailed(failed) {
542
- const prioritized = failed.filter(r => !(r.category === 'hygiene' && r.impact === 'low'));
543
- return prioritized.length > 0 ? prioritized : failed;
544
- }
545
-
546
- function codexEvidenceClass(item) {
547
- return CODEX_EVIDENCE_CLASSES[item.id] || 'derived';
548
- }
549
-
550
- function codexCategoryBonus(category) {
551
- if (category === 'trust' || category === 'config') return 12;
552
- if (category === 'rules' || category === 'hooks' || category === 'mcp') return 8;
553
- if (category === 'instructions') return 4;
554
- return 0;
555
- }
556
-
557
- function codexEvidenceBonus(item) {
558
- const evidenceClass = codexEvidenceClass(item);
559
- if (evidenceClass === 'runtime') return 8;
560
- if (evidenceClass === 'mixed') return 6;
561
- if (evidenceClass === 'source') return 3;
562
- return 0;
563
- }
564
-
565
- function codexPriorityScore(item, outcomeSummaryByKey = {}) {
566
- const impactBase = item.impact === 'critical'
567
- ? 60
568
- : item.impact === 'high'
569
- ? 40
570
- : item.impact === 'medium'
571
- ? 20
572
- : 8;
573
- const feedbackAdjustment = getRecommendationAdjustment(outcomeSummaryByKey, item.key) * 10;
574
- const hardFailBonus = CODEX_HARD_FAIL_KEYS.has(item.key) ? 12 : 0;
575
- return Math.max(0, Math.min(100, impactBase + codexCategoryBonus(item.category) + codexEvidenceBonus(item) + hardFailBonus + feedbackAdjustment));
576
- }
577
-
578
- function codexQuickWinScore(item) {
579
- if (CODEX_QUICKWIN_AVOID_KEYS.has(item.key)) {
580
- return -100;
581
- }
582
-
583
- let score = 0;
584
- if (CODEX_QUICKWIN_CONFIG_KEYS.has(item.key)) {
585
- score += 40;
586
- } else if (CODEX_QUICKWIN_FILE_KEYS.has(item.key)) {
587
- score += 34;
588
- } else if (CODEX_QUICKWIN_DOC_KEYS.has(item.key)) {
589
- score += 26;
590
- } else if (CODEX_QUICKWIN_POLICY_KEYS.has(item.key)) {
591
- score += 20;
592
- }
593
-
594
- score += item.impact === 'low' ? 8 : item.impact === 'medium' ? 6 : item.impact === 'high' ? 4 : 0;
595
- score -= Math.min((item.fix || '').length, 240) / 24;
596
- return score;
597
- }
598
-
599
- function getQuickWins(failed, options = {}) {
600
- const pool = getPrioritizedFailed(failed);
601
-
602
- if (options.platform === 'codex') {
603
- const codexPool = pool.filter((item) => !CODEX_QUICKWIN_AVOID_KEYS.has(item.key));
604
- const rankedPool = (codexPool.length > 0 ? codexPool : pool)
605
- .slice()
606
- .sort((a, b) => codexQuickWinScore(b) - codexQuickWinScore(a));
607
- return rankedPool.slice(0, 3);
608
- }
609
-
610
- // QuickWins prioritize short fixes (easy to implement) first, then impact
611
- return [...pool]
612
- .sort((a, b) => {
613
- const fixLenA = (a.fix || '').length;
614
- const fixLenB = (b.fix || '').length;
615
- if (fixLenA !== fixLenB) return fixLenA - fixLenB;
616
- const impactA = IMPACT_ORDER[a.impact] ?? 0;
617
- const impactB = IMPACT_ORDER[b.impact] ?? 0;
618
- return impactB - impactA;
619
- })
620
- .slice(0, 3);
621
- }
622
-
623
- /**
624
- * Compute a multiplier based on FP (helpful/not-helpful) feedback for a check key.
625
- * - >50% "not helpful" feedback: lower priority by 30% (multiplier 0.7)
626
- * - >80% "helpful" feedback: boost priority by 20% (multiplier 1.2)
627
- * - Otherwise: no change (multiplier 1.0)
628
- * @param {Object} fpFeedbackByKey - Keyed feedback summary from getFeedbackSummary().byKey
629
- * @param {string} key - The check key to look up
630
- * @returns {number} Multiplier to apply to priority score
631
- */
632
- function getFpFeedbackMultiplier(fpFeedbackByKey, key) {
633
- if (!fpFeedbackByKey) return 1.0;
634
- const bucket = fpFeedbackByKey[key];
635
- if (!bucket || bucket.total === 0) return 1.0;
636
-
637
- const unhelpfulRate = bucket.unhelpful / bucket.total;
638
- const helpfulRate = bucket.helpful / bucket.total;
639
-
640
- if (unhelpfulRate > 0.5) return 0.7;
641
- if (helpfulRate > 0.8) return 1.2;
642
- return 1.0;
643
- }
644
-
645
- function getRecommendationPriorityScore(item, outcomeSummaryByKey = {}, fpFeedbackByKey = null) {
646
- const impactScore = (IMPACT_ORDER[item.impact] ?? 0) * 100;
647
- const feedbackAdjustment = getRecommendationAdjustment(outcomeSummaryByKey, item.key);
648
- const brevityPenalty = Math.min((item.fix || '').length, 240) / 20;
649
- const raw = impactScore + (feedbackAdjustment * 10) - brevityPenalty;
650
- return raw * getFpFeedbackMultiplier(fpFeedbackByKey, item.key);
651
- }
652
-
653
- function buildTopNextActions(failed, limit = 5, outcomeSummaryByKey = {}, options = {}) {
654
- const pool = getPrioritizedFailed(failed);
655
- const fpByKey = options.fpFeedbackByKey || null;
656
-
657
- return [...pool]
658
- .sort((a, b) => {
659
- const scoreB = options.platform === 'codex'
660
- ? codexPriorityScore(b, outcomeSummaryByKey)
661
- : getRecommendationPriorityScore(b, outcomeSummaryByKey, fpByKey);
662
- const scoreA = options.platform === 'codex'
663
- ? codexPriorityScore(a, outcomeSummaryByKey)
664
- : getRecommendationPriorityScore(a, outcomeSummaryByKey, fpByKey);
665
- return scoreB - scoreA;
666
- })
667
- .slice(0, limit)
668
- .map(({ key, id, name, impact, fix, category, sourceUrl }) => {
669
- const feedback = outcomeSummaryByKey[key] || null;
670
- const rankingAdjustment = getRecommendationAdjustment(outcomeSummaryByKey, key);
671
- const signals = [
672
- `failed-check:${key}`,
673
- `impact:${impact}`,
674
- `category:${category}`,
675
- ];
676
- if (feedback) {
677
- signals.push(`feedback:${feedback.total}`);
678
- signals.push(`ranking-adjustment:${rankingAdjustment >= 0 ? '+' : ''}${rankingAdjustment}`);
679
- }
680
-
681
- const fullItem = pool.find((item) => item.key === key) || { key, id, name, impact, fix, category };
682
- const evidenceClass = options.platform === 'codex' ? codexEvidenceClass(fullItem) : (feedback ? 'measured' : 'estimated');
683
- const priorityScore = options.platform === 'codex'
684
- ? codexPriorityScore(fullItem, outcomeSummaryByKey)
685
- : Math.max(0, Math.min(100, Math.round(getRecommendationPriorityScore(fullItem, outcomeSummaryByKey, fpByKey) / 3)));
686
-
687
- signals.push(`evidence:${evidenceClass}`);
688
- if (options.platform === 'codex' && CODEX_HARD_FAIL_KEYS.has(key)) {
689
- signals.push('hard-fail:true');
690
- }
691
-
692
- return ({
693
- key,
694
- id,
695
- name,
696
- impact,
697
- category,
698
- sourceUrl,
699
- module: CATEGORY_MODULES[category] || category,
700
- fix,
701
- priorityScore,
702
- why: ACTION_RATIONALES[key] || fix,
703
- risk: riskFromImpact(impact),
704
- confidence: confidenceFromImpact(impact),
705
- signals,
706
- evidenceClass,
707
- rankingAdjustment,
708
- feedback: feedback ? {
709
- total: feedback.total,
710
- accepted: feedback.accepted,
711
- rejected: feedback.rejected,
712
- deferred: feedback.deferred,
713
- positive: feedback.positive,
714
- negative: feedback.negative,
715
- avgScoreDelta: feedback.avgScoreDelta,
716
- } : null,
717
- });
718
- });
719
- }
720
-
721
- function computeCategoryScores(applicable, passed) {
722
- const grouped = {};
723
-
724
- for (const item of applicable) {
725
- const category = item.category || 'unknown';
726
- if (!grouped[category]) {
727
- grouped[category] = { passed: 0, total: 0, earnedPoints: 0, maxPoints: 0 };
728
- }
729
- grouped[category].total += 1;
730
- grouped[category].maxPoints += WEIGHTS[item.impact] || 5;
731
- }
732
-
733
- for (const item of passed) {
734
- const category = item.category || 'unknown';
735
- if (!grouped[category]) continue;
736
- grouped[category].passed += 1;
737
- grouped[category].earnedPoints += WEIGHTS[item.impact] || 5;
738
- }
739
-
740
- const result = {};
741
- for (const [category, summary] of Object.entries(grouped)) {
742
- result[category] = {
743
- ...summary,
744
- score: summary.maxPoints > 0 ? Math.round((summary.earnedPoints / summary.maxPoints) * 100) : 0,
745
- };
746
- }
747
-
748
- return result;
749
- }
750
-
751
- function inferSuggestedNextCommand(result) {
752
- if (result.platform === 'codex') {
753
- if (result.failed === 0) {
754
- return 'npx nerviq --platform codex augment';
755
- }
756
-
757
- const actionKeys = new Set((result.topNextActions || []).map(item => item.key));
758
- if (
759
- result.score < 50 ||
760
- actionKeys.has('codexAgentsMd') ||
761
- actionKeys.has('codexConfigExists') ||
762
- actionKeys.has('codexNoDangerFullAccess') ||
763
- actionKeys.has('codexApprovalPolicyExplicit')
764
- ) {
765
- return 'npx nerviq --platform codex suggest-only';
766
- }
767
-
768
- return 'npx nerviq --platform codex augment';
769
- }
770
-
771
- const actionKeys = new Set((result.topNextActions || []).map(item => item.key));
772
- const platFlag = result.platform && result.platform !== 'claude' ? ` --platform ${result.platform}` : '';
773
-
774
- if (result.failed === 0) {
775
- return `npx nerviq${platFlag} augment`;
776
- }
777
-
778
- if (
779
- result.score < 50 ||
780
- actionKeys.has('claudeMd') ||
781
- actionKeys.has('hooks') ||
782
- actionKeys.has('settingsPermissions') ||
783
- actionKeys.has('permissionDeny')
784
- ) {
785
- return `npx nerviq${platFlag} setup`;
786
- }
787
-
788
- if (result.score < 80) {
789
- return `npx nerviq${platFlag} suggest-only`;
790
- }
791
-
792
- return `npx nerviq${platFlag} augment`;
793
- }
794
-
795
- function getPlatformScopeNote(spec, ctx) {
796
- if (spec.platform !== 'codex') {
797
- return null;
798
- }
799
-
800
- const hasClaudeSurface = Boolean(
801
- (typeof ctx.fileContent === 'function' && ctx.fileContent('CLAUDE.md')) ||
802
- (typeof ctx.hasDir === 'function' && ctx.hasDir('.claude'))
803
- );
804
-
805
- if (!hasClaudeSurface) {
806
- return null;
807
- }
808
-
809
- return {
810
- kind: 'codex-only-pass',
811
- message: 'This is a Codex-only pass. Claude Code surfaces were also detected and should be audited separately with `npx nerviq`.',
812
- };
813
- }
814
-
815
- function getPlatformCaveats(spec, ctx) {
816
- if (spec.platform !== 'codex') {
817
- return [];
818
- }
819
-
820
- const caveats = [];
821
- const hooksJson = typeof ctx.hooksJsonContent === 'function' ? (ctx.hooksJsonContent() || '') : '';
822
- const agentsContent = typeof ctx.agentsMdContent === 'function' ? (ctx.agentsMdContent() || '') : '';
823
- const hooksClaimed = Boolean(
824
- hooksJson ||
825
- (typeof ctx.hasDir === 'function' && ctx.hasDir('.codex/hooks')) ||
826
- /\bhooks?\b|\bSessionStart\b|\bPreToolUse\b|\bPostToolUse\b|\bUserPromptSubmit\b|\bStop\b/i.test(agentsContent)
827
- );
828
-
829
- if (process.platform === 'win32') {
830
- caveats.push({
831
- key: 'codex-windows-hooks',
832
- severity: hooksClaimed ? 'critical' : 'info',
833
- title: 'Codex hooks are not available on Windows',
834
- message: hooksClaimed
835
- ? 'This repo claims Codex hooks, but native Windows sessions do not execute them. Keep enforcement in rules, CI, or another documented fallback.'
836
- : 'Native Windows sessions do not execute Codex hooks. If you add hooks later, treat them as non-enforcing on Windows and keep critical enforcement in rules or CI.',
837
- file: hooksJson ? '.codex/hooks.json' : null,
838
- line: hooksJson ? 1 : null,
839
- });
840
- }
841
-
842
- const maxThreads = typeof ctx.configValue === 'function' ? ctx.configValue('agents.max_threads') : undefined;
843
- caveats.push({
844
- key: 'codex-max-threads-default',
845
- severity: typeof maxThreads === 'number' && maxThreads > 6 ? 'warning' : 'info',
846
- title: 'Codex agent thread concurrency defaults to 6 when unset',
847
- message: typeof maxThreads === 'number'
848
- ? `This repo sets agents.max_threads = ${maxThreads}. Codex defaults to 6 when unset, so any higher concurrency assumption should be validated in the runtime you actually use.`
849
- : 'Codex defaults agents.max_threads to 6 when unset. If your workflow depends on heavy parallel subagent usage, set it intentionally and validate the behavior in your real runtime.',
850
- file: typeof ctx.fileContent === 'function' && ctx.fileContent('.codex/config.toml') ? '.codex/config.toml' : null,
851
- line: typeof ctx.lineNumber === 'function' ? (ctx.lineNumber('.codex/config.toml', /\bagents\.max_threads\b|\bmax_threads\b/i) || null) : null,
852
- });
853
-
854
- return caveats;
855
- }
856
-
857
- function getCodexDomainPackSignals(ctx) {
858
- return {
859
- instructionPath: typeof ctx.agentsMdPath === 'function' ? ctx.agentsMdPath() : null,
860
- trust: {
861
- approvalPolicy: typeof ctx.configValue === 'function' ? (ctx.configValue('approval_policy') || null) : null,
862
- sandboxMode: typeof ctx.configValue === 'function' ? (ctx.configValue('sandbox_mode') || null) : null,
863
- isTrustedProject: typeof ctx.isProjectTrusted === 'function' ? ctx.isProjectTrusted() : false,
864
- },
865
- counts: {
866
- rules: typeof ctx.ruleFiles === 'function' ? ctx.ruleFiles().length : 0,
867
- workflows: typeof ctx.workflowFiles === 'function' ? ctx.workflowFiles().length : 0,
868
- mcpServers: typeof ctx.mcpServers === 'function' ? Object.keys(ctx.mcpServers() || {}).length : 0,
869
- },
870
- };
871
- }
872
-
873
- function printLiteAudit(result, dir) {
874
- console.log('');
875
- const productLabel = result.platform === 'codex' ? 'nerviq codex quick scan' : 'nerviq quick scan';
876
- console.log(colorize(` ${productLabel}`, 'bold'));
877
- console.log(colorize(' ═══════════════════════════════════════', 'dim'));
878
- console.log(colorize(` Scanning: ${dir}`, 'dim'));
879
- console.log('');
880
- if (result.detectedConfigFiles && result.detectedConfigFiles.length > 0) {
881
- console.log(colorize(` Found: ${result.detectedConfigFiles.join(', ')}`, 'dim'));
882
- }
883
- console.log('');
884
- console.log(` Score: ${colorize(`${result.score}/100`, 'bold')} (${result.passed}/${result.passed + result.failed} checks passing)`);
885
-
886
- // Score explanation line (lite mode only)
887
- const _critCount = (result.results || []).filter(r => r.passed === false && r.impact === 'critical').length;
888
- const _highCount = (result.results || []).filter(r => r.passed === false && r.impact === 'high').length;
889
- let scoreExplanation;
890
- if (result.score >= 90) {
891
- scoreExplanation = 'Excellent setup — production-ready governance';
892
- } else if (result.score >= 70) {
893
- scoreExplanation = `Strong setup — ${_critCount} critical items to address`;
894
- } else if (result.score >= 50) {
895
- scoreExplanation = `Good foundation — ${_critCount + _highCount} items need attention`;
896
- } else if (result.score >= 30) {
897
- // Find weakest category (most failures)
898
- const catFailures = {};
899
- (result.results || []).filter(r => r.passed === false).forEach(r => {
900
- const cat = r.category || 'unknown';
901
- catFailures[cat] = (catFailures[cat] || 0) + 1;
902
- });
903
- const weakestCategory = Object.keys(catFailures).sort((a, b) => catFailures[b] - catFailures[a])[0] || 'config';
904
- scoreExplanation = `Basic setup — significant gaps in ${weakestCategory}`;
905
- } else {
906
- scoreExplanation = 'Early stage — run `nerviq setup` to bootstrap your config';
907
- }
908
- console.log(colorize(` ${scoreExplanation}`, 'dim'));
909
-
910
- if (result.platformScopeNote) {
911
- console.log(colorize(` Scope: ${result.platformScopeNote.message}`, 'dim'));
912
- }
913
- if (result.workspaceHint && result.workspaceHint.workspaces.length > 0) {
914
- console.log(colorize(` Workspaces: ${result.workspaceHint.workspaces.join(', ')}`, 'dim'));
915
- }
916
- if (result.platformCaveats && result.platformCaveats.length > 0) {
917
- console.log(colorize(' Platform caveats:', 'yellow'));
918
- result.platformCaveats.slice(0, 2).forEach((item) => {
919
- console.log(colorize(` - ${item.title}: ${item.message}`, 'dim'));
920
- });
921
- }
922
- if (result.largeInstructionFiles && result.largeInstructionFiles.length > 0) {
923
- result.largeInstructionFiles.slice(0, 2).forEach((item) => {
924
- console.log(colorize(` Large file: ${item.file} (${Math.round(item.byteCount / 1024)}KB)`, 'yellow'));
925
- });
926
- }
927
- console.log('');
928
-
929
- if (result.failed === 0) {
930
- const platformLabel = result.platform === 'codex' ? 'Codex' : 'Claude';
931
- console.log(colorize(` Your ${platformLabel} setup looks solid.`, 'green'));
932
- console.log(` Next: ${colorize(result.suggestedNextCommand, 'bold')}`);
933
- if (result.platform === 'codex') {
934
- console.log(colorize(' Note: Codex now supports no-write advisory flows via augment and suggest-only before setup/apply.', 'dim'));
935
- }
936
- console.log(colorize(' Star: github.com/nerviq/nerviq | Discord: discord.gg/nerviq', 'dim'));
937
- console.log('');
938
- return;
939
- }
940
-
941
- // Urgency summary line (only count actual failures, not skipped/null)
942
- const criticalCount = (result.results || []).filter(r => r.passed === false && r.impact === 'critical').length;
943
- const highCount = (result.results || []).filter(r => r.passed === false && r.impact === 'high').length;
944
- const mediumCount = result.failed - criticalCount - highCount;
945
- const urgencyParts = [];
946
- if (criticalCount > 0) urgencyParts.push(colorize(`🔴 ${criticalCount} critical`, 'red'));
947
- if (highCount > 0) urgencyParts.push(colorize(`🟡 ${highCount} high`, 'yellow'));
948
- if (mediumCount > 0) urgencyParts.push(colorize(`🔵 ${mediumCount} recommended`, 'blue'));
949
- if (urgencyParts.length > 0) {
950
- console.log(` ${urgencyParts.join(' ')}`);
951
- console.log('');
952
- }
953
-
954
- console.log(colorize(' Top 3 things to fix right now:', 'magenta'));
955
- console.log('');
956
- let usagePatterns;
957
- try { usagePatterns = require('./usage-patterns'); } catch { usagePatterns = null; }
958
- result.liteSummary.topNextActions.forEach((item, index) => {
959
- const tier = item.impact === 'critical' ? '🔴' : item.impact === 'high' ? '🟡' : '🔵';
960
- const suppressed = usagePatterns && usagePatterns.getPriorityAdjustment(dir, item.key) === 'suppress';
961
- const suffix = suppressed ? colorize(' (suppressed)', 'dim') : '';
962
- console.log(` ${index + 1}. ${tier} ${colorize(item.name, 'bold')}${suffix}`);
963
- console.log(colorize(` ${item.fix}`, 'dim'));
964
- });
965
- console.log('');
966
- console.log(` Ready? Run: ${colorize(result.suggestedNextCommand, 'bold')}`);
967
- if (result.platform === 'codex') {
968
- console.log(colorize(' Note: Codex now supports no-write advisory flows via augment and suggest-only before setup/apply.', 'dim'));
969
- }
970
- console.log(colorize(` See all ${result.failed} failed checks: ${colorize('nerviq audit --full', 'bold')}`, 'dim'));
971
- console.log(colorize(' Star: github.com/nerviq/nerviq | Discord: discord.gg/nerviq', 'dim'));
972
- console.log('');
973
- }
974
-
975
- /**
976
- * Run a full audit of a project's Claude Code setup against the CLAUDEX technique database.
977
- * @param {Object} options - Audit options.
978
- * @param {string} options.dir - Project directory to audit.
979
- * @param {boolean} [options.silent] - Skip all console output, return result only.
980
- * @param {boolean} [options.json] - Output result as JSON.
981
- * @param {boolean} [options.lite] - Show short top-3 quick scan.
982
- * @param {boolean} [options.verbose] - Show all recommendations including medium-impact.
983
- * @param {boolean} [options.showDeprecated] - Include deprecated checks in output.
984
- * @returns {Promise<Object>} Audit result with score, passed/failed counts, quickWins, and topNextActions.
985
- */
986
- async function audit(options) {
987
- const spec = getAuditSpec(options.platform || 'claude');
988
- const silent = options.silent || false;
989
- const ctx = new spec.ContextClass(options.dir);
990
- const largeInstructionFiles = inspectInstructionFiles(spec, ctx);
991
- guardSkippedInstructionFiles(ctx, largeInstructionFiles);
992
- const stacks = ctx.detectStacks(STACKS);
993
- const results = [];
994
- const outcomeSummary = getRecommendationOutcomeSummary(options.dir);
995
- const fpFeedback = getFeedbackSummary(options.dir);
996
- const workspaceHint = buildWorkspaceHint(options.dir);
997
-
998
- // Load and merge plugin checks
999
- const plugins = loadPlugins(options.dir);
1000
- const techniques = plugins.length > 0
1001
- ? mergePluginChecks(spec.techniques, plugins)
1002
- : spec.techniques;
1003
-
1004
- // Pre-compute which stack categories are active for this project
1005
- const activeStackCategories = new Set();
1006
- for (const [category, detector] of Object.entries(STACK_CATEGORY_DETECTORS)) {
1007
- if (detector(ctx)) activeStackCategories.add(category);
1008
- }
1009
-
1010
- // Generic quality categories that are NOT about AI agent configuration.
1011
- // These are only included with --verbose or --full --verbose (deep quality mode).
1012
- const GENERIC_QUALITY_CATEGORIES = new Set([
1013
- 'observability', 'accessibility', 'i18n', 'privacy', 'error-tracking',
1014
- 'supply-chain', 'api-versioning', 'caching', 'rate-limiting', 'feature-flags',
1015
- 'docs-quality', 'monorepo', 'performance-budget', 'realtime', 'graphql',
1016
- 'testing-strategy', 'code-quality', 'api-design', 'database', 'authentication',
1017
- 'monitoring', 'dependency-management', 'cost-optimization',
1018
- ]);
1019
- const includeGenericQuality = options.verbose;
1020
-
1021
- // Run all technique checks
1022
- for (const [key, technique] of Object.entries(techniques)) {
1023
- // Skip entire stack category if the stack is not detected at a core location
1024
- // Skip generic quality categories unless --verbose is set
1025
- const cat = technique.category;
1026
- if ((!includeGenericQuality && GENERIC_QUALITY_CATEGORIES.has(cat)) ||
1027
- (STACK_CATEGORY_DETECTORS[cat] && !activeStackCategories.has(cat))) {
1028
- results.push({
1029
- key,
1030
- ...technique,
1031
- file: null,
1032
- line: null,
1033
- passed: null, // not applicable
1034
- });
1035
- continue;
1036
- }
1037
-
1038
- const passed = technique.check(ctx);
1039
- const file = typeof technique.file === 'function' ? (technique.file(ctx) ?? null) : (technique.file ?? null);
1040
- const line = typeof technique.line === 'function' ? (technique.line(ctx) ?? null) : (technique.line ?? null);
1041
- results.push({
1042
- key,
1043
- ...technique,
1044
- file,
1045
- line: Number.isFinite(line) ? line : null,
1046
- passed,
1047
- });
1048
- }
1049
-
1050
- if (largeInstructionFiles.length > 0) {
1051
- results.push({
1052
- key: 'largeInstructionFile',
1053
- id: null,
1054
- name: 'Large instruction file warning',
1055
- category: 'performance',
1056
- impact: 'medium',
1057
- rating: null,
1058
- fix: 'Split oversized instruction files so they stay under 50KB, and keep any single instruction file below 1MB.',
1059
- sourceUrl: null,
1060
- confidence: 'high',
1061
- file: largeInstructionFiles[0].file,
1062
- line: null,
1063
- passed: null,
1064
- details: largeInstructionFiles,
1065
- });
1066
- }
1067
-
1068
- // Separate deprecated checks from active checks.
1069
- // Deprecated checks are excluded from scoring but preserved for display.
1070
- const deprecated = results.filter(r => r.deprecated === true);
1071
- const activeResults = results.filter(r => r.deprecated !== true);
1072
-
1073
- // null = not applicable (skip), true = pass, false = fail
1074
- const applicable = activeResults.filter(r => r.passed !== null);
1075
- const skipped = activeResults.filter(r => r.passed === null);
1076
- const passed = applicable.filter(r => r.passed);
1077
- const failed = applicable.filter(r => !r.passed);
1078
- const critical = failed.filter(r => r.impact === 'critical');
1079
- const high = failed.filter(r => r.impact === 'high');
1080
- const medium = failed.filter(r => r.impact === 'medium');
1081
-
1082
- // Calculate score only from applicable checks
1083
- const maxScore = applicable.reduce((sum, r) => sum + (WEIGHTS[r.impact] || 5), 0);
1084
- const earnedScore = passed.reduce((sum, r) => sum + (WEIGHTS[r.impact] || 5), 0);
1085
- const score = maxScore > 0 ? Math.round((earnedScore / maxScore) * 100) : 0;
1086
-
1087
- // Detect scaffolded vs organic: if CLAUDE.md contains our version stamp, some checks
1088
- // are passing because WE generated them, not the user
1089
- const instructionSource = spec.platform === 'codex'
1090
- ? (ctx.agentsMdContent ? (ctx.agentsMdContent() || '') : '')
1091
- : (ctx.claudeMdContent() || '');
1092
- const isScaffolded = instructionSource.includes('Generated by nerviq') ||
1093
- instructionSource.includes('nerviq');
1094
- // Scaffolded checks: things our setup creates (CLAUDE.md / AGENTS.md, hooks, commands, agents, rules, skills)
1095
- const scaffoldedKeys = spec.platform === 'codex'
1096
- ? new Set([
1097
- 'codexAgentsMd',
1098
- 'codexAgentsMdSubstantive',
1099
- 'codexAgentsVerificationCommands',
1100
- 'codexAgentsArchitecture',
1101
- 'codexConfigExists',
1102
- 'codexModelExplicit',
1103
- 'codexReasoningEffortExplicit',
1104
- 'codexWeakModelExplicit',
1105
- 'codexSandboxModeExplicit',
1106
- 'codexApprovalPolicyExplicit',
1107
- 'codexFullAutoErrorModeExplicit',
1108
- 'codexHistorySendToServerExplicit',
1109
- ])
1110
- : new Set(['claudeMd', 'mermaidArchitecture', 'verificationLoop',
1111
- 'hooks', 'customCommands', 'multipleCommands', 'agents', 'pathRules', 'multipleRules',
1112
- 'skills', 'hooksConfigured', 'preToolUseHook', 'postToolUseHook', 'fewShotExamples',
1113
- 'constraintBlocks', 'xmlTags']);
1114
- const organicPassed = passed.filter(r => !scaffoldedKeys.has(r.key));
1115
- const scaffoldedPassed = passed.filter(r => scaffoldedKeys.has(r.key));
1116
- const organicEarned = organicPassed.reduce((sum, r) => sum + (WEIGHTS[r.impact] || 5), 0);
1117
- const organicScore = maxScore > 0 ? Math.round((organicEarned / maxScore) * 100) : 0;
1118
- const quickWins = getQuickWins(failed, { platform: spec.platform });
1119
- const topNextActions = buildTopNextActions(failed, 5, outcomeSummary.byKey, { platform: spec.platform, fpFeedbackByKey: fpFeedback.byKey });
1120
- const categoryScores = computeCategoryScores(applicable, passed);
1121
- const platformScopeNote = getPlatformScopeNote(spec, ctx);
1122
- const platformCaveats = getPlatformCaveats(spec, ctx);
1123
- const deprecationWarnings = detectDeprecationWarnings(failed, packageVersion);
1124
- const warnings = [
1125
- ...largeInstructionFiles.map((item) => ({
1126
- kind: 'large-instruction-file',
1127
- severity: item.severity,
1128
- message: item.message,
1129
- file: item.file,
1130
- lineCount: item.lineCount,
1131
- byteCount: item.byteCount,
1132
- skipped: item.skipped,
1133
- })),
1134
- ...deprecationWarnings.map((item) => ({
1135
- kind: 'deprecated-feature',
1136
- severity: 'warning',
1137
- ...item,
1138
- })),
1139
- ];
1140
- const recommendedDomainPacks = spec.platform === 'codex'
1141
- ? detectCodexDomainPacks(ctx, stacks, getCodexDomainPackSignals(ctx))
1142
- : [];
1143
- const result = {
1144
- platform: spec.platform,
1145
- platformLabel: spec.platformLabel,
1146
- platformVersion: spec.platformVersion,
1147
- score,
1148
- organicScore,
1149
- earnedPoints: earnedScore,
1150
- maxPoints: maxScore,
1151
- isScaffolded,
1152
- passed: passed.length,
1153
- failed: failed.length,
1154
- skipped: skipped.length,
1155
- deprecated: deprecated.length,
1156
- checkCount: applicable.length,
1157
- stacks,
1158
- results,
1159
- deprecatedChecks: deprecated.map(r => ({
1160
- key: r.key,
1161
- name: r.name,
1162
- category: r.category,
1163
- deprecatedReason: r.deprecatedReason || null,
1164
- sunsetDate: r.sunsetDate || null,
1165
- })),
1166
- categoryScores,
1167
- quickWins: quickWins.map(({ key, name, impact, fix, category, sourceUrl }) => ({ key, name, impact, category, fix, sourceUrl })),
1168
- topNextActions,
1169
- recommendationOutcomes: {
1170
- totalEntries: outcomeSummary.totalEntries,
1171
- keysTracked: outcomeSummary.keys,
1172
- },
1173
- largeInstructionFiles,
1174
- deprecationWarnings,
1175
- warnings,
1176
- workspaceHint,
1177
- platformScopeNote,
1178
- platformCaveats,
1179
- recommendedDomainPacks,
1180
- };
1181
- // Detect which AI config files are present
1182
- const configFiles = [];
1183
- const configChecks = [
1184
- ['CLAUDE.md', 'CLAUDE.md'], ['.claude/settings.json', '.claude/settings.json'],
1185
- ['AGENTS.md', 'AGENTS.md'], ['.cursorrules', '.cursorrules'],
1186
- ['.cursor/rules', '.cursor/rules/'], ['GEMINI.md', 'GEMINI.md'],
1187
- ['.windsurfrules', '.windsurfrules'], ['.aider.conf.yml', '.aider.conf.yml'],
1188
- ['opencode.json', 'opencode.json'], ['.mcp.json', '.mcp.json'],
1189
- ];
1190
- for (const [file, label] of configChecks) {
1191
- try {
1192
- if (require('fs').existsSync(require('path').join(options.dir, file))) configFiles.push(label);
1193
- } catch {}
1194
- }
1195
- result.detectedConfigFiles = configFiles;
1196
-
1197
- result.suggestedNextCommand = inferSuggestedNextCommand(result);
1198
- result.liteSummary = {
1199
- topNextActions: topNextActions.slice(0, 3),
1200
- nextCommand: result.suggestedNextCommand,
1201
- platformCaveats: platformCaveats.slice(0, 2),
1202
- };
1203
-
1204
- // Silent mode: skip all output, just return result
1205
- if (silent) {
1206
- return result;
1207
- }
1208
-
1209
- if (options.json) {
1210
- console.log(JSON.stringify({
1211
- version: packageVersion,
1212
- timestamp: new Date().toISOString(),
1213
- ...result
1214
- }, null, 2));
1215
- return result;
1216
- }
1217
-
1218
- if (options.format === 'sarif') {
1219
- console.log(JSON.stringify(formatSarif(result, { dir: options.dir }), null, 2));
1220
- return result;
1221
- }
1222
-
1223
- if (options.format === 'otel') {
1224
- console.log(JSON.stringify(formatOtelMetrics(result), null, 2));
1225
- return result;
1226
- }
1227
-
1228
- if (options.lite) {
1229
- printLiteAudit(result, options.dir);
1230
- sendInsights(result);
1231
- return result;
1232
- }
1233
-
1234
- // Display results
1235
- console.log('');
1236
- const auditTitle = spec.platform === 'codex' ? 'nerviq codex audit' : 'nerviq audit';
1237
- console.log(colorize(` ${auditTitle}`, 'bold'));
1238
- console.log(colorize(' ═══════════════════════════════════════', 'dim'));
1239
- console.log(colorize(` Scanning: ${options.dir}`, 'dim'));
1240
- if (spec.platformVersion) {
1241
- console.log(colorize(` Platform: ${spec.platformLabel} (${spec.platformVersion})`, 'blue'));
1242
- }
1243
- if (spec.platform === 'codex' && recommendedDomainPacks.length > 0) {
1244
- console.log(colorize(` Domain packs: ${recommendedDomainPacks.map((pack) => pack.label).join(', ')}`, 'dim'));
1245
- }
1246
- if (platformScopeNote) {
1247
- console.log(colorize(` Scope: ${platformScopeNote.message}`, 'dim'));
1248
- }
1249
- if (platformCaveats.length > 0) {
1250
- console.log(colorize(' Platform caveats', 'yellow'));
1251
- for (const caveat of platformCaveats) {
1252
- console.log(colorize(` ${caveat.title}`, 'bold'));
1253
- console.log(colorize(` → ${caveat.message}`, 'dim'));
1254
- if (caveat.file) {
1255
- console.log(colorize(` at ${formatLocation(caveat.file, caveat.line)}`, 'dim'));
1256
- }
1257
- }
1258
- console.log('');
1259
- }
1260
-
1261
- if (largeInstructionFiles.length > 0) {
1262
- console.log(colorize(' Large instruction files', 'yellow'));
1263
- for (const item of largeInstructionFiles) {
1264
- const sizeKb = Math.round(item.byteCount / 1024);
1265
- console.log(colorize(` ${item.file} (${sizeKb}KB, ${item.lineCount || '?'} lines)`, 'bold'));
1266
- console.log(colorize(` → ${item.message}`, 'dim'));
1267
- }
1268
- console.log('');
1269
- }
1270
-
1271
- if (deprecationWarnings.length > 0) {
1272
- console.log(colorize(' Deprecated feature warnings', 'yellow'));
1273
- for (const item of deprecationWarnings) {
1274
- console.log(colorize(` ${item.feature}`, 'bold'));
1275
- console.log(colorize(` → ${item.message}`, 'dim'));
1276
- console.log(colorize(` Alternative: ${item.alternative}`, 'dim'));
1277
- }
1278
- console.log('');
1279
- }
1280
-
1281
- if (workspaceHint && !options.workspace) {
1282
- console.log(colorize(' Monorepo detected', 'blue'));
1283
- if (workspaceHint.workspaces.length > 0) {
1284
- console.log(colorize(` Workspaces: ${workspaceHint.workspaces.join(', ')}`, 'dim'));
1285
- }
1286
- console.log(colorize(` Tip: ${workspaceHint.suggestedCommand}`, 'dim'));
1287
- console.log('');
1288
- }
1289
-
1290
- if (stacks.length > 0) {
1291
- console.log(colorize(` Detected: ${stacks.map(s => s.label).join(', ')}`, 'blue'));
1292
- }
1293
-
1294
- console.log('');
1295
-
1296
- // Score
1297
- console.log(` ${progressBar(score)} ${colorize(`${score}/100`, 'bold')}`);
1298
- if (isScaffolded && scaffoldedPassed.length > 0) {
1299
- console.log(colorize(` Organic: ${organicScore}/100 (without nerviq generated files)`, 'dim'));
1300
- }
1301
- console.log('');
1302
-
1303
- // Passed
1304
- if (passed.length > 0) {
1305
- console.log(colorize(' ✅ Passing', 'green'));
1306
- for (const r of passed) {
1307
- console.log(colorize(` ${r.name}`, 'dim'));
1308
- }
1309
- console.log('');
1310
- }
1311
-
1312
- // Deprecated checks (shown with --show-deprecated or --full)
1313
- if (deprecated.length > 0 && (options.showDeprecated || options.full)) {
1314
- console.log(colorize(` ⏳ Deprecated (${deprecated.length} checks excluded from scoring)`, 'dim'));
1315
- for (const r of deprecated) {
1316
- const reason = r.deprecatedReason ? ` — ${r.deprecatedReason}` : '';
1317
- const sunset = r.sunsetDate ? ` (sunset: ${r.sunsetDate})` : '';
1318
- console.log(colorize(` [DEPRECATED] ${r.name}${reason}${sunset}`, 'dim'));
1319
- }
1320
- console.log('');
1321
- }
1322
-
1323
- // Failed - by priority
1324
- if (critical.length > 0) {
1325
- console.log(colorize(' 🔴 Critical (fix immediately)', 'red'));
1326
- for (const r of critical) {
1327
- const conf = r.confidence ? ` [${confidenceLabel(r.confidence)}]` : '';
1328
- console.log(` ${colorize(r.name, 'bold')}${colorize(conf, 'dim')}`);
1329
- if (r.file) {
1330
- console.log(colorize(` at ${formatLocation(r.file, r.line)}`, 'dim'));
1331
- }
1332
- console.log(colorize(` → ${r.fix}`, 'dim'));
1333
- }
1334
- console.log('');
1335
- }
1336
-
1337
- if (high.length > 0) {
1338
- console.log(colorize(' 🟡 High Impact', 'yellow'));
1339
- for (const r of high) {
1340
- const conf = r.confidence ? ` [${confidenceLabel(r.confidence)}]` : '';
1341
- console.log(` ${colorize(r.name, 'bold')}${colorize(conf, 'dim')}`);
1342
- if (r.file) {
1343
- console.log(colorize(` at ${formatLocation(r.file, r.line)}`, 'dim'));
1344
- }
1345
- console.log(colorize(` → ${r.fix}`, 'dim'));
1346
- }
1347
- console.log('');
1348
- }
1349
-
1350
- if (medium.length > 0 && options.verbose) {
1351
- console.log(colorize(' 🔵 Recommended', 'blue'));
1352
- for (const r of medium) {
1353
- const conf = r.confidence ? ` [${confidenceLabel(r.confidence)}]` : '';
1354
- console.log(` ${colorize(r.name, 'bold')}${colorize(conf, 'dim')}`);
1355
- if (r.file) {
1356
- console.log(colorize(` at ${formatLocation(r.file, r.line)}`, 'dim'));
1357
- }
1358
- console.log(colorize(` → ${r.fix}`, 'dim'));
1359
- }
1360
- console.log('');
1361
- } else if (medium.length > 0) {
1362
- console.log(colorize(` 🔵 ${medium.length} more recommendations (use --verbose)`, 'blue'));
1363
- console.log('');
1364
- }
1365
-
1366
- // Top next actions
1367
- if (topNextActions.length > 0) {
1368
- console.log(colorize(' ⚡ Top 5 Next Actions', 'magenta'));
1369
- for (let i = 0; i < topNextActions.length; i++) {
1370
- const item = topNextActions[i];
1371
- console.log(` ${i + 1}. ${colorize(item.name, 'bold')}`);
1372
- console.log(colorize(` Why: ${item.why}`, 'dim'));
1373
- console.log(colorize(` Trace: ${item.signals.join(' | ')}`, 'dim'));
1374
- console.log(colorize(` Risk: ${item.risk} | Confidence: ${item.confidence}`, 'dim'));
1375
- const sourceResult = result.results.find(r => r.key === item.key);
1376
- if (sourceResult && sourceResult.file) {
1377
- console.log(colorize(` Evidence: ${formatLocation(sourceResult.file, sourceResult.line)}`, 'dim'));
1378
- }
1379
- if (item.feedback) {
1380
- const avgDelta = Number.isFinite(item.feedback.avgScoreDelta) ? ` | Avg score delta: ${item.feedback.avgScoreDelta >= 0 ? '+' : ''}${item.feedback.avgScoreDelta}` : '';
1381
- console.log(colorize(` Feedback: accepted ${item.feedback.accepted}, rejected ${item.feedback.rejected}, positive ${item.feedback.positive}, negative ${item.feedback.negative}${avgDelta}`, 'dim'));
1382
- }
1383
- console.log(colorize(` Fix: ${item.fix}`, 'dim'));
1384
- }
1385
- console.log('');
1386
- }
1387
-
1388
- // Summary
1389
- console.log(colorize(' ─────────────────────────────────────', 'dim'));
1390
- const deprecatedNote = deprecated.length > 0 ? colorize(`, ${deprecated.length} deprecated`, 'dim') : '';
1391
- console.log(` ${colorize(`${passed.length}/${applicable.length}`, 'bold')} checks passing${skipped.length > 0 ? colorize(` (${skipped.length} not applicable${deprecatedNote})`, 'dim') : (deprecatedNote ? colorize(` (${deprecatedNote})`, 'dim') : '')}`);
1392
-
1393
- if (failed.length > 0) {
1394
- console.log(` Next command: ${colorize(result.suggestedNextCommand, 'bold')}`);
1395
- if (result.platform === 'codex') {
1396
- console.log(colorize(' Codex now supports advisory no-write flows through augment and suggest-only before setup/apply.', 'dim'));
1397
- }
1398
- }
1399
-
1400
- console.log('');
1401
- console.log(` Add to README: ${getBadgeMarkdown(score)}`);
1402
- console.log('');
1403
-
1404
- // Weakest categories insight
1405
- const insights = getLocalInsights({ score, results });
1406
- if (insights.weakest.length > 0) {
1407
- console.log(colorize(' Weakest areas:', 'dim'));
1408
- for (const w of insights.weakest) {
1409
- const bar = w.score === 0 ? colorize('none', 'red') : `${w.score}%`;
1410
- console.log(colorize(` ${w.name}: ${bar} (${w.passed}/${w.total})`, 'dim'));
1411
- }
1412
- console.log('');
1413
- }
1414
-
1415
- // Cross-platform synergy hint
1416
- try {
1417
- const { detectActivePlatforms } = require('./harmony/canon');
1418
- const { analyzeCompensation } = require('./synergy/compensation');
1419
- const { calculateSynergyScore } = require('./synergy/ranking');
1420
- const detected = detectActivePlatforms(options.dir);
1421
- const activePlatforms = (detected || []).filter(p => p.detected).map(p => p.platform);
1422
- if (activePlatforms.length >= 2) {
1423
- const comp = analyzeCompensation(activePlatforms);
1424
- const synergyScore = calculateSynergyScore(activePlatforms);
1425
- console.log(colorize(` Cross-platform synergy [EXPERIMENTAL]: ${activePlatforms.length} platforms detected`, 'blue'));
1426
- console.log(colorize(` Platforms: ${activePlatforms.join(', ')}`, 'dim'));
1427
- console.log(colorize(` Compensations: ${comp.compensations.length} | Gaps: ${comp.uncoveredGaps.length}`, 'dim'));
1428
- console.log(colorize(` Run: npx nerviq harmony-audit for full cross-platform analysis`, 'dim'));
1429
- console.log('');
1430
- }
1431
- } catch { /* synergy display is optional */ }
1432
-
1433
- console.log(colorize(` Backed by NERVIQ research and evidence for ${spec.platformLabel}`, 'dim'));
1434
- console.log(colorize(' https://github.com/nerviq/nerviq', 'dim'));
1435
- console.log('');
1436
-
1437
- // Send anonymous insights (opt-in, privacy-first, fire-and-forget)
1438
- sendInsights(result);
1439
-
1440
- return result;
1441
- }
1442
-
1443
- module.exports = { audit, buildTopNextActions, getFpFeedbackMultiplier, getRecommendationPriorityScore };
1
+ /**
2
+ * Audit engine - evaluates project against NERVIQ technique database.
3
+ */
4
+
5
+ const path = require('path');
6
+ const { TECHNIQUES: CLAUDE_TECHNIQUES, STACKS, STACK_CATEGORY_DETECTORS } = require('./techniques');
7
+ const { ProjectContext } = require('./context');
8
+ const { CODEX_TECHNIQUES } = require('./codex/techniques');
9
+ const { detectCodexDomainPacks } = require('./codex/domain-packs');
10
+ const { CodexProjectContext, detectCodexVersion } = require('./codex/context');
11
+ const { GEMINI_TECHNIQUES } = require('./gemini/techniques');
12
+ const { detectGeminiDomainPacks } = require('./gemini/domain-packs');
13
+ const { GeminiProjectContext, detectGeminiVersion } = require('./gemini/context');
14
+ const { COPILOT_TECHNIQUES } = require('./copilot/techniques');
15
+ const { detectCopilotDomainPacks } = require('./copilot/domain-packs');
16
+ const { CopilotProjectContext } = require('./copilot/context');
17
+ const { CURSOR_TECHNIQUES } = require('./cursor/techniques');
18
+ const { detectCursorDomainPacks } = require('./cursor/domain-packs');
19
+ const { CursorProjectContext } = require('./cursor/context');
20
+ const { WINDSURF_TECHNIQUES } = require('./windsurf/techniques');
21
+ const { WindsurfProjectContext } = require('./windsurf/context');
22
+ const { AIDER_TECHNIQUES } = require('./aider/techniques');
23
+ const { AiderProjectContext } = require('./aider/context');
24
+ const { OPENCODE_TECHNIQUES } = require('./opencode/techniques');
25
+ const { OpenCodeProjectContext } = require('./opencode/context');
26
+ const { getBadgeMarkdown } = require('./badge');
27
+ const { sendInsights, getLocalInsights } = require('./insights');
28
+ const { getRecommendationOutcomeSummary, getRecommendationAdjustment } = require('./activity');
29
+ const { getFeedbackSummary } = require('./feedback');
30
+ const { formatSarif } = require('./formatters/sarif');
31
+ const { formatOtelMetrics } = require('./formatters/otel');
32
+ const { loadPlugins, mergePluginChecks } = require('./plugins');
33
+ const { hasWorkspaceConfig, detectWorkspaceGlobs, detectWorkspaces } = require('./workspace');
34
+ const { detectDeprecationWarnings } = require('./deprecation');
35
+ const { version: packageVersion } = require('../package.json');
36
+
37
+ const COLORS = {
38
+ reset: '\x1b[0m',
39
+ bold: '\x1b[1m',
40
+ dim: '\x1b[2m',
41
+ red: '\x1b[31m',
42
+ green: '\x1b[32m',
43
+ yellow: '\x1b[33m',
44
+ blue: '\x1b[36m',
45
+ magenta: '\x1b[35m',
46
+ };
47
+
48
+ function colorize(text, color) {
49
+ return `${COLORS[color] || ''}${text}${COLORS.reset}`;
50
+ }
51
+
52
+ function progressBar(score, max = 100, width = 20) {
53
+ const filled = Math.round((score / max) * width);
54
+ const empty = width - filled;
55
+ const color = score >= 70 ? 'green' : score >= 40 ? 'yellow' : 'red';
56
+ return colorize('█'.repeat(filled), color) + colorize('░'.repeat(empty), 'dim');
57
+ }
58
+
59
+ function formatLocation(file, line) {
60
+ if (!file) return null;
61
+ return line ? `${file}:${line}` : file;
62
+ }
63
+
64
+ const IMPACT_ORDER = { critical: 3, high: 2, medium: 1, low: 0 };
65
+ const WEIGHTS = { critical: 15, high: 10, medium: 5, low: 2 };
66
+ const LARGE_INSTRUCTION_WARN_BYTES = 50 * 1024;
67
+ const LARGE_INSTRUCTION_SKIP_BYTES = 1024 * 1024;
68
+ const CATEGORY_MODULES = {
69
+ memory: 'CLAUDE.md',
70
+ quality: 'verification',
71
+ git: 'safety',
72
+ workflow: 'commands-agents-skills',
73
+ security: 'permissions',
74
+ automation: 'hooks',
75
+ design: 'design-rules',
76
+ devops: 'ci-devops',
77
+ hygiene: 'project-hygiene',
78
+ performance: 'context-management',
79
+ tools: 'mcp-tools',
80
+ prompting: 'prompt-structure',
81
+ features: 'modern-claude-features',
82
+ 'quality-deep': 'quality-deep',
83
+ skills: 'skills',
84
+ agents: 'subagents',
85
+ review: 'review-workflow',
86
+ local: 'local-environment',
87
+ };
88
+ const ACTION_RATIONALES = {
89
+ noBypassPermissions: 'bypassPermissions skips the main safety layer. Explicit allow and deny rules create safer autonomy.',
90
+ secretsProtection: 'Without secret protection, Claude can accidentally inspect sensitive files and leak them into outputs.',
91
+ permissionDeny: 'Deny rules are the strongest way to prevent dangerous reads and destructive operations.',
92
+ settingsPermissions: 'Explicit permission settings make the workflow safer, more governable, and easier to review.',
93
+ testCommand: 'Without a test command, Claude cannot verify that its changes actually work before handoff.',
94
+ lintCommand: 'Without a lint command, Claude will miss formatting and style regressions that teams expect to catch automatically.',
95
+ buildCommand: 'Without a build command, compile and packaging failures stay invisible until later in the workflow.',
96
+ ciPipeline: 'CI is what turns a local setup improvement into a repeatable team-wide standard.',
97
+ securityReview: 'If you do not wire in security review guidance, high-risk changes are easier to ship without the right scrutiny.',
98
+ skills: 'Skills package reusable expertise so Claude does not need the same context re-explained every session.',
99
+ multipleAgents: 'Specialized agents unlock role-based work such as security review, implementation, and QA in parallel.',
100
+ multipleMcpServers: 'A richer MCP surface gives Claude access to live tools and documentation instead of stale assumptions.',
101
+ roleDefinition: 'A clear role definition calibrates how Claude thinks, explains, and validates work in this repo.',
102
+ importSyntax: 'Imported modules keep CLAUDE.md maintainable as the workflow grows more sophisticated.',
103
+ claudeMd: 'CLAUDE.md is the foundation of project-specific context. Without it, Claude starts every task half-blind.',
104
+ hooks: 'Hooks enforce the rules programmatically, which is much more reliable than relying on instructions alone.',
105
+ pathRules: 'Path-specific rules help Claude behave differently in different parts of the repo without global noise.',
106
+ context7Mcp: 'Live documentation reduces version drift and cuts down on confident but outdated answers.',
107
+ codexAgentsMd: 'AGENTS.md is the main Codex instruction surface. Without it, Codex starts without repo-specific guidance.',
108
+ codexAgentsMdSubstantive: 'A thin AGENTS.md is almost as bad as no AGENTS.md because Codex still lacks the repo context it needs.',
109
+ codexAgentsVerificationCommands: 'If AGENTS.md does not document how to verify work, Codex cannot reliably prove its own changes are safe.',
110
+ codexAgentsArchitecture: 'A small architecture map reduces navigation drift and helps Codex change the right part of the repo first.',
111
+ codexConfigExists: 'Without .codex/config.toml, trust and model behavior are implicit instead of explicit.',
112
+ codexReasoningEffortExplicit: 'Reasoning depth should be intentional for cost and latency, not left to implicit defaults.',
113
+ codexApprovalPolicyExplicit: 'Explicit approvals make Codex behavior predictable and reviewable across sessions.',
114
+ codexNoDangerFullAccess: 'danger-full-access removes the main safety boundary and should be treated as a critical risk.',
115
+ codexHistorySendToServerExplicit: 'History sync is a privacy and governance surface. Teams should decide it explicitly, not inherit it accidentally.',
116
+ codexNoSecretsInAgents: 'Secrets in AGENTS.md can leak directly into agent context, outputs, and logs.',
117
+ codexHooksWindowsCaveat: 'Windows does not support Codex hooks today, so relying on them there creates a false sense of runtime enforcement.',
118
+ codexSkillsDirPresentWhenUsed: 'Versioned repo-local skills are the safest way to keep Codex expertise reviewable and consistent across contributors.',
119
+ codexSkillsHaveMetadata: 'Without a usable SKILL.md, Codex cannot reliably decide when a skill should run or what it is for.',
120
+ codexSkillNamesKebabCase: 'Consistent skill naming improves discoverability and avoids invocation drift.',
121
+ codexSkillDescriptionsBounded: 'A bounded skill description helps Codex invoke the right skill without inflating prompt context.',
122
+ codexSkillsNoAutoRunRisk: 'Skills should guide Codex, not silently authorize risky automation or destructive actions.',
123
+ codexCustomAgentsRequiredFields: 'Custom agents need clear metadata and developer instructions so delegation stays predictable.',
124
+ codexMaxThreadsExplicit: 'Explicit fanout limits make Codex delegation safer and easier to reason about.',
125
+ codexMaxDepthExplicit: 'Nested delegation should be deliberate, not accidental.',
126
+ codexPerAgentSandboxOverridesSafe: 'Per-agent overrides can quietly bypass the main trust model if they are not constrained.',
127
+ codexExecUsageSafe: 'Unsafe Codex automation quickly turns small workflow mistakes into real repo damage.',
128
+ codexGitHubActionSafeStrategy: 'CI safety posture should be visible and intentional, especially when Codex is acting in automation.',
129
+ codexCiAuthUsesManagedKey: 'Managed secrets are the minimum trust boundary for Codex in CI.',
130
+ codexAutomationManuallyTested: 'Manual dry-runs catch automation footguns before they become scheduled failures.',
131
+ codexReviewWorkflowDocumented: 'A documented review path makes Codex safer to use on risky diffs and refactors.',
132
+ codexReviewModelOverrideExplicit: 'Explicit review model selection keeps review quality and cost predictable when automation is involved.',
133
+ codexWorkingTreeReviewExpectations: 'Codex reviews are much safer when the repo states how to treat staged, unstaged, and unrelated changes.',
134
+ codexCostAwarenessDocumented: 'Heavy workflows should be intentional, not the invisible default.',
135
+ codexArtifactsSharedIntentionally: 'If `.codex` is hidden from version control, the team loses a shared and reviewable Codex contract.',
136
+ codexLifecycleScriptsPlatformSafe: 'Local setup/teardown scripts are part of the trust model and should not surprise contributors on other platforms.',
137
+ codexActionsNotRedundant: 'Redundant automation expands the surface area without adding real value.',
138
+ codexWorktreeLifecycleDocumented: 'Parallel worktree flows need explicit setup and cleanup expectations.',
139
+ codexAgentsMentionModernFeatures: 'When the repo uses modern Codex surfaces, AGENTS.md should tell Codex they exist.',
140
+ codexNoDeprecatedPatterns: 'Deprecated Codex patterns create silent drift and confusing behavior over time.',
141
+ codexProfilesUsedWhenNeeded: 'Profiles become more important as Codex automation and delegation get more complex.',
142
+ codexPluginConfigValid: 'Broken plugin metadata creates discoverability and tooling drift.',
143
+ codexUndoExplicit: 'Undo is a user-facing safety feature and should be an explicit repo choice.',
144
+ };
145
+ const CODEX_HARD_FAIL_KEYS = new Set([
146
+ 'codexAgentsMd',
147
+ 'codexConfigValidToml',
148
+ 'codexNoDangerFullAccess',
149
+ 'codexApprovalPolicyExplicit',
150
+ 'codexNoSecretsInAgents',
151
+ 'codexHooksWindowsCaveat',
152
+ ]);
153
+ const CODEX_EVIDENCE_CLASSES = {
154
+ 'CX-A01': 'runtime',
155
+ 'CX-A02': 'derived',
156
+ 'CX-A03': 'derived',
157
+ 'CX-A04': 'derived',
158
+ 'CX-A05': 'mixed',
159
+ 'CX-A06': 'source',
160
+ 'CX-A07': 'derived',
161
+ 'CX-A08': 'derived',
162
+ 'CX-B01': 'runtime',
163
+ 'CX-B02': 'mixed',
164
+ 'CX-B03': 'mixed',
165
+ 'CX-B04': 'source',
166
+ 'CX-B05': 'source',
167
+ 'CX-B06': 'source',
168
+ 'CX-B07': 'source',
169
+ 'CX-B08': 'source',
170
+ 'CX-B09': 'source',
171
+ 'CX-C01': 'mixed',
172
+ 'CX-C02': 'mixed',
173
+ 'CX-C03': 'mixed',
174
+ 'CX-C04': 'derived',
175
+ 'CX-C05': 'source',
176
+ 'CX-C06': 'source',
177
+ 'CX-C07': 'mixed',
178
+ 'CX-C08': 'source',
179
+ 'CX-C09': 'mixed',
180
+ 'CX-D01': 'runtime',
181
+ 'CX-D02': 'mixed',
182
+ 'CX-D03': 'source',
183
+ 'CX-D04': 'mixed',
184
+ 'CX-D05': 'mixed',
185
+ 'CX-E01': 'mixed',
186
+ 'CX-E02': 'runtime',
187
+ 'CX-E03': 'mixed',
188
+ 'CX-E04': 'mixed',
189
+ 'CX-E05': 'source',
190
+ 'CX-F01': 'mixed',
191
+ 'CX-F02': 'mixed',
192
+ 'CX-F03': 'source',
193
+ 'CX-F04': 'mixed',
194
+ 'CX-F05': 'source',
195
+ 'CX-F06': 'source',
196
+ 'CX-G01': 'mixed',
197
+ 'CX-G02': 'source',
198
+ 'CX-G03': 'source',
199
+ 'CX-G04': 'derived',
200
+ 'CX-G05': 'derived',
201
+ 'CX-H01': 'source',
202
+ 'CX-H02': 'runtime',
203
+ 'CX-H03': 'runtime',
204
+ 'CX-H04': 'source',
205
+ 'CX-I01': 'mixed',
206
+ 'CX-I02': 'mixed',
207
+ 'CX-I03': 'source',
208
+ 'CX-I04': 'source',
209
+ 'CX-J01': 'source',
210
+ 'CX-J02': 'source',
211
+ 'CX-J03': 'source',
212
+ 'CX-J04': 'source',
213
+ 'CX-K01': 'source',
214
+ 'CX-K02': 'source',
215
+ 'CX-K03': 'source',
216
+ 'CX-K04': 'source',
217
+ 'CX-L01': 'derived',
218
+ 'CX-L02': 'source',
219
+ 'CX-L03': 'derived',
220
+ 'CX-L04': 'source',
221
+ 'CX-L05': 'source',
222
+ };
223
+ const CODEX_QUICKWIN_CONFIG_KEYS = new Set([
224
+ 'codexConfigExists',
225
+ 'codexModelExplicit',
226
+ 'codexReasoningEffortExplicit',
227
+ 'codexWeakModelExplicit',
228
+ 'codexProfilesUsedAppropriately',
229
+ 'codexFullAutoErrorModeExplicit',
230
+ 'codexHistorySendToServerExplicit',
231
+ 'codexNetworkAccessExplicit',
232
+ 'codexHooksDeliberate',
233
+ 'codexMcpStartupTimeoutReasonable',
234
+ 'codexMaxThreadsExplicit',
235
+ 'codexMaxDepthExplicit',
236
+ ]);
237
+ const CODEX_QUICKWIN_FILE_KEYS = new Set([
238
+ 'codexAgentsMd',
239
+ 'codexHooksJsonExistsWhenClaimed',
240
+ 'codexSkillsDirPresentWhenUsed',
241
+ ]);
242
+ const CODEX_QUICKWIN_DOC_KEYS = new Set([
243
+ 'codexAgentsArchitecture',
244
+ 'codexOverrideDocumented',
245
+ 'codexNoGenericFiller',
246
+ 'codexNoInstructionContradictions',
247
+ 'codexRulesExamplesPresent',
248
+ 'codexRuleWrapperRiskDocumented',
249
+ 'codexSkillsHaveMetadata',
250
+ 'codexSkillNamesKebabCase',
251
+ 'codexSkillDescriptionsBounded',
252
+ 'codexAutomationManuallyTested',
253
+ 'codexReviewWorkflowDocumented',
254
+ 'codexWorkingTreeReviewExpectations',
255
+ 'codexCostAwarenessDocumented',
256
+ ]);
257
+ const CODEX_QUICKWIN_POLICY_KEYS = new Set([
258
+ 'codexRulesSpecificPatterns',
259
+ 'codexNoBroadAllowAllRules',
260
+ 'codexMcpWhitelistsExplicit',
261
+ 'codexNoDeprecatedMcpTransport',
262
+ 'codexGitHubActionSafeStrategy',
263
+ 'codexProfilesUsedWhenNeeded',
264
+ 'codexUndoExplicit',
265
+ ]);
266
+ const CODEX_QUICKWIN_AVOID_KEYS = new Set([
267
+ 'codexNoDangerFullAccess',
268
+ 'codexApprovalPolicyExplicit',
269
+ 'codexGitHubActionUnsafeJustified',
270
+ 'codexProjectScopedMcpTrusted',
271
+ 'codexMcpAuthDocumented',
272
+ 'codexHooksWindowsCaveat',
273
+ 'codexNoSecretsInAgents',
274
+ 'codexPerAgentSandboxOverridesSafe',
275
+ 'codexExecUsageSafe',
276
+ 'codexCiAuthUsesManagedKey',
277
+ 'codexLifecycleScriptsPlatformSafe',
278
+ ]);
279
+
280
+ function getAuditSpec(platform = 'claude') {
281
+ if (platform === 'codex') {
282
+ return {
283
+ platform: 'codex',
284
+ platformLabel: 'Codex',
285
+ techniques: CODEX_TECHNIQUES,
286
+ ContextClass: CodexProjectContext,
287
+ platformVersion: detectCodexVersion(),
288
+ };
289
+ }
290
+
291
+ if (platform === 'gemini') {
292
+ return {
293
+ platform: 'gemini',
294
+ platformLabel: 'Gemini CLI',
295
+ techniques: GEMINI_TECHNIQUES,
296
+ ContextClass: GeminiProjectContext,
297
+ platformVersion: detectGeminiVersion(),
298
+ };
299
+ }
300
+
301
+ if (platform === 'copilot') {
302
+ return {
303
+ platform: 'copilot',
304
+ platformLabel: 'GitHub Copilot',
305
+ techniques: COPILOT_TECHNIQUES,
306
+ ContextClass: CopilotProjectContext,
307
+ platformVersion: null,
308
+ };
309
+ }
310
+
311
+ if (platform === 'cursor') {
312
+ return {
313
+ platform: 'cursor',
314
+ platformLabel: 'Cursor',
315
+ techniques: CURSOR_TECHNIQUES,
316
+ ContextClass: CursorProjectContext,
317
+ platformVersion: null,
318
+ };
319
+ }
320
+
321
+ if (platform === 'windsurf') {
322
+ return {
323
+ platform: 'windsurf',
324
+ platformLabel: 'Windsurf',
325
+ techniques: WINDSURF_TECHNIQUES,
326
+ ContextClass: WindsurfProjectContext,
327
+ platformVersion: null,
328
+ };
329
+ }
330
+
331
+ if (platform === 'aider') {
332
+ return {
333
+ platform: 'aider',
334
+ platformLabel: 'Aider',
335
+ techniques: AIDER_TECHNIQUES,
336
+ ContextClass: AiderProjectContext,
337
+ platformVersion: null,
338
+ };
339
+ }
340
+
341
+ if (platform === 'opencode') {
342
+ return {
343
+ platform: 'opencode',
344
+ platformLabel: 'OpenCode',
345
+ techniques: OPENCODE_TECHNIQUES,
346
+ ContextClass: OpenCodeProjectContext,
347
+ platformVersion: null,
348
+ };
349
+ }
350
+
351
+ return {
352
+ platform: 'claude',
353
+ platformLabel: 'Claude',
354
+ techniques: CLAUDE_TECHNIQUES,
355
+ ContextClass: ProjectContext,
356
+ platformVersion: null,
357
+ };
358
+ }
359
+
360
+ function normalizeRelativePath(filePath) {
361
+ return String(filePath || '').replace(/\\/g, '/').replace(/^\.\//, '');
362
+ }
363
+
364
+ function addPath(target, filePath) {
365
+ if (!filePath || typeof filePath !== 'string') return;
366
+ target.add(normalizeRelativePath(filePath));
367
+ }
368
+
369
+ function addDirFiles(ctx, target, dirPath, filter) {
370
+ if (typeof ctx.dirFiles !== 'function') return;
371
+ for (const file of ctx.dirFiles(dirPath)) {
372
+ if (filter && !filter.test(file)) continue;
373
+ addPath(target, path.join(dirPath, file));
374
+ }
375
+ }
376
+
377
+ function instructionFileCandidates(spec, ctx) {
378
+ const candidates = new Set();
379
+
380
+ if (spec.platform === 'claude') {
381
+ addPath(candidates, 'CLAUDE.md');
382
+ addPath(candidates, '.claude/CLAUDE.md');
383
+ addDirFiles(ctx, candidates, '.claude/rules', /\.md$/i);
384
+ addDirFiles(ctx, candidates, '.claude/commands', /\.md$/i);
385
+ addDirFiles(ctx, candidates, '.claude/agents', /\.md$/i);
386
+ if (typeof ctx.dirFiles === 'function') {
387
+ for (const skillDir of ctx.dirFiles('.claude/skills')) {
388
+ addPath(candidates, path.join('.claude', 'skills', skillDir, 'SKILL.md'));
389
+ }
390
+ }
391
+ }
392
+
393
+ if (spec.platform === 'codex') {
394
+ addPath(candidates, 'AGENTS.md');
395
+ addPath(candidates, 'AGENTS.override.md');
396
+ addPath(candidates, typeof ctx.agentsMdPath === 'function' ? ctx.agentsMdPath() : null);
397
+ addDirFiles(ctx, candidates, 'codex/rules');
398
+ addDirFiles(ctx, candidates, '.codex/rules');
399
+ if (typeof ctx.skillDirs === 'function') {
400
+ for (const skillDir of ctx.skillDirs()) {
401
+ addPath(candidates, path.join('.agents', 'skills', skillDir, 'SKILL.md'));
402
+ }
403
+ }
404
+ }
405
+
406
+ if (spec.platform === 'gemini') {
407
+ addPath(candidates, 'GEMINI.md');
408
+ addPath(candidates, '.gemini/GEMINI.md');
409
+ addDirFiles(ctx, candidates, '.gemini/agents', /\.md$/i);
410
+ if (typeof ctx.skillDirs === 'function') {
411
+ for (const skillDir of ctx.skillDirs()) {
412
+ addPath(candidates, path.join('.gemini', 'skills', skillDir, 'SKILL.md'));
413
+ }
414
+ }
415
+ }
416
+
417
+ if (spec.platform === 'copilot') {
418
+ addPath(candidates, '.github/copilot-instructions.md');
419
+ addDirFiles(ctx, candidates, '.github/instructions', /\.instructions\.md$/i);
420
+ addDirFiles(ctx, candidates, '.github/prompts', /\.prompt\.md$/i);
421
+ }
422
+
423
+ if (spec.platform === 'cursor') {
424
+ addPath(candidates, '.cursorrules');
425
+ addDirFiles(ctx, candidates, '.cursor/rules', /\.mdc$/i);
426
+ addDirFiles(ctx, candidates, '.cursor/commands', /\.md$/i);
427
+ }
428
+
429
+ if (spec.platform === 'windsurf') {
430
+ addPath(candidates, '.windsurfrules');
431
+ addDirFiles(ctx, candidates, '.windsurf/rules', /\.md$/i);
432
+ addDirFiles(ctx, candidates, '.windsurf/workflows', /\.md$/i);
433
+ addDirFiles(ctx, candidates, '.windsurf/memories', /\.(md|json)$/i);
434
+ }
435
+
436
+ if (spec.platform === 'aider' && typeof ctx.conventionFiles === 'function') {
437
+ for (const file of ctx.conventionFiles()) {
438
+ addPath(candidates, file);
439
+ }
440
+ }
441
+
442
+ if (spec.platform === 'opencode') {
443
+ addPath(candidates, 'AGENTS.md');
444
+ addPath(candidates, 'CLAUDE.md');
445
+ addDirFiles(ctx, candidates, '.opencode/commands', /\.(md|markdown|ya?ml)$/i);
446
+ if (typeof ctx.skillDirs === 'function') {
447
+ for (const skillDir of ctx.skillDirs()) {
448
+ addPath(candidates, path.join('.opencode', 'commands', skillDir, 'SKILL.md'));
449
+ }
450
+ }
451
+ }
452
+
453
+ return [...candidates];
454
+ }
455
+
456
+ function inspectInstructionFiles(spec, ctx) {
457
+ const warnings = [];
458
+
459
+ for (const filePath of instructionFileCandidates(spec, ctx)) {
460
+ const byteCount = typeof ctx.fileSizeBytes === 'function' ? ctx.fileSizeBytes(filePath) : null;
461
+ if (!Number.isFinite(byteCount) || byteCount <= LARGE_INSTRUCTION_WARN_BYTES) continue;
462
+
463
+ const content = typeof ctx.fileContent === 'function' ? ctx.fileContent(filePath) : null;
464
+ warnings.push({
465
+ file: normalizeRelativePath(filePath),
466
+ byteCount,
467
+ lineCount: typeof content === 'string' ? content.split(/\r?\n/).length : null,
468
+ skipped: byteCount > LARGE_INSTRUCTION_SKIP_BYTES,
469
+ severity: byteCount > LARGE_INSTRUCTION_SKIP_BYTES ? 'critical' : 'warning',
470
+ message: byteCount > LARGE_INSTRUCTION_SKIP_BYTES
471
+ ? 'Instruction file exceeds 1MB and will be skipped during audit.'
472
+ : 'Instruction file exceeds 50KB. Audit will continue, but this file may reduce runtime clarity.',
473
+ });
474
+ }
475
+
476
+ return warnings;
477
+ }
478
+
479
+ function guardSkippedInstructionFiles(ctx, warnings) {
480
+ const skippedFiles = new Set(
481
+ warnings.filter((item) => item.skipped).map((item) => normalizeRelativePath(item.file))
482
+ );
483
+
484
+ if (skippedFiles.size === 0) return;
485
+
486
+ const originalFileContent = typeof ctx.fileContent === 'function' ? ctx.fileContent.bind(ctx) : null;
487
+ const originalLineNumber = typeof ctx.lineNumber === 'function' ? ctx.lineNumber.bind(ctx) : null;
488
+
489
+ if (originalFileContent) {
490
+ ctx.fileContent = (filePath) => {
491
+ if (skippedFiles.has(normalizeRelativePath(filePath))) return null;
492
+ return originalFileContent(filePath);
493
+ };
494
+ }
495
+
496
+ if (originalLineNumber) {
497
+ ctx.lineNumber = (filePath, matcher) => {
498
+ if (skippedFiles.has(normalizeRelativePath(filePath))) return null;
499
+ return originalLineNumber(filePath, matcher);
500
+ };
501
+ }
502
+ }
503
+
504
+ function buildWorkspaceHint(dir) {
505
+ if (!hasWorkspaceConfig(dir)) {
506
+ return null;
507
+ }
508
+
509
+ const patterns = detectWorkspaceGlobs(dir);
510
+ const workspaces = detectWorkspaces(dir);
511
+ if (patterns.length === 0 && workspaces.length === 0) {
512
+ return null;
513
+ }
514
+
515
+ return {
516
+ detected: true,
517
+ patterns,
518
+ workspaces,
519
+ suggestedCommand: patterns.length > 0
520
+ ? `npx nerviq audit --workspace ${patterns.join(',')}`
521
+ : `npx nerviq audit --workspace ${workspaces.join(',')}`,
522
+ };
523
+ }
524
+
525
+ function riskFromImpact(impact) {
526
+ if (impact === 'critical') return 'high';
527
+ if (impact === 'high') return 'medium';
528
+ return 'low';
529
+ }
530
+
531
+ function confidenceFromImpact(impact) {
532
+ return impact === 'critical' || impact === 'high' ? 'high' : 'medium';
533
+ }
534
+
535
+ function confidenceLabel(confidence) {
536
+ if (confidence >= 0.6) return 'HIGH';
537
+ if (confidence >= 0.3) return 'MEDIUM';
538
+ return 'HEURISTIC';
539
+ }
540
+
541
+ function getPrioritizedFailed(failed) {
542
+ const prioritized = failed.filter(r => !(r.category === 'hygiene' && r.impact === 'low'));
543
+ return prioritized.length > 0 ? prioritized : failed;
544
+ }
545
+
546
+ function codexEvidenceClass(item) {
547
+ return CODEX_EVIDENCE_CLASSES[item.id] || 'derived';
548
+ }
549
+
550
+ function codexCategoryBonus(category) {
551
+ if (category === 'trust' || category === 'config') return 12;
552
+ if (category === 'rules' || category === 'hooks' || category === 'mcp') return 8;
553
+ if (category === 'instructions') return 4;
554
+ return 0;
555
+ }
556
+
557
+ function codexEvidenceBonus(item) {
558
+ const evidenceClass = codexEvidenceClass(item);
559
+ if (evidenceClass === 'runtime') return 8;
560
+ if (evidenceClass === 'mixed') return 6;
561
+ if (evidenceClass === 'source') return 3;
562
+ return 0;
563
+ }
564
+
565
+ function codexPriorityScore(item, outcomeSummaryByKey = {}) {
566
+ const impactBase = item.impact === 'critical'
567
+ ? 60
568
+ : item.impact === 'high'
569
+ ? 40
570
+ : item.impact === 'medium'
571
+ ? 20
572
+ : 8;
573
+ const feedbackAdjustment = getRecommendationAdjustment(outcomeSummaryByKey, item.key) * 10;
574
+ const hardFailBonus = CODEX_HARD_FAIL_KEYS.has(item.key) ? 12 : 0;
575
+ return Math.max(0, Math.min(100, impactBase + codexCategoryBonus(item.category) + codexEvidenceBonus(item) + hardFailBonus + feedbackAdjustment));
576
+ }
577
+
578
+ function codexQuickWinScore(item) {
579
+ if (CODEX_QUICKWIN_AVOID_KEYS.has(item.key)) {
580
+ return -100;
581
+ }
582
+
583
+ let score = 0;
584
+ if (CODEX_QUICKWIN_CONFIG_KEYS.has(item.key)) {
585
+ score += 40;
586
+ } else if (CODEX_QUICKWIN_FILE_KEYS.has(item.key)) {
587
+ score += 34;
588
+ } else if (CODEX_QUICKWIN_DOC_KEYS.has(item.key)) {
589
+ score += 26;
590
+ } else if (CODEX_QUICKWIN_POLICY_KEYS.has(item.key)) {
591
+ score += 20;
592
+ }
593
+
594
+ score += item.impact === 'low' ? 8 : item.impact === 'medium' ? 6 : item.impact === 'high' ? 4 : 0;
595
+ score -= Math.min((item.fix || '').length, 240) / 24;
596
+ return score;
597
+ }
598
+
599
+ function getQuickWins(failed, options = {}) {
600
+ const pool = getPrioritizedFailed(failed);
601
+
602
+ if (options.platform === 'codex') {
603
+ const codexPool = pool.filter((item) => !CODEX_QUICKWIN_AVOID_KEYS.has(item.key));
604
+ const rankedPool = (codexPool.length > 0 ? codexPool : pool)
605
+ .slice()
606
+ .sort((a, b) => codexQuickWinScore(b) - codexQuickWinScore(a));
607
+ return rankedPool.slice(0, 3);
608
+ }
609
+
610
+ // QuickWins prioritize short fixes (easy to implement) first, then impact
611
+ return [...pool]
612
+ .sort((a, b) => {
613
+ const fixLenA = (a.fix || '').length;
614
+ const fixLenB = (b.fix || '').length;
615
+ if (fixLenA !== fixLenB) return fixLenA - fixLenB;
616
+ const impactA = IMPACT_ORDER[a.impact] ?? 0;
617
+ const impactB = IMPACT_ORDER[b.impact] ?? 0;
618
+ return impactB - impactA;
619
+ })
620
+ .slice(0, 3);
621
+ }
622
+
623
+ /**
624
+ * Compute a multiplier based on FP (helpful/not-helpful) feedback for a check key.
625
+ * - >50% "not helpful" feedback: lower priority by 30% (multiplier 0.7)
626
+ * - >80% "helpful" feedback: boost priority by 20% (multiplier 1.2)
627
+ * - Otherwise: no change (multiplier 1.0)
628
+ * @param {Object} fpFeedbackByKey - Keyed feedback summary from getFeedbackSummary().byKey
629
+ * @param {string} key - The check key to look up
630
+ * @returns {number} Multiplier to apply to priority score
631
+ */
632
+ function getFpFeedbackMultiplier(fpFeedbackByKey, key) {
633
+ if (!fpFeedbackByKey) return 1.0;
634
+ const bucket = fpFeedbackByKey[key];
635
+ if (!bucket || bucket.total === 0) return 1.0;
636
+
637
+ const unhelpfulRate = bucket.unhelpful / bucket.total;
638
+ const helpfulRate = bucket.helpful / bucket.total;
639
+
640
+ if (unhelpfulRate > 0.5) return 0.7;
641
+ if (helpfulRate > 0.8) return 1.2;
642
+ return 1.0;
643
+ }
644
+
645
+ function getRecommendationPriorityScore(item, outcomeSummaryByKey = {}, fpFeedbackByKey = null) {
646
+ const impactScore = (IMPACT_ORDER[item.impact] ?? 0) * 100;
647
+ const feedbackAdjustment = getRecommendationAdjustment(outcomeSummaryByKey, item.key);
648
+ const brevityPenalty = Math.min((item.fix || '').length, 240) / 20;
649
+ const raw = impactScore + (feedbackAdjustment * 10) - brevityPenalty;
650
+ return raw * getFpFeedbackMultiplier(fpFeedbackByKey, item.key);
651
+ }
652
+
653
+ function buildTopNextActions(failed, limit = 5, outcomeSummaryByKey = {}, options = {}) {
654
+ const pool = getPrioritizedFailed(failed);
655
+ const fpByKey = options.fpFeedbackByKey || null;
656
+
657
+ return [...pool]
658
+ .sort((a, b) => {
659
+ const scoreB = options.platform === 'codex'
660
+ ? codexPriorityScore(b, outcomeSummaryByKey)
661
+ : getRecommendationPriorityScore(b, outcomeSummaryByKey, fpByKey);
662
+ const scoreA = options.platform === 'codex'
663
+ ? codexPriorityScore(a, outcomeSummaryByKey)
664
+ : getRecommendationPriorityScore(a, outcomeSummaryByKey, fpByKey);
665
+ return scoreB - scoreA;
666
+ })
667
+ .slice(0, limit)
668
+ .map(({ key, id, name, impact, fix, category, sourceUrl }) => {
669
+ const feedback = outcomeSummaryByKey[key] || null;
670
+ const rankingAdjustment = getRecommendationAdjustment(outcomeSummaryByKey, key);
671
+ const signals = [
672
+ `failed-check:${key}`,
673
+ `impact:${impact}`,
674
+ `category:${category}`,
675
+ ];
676
+ if (feedback) {
677
+ signals.push(`feedback:${feedback.total}`);
678
+ signals.push(`ranking-adjustment:${rankingAdjustment >= 0 ? '+' : ''}${rankingAdjustment}`);
679
+ }
680
+
681
+ const fullItem = pool.find((item) => item.key === key) || { key, id, name, impact, fix, category };
682
+ const evidenceClass = options.platform === 'codex' ? codexEvidenceClass(fullItem) : (feedback ? 'measured' : 'estimated');
683
+ const priorityScore = options.platform === 'codex'
684
+ ? codexPriorityScore(fullItem, outcomeSummaryByKey)
685
+ : Math.max(0, Math.min(100, Math.round(getRecommendationPriorityScore(fullItem, outcomeSummaryByKey, fpByKey) / 3)));
686
+
687
+ signals.push(`evidence:${evidenceClass}`);
688
+ if (options.platform === 'codex' && CODEX_HARD_FAIL_KEYS.has(key)) {
689
+ signals.push('hard-fail:true');
690
+ }
691
+
692
+ return ({
693
+ key,
694
+ id,
695
+ name,
696
+ impact,
697
+ category,
698
+ sourceUrl,
699
+ module: CATEGORY_MODULES[category] || category,
700
+ fix,
701
+ priorityScore,
702
+ why: ACTION_RATIONALES[key] || fix,
703
+ risk: riskFromImpact(impact),
704
+ confidence: confidenceFromImpact(impact),
705
+ signals,
706
+ evidenceClass,
707
+ rankingAdjustment,
708
+ feedback: feedback ? {
709
+ total: feedback.total,
710
+ accepted: feedback.accepted,
711
+ rejected: feedback.rejected,
712
+ deferred: feedback.deferred,
713
+ positive: feedback.positive,
714
+ negative: feedback.negative,
715
+ avgScoreDelta: feedback.avgScoreDelta,
716
+ } : null,
717
+ });
718
+ });
719
+ }
720
+
721
+ function computeCategoryScores(applicable, passed) {
722
+ const grouped = {};
723
+
724
+ for (const item of applicable) {
725
+ const category = item.category || 'unknown';
726
+ if (!grouped[category]) {
727
+ grouped[category] = { passed: 0, total: 0, earnedPoints: 0, maxPoints: 0 };
728
+ }
729
+ grouped[category].total += 1;
730
+ grouped[category].maxPoints += WEIGHTS[item.impact] || 5;
731
+ }
732
+
733
+ for (const item of passed) {
734
+ const category = item.category || 'unknown';
735
+ if (!grouped[category]) continue;
736
+ grouped[category].passed += 1;
737
+ grouped[category].earnedPoints += WEIGHTS[item.impact] || 5;
738
+ }
739
+
740
+ const result = {};
741
+ for (const [category, summary] of Object.entries(grouped)) {
742
+ result[category] = {
743
+ ...summary,
744
+ score: summary.maxPoints > 0 ? Math.round((summary.earnedPoints / summary.maxPoints) * 100) : 0,
745
+ };
746
+ }
747
+
748
+ return result;
749
+ }
750
+
751
+ function inferSuggestedNextCommand(result) {
752
+ if (result.platform === 'codex') {
753
+ if (result.failed === 0) {
754
+ return 'npx nerviq --platform codex augment';
755
+ }
756
+
757
+ const actionKeys = new Set((result.topNextActions || []).map(item => item.key));
758
+ if (
759
+ result.score < 50 ||
760
+ actionKeys.has('codexAgentsMd') ||
761
+ actionKeys.has('codexConfigExists') ||
762
+ actionKeys.has('codexNoDangerFullAccess') ||
763
+ actionKeys.has('codexApprovalPolicyExplicit')
764
+ ) {
765
+ return 'npx nerviq --platform codex suggest-only';
766
+ }
767
+
768
+ return 'npx nerviq --platform codex augment';
769
+ }
770
+
771
+ const actionKeys = new Set((result.topNextActions || []).map(item => item.key));
772
+ const platFlag = result.platform && result.platform !== 'claude' ? ` --platform ${result.platform}` : '';
773
+
774
+ if (result.failed === 0) {
775
+ return `npx nerviq${platFlag} augment`;
776
+ }
777
+
778
+ if (
779
+ result.score < 50 ||
780
+ actionKeys.has('claudeMd') ||
781
+ actionKeys.has('hooks') ||
782
+ actionKeys.has('settingsPermissions') ||
783
+ actionKeys.has('permissionDeny')
784
+ ) {
785
+ return `npx nerviq${platFlag} setup`;
786
+ }
787
+
788
+ if (result.score < 80) {
789
+ return `npx nerviq${platFlag} suggest-only`;
790
+ }
791
+
792
+ return `npx nerviq${platFlag} augment`;
793
+ }
794
+
795
+ function getPlatformScopeNote(spec, ctx) {
796
+ if (spec.platform !== 'codex') {
797
+ return null;
798
+ }
799
+
800
+ const hasClaudeSurface = Boolean(
801
+ (typeof ctx.fileContent === 'function' && ctx.fileContent('CLAUDE.md')) ||
802
+ (typeof ctx.hasDir === 'function' && ctx.hasDir('.claude'))
803
+ );
804
+
805
+ if (!hasClaudeSurface) {
806
+ return null;
807
+ }
808
+
809
+ return {
810
+ kind: 'codex-only-pass',
811
+ message: 'This is a Codex-only pass. Claude Code surfaces were also detected and should be audited separately with `npx nerviq`.',
812
+ };
813
+ }
814
+
815
+ function getPlatformCaveats(spec, ctx) {
816
+ if (spec.platform !== 'codex') {
817
+ return [];
818
+ }
819
+
820
+ const caveats = [];
821
+ const hooksJson = typeof ctx.hooksJsonContent === 'function' ? (ctx.hooksJsonContent() || '') : '';
822
+ const agentsContent = typeof ctx.agentsMdContent === 'function' ? (ctx.agentsMdContent() || '') : '';
823
+ const hooksClaimed = Boolean(
824
+ hooksJson ||
825
+ (typeof ctx.hasDir === 'function' && ctx.hasDir('.codex/hooks')) ||
826
+ /\bhooks?\b|\bSessionStart\b|\bPreToolUse\b|\bPostToolUse\b|\bUserPromptSubmit\b|\bStop\b/i.test(agentsContent)
827
+ );
828
+
829
+ if (process.platform === 'win32') {
830
+ caveats.push({
831
+ key: 'codex-windows-hooks',
832
+ severity: hooksClaimed ? 'critical' : 'info',
833
+ title: 'Codex hooks are not available on Windows',
834
+ message: hooksClaimed
835
+ ? 'This repo claims Codex hooks, but native Windows sessions do not execute them. Keep enforcement in rules, CI, or another documented fallback.'
836
+ : 'Native Windows sessions do not execute Codex hooks. If you add hooks later, treat them as non-enforcing on Windows and keep critical enforcement in rules or CI.',
837
+ file: hooksJson ? '.codex/hooks.json' : null,
838
+ line: hooksJson ? 1 : null,
839
+ });
840
+ }
841
+
842
+ const maxThreads = typeof ctx.configValue === 'function' ? ctx.configValue('agents.max_threads') : undefined;
843
+ caveats.push({
844
+ key: 'codex-max-threads-default',
845
+ severity: typeof maxThreads === 'number' && maxThreads > 6 ? 'warning' : 'info',
846
+ title: 'Codex agent thread concurrency defaults to 6 when unset',
847
+ message: typeof maxThreads === 'number'
848
+ ? `This repo sets agents.max_threads = ${maxThreads}. Codex defaults to 6 when unset, so any higher concurrency assumption should be validated in the runtime you actually use.`
849
+ : 'Codex defaults agents.max_threads to 6 when unset. If your workflow depends on heavy parallel subagent usage, set it intentionally and validate the behavior in your real runtime.',
850
+ file: typeof ctx.fileContent === 'function' && ctx.fileContent('.codex/config.toml') ? '.codex/config.toml' : null,
851
+ line: typeof ctx.lineNumber === 'function' ? (ctx.lineNumber('.codex/config.toml', /\bagents\.max_threads\b|\bmax_threads\b/i) || null) : null,
852
+ });
853
+
854
+ return caveats;
855
+ }
856
+
857
+ function getCodexDomainPackSignals(ctx) {
858
+ return {
859
+ instructionPath: typeof ctx.agentsMdPath === 'function' ? ctx.agentsMdPath() : null,
860
+ trust: {
861
+ approvalPolicy: typeof ctx.configValue === 'function' ? (ctx.configValue('approval_policy') || null) : null,
862
+ sandboxMode: typeof ctx.configValue === 'function' ? (ctx.configValue('sandbox_mode') || null) : null,
863
+ isTrustedProject: typeof ctx.isProjectTrusted === 'function' ? ctx.isProjectTrusted() : false,
864
+ },
865
+ counts: {
866
+ rules: typeof ctx.ruleFiles === 'function' ? ctx.ruleFiles().length : 0,
867
+ workflows: typeof ctx.workflowFiles === 'function' ? ctx.workflowFiles().length : 0,
868
+ mcpServers: typeof ctx.mcpServers === 'function' ? Object.keys(ctx.mcpServers() || {}).length : 0,
869
+ },
870
+ };
871
+ }
872
+
873
+ function printLiteAudit(result, dir) {
874
+ console.log('');
875
+ const productLabel = result.platform === 'codex' ? 'nerviq codex quick scan' : 'nerviq quick scan';
876
+ console.log(colorize(` ${productLabel}`, 'bold'));
877
+ console.log(colorize(' ═══════════════════════════════════════', 'dim'));
878
+ console.log(colorize(` Scanning: ${dir}`, 'dim'));
879
+ console.log('');
880
+ if (result.detectedConfigFiles && result.detectedConfigFiles.length > 0) {
881
+ console.log(colorize(` Found: ${result.detectedConfigFiles.join(', ')}`, 'dim'));
882
+ }
883
+ console.log('');
884
+ console.log(` Score: ${colorize(`${result.score}/100`, 'bold')} (${result.passed}/${result.passed + result.failed} checks passing)`);
885
+
886
+ // Score explanation line (lite mode only)
887
+ const _critCount = (result.results || []).filter(r => r.passed === false && r.impact === 'critical').length;
888
+ const _highCount = (result.results || []).filter(r => r.passed === false && r.impact === 'high').length;
889
+ let scoreExplanation;
890
+ if (result.score >= 90) {
891
+ scoreExplanation = 'Excellent setup — production-ready governance';
892
+ } else if (result.score >= 70) {
893
+ scoreExplanation = `Strong setup — ${_critCount} critical items to address`;
894
+ } else if (result.score >= 50) {
895
+ scoreExplanation = `Good foundation — ${_critCount + _highCount} items need attention`;
896
+ } else if (result.score >= 30) {
897
+ // Find weakest category (most failures)
898
+ const catFailures = {};
899
+ (result.results || []).filter(r => r.passed === false).forEach(r => {
900
+ const cat = r.category || 'unknown';
901
+ catFailures[cat] = (catFailures[cat] || 0) + 1;
902
+ });
903
+ const weakestCategory = Object.keys(catFailures).sort((a, b) => catFailures[b] - catFailures[a])[0] || 'config';
904
+ scoreExplanation = `Basic setup — significant gaps in ${weakestCategory}`;
905
+ } else {
906
+ scoreExplanation = 'Early stage — run `nerviq setup` to bootstrap your config';
907
+ }
908
+ console.log(colorize(` ${scoreExplanation}`, 'dim'));
909
+
910
+ if (result.platformScopeNote) {
911
+ console.log(colorize(` Scope: ${result.platformScopeNote.message}`, 'dim'));
912
+ }
913
+ if (result.workspaceHint && result.workspaceHint.workspaces.length > 0) {
914
+ console.log(colorize(` Workspaces: ${result.workspaceHint.workspaces.join(', ')}`, 'dim'));
915
+ }
916
+ if (result.platformCaveats && result.platformCaveats.length > 0) {
917
+ console.log(colorize(' Platform caveats:', 'yellow'));
918
+ result.platformCaveats.slice(0, 2).forEach((item) => {
919
+ console.log(colorize(` - ${item.title}: ${item.message}`, 'dim'));
920
+ });
921
+ }
922
+ if (result.largeInstructionFiles && result.largeInstructionFiles.length > 0) {
923
+ result.largeInstructionFiles.slice(0, 2).forEach((item) => {
924
+ console.log(colorize(` Large file: ${item.file} (${Math.round(item.byteCount / 1024)}KB)`, 'yellow'));
925
+ });
926
+ }
927
+ console.log('');
928
+
929
+ if (result.failed === 0) {
930
+ const platformLabel = result.platform === 'codex' ? 'Codex' : 'Claude';
931
+ console.log(colorize(` Your ${platformLabel} setup looks solid.`, 'green'));
932
+ console.log(` Next: ${colorize(result.suggestedNextCommand, 'bold')}`);
933
+ if (result.platform === 'codex') {
934
+ console.log(colorize(' Note: Codex now supports no-write advisory flows via augment and suggest-only before setup/apply.', 'dim'));
935
+ }
936
+ console.log(colorize(' Star: github.com/nerviq/nerviq | Discord: discord.gg/nerviq', 'dim'));
937
+ console.log('');
938
+ return;
939
+ }
940
+
941
+ // Urgency summary line (only count actual failures, not skipped/null)
942
+ const criticalCount = (result.results || []).filter(r => r.passed === false && r.impact === 'critical').length;
943
+ const highCount = (result.results || []).filter(r => r.passed === false && r.impact === 'high').length;
944
+ const mediumCount = result.failed - criticalCount - highCount;
945
+ const urgencyParts = [];
946
+ if (criticalCount > 0) urgencyParts.push(colorize(`🔴 ${criticalCount} critical`, 'red'));
947
+ if (highCount > 0) urgencyParts.push(colorize(`🟡 ${highCount} high`, 'yellow'));
948
+ if (mediumCount > 0) urgencyParts.push(colorize(`🔵 ${mediumCount} recommended`, 'blue'));
949
+ if (urgencyParts.length > 0) {
950
+ console.log(` ${urgencyParts.join(' ')}`);
951
+ console.log('');
952
+ }
953
+
954
+ console.log(colorize(' Top 3 things to fix right now:', 'magenta'));
955
+ console.log('');
956
+ let usagePatterns;
957
+ try { usagePatterns = require('./usage-patterns'); } catch { usagePatterns = null; }
958
+ result.liteSummary.topNextActions.forEach((item, index) => {
959
+ const tier = item.impact === 'critical' ? '🔴' : item.impact === 'high' ? '🟡' : '🔵';
960
+ const suppressed = usagePatterns && usagePatterns.getPriorityAdjustment(dir, item.key) === 'suppress';
961
+ const suffix = suppressed ? colorize(' (suppressed)', 'dim') : '';
962
+ console.log(` ${index + 1}. ${tier} ${colorize(item.name, 'bold')}${suffix}`);
963
+ console.log(colorize(` ${item.fix}`, 'dim'));
964
+ });
965
+ console.log('');
966
+ console.log(` Ready? Run: ${colorize(result.suggestedNextCommand, 'bold')}`);
967
+ if (result.platform === 'codex') {
968
+ console.log(colorize(' Note: Codex now supports no-write advisory flows via augment and suggest-only before setup/apply.', 'dim'));
969
+ }
970
+ console.log(colorize(` See all ${result.failed} failed checks: ${colorize('nerviq audit --full', 'bold')}`, 'dim'));
971
+ console.log(colorize(' Star: github.com/nerviq/nerviq | Discord: discord.gg/nerviq', 'dim'));
972
+ console.log('');
973
+ }
974
+
975
+ /**
976
+ * Run a full audit of a project's Claude Code setup against the NERVIQ technique database.
977
+ * @param {Object} options - Audit options.
978
+ * @param {string} options.dir - Project directory to audit.
979
+ * @param {boolean} [options.silent] - Skip all console output, return result only.
980
+ * @param {boolean} [options.json] - Output result as JSON.
981
+ * @param {boolean} [options.lite] - Show short top-3 quick scan.
982
+ * @param {boolean} [options.verbose] - Show all recommendations including medium-impact.
983
+ * @param {boolean} [options.showDeprecated] - Include deprecated checks in output.
984
+ * @returns {Promise<Object>} Audit result with score, passed/failed counts, quickWins, and topNextActions.
985
+ */
986
+ async function audit(options) {
987
+ const spec = getAuditSpec(options.platform || 'claude');
988
+ const silent = options.silent || false;
989
+ const ctx = new spec.ContextClass(options.dir);
990
+ const largeInstructionFiles = inspectInstructionFiles(spec, ctx);
991
+ guardSkippedInstructionFiles(ctx, largeInstructionFiles);
992
+ const stacks = ctx.detectStacks(STACKS);
993
+ const results = [];
994
+ const outcomeSummary = getRecommendationOutcomeSummary(options.dir);
995
+ const fpFeedback = getFeedbackSummary(options.dir);
996
+ const workspaceHint = buildWorkspaceHint(options.dir);
997
+
998
+ // Load and merge plugin checks
999
+ const plugins = loadPlugins(options.dir);
1000
+ const techniques = plugins.length > 0
1001
+ ? mergePluginChecks(spec.techniques, plugins)
1002
+ : spec.techniques;
1003
+
1004
+ // Pre-compute which stack categories are active for this project
1005
+ const activeStackCategories = new Set();
1006
+ for (const [category, detector] of Object.entries(STACK_CATEGORY_DETECTORS)) {
1007
+ if (detector(ctx)) activeStackCategories.add(category);
1008
+ }
1009
+
1010
+ // Generic quality categories that are NOT about AI agent configuration.
1011
+ // These are only included with --verbose or --full --verbose (deep quality mode).
1012
+ const GENERIC_QUALITY_CATEGORIES = new Set([
1013
+ 'observability', 'accessibility', 'i18n', 'privacy', 'error-tracking',
1014
+ 'supply-chain', 'api-versioning', 'caching', 'rate-limiting', 'feature-flags',
1015
+ 'docs-quality', 'monorepo', 'performance-budget', 'realtime', 'graphql',
1016
+ 'testing-strategy', 'code-quality', 'api-design', 'database', 'authentication',
1017
+ 'monitoring', 'dependency-management', 'cost-optimization',
1018
+ ]);
1019
+ const includeGenericQuality = options.verbose;
1020
+
1021
+ // Run all technique checks
1022
+ for (const [key, technique] of Object.entries(techniques)) {
1023
+ // Skip entire stack category if the stack is not detected at a core location
1024
+ // Skip generic quality categories unless --verbose is set
1025
+ const cat = technique.category;
1026
+ if ((!includeGenericQuality && GENERIC_QUALITY_CATEGORIES.has(cat)) ||
1027
+ (STACK_CATEGORY_DETECTORS[cat] && !activeStackCategories.has(cat))) {
1028
+ results.push({
1029
+ key,
1030
+ ...technique,
1031
+ file: null,
1032
+ line: null,
1033
+ passed: null, // not applicable
1034
+ });
1035
+ continue;
1036
+ }
1037
+
1038
+ const passed = technique.check(ctx);
1039
+ const file = typeof technique.file === 'function' ? (technique.file(ctx) ?? null) : (technique.file ?? null);
1040
+ const line = typeof technique.line === 'function' ? (technique.line(ctx) ?? null) : (technique.line ?? null);
1041
+ results.push({
1042
+ key,
1043
+ ...technique,
1044
+ file,
1045
+ line: Number.isFinite(line) ? line : null,
1046
+ passed,
1047
+ });
1048
+ }
1049
+
1050
+ if (largeInstructionFiles.length > 0) {
1051
+ results.push({
1052
+ key: 'largeInstructionFile',
1053
+ id: null,
1054
+ name: 'Large instruction file warning',
1055
+ category: 'performance',
1056
+ impact: 'medium',
1057
+ rating: null,
1058
+ fix: 'Split oversized instruction files so they stay under 50KB, and keep any single instruction file below 1MB.',
1059
+ sourceUrl: null,
1060
+ confidence: 'high',
1061
+ file: largeInstructionFiles[0].file,
1062
+ line: null,
1063
+ passed: null,
1064
+ details: largeInstructionFiles,
1065
+ });
1066
+ }
1067
+
1068
+ // Separate deprecated checks from active checks.
1069
+ // Deprecated checks are excluded from scoring but preserved for display.
1070
+ const deprecated = results.filter(r => r.deprecated === true);
1071
+ const activeResults = results.filter(r => r.deprecated !== true);
1072
+
1073
+ // null = not applicable (skip), true = pass, false = fail
1074
+ const applicable = activeResults.filter(r => r.passed !== null);
1075
+ const skipped = activeResults.filter(r => r.passed === null);
1076
+ const passed = applicable.filter(r => r.passed);
1077
+ const failed = applicable.filter(r => !r.passed);
1078
+ const critical = failed.filter(r => r.impact === 'critical');
1079
+ const high = failed.filter(r => r.impact === 'high');
1080
+ const medium = failed.filter(r => r.impact === 'medium');
1081
+
1082
+ // Calculate score only from applicable checks
1083
+ const maxScore = applicable.reduce((sum, r) => sum + (WEIGHTS[r.impact] || 5), 0);
1084
+ const earnedScore = passed.reduce((sum, r) => sum + (WEIGHTS[r.impact] || 5), 0);
1085
+ const score = maxScore > 0 ? Math.round((earnedScore / maxScore) * 100) : 0;
1086
+
1087
+ // Detect scaffolded vs organic: if CLAUDE.md contains our version stamp, some checks
1088
+ // are passing because WE generated them, not the user
1089
+ const instructionSource = spec.platform === 'codex'
1090
+ ? (ctx.agentsMdContent ? (ctx.agentsMdContent() || '') : '')
1091
+ : (ctx.claudeMdContent() || '');
1092
+ const isScaffolded = instructionSource.includes('Generated by nerviq') ||
1093
+ instructionSource.includes('nerviq');
1094
+ // Scaffolded checks: things our setup creates (CLAUDE.md / AGENTS.md, hooks, commands, agents, rules, skills)
1095
+ const scaffoldedKeys = spec.platform === 'codex'
1096
+ ? new Set([
1097
+ 'codexAgentsMd',
1098
+ 'codexAgentsMdSubstantive',
1099
+ 'codexAgentsVerificationCommands',
1100
+ 'codexAgentsArchitecture',
1101
+ 'codexConfigExists',
1102
+ 'codexModelExplicit',
1103
+ 'codexReasoningEffortExplicit',
1104
+ 'codexWeakModelExplicit',
1105
+ 'codexSandboxModeExplicit',
1106
+ 'codexApprovalPolicyExplicit',
1107
+ 'codexFullAutoErrorModeExplicit',
1108
+ 'codexHistorySendToServerExplicit',
1109
+ ])
1110
+ : new Set(['claudeMd', 'mermaidArchitecture', 'verificationLoop',
1111
+ 'hooks', 'customCommands', 'multipleCommands', 'agents', 'pathRules', 'multipleRules',
1112
+ 'skills', 'hooksConfigured', 'preToolUseHook', 'postToolUseHook', 'fewShotExamples',
1113
+ 'constraintBlocks', 'xmlTags']);
1114
+ const organicPassed = passed.filter(r => !scaffoldedKeys.has(r.key));
1115
+ const scaffoldedPassed = passed.filter(r => scaffoldedKeys.has(r.key));
1116
+ const organicEarned = organicPassed.reduce((sum, r) => sum + (WEIGHTS[r.impact] || 5), 0);
1117
+ const organicScore = maxScore > 0 ? Math.round((organicEarned / maxScore) * 100) : 0;
1118
+ const quickWins = getQuickWins(failed, { platform: spec.platform });
1119
+ const topNextActions = buildTopNextActions(failed, 5, outcomeSummary.byKey, { platform: spec.platform, fpFeedbackByKey: fpFeedback.byKey });
1120
+ const categoryScores = computeCategoryScores(applicable, passed);
1121
+ const platformScopeNote = getPlatformScopeNote(spec, ctx);
1122
+ const platformCaveats = getPlatformCaveats(spec, ctx);
1123
+ const deprecationWarnings = detectDeprecationWarnings(failed, packageVersion);
1124
+ const warnings = [
1125
+ ...largeInstructionFiles.map((item) => ({
1126
+ kind: 'large-instruction-file',
1127
+ severity: item.severity,
1128
+ message: item.message,
1129
+ file: item.file,
1130
+ lineCount: item.lineCount,
1131
+ byteCount: item.byteCount,
1132
+ skipped: item.skipped,
1133
+ })),
1134
+ ...deprecationWarnings.map((item) => ({
1135
+ kind: 'deprecated-feature',
1136
+ severity: 'warning',
1137
+ ...item,
1138
+ })),
1139
+ ];
1140
+ const recommendedDomainPacks = spec.platform === 'codex'
1141
+ ? detectCodexDomainPacks(ctx, stacks, getCodexDomainPackSignals(ctx))
1142
+ : [];
1143
+ const result = {
1144
+ platform: spec.platform,
1145
+ platformLabel: spec.platformLabel,
1146
+ platformVersion: spec.platformVersion,
1147
+ score,
1148
+ organicScore,
1149
+ earnedPoints: earnedScore,
1150
+ maxPoints: maxScore,
1151
+ isScaffolded,
1152
+ passed: passed.length,
1153
+ failed: failed.length,
1154
+ skipped: skipped.length,
1155
+ deprecated: deprecated.length,
1156
+ checkCount: applicable.length,
1157
+ stacks,
1158
+ results,
1159
+ deprecatedChecks: deprecated.map(r => ({
1160
+ key: r.key,
1161
+ name: r.name,
1162
+ category: r.category,
1163
+ deprecatedReason: r.deprecatedReason || null,
1164
+ sunsetDate: r.sunsetDate || null,
1165
+ })),
1166
+ categoryScores,
1167
+ quickWins: quickWins.map(({ key, name, impact, fix, category, sourceUrl }) => ({ key, name, impact, category, fix, sourceUrl })),
1168
+ topNextActions,
1169
+ recommendationOutcomes: {
1170
+ totalEntries: outcomeSummary.totalEntries,
1171
+ keysTracked: outcomeSummary.keys,
1172
+ },
1173
+ largeInstructionFiles,
1174
+ deprecationWarnings,
1175
+ warnings,
1176
+ workspaceHint,
1177
+ platformScopeNote,
1178
+ platformCaveats,
1179
+ recommendedDomainPacks,
1180
+ };
1181
+ // Detect which AI config files are present
1182
+ const configFiles = [];
1183
+ const configChecks = [
1184
+ ['CLAUDE.md', 'CLAUDE.md'], ['.claude/settings.json', '.claude/settings.json'],
1185
+ ['AGENTS.md', 'AGENTS.md'], ['.cursorrules', '.cursorrules'],
1186
+ ['.cursor/rules', '.cursor/rules/'], ['GEMINI.md', 'GEMINI.md'],
1187
+ ['.windsurfrules', '.windsurfrules'], ['.aider.conf.yml', '.aider.conf.yml'],
1188
+ ['opencode.json', 'opencode.json'], ['.mcp.json', '.mcp.json'],
1189
+ ];
1190
+ for (const [file, label] of configChecks) {
1191
+ try {
1192
+ if (require('fs').existsSync(require('path').join(options.dir, file))) configFiles.push(label);
1193
+ } catch {}
1194
+ }
1195
+ result.detectedConfigFiles = configFiles;
1196
+
1197
+ result.suggestedNextCommand = inferSuggestedNextCommand(result);
1198
+ result.liteSummary = {
1199
+ topNextActions: topNextActions.slice(0, 3),
1200
+ nextCommand: result.suggestedNextCommand,
1201
+ platformCaveats: platformCaveats.slice(0, 2),
1202
+ };
1203
+
1204
+ // Silent mode: skip all output, just return result
1205
+ if (silent) {
1206
+ return result;
1207
+ }
1208
+
1209
+ if (options.json) {
1210
+ console.log(JSON.stringify({
1211
+ version: packageVersion,
1212
+ timestamp: new Date().toISOString(),
1213
+ ...result
1214
+ }, null, 2));
1215
+ return result;
1216
+ }
1217
+
1218
+ if (options.format === 'sarif') {
1219
+ console.log(JSON.stringify(formatSarif(result, { dir: options.dir }), null, 2));
1220
+ return result;
1221
+ }
1222
+
1223
+ if (options.format === 'otel') {
1224
+ console.log(JSON.stringify(formatOtelMetrics(result), null, 2));
1225
+ return result;
1226
+ }
1227
+
1228
+ if (options.lite) {
1229
+ printLiteAudit(result, options.dir);
1230
+ sendInsights(result);
1231
+ return result;
1232
+ }
1233
+
1234
+ // Display results
1235
+ console.log('');
1236
+ const auditTitle = spec.platform === 'codex' ? 'nerviq codex audit' : 'nerviq audit';
1237
+ console.log(colorize(` ${auditTitle}`, 'bold'));
1238
+ console.log(colorize(' ═══════════════════════════════════════', 'dim'));
1239
+ console.log(colorize(` Scanning: ${options.dir}`, 'dim'));
1240
+ if (spec.platformVersion) {
1241
+ console.log(colorize(` Platform: ${spec.platformLabel} (${spec.platformVersion})`, 'blue'));
1242
+ }
1243
+ if (spec.platform === 'codex' && recommendedDomainPacks.length > 0) {
1244
+ console.log(colorize(` Domain packs: ${recommendedDomainPacks.map((pack) => pack.label).join(', ')}`, 'dim'));
1245
+ }
1246
+ if (platformScopeNote) {
1247
+ console.log(colorize(` Scope: ${platformScopeNote.message}`, 'dim'));
1248
+ }
1249
+ if (platformCaveats.length > 0) {
1250
+ console.log(colorize(' Platform caveats', 'yellow'));
1251
+ for (const caveat of platformCaveats) {
1252
+ console.log(colorize(` ${caveat.title}`, 'bold'));
1253
+ console.log(colorize(` → ${caveat.message}`, 'dim'));
1254
+ if (caveat.file) {
1255
+ console.log(colorize(` at ${formatLocation(caveat.file, caveat.line)}`, 'dim'));
1256
+ }
1257
+ }
1258
+ console.log('');
1259
+ }
1260
+
1261
+ if (largeInstructionFiles.length > 0) {
1262
+ console.log(colorize(' Large instruction files', 'yellow'));
1263
+ for (const item of largeInstructionFiles) {
1264
+ const sizeKb = Math.round(item.byteCount / 1024);
1265
+ console.log(colorize(` ${item.file} (${sizeKb}KB, ${item.lineCount || '?'} lines)`, 'bold'));
1266
+ console.log(colorize(` → ${item.message}`, 'dim'));
1267
+ }
1268
+ console.log('');
1269
+ }
1270
+
1271
+ if (deprecationWarnings.length > 0) {
1272
+ console.log(colorize(' Deprecated feature warnings', 'yellow'));
1273
+ for (const item of deprecationWarnings) {
1274
+ console.log(colorize(` ${item.feature}`, 'bold'));
1275
+ console.log(colorize(` → ${item.message}`, 'dim'));
1276
+ console.log(colorize(` Alternative: ${item.alternative}`, 'dim'));
1277
+ }
1278
+ console.log('');
1279
+ }
1280
+
1281
+ if (workspaceHint && !options.workspace) {
1282
+ console.log(colorize(' Monorepo detected', 'blue'));
1283
+ if (workspaceHint.workspaces.length > 0) {
1284
+ console.log(colorize(` Workspaces: ${workspaceHint.workspaces.join(', ')}`, 'dim'));
1285
+ }
1286
+ console.log(colorize(` Tip: ${workspaceHint.suggestedCommand}`, 'dim'));
1287
+ console.log('');
1288
+ }
1289
+
1290
+ if (stacks.length > 0) {
1291
+ console.log(colorize(` Detected: ${stacks.map(s => s.label).join(', ')}`, 'blue'));
1292
+ }
1293
+
1294
+ console.log('');
1295
+
1296
+ // Score
1297
+ console.log(` ${progressBar(score)} ${colorize(`${score}/100`, 'bold')}`);
1298
+ if (isScaffolded && scaffoldedPassed.length > 0) {
1299
+ console.log(colorize(` Organic: ${organicScore}/100 (without nerviq generated files)`, 'dim'));
1300
+ }
1301
+ console.log('');
1302
+
1303
+ // Passed
1304
+ if (passed.length > 0) {
1305
+ console.log(colorize(' ✅ Passing', 'green'));
1306
+ for (const r of passed) {
1307
+ console.log(colorize(` ${r.name}`, 'dim'));
1308
+ }
1309
+ console.log('');
1310
+ }
1311
+
1312
+ // Deprecated checks (shown with --show-deprecated or --full)
1313
+ if (deprecated.length > 0 && (options.showDeprecated || options.full)) {
1314
+ console.log(colorize(` ⏳ Deprecated (${deprecated.length} checks excluded from scoring)`, 'dim'));
1315
+ for (const r of deprecated) {
1316
+ const reason = r.deprecatedReason ? ` — ${r.deprecatedReason}` : '';
1317
+ const sunset = r.sunsetDate ? ` (sunset: ${r.sunsetDate})` : '';
1318
+ console.log(colorize(` [DEPRECATED] ${r.name}${reason}${sunset}`, 'dim'));
1319
+ }
1320
+ console.log('');
1321
+ }
1322
+
1323
+ // Failed - by priority
1324
+ if (critical.length > 0) {
1325
+ console.log(colorize(' 🔴 Critical (fix immediately)', 'red'));
1326
+ for (const r of critical) {
1327
+ const conf = r.confidence ? ` [${confidenceLabel(r.confidence)}]` : '';
1328
+ console.log(` ${colorize(r.name, 'bold')}${colorize(conf, 'dim')}`);
1329
+ if (r.file) {
1330
+ console.log(colorize(` at ${formatLocation(r.file, r.line)}`, 'dim'));
1331
+ }
1332
+ console.log(colorize(` → ${r.fix}`, 'dim'));
1333
+ }
1334
+ console.log('');
1335
+ }
1336
+
1337
+ if (high.length > 0) {
1338
+ console.log(colorize(' 🟡 High Impact', 'yellow'));
1339
+ for (const r of high) {
1340
+ const conf = r.confidence ? ` [${confidenceLabel(r.confidence)}]` : '';
1341
+ console.log(` ${colorize(r.name, 'bold')}${colorize(conf, 'dim')}`);
1342
+ if (r.file) {
1343
+ console.log(colorize(` at ${formatLocation(r.file, r.line)}`, 'dim'));
1344
+ }
1345
+ console.log(colorize(` → ${r.fix}`, 'dim'));
1346
+ }
1347
+ console.log('');
1348
+ }
1349
+
1350
+ if (medium.length > 0 && options.verbose) {
1351
+ console.log(colorize(' 🔵 Recommended', 'blue'));
1352
+ for (const r of medium) {
1353
+ const conf = r.confidence ? ` [${confidenceLabel(r.confidence)}]` : '';
1354
+ console.log(` ${colorize(r.name, 'bold')}${colorize(conf, 'dim')}`);
1355
+ if (r.file) {
1356
+ console.log(colorize(` at ${formatLocation(r.file, r.line)}`, 'dim'));
1357
+ }
1358
+ console.log(colorize(` → ${r.fix}`, 'dim'));
1359
+ }
1360
+ console.log('');
1361
+ } else if (medium.length > 0) {
1362
+ console.log(colorize(` 🔵 ${medium.length} more recommendations (use --verbose)`, 'blue'));
1363
+ console.log('');
1364
+ }
1365
+
1366
+ // Top next actions
1367
+ if (topNextActions.length > 0) {
1368
+ console.log(colorize(' ⚡ Top 5 Next Actions', 'magenta'));
1369
+ for (let i = 0; i < topNextActions.length; i++) {
1370
+ const item = topNextActions[i];
1371
+ console.log(` ${i + 1}. ${colorize(item.name, 'bold')}`);
1372
+ console.log(colorize(` Why: ${item.why}`, 'dim'));
1373
+ console.log(colorize(` Trace: ${item.signals.join(' | ')}`, 'dim'));
1374
+ console.log(colorize(` Risk: ${item.risk} | Confidence: ${item.confidence}`, 'dim'));
1375
+ const sourceResult = result.results.find(r => r.key === item.key);
1376
+ if (sourceResult && sourceResult.file) {
1377
+ console.log(colorize(` Evidence: ${formatLocation(sourceResult.file, sourceResult.line)}`, 'dim'));
1378
+ }
1379
+ if (item.feedback) {
1380
+ const avgDelta = Number.isFinite(item.feedback.avgScoreDelta) ? ` | Avg score delta: ${item.feedback.avgScoreDelta >= 0 ? '+' : ''}${item.feedback.avgScoreDelta}` : '';
1381
+ console.log(colorize(` Feedback: accepted ${item.feedback.accepted}, rejected ${item.feedback.rejected}, positive ${item.feedback.positive}, negative ${item.feedback.negative}${avgDelta}`, 'dim'));
1382
+ }
1383
+ console.log(colorize(` Fix: ${item.fix}`, 'dim'));
1384
+ }
1385
+ console.log('');
1386
+ }
1387
+
1388
+ // Summary
1389
+ console.log(colorize(' ─────────────────────────────────────', 'dim'));
1390
+ const deprecatedNote = deprecated.length > 0 ? colorize(`, ${deprecated.length} deprecated`, 'dim') : '';
1391
+ console.log(` ${colorize(`${passed.length}/${applicable.length}`, 'bold')} checks passing${skipped.length > 0 ? colorize(` (${skipped.length} not applicable${deprecatedNote})`, 'dim') : (deprecatedNote ? colorize(` (${deprecatedNote})`, 'dim') : '')}`);
1392
+
1393
+ if (failed.length > 0) {
1394
+ console.log(` Next command: ${colorize(result.suggestedNextCommand, 'bold')}`);
1395
+ if (result.platform === 'codex') {
1396
+ console.log(colorize(' Codex now supports advisory no-write flows through augment and suggest-only before setup/apply.', 'dim'));
1397
+ }
1398
+ }
1399
+
1400
+ console.log('');
1401
+ console.log(` Add to README: ${getBadgeMarkdown(score)}`);
1402
+ console.log('');
1403
+
1404
+ // Weakest categories insight
1405
+ const insights = getLocalInsights({ score, results });
1406
+ if (insights.weakest.length > 0) {
1407
+ console.log(colorize(' Weakest areas:', 'dim'));
1408
+ for (const w of insights.weakest) {
1409
+ const bar = w.score === 0 ? colorize('none', 'red') : `${w.score}%`;
1410
+ console.log(colorize(` ${w.name}: ${bar} (${w.passed}/${w.total})`, 'dim'));
1411
+ }
1412
+ console.log('');
1413
+ }
1414
+
1415
+ // Cross-platform synergy hint
1416
+ try {
1417
+ const { detectActivePlatforms } = require('./harmony/canon');
1418
+ const { analyzeCompensation } = require('./synergy/compensation');
1419
+ const { calculateSynergyScore } = require('./synergy/ranking');
1420
+ const detected = detectActivePlatforms(options.dir);
1421
+ const activePlatforms = (detected || []).filter(p => p.detected).map(p => p.platform);
1422
+ if (activePlatforms.length >= 2) {
1423
+ const comp = analyzeCompensation(activePlatforms);
1424
+ const synergyScore = calculateSynergyScore(activePlatforms);
1425
+ console.log(colorize(` Cross-platform synergy [EXPERIMENTAL]: ${activePlatforms.length} platforms detected`, 'blue'));
1426
+ console.log(colorize(` Platforms: ${activePlatforms.join(', ')}`, 'dim'));
1427
+ console.log(colorize(` Compensations: ${comp.compensations.length} | Gaps: ${comp.uncoveredGaps.length}`, 'dim'));
1428
+ console.log(colorize(` Run: npx nerviq harmony-audit for full cross-platform analysis`, 'dim'));
1429
+ console.log('');
1430
+ }
1431
+ } catch { /* synergy display is optional */ }
1432
+
1433
+ console.log(colorize(` Backed by NERVIQ research and evidence for ${spec.platformLabel}`, 'dim'));
1434
+ console.log(colorize(' https://github.com/nerviq/nerviq', 'dim'));
1435
+ console.log('');
1436
+
1437
+ // Send anonymous insights (opt-in, privacy-first, fire-and-forget)
1438
+ sendInsights(result);
1439
+
1440
+ return result;
1441
+ }
1442
+
1443
+ module.exports = { audit, buildTopNextActions, getFpFeedbackMultiplier, getRecommendationPriorityScore };