@nerviq/cli 1.12.0 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/audit.js CHANGED
@@ -2,8 +2,7 @@
2
2
  * Audit engine - evaluates project against NERVIQ technique database.
3
3
  */
4
4
 
5
- const path = require('path');
6
- const { TECHNIQUES: CLAUDE_TECHNIQUES, STACKS, STACK_CATEGORY_DETECTORS } = require('./techniques');
5
+ const { TECHNIQUES: CLAUDE_TECHNIQUES, STACKS, STACK_CATEGORY_DETECTORS } = require('./techniques');
7
6
  const { ProjectContext } = require('./context');
8
7
  const { CODEX_TECHNIQUES } = require('./codex/techniques');
9
8
  const { detectCodexDomainPacks } = require('./codex/domain-packs');
@@ -25,15 +24,25 @@ const { OPENCODE_TECHNIQUES } = require('./opencode/techniques');
25
24
  const { OpenCodeProjectContext } = require('./opencode/context');
26
25
  const { getBadgeMarkdown } = require('./badge');
27
26
  const { sendInsights, getLocalInsights } = require('./insights');
28
- const { getRecommendationOutcomeSummary, getRecommendationAdjustment } = require('./activity');
27
+ const { getRecommendationOutcomeSummary } = require('./activity');
29
28
  const { getFeedbackSummary } = require('./feedback');
30
29
  const { formatSarif } = require('./formatters/sarif');
31
30
  const { formatOtelMetrics } = require('./formatters/otel');
32
31
  const { collectAuditTerminology, formatTerminologyLines } = require('./terminology');
33
32
  const { loadPlugins, mergePluginChecks } = require('./plugins');
34
- const { hasWorkspaceConfig, detectWorkspaceGlobs, detectWorkspaces } = require('./workspace');
35
33
  const { detectDeprecationWarnings } = require('./deprecation');
36
- const { estimateTokenCount } = require('./token-estimate');
34
+ const { buildWorkspaceHint, formatCount, guardSkippedInstructionFiles, inspectInstructionFiles } = require('./audit/instruction-files');
35
+ const {
36
+ WEIGHTS,
37
+ buildScoreCoaching,
38
+ buildTopNextActions,
39
+ confidenceLabel,
40
+ computeCategoryScores,
41
+ getFpFeedbackMultiplier,
42
+ getQuickWins,
43
+ getRecommendationPriorityScore,
44
+ inferSuggestedNextCommand,
45
+ } = require('./audit/recommendations');
37
46
  const { version: packageVersion } = require('../package.json');
38
47
  const { t } = require('./i18n');
39
48
 
@@ -59,227 +68,10 @@ function progressBar(score, max = 100, width = 20) {
59
68
  return colorize('█'.repeat(filled), color) + colorize('░'.repeat(empty), 'dim');
60
69
  }
61
70
 
62
- function formatLocation(file, line) {
63
- if (!file) return null;
64
- return line ? `${file}:${line}` : file;
65
- }
66
-
67
- const IMPACT_ORDER = { critical: 3, high: 2, medium: 1, low: 0 };
68
- const WEIGHTS = { critical: 15, high: 10, medium: 5, low: 2 };
69
- const SCORE_MILESTONES = [50, 70, 90, 100];
70
- const LARGE_INSTRUCTION_WARN_TOKENS = 12000;
71
- const LARGE_INSTRUCTION_SKIP_TOKENS = 240000;
72
- const CATEGORY_MODULES = {
73
- memory: 'CLAUDE.md',
74
- quality: 'verification',
75
- git: 'safety',
76
- workflow: 'commands-agents-skills',
77
- security: 'permissions',
78
- automation: 'hooks',
79
- design: 'design-rules',
80
- devops: 'ci-devops',
81
- hygiene: 'project-hygiene',
82
- performance: 'context-management',
83
- tools: 'mcp-tools',
84
- prompting: 'prompt-structure',
85
- features: 'modern-claude-features',
86
- 'quality-deep': 'quality-deep',
87
- skills: 'skills',
88
- agents: 'subagents',
89
- review: 'review-workflow',
90
- local: 'local-environment',
91
- };
92
- const ACTION_RATIONALES = {
93
- noBypassPermissions: 'bypassPermissions skips the main safety layer. Explicit allow and deny rules create safer autonomy.',
94
- secretsProtection: 'Without secret protection, Claude can accidentally inspect sensitive files and leak them into outputs.',
95
- permissionDeny: 'Deny rules are the strongest way to prevent dangerous reads and destructive operations.',
96
- settingsPermissions: 'Explicit permission settings make the workflow safer, more governable, and easier to review.',
97
- testCommand: 'Without a test command, Claude cannot verify that its changes actually work before handoff.',
98
- lintCommand: 'Without a lint command, Claude will miss formatting and style regressions that teams expect to catch automatically.',
99
- buildCommand: 'Without a build command, compile and packaging failures stay invisible until later in the workflow.',
100
- ciPipeline: 'CI is what turns a local setup improvement into a repeatable team-wide standard.',
101
- securityReview: 'If you do not wire in security review guidance, high-risk changes are easier to ship without the right scrutiny.',
102
- skills: 'Skills package reusable expertise so Claude does not need the same context re-explained every session.',
103
- multipleAgents: 'Specialized agents unlock role-based work such as security review, implementation, and QA in parallel.',
104
- multipleMcpServers: 'A richer MCP surface gives Claude access to live tools and documentation instead of stale assumptions.',
105
- roleDefinition: 'A clear role definition calibrates how Claude thinks, explains, and validates work in this repo.',
106
- importSyntax: 'Imported modules keep CLAUDE.md maintainable as the workflow grows more sophisticated.',
107
- claudeMd: 'CLAUDE.md is the foundation of project-specific context. Without it, Claude starts every task half-blind.',
108
- hooks: 'Hooks enforce the rules programmatically, which is much more reliable than relying on instructions alone.',
109
- pathRules: 'Path-specific rules help Claude behave differently in different parts of the repo without global noise.',
110
- context7Mcp: 'Live documentation reduces version drift and cuts down on confident but outdated answers.',
111
- codexAgentsMd: 'AGENTS.md is the main Codex instruction surface. Without it, Codex starts without repo-specific guidance.',
112
- codexAgentsMdSubstantive: 'A thin AGENTS.md is almost as bad as no AGENTS.md because Codex still lacks the repo context it needs.',
113
- codexAgentsVerificationCommands: 'If AGENTS.md does not document how to verify work, Codex cannot reliably prove its own changes are safe.',
114
- codexAgentsArchitecture: 'A small architecture map reduces navigation drift and helps Codex change the right part of the repo first.',
115
- codexConfigExists: 'Without .codex/config.toml, trust and model behavior are implicit instead of explicit.',
116
- codexReasoningEffortExplicit: 'Reasoning depth should be intentional for cost and latency, not left to implicit defaults.',
117
- codexApprovalPolicyExplicit: 'Explicit approvals make Codex behavior predictable and reviewable across sessions.',
118
- codexNoDangerFullAccess: 'danger-full-access removes the main safety boundary and should be treated as a critical risk.',
119
- codexHistorySendToServerExplicit: 'History sync is a privacy and governance surface. Teams should decide it explicitly, not inherit it accidentally.',
120
- codexNoSecretsInAgents: 'Secrets in AGENTS.md can leak directly into agent context, outputs, and logs.',
121
- codexHooksWindowsCaveat: 'Windows does not support Codex hooks today, so relying on them there creates a false sense of runtime enforcement.',
122
- codexSkillsDirPresentWhenUsed: 'Versioned repo-local skills are the safest way to keep Codex expertise reviewable and consistent across contributors.',
123
- codexSkillsHaveMetadata: 'Without a usable SKILL.md, Codex cannot reliably decide when a skill should run or what it is for.',
124
- codexSkillNamesKebabCase: 'Consistent skill naming improves discoverability and avoids invocation drift.',
125
- codexSkillDescriptionsBounded: 'A bounded skill description helps Codex invoke the right skill without inflating prompt context.',
126
- codexSkillsNoAutoRunRisk: 'Skills should guide Codex, not silently authorize risky automation or destructive actions.',
127
- codexCustomAgentsRequiredFields: 'Custom agents need clear metadata and developer instructions so delegation stays predictable.',
128
- codexMaxThreadsExplicit: 'Explicit fanout limits make Codex delegation safer and easier to reason about.',
129
- codexMaxDepthExplicit: 'Nested delegation should be deliberate, not accidental.',
130
- codexPerAgentSandboxOverridesSafe: 'Per-agent overrides can quietly bypass the main trust model if they are not constrained.',
131
- codexExecUsageSafe: 'Unsafe Codex automation quickly turns small workflow mistakes into real repo damage.',
132
- codexGitHubActionSafeStrategy: 'CI safety posture should be visible and intentional, especially when Codex is acting in automation.',
133
- codexCiAuthUsesManagedKey: 'Managed secrets are the minimum trust boundary for Codex in CI.',
134
- codexAutomationManuallyTested: 'Manual dry-runs catch automation footguns before they become scheduled failures.',
135
- codexReviewWorkflowDocumented: 'A documented review path makes Codex safer to use on risky diffs and refactors.',
136
- codexReviewModelOverrideExplicit: 'Explicit review model selection keeps review quality and cost predictable when automation is involved.',
137
- codexWorkingTreeReviewExpectations: 'Codex reviews are much safer when the repo states how to treat staged, unstaged, and unrelated changes.',
138
- codexCostAwarenessDocumented: 'Heavy workflows should be intentional, not the invisible default.',
139
- codexArtifactsSharedIntentionally: 'If `.codex` is hidden from version control, the team loses a shared and reviewable Codex contract.',
140
- codexLifecycleScriptsPlatformSafe: 'Local setup/teardown scripts are part of the trust model and should not surprise contributors on other platforms.',
141
- codexActionsNotRedundant: 'Redundant automation expands the surface area without adding real value.',
142
- codexWorktreeLifecycleDocumented: 'Parallel worktree flows need explicit setup and cleanup expectations.',
143
- codexAgentsMentionModernFeatures: 'When the repo uses modern Codex surfaces, AGENTS.md should tell Codex they exist.',
144
- codexNoDeprecatedPatterns: 'Deprecated Codex patterns create silent drift and confusing behavior over time.',
145
- codexProfilesUsedWhenNeeded: 'Profiles become more important as Codex automation and delegation get more complex.',
146
- codexPluginConfigValid: 'Broken plugin metadata creates discoverability and tooling drift.',
147
- codexUndoExplicit: 'Undo is a user-facing safety feature and should be an explicit repo choice.',
148
- };
149
- const CODEX_HARD_FAIL_KEYS = new Set([
150
- 'codexAgentsMd',
151
- 'codexConfigValidToml',
152
- 'codexNoDangerFullAccess',
153
- 'codexApprovalPolicyExplicit',
154
- 'codexNoSecretsInAgents',
155
- 'codexHooksWindowsCaveat',
156
- ]);
157
- const CODEX_EVIDENCE_CLASSES = {
158
- 'CX-A01': 'runtime',
159
- 'CX-A02': 'derived',
160
- 'CX-A03': 'derived',
161
- 'CX-A04': 'derived',
162
- 'CX-A05': 'mixed',
163
- 'CX-A06': 'source',
164
- 'CX-A07': 'derived',
165
- 'CX-A08': 'derived',
166
- 'CX-B01': 'runtime',
167
- 'CX-B02': 'mixed',
168
- 'CX-B03': 'mixed',
169
- 'CX-B04': 'source',
170
- 'CX-B05': 'source',
171
- 'CX-B06': 'source',
172
- 'CX-B07': 'source',
173
- 'CX-B08': 'source',
174
- 'CX-B09': 'source',
175
- 'CX-C01': 'mixed',
176
- 'CX-C02': 'mixed',
177
- 'CX-C03': 'mixed',
178
- 'CX-C04': 'derived',
179
- 'CX-C05': 'source',
180
- 'CX-C06': 'source',
181
- 'CX-C07': 'mixed',
182
- 'CX-C08': 'source',
183
- 'CX-C09': 'mixed',
184
- 'CX-D01': 'runtime',
185
- 'CX-D02': 'mixed',
186
- 'CX-D03': 'source',
187
- 'CX-D04': 'mixed',
188
- 'CX-D05': 'mixed',
189
- 'CX-E01': 'mixed',
190
- 'CX-E02': 'runtime',
191
- 'CX-E03': 'mixed',
192
- 'CX-E04': 'mixed',
193
- 'CX-E05': 'source',
194
- 'CX-F01': 'mixed',
195
- 'CX-F02': 'mixed',
196
- 'CX-F03': 'source',
197
- 'CX-F04': 'mixed',
198
- 'CX-F05': 'source',
199
- 'CX-F06': 'source',
200
- 'CX-G01': 'mixed',
201
- 'CX-G02': 'source',
202
- 'CX-G03': 'source',
203
- 'CX-G04': 'derived',
204
- 'CX-G05': 'derived',
205
- 'CX-H01': 'source',
206
- 'CX-H02': 'runtime',
207
- 'CX-H03': 'runtime',
208
- 'CX-H04': 'source',
209
- 'CX-I01': 'mixed',
210
- 'CX-I02': 'mixed',
211
- 'CX-I03': 'source',
212
- 'CX-I04': 'source',
213
- 'CX-J01': 'source',
214
- 'CX-J02': 'source',
215
- 'CX-J03': 'source',
216
- 'CX-J04': 'source',
217
- 'CX-K01': 'source',
218
- 'CX-K02': 'source',
219
- 'CX-K03': 'source',
220
- 'CX-K04': 'source',
221
- 'CX-L01': 'derived',
222
- 'CX-L02': 'source',
223
- 'CX-L03': 'derived',
224
- 'CX-L04': 'source',
225
- 'CX-L05': 'source',
226
- };
227
- const CODEX_QUICKWIN_CONFIG_KEYS = new Set([
228
- 'codexConfigExists',
229
- 'codexModelExplicit',
230
- 'codexReasoningEffortExplicit',
231
- 'codexWeakModelExplicit',
232
- 'codexProfilesUsedAppropriately',
233
- 'codexFullAutoErrorModeExplicit',
234
- 'codexHistorySendToServerExplicit',
235
- 'codexNetworkAccessExplicit',
236
- 'codexHooksDeliberate',
237
- 'codexMcpStartupTimeoutReasonable',
238
- 'codexMaxThreadsExplicit',
239
- 'codexMaxDepthExplicit',
240
- ]);
241
- const CODEX_QUICKWIN_FILE_KEYS = new Set([
242
- 'codexAgentsMd',
243
- 'codexHooksJsonExistsWhenClaimed',
244
- 'codexSkillsDirPresentWhenUsed',
245
- ]);
246
- const CODEX_QUICKWIN_DOC_KEYS = new Set([
247
- 'codexAgentsArchitecture',
248
- 'codexOverrideDocumented',
249
- 'codexNoGenericFiller',
250
- 'codexNoInstructionContradictions',
251
- 'codexRulesExamplesPresent',
252
- 'codexRuleWrapperRiskDocumented',
253
- 'codexSkillsHaveMetadata',
254
- 'codexSkillNamesKebabCase',
255
- 'codexSkillDescriptionsBounded',
256
- 'codexAutomationManuallyTested',
257
- 'codexReviewWorkflowDocumented',
258
- 'codexWorkingTreeReviewExpectations',
259
- 'codexCostAwarenessDocumented',
260
- ]);
261
- const CODEX_QUICKWIN_POLICY_KEYS = new Set([
262
- 'codexRulesSpecificPatterns',
263
- 'codexNoBroadAllowAllRules',
264
- 'codexMcpWhitelistsExplicit',
265
- 'codexNoDeprecatedMcpTransport',
266
- 'codexGitHubActionSafeStrategy',
267
- 'codexProfilesUsedWhenNeeded',
268
- 'codexUndoExplicit',
269
- ]);
270
- const CODEX_QUICKWIN_AVOID_KEYS = new Set([
271
- 'codexNoDangerFullAccess',
272
- 'codexApprovalPolicyExplicit',
273
- 'codexGitHubActionUnsafeJustified',
274
- 'codexProjectScopedMcpTrusted',
275
- 'codexMcpAuthDocumented',
276
- 'codexHooksWindowsCaveat',
277
- 'codexNoSecretsInAgents',
278
- 'codexPerAgentSandboxOverridesSafe',
279
- 'codexExecUsageSafe',
280
- 'codexCiAuthUsesManagedKey',
281
- 'codexLifecycleScriptsPlatformSafe',
282
- ]);
71
+ function formatLocation(file, line) {
72
+ if (!file) return null;
73
+ return line ? `${file}:${line}` : file;
74
+ }
283
75
 
284
76
  function getAuditSpec(platform = 'claude') {
285
77
  if (platform === 'codex') {
@@ -361,502 +153,7 @@ function getAuditSpec(platform = 'claude') {
361
153
  };
362
154
  }
363
155
 
364
- function normalizeRelativePath(filePath) {
365
- return String(filePath || '').replace(/\\/g, '/').replace(/^\.\//, '');
366
- }
367
-
368
- function formatCount(value) {
369
- return Number(value || 0).toLocaleString('en-US');
370
- }
371
-
372
- function addPath(target, filePath) {
373
- if (!filePath || typeof filePath !== 'string') return;
374
- target.add(normalizeRelativePath(filePath));
375
- }
376
-
377
- function addDirFiles(ctx, target, dirPath, filter) {
378
- if (typeof ctx.dirFiles !== 'function') return;
379
- for (const file of ctx.dirFiles(dirPath)) {
380
- if (filter && !filter.test(file)) continue;
381
- addPath(target, path.join(dirPath, file));
382
- }
383
- }
384
-
385
- function instructionFileCandidates(spec, ctx) {
386
- const candidates = new Set();
387
-
388
- if (spec.platform === 'claude') {
389
- addPath(candidates, 'CLAUDE.md');
390
- addPath(candidates, '.claude/CLAUDE.md');
391
- addDirFiles(ctx, candidates, '.claude/rules', /\.md$/i);
392
- addDirFiles(ctx, candidates, '.claude/commands', /\.md$/i);
393
- addDirFiles(ctx, candidates, '.claude/agents', /\.md$/i);
394
- if (typeof ctx.dirFiles === 'function') {
395
- for (const skillDir of ctx.dirFiles('.claude/skills')) {
396
- addPath(candidates, path.join('.claude', 'skills', skillDir, 'SKILL.md'));
397
- }
398
- }
399
- }
400
-
401
- if (spec.platform === 'codex') {
402
- addPath(candidates, 'AGENTS.md');
403
- addPath(candidates, 'AGENTS.override.md');
404
- addPath(candidates, typeof ctx.agentsMdPath === 'function' ? ctx.agentsMdPath() : null);
405
- addDirFiles(ctx, candidates, 'codex/rules');
406
- addDirFiles(ctx, candidates, '.codex/rules');
407
- if (typeof ctx.skillDirs === 'function') {
408
- for (const skillDir of ctx.skillDirs()) {
409
- addPath(candidates, path.join('.agents', 'skills', skillDir, 'SKILL.md'));
410
- }
411
- }
412
- }
413
-
414
- if (spec.platform === 'gemini') {
415
- addPath(candidates, 'GEMINI.md');
416
- addPath(candidates, '.gemini/GEMINI.md');
417
- addDirFiles(ctx, candidates, '.gemini/agents', /\.md$/i);
418
- if (typeof ctx.skillDirs === 'function') {
419
- for (const skillDir of ctx.skillDirs()) {
420
- addPath(candidates, path.join('.gemini', 'skills', skillDir, 'SKILL.md'));
421
- }
422
- }
423
- }
424
-
425
- if (spec.platform === 'copilot') {
426
- addPath(candidates, '.github/copilot-instructions.md');
427
- addDirFiles(ctx, candidates, '.github/instructions', /\.instructions\.md$/i);
428
- addDirFiles(ctx, candidates, '.github/prompts', /\.prompt\.md$/i);
429
- }
430
-
431
- if (spec.platform === 'cursor') {
432
- addPath(candidates, '.cursorrules');
433
- addDirFiles(ctx, candidates, '.cursor/rules', /\.mdc$/i);
434
- addDirFiles(ctx, candidates, '.cursor/commands', /\.md$/i);
435
- }
436
-
437
- if (spec.platform === 'windsurf') {
438
- addPath(candidates, '.windsurfrules');
439
- addDirFiles(ctx, candidates, '.windsurf/rules', /\.md$/i);
440
- addDirFiles(ctx, candidates, '.windsurf/workflows', /\.md$/i);
441
- addDirFiles(ctx, candidates, '.windsurf/memories', /\.(md|json)$/i);
442
- }
443
-
444
- if (spec.platform === 'aider' && typeof ctx.conventionFiles === 'function') {
445
- for (const file of ctx.conventionFiles()) {
446
- addPath(candidates, file);
447
- }
448
- }
449
-
450
- if (spec.platform === 'opencode') {
451
- addPath(candidates, 'AGENTS.md');
452
- addPath(candidates, 'CLAUDE.md');
453
- addDirFiles(ctx, candidates, '.opencode/commands', /\.(md|markdown|ya?ml)$/i);
454
- if (typeof ctx.skillDirs === 'function') {
455
- for (const skillDir of ctx.skillDirs()) {
456
- addPath(candidates, path.join('.opencode', 'commands', skillDir, 'SKILL.md'));
457
- }
458
- }
459
- }
460
-
461
- return [...candidates];
462
- }
463
-
464
- function inspectInstructionFiles(spec, ctx) {
465
- const warnings = [];
466
-
467
- for (const filePath of instructionFileCandidates(spec, ctx)) {
468
- const content = typeof ctx.fileContent === 'function' ? ctx.fileContent(filePath) : null;
469
- const byteCount = typeof ctx.fileSizeBytes === 'function' ? ctx.fileSizeBytes(filePath) : null;
470
- const tokenCount = typeof content === 'string' ? estimateTokenCount(content) : null;
471
- if (!Number.isFinite(tokenCount) || tokenCount <= LARGE_INSTRUCTION_WARN_TOKENS) continue;
472
-
473
- warnings.push({
474
- file: normalizeRelativePath(filePath),
475
- byteCount,
476
- tokenCount,
477
- lineCount: typeof content === 'string' ? content.split(/\r?\n/).length : null,
478
- skipped: tokenCount > LARGE_INSTRUCTION_SKIP_TOKENS,
479
- severity: tokenCount > LARGE_INSTRUCTION_SKIP_TOKENS ? 'critical' : 'warning',
480
- message: tokenCount > LARGE_INSTRUCTION_SKIP_TOKENS
481
- ? 'Instruction file exceeds ~240,000 tokens and will be skipped during audit.'
482
- : 'Instruction file exceeds ~12,000 tokens. Audit will continue, but this file may reduce runtime clarity.',
483
- });
484
- }
485
-
486
- return warnings;
487
- }
488
-
489
- function guardSkippedInstructionFiles(ctx, warnings) {
490
- const skippedFiles = new Set(
491
- warnings.filter((item) => item.skipped).map((item) => normalizeRelativePath(item.file))
492
- );
493
-
494
- if (skippedFiles.size === 0) return;
495
-
496
- const originalFileContent = typeof ctx.fileContent === 'function' ? ctx.fileContent.bind(ctx) : null;
497
- const originalLineNumber = typeof ctx.lineNumber === 'function' ? ctx.lineNumber.bind(ctx) : null;
498
-
499
- if (originalFileContent) {
500
- ctx.fileContent = (filePath) => {
501
- if (skippedFiles.has(normalizeRelativePath(filePath))) return null;
502
- return originalFileContent(filePath);
503
- };
504
- }
505
-
506
- if (originalLineNumber) {
507
- ctx.lineNumber = (filePath, matcher) => {
508
- if (skippedFiles.has(normalizeRelativePath(filePath))) return null;
509
- return originalLineNumber(filePath, matcher);
510
- };
511
- }
512
- }
513
-
514
- function buildWorkspaceHint(dir) {
515
- if (!hasWorkspaceConfig(dir)) {
516
- return null;
517
- }
518
-
519
- const patterns = detectWorkspaceGlobs(dir);
520
- const workspaces = detectWorkspaces(dir);
521
- if (patterns.length === 0 && workspaces.length === 0) {
522
- return null;
523
- }
524
-
525
- return {
526
- detected: true,
527
- patterns,
528
- workspaces,
529
- suggestedCommand: patterns.length > 0
530
- ? `npx nerviq audit --workspace ${patterns.join(',')}`
531
- : `npx nerviq audit --workspace ${workspaces.join(',')}`,
532
- };
533
- }
534
-
535
- function riskFromImpact(impact) {
536
- if (impact === 'critical') return 'high';
537
- if (impact === 'high') return 'medium';
538
- return 'low';
539
- }
540
-
541
- function confidenceFromImpact(impact) {
542
- return impact === 'critical' || impact === 'high' ? 'high' : 'medium';
543
- }
544
-
545
- function confidenceLabel(confidence) {
546
- if (confidence >= 0.6) return 'HIGH';
547
- if (confidence >= 0.3) return 'MEDIUM';
548
- return 'HEURISTIC';
549
- }
550
-
551
- function getPrioritizedFailed(failed) {
552
- const prioritized = failed.filter(r => !(r.category === 'hygiene' && r.impact === 'low'));
553
- return prioritized.length > 0 ? prioritized : failed;
554
- }
555
-
556
- function codexEvidenceClass(item) {
557
- return CODEX_EVIDENCE_CLASSES[item.id] || 'derived';
558
- }
559
-
560
- function codexCategoryBonus(category) {
561
- if (category === 'trust' || category === 'config') return 12;
562
- if (category === 'rules' || category === 'hooks' || category === 'mcp') return 8;
563
- if (category === 'instructions') return 4;
564
- return 0;
565
- }
566
-
567
- function codexEvidenceBonus(item) {
568
- const evidenceClass = codexEvidenceClass(item);
569
- if (evidenceClass === 'runtime') return 8;
570
- if (evidenceClass === 'mixed') return 6;
571
- if (evidenceClass === 'source') return 3;
572
- return 0;
573
- }
574
-
575
- function codexPriorityScore(item, outcomeSummaryByKey = {}) {
576
- const impactBase = item.impact === 'critical'
577
- ? 60
578
- : item.impact === 'high'
579
- ? 40
580
- : item.impact === 'medium'
581
- ? 20
582
- : 8;
583
- const feedbackAdjustment = getRecommendationAdjustment(outcomeSummaryByKey, item.key) * 10;
584
- const hardFailBonus = CODEX_HARD_FAIL_KEYS.has(item.key) ? 12 : 0;
585
- return Math.max(0, Math.min(100, impactBase + codexCategoryBonus(item.category) + codexEvidenceBonus(item) + hardFailBonus + feedbackAdjustment));
586
- }
587
-
588
- function codexQuickWinScore(item) {
589
- if (CODEX_QUICKWIN_AVOID_KEYS.has(item.key)) {
590
- return -100;
591
- }
592
-
593
- let score = 0;
594
- if (CODEX_QUICKWIN_CONFIG_KEYS.has(item.key)) {
595
- score += 40;
596
- } else if (CODEX_QUICKWIN_FILE_KEYS.has(item.key)) {
597
- score += 34;
598
- } else if (CODEX_QUICKWIN_DOC_KEYS.has(item.key)) {
599
- score += 26;
600
- } else if (CODEX_QUICKWIN_POLICY_KEYS.has(item.key)) {
601
- score += 20;
602
- }
603
-
604
- score += item.impact === 'low' ? 8 : item.impact === 'medium' ? 6 : item.impact === 'high' ? 4 : 0;
605
- score -= Math.min((item.fix || '').length, 240) / 24;
606
- return score;
607
- }
608
-
609
- function getQuickWins(failed, options = {}) {
610
- const pool = getPrioritizedFailed(failed);
611
-
612
- if (options.platform === 'codex') {
613
- const codexPool = pool.filter((item) => !CODEX_QUICKWIN_AVOID_KEYS.has(item.key));
614
- const rankedPool = (codexPool.length > 0 ? codexPool : pool)
615
- .slice()
616
- .sort((a, b) => codexQuickWinScore(b) - codexQuickWinScore(a));
617
- return rankedPool.slice(0, 3);
618
- }
619
-
620
- // QuickWins prioritize short fixes (easy to implement) first, then impact
621
- return [...pool]
622
- .sort((a, b) => {
623
- const fixLenA = (a.fix || '').length;
624
- const fixLenB = (b.fix || '').length;
625
- if (fixLenA !== fixLenB) return fixLenA - fixLenB;
626
- const impactA = IMPACT_ORDER[a.impact] ?? 0;
627
- const impactB = IMPACT_ORDER[b.impact] ?? 0;
628
- return impactB - impactA;
629
- })
630
- .slice(0, 3);
631
- }
632
-
633
- /**
634
- * Compute a multiplier based on FP (helpful/not-helpful) feedback for a check key.
635
- * - >50% "not helpful" feedback: lower priority by 30% (multiplier 0.7)
636
- * - >80% "helpful" feedback: boost priority by 20% (multiplier 1.2)
637
- * - Otherwise: no change (multiplier 1.0)
638
- * @param {Object} fpFeedbackByKey - Keyed feedback summary from getFeedbackSummary().byKey
639
- * @param {string} key - The check key to look up
640
- * @returns {number} Multiplier to apply to priority score
641
- */
642
- function getFpFeedbackMultiplier(fpFeedbackByKey, key) {
643
- if (!fpFeedbackByKey) return 1.0;
644
- const bucket = fpFeedbackByKey[key];
645
- if (!bucket || bucket.total === 0) return 1.0;
646
-
647
- const unhelpfulRate = bucket.unhelpful / bucket.total;
648
- const helpfulRate = bucket.helpful / bucket.total;
649
-
650
- if (unhelpfulRate > 0.5) return 0.7;
651
- if (helpfulRate > 0.8) return 1.2;
652
- return 1.0;
653
- }
654
-
655
- function getRecommendationPriorityScore(item, outcomeSummaryByKey = {}, fpFeedbackByKey = null) {
656
- const impactScore = (IMPACT_ORDER[item.impact] ?? 0) * 100;
657
- const feedbackAdjustment = getRecommendationAdjustment(outcomeSummaryByKey, item.key);
658
- const brevityPenalty = Math.min((item.fix || '').length, 240) / 20;
659
- const raw = impactScore + (feedbackAdjustment * 10) - brevityPenalty;
660
- return raw * getFpFeedbackMultiplier(fpFeedbackByKey, item.key);
661
- }
662
-
663
- function buildTopNextActions(failed, limit = 5, outcomeSummaryByKey = {}, options = {}) {
664
- const pool = getPrioritizedFailed(failed);
665
- const fpByKey = options.fpFeedbackByKey || null;
666
-
667
- return [...pool]
668
- .sort((a, b) => {
669
- const scoreB = options.platform === 'codex'
670
- ? codexPriorityScore(b, outcomeSummaryByKey)
671
- : getRecommendationPriorityScore(b, outcomeSummaryByKey, fpByKey);
672
- const scoreA = options.platform === 'codex'
673
- ? codexPriorityScore(a, outcomeSummaryByKey)
674
- : getRecommendationPriorityScore(a, outcomeSummaryByKey, fpByKey);
675
- return scoreB - scoreA;
676
- })
677
- .slice(0, limit)
678
- .map(({ key, id, name, impact, fix, category, sourceUrl }) => {
679
- const feedback = outcomeSummaryByKey[key] || null;
680
- const rankingAdjustment = getRecommendationAdjustment(outcomeSummaryByKey, key);
681
- const signals = [
682
- `failed-check:${key}`,
683
- `impact:${impact}`,
684
- `category:${category}`,
685
- ];
686
- if (feedback) {
687
- signals.push(`feedback:${feedback.total}`);
688
- signals.push(`ranking-adjustment:${rankingAdjustment >= 0 ? '+' : ''}${rankingAdjustment}`);
689
- }
690
-
691
- const fullItem = pool.find((item) => item.key === key) || { key, id, name, impact, fix, category };
692
- const evidenceClass = options.platform === 'codex' ? codexEvidenceClass(fullItem) : (feedback ? 'measured' : 'estimated');
693
- const priorityScore = options.platform === 'codex'
694
- ? codexPriorityScore(fullItem, outcomeSummaryByKey)
695
- : Math.max(0, Math.min(100, Math.round(getRecommendationPriorityScore(fullItem, outcomeSummaryByKey, fpByKey) / 3)));
696
-
697
- signals.push(`evidence:${evidenceClass}`);
698
- if (options.platform === 'codex' && CODEX_HARD_FAIL_KEYS.has(key)) {
699
- signals.push('hard-fail:true');
700
- }
701
-
702
- return ({
703
- key,
704
- id,
705
- name,
706
- impact,
707
- category,
708
- sourceUrl,
709
- module: CATEGORY_MODULES[category] || category,
710
- fix,
711
- priorityScore,
712
- why: ACTION_RATIONALES[key] || fix,
713
- risk: riskFromImpact(impact),
714
- confidence: confidenceFromImpact(impact),
715
- signals,
716
- evidenceClass,
717
- rankingAdjustment,
718
- feedback: feedback ? {
719
- total: feedback.total,
720
- accepted: feedback.accepted,
721
- rejected: feedback.rejected,
722
- deferred: feedback.deferred,
723
- positive: feedback.positive,
724
- negative: feedback.negative,
725
- avgScoreDelta: feedback.avgScoreDelta,
726
- } : null,
727
- });
728
- });
729
- }
730
-
731
- function getNextScoreMilestone(score) {
732
- return SCORE_MILESTONES.find((milestone) => score < milestone) || null;
733
- }
734
-
735
- function buildScoreCoaching({ score, earnedPoints, maxPoints, failed, outcomeSummaryByKey = {}, platform, fpFeedbackByKey = null }) {
736
- if (!Array.isArray(failed) || failed.length === 0 || !Number.isFinite(maxPoints) || maxPoints <= 0) {
737
- return null;
738
- }
739
-
740
- const nextMilestone = getNextScoreMilestone(score);
741
- if (!nextMilestone) return null;
742
-
743
- const targetEarnedPoints = Math.ceil((nextMilestone / 100) * maxPoints);
744
- const pointsNeeded = Math.max(0, targetEarnedPoints - earnedPoints);
745
- if (pointsNeeded <= 0) return null;
746
-
747
- const rankedActions = buildTopNextActions(failed, failed.length, outcomeSummaryByKey, { platform, fpFeedbackByKey });
748
- if (rankedActions.length === 0) return null;
749
-
750
- const failedByKey = new Map(failed.map((item) => [item.key, item]));
751
- const selected = [];
752
- let recoveredPoints = 0;
753
-
754
- for (const action of rankedActions) {
755
- const source = failedByKey.get(action.key);
756
- if (!source) continue;
757
- selected.push({
758
- key: source.key,
759
- name: source.name,
760
- impact: source.impact,
761
- weight: WEIGHTS[source.impact] || 0,
762
- });
763
- recoveredPoints += WEIGHTS[source.impact] || 0;
764
- if (recoveredPoints >= pointsNeeded) break;
765
- }
766
-
767
- if (selected.length === 0) return null;
768
-
769
- const fixesNeeded = selected.length;
770
- const projectedScore = Math.round(((earnedPoints + recoveredPoints) / maxPoints) * 100);
771
- const summary = `You're ${fixesNeeded} ${fixesNeeded === 1 ? 'fix' : 'fixes'} away from ${nextMilestone}/100.`;
772
-
773
- return {
774
- currentScore: score,
775
- nextMilestone,
776
- pointsNeeded,
777
- fixesNeeded,
778
- projectedScore: Math.min(100, projectedScore),
779
- summary,
780
- recommendedKeys: selected.map((item) => item.key),
781
- recommendedNames: selected.map((item) => item.name),
782
- };
783
- }
784
-
785
- function computeCategoryScores(applicable, passed) {
786
- const grouped = {};
787
-
788
- for (const item of applicable) {
789
- const category = item.category || 'unknown';
790
- if (!grouped[category]) {
791
- grouped[category] = { passed: 0, total: 0, earnedPoints: 0, maxPoints: 0 };
792
- }
793
- grouped[category].total += 1;
794
- grouped[category].maxPoints += WEIGHTS[item.impact] || 5;
795
- }
796
-
797
- for (const item of passed) {
798
- const category = item.category || 'unknown';
799
- if (!grouped[category]) continue;
800
- grouped[category].passed += 1;
801
- grouped[category].earnedPoints += WEIGHTS[item.impact] || 5;
802
- }
803
-
804
- const result = {};
805
- for (const [category, summary] of Object.entries(grouped)) {
806
- result[category] = {
807
- ...summary,
808
- score: summary.maxPoints > 0 ? Math.round((summary.earnedPoints / summary.maxPoints) * 100) : 0,
809
- };
810
- }
811
-
812
- return result;
813
- }
814
-
815
- function inferSuggestedNextCommand(result) {
816
- if (result.platform === 'codex') {
817
- if (result.failed === 0) {
818
- return 'npx nerviq --platform codex augment';
819
- }
820
-
821
- const actionKeys = new Set((result.topNextActions || []).map(item => item.key));
822
- if (
823
- result.score < 50 ||
824
- actionKeys.has('codexAgentsMd') ||
825
- actionKeys.has('codexConfigExists') ||
826
- actionKeys.has('codexNoDangerFullAccess') ||
827
- actionKeys.has('codexApprovalPolicyExplicit')
828
- ) {
829
- return 'npx nerviq --platform codex suggest-only';
830
- }
831
-
832
- return 'npx nerviq --platform codex augment';
833
- }
834
-
835
- const actionKeys = new Set((result.topNextActions || []).map(item => item.key));
836
- const platFlag = result.platform && result.platform !== 'claude' ? ` --platform ${result.platform}` : '';
837
-
838
- if (result.failed === 0) {
839
- return `npx nerviq${platFlag} augment`;
840
- }
841
-
842
- if (
843
- result.score < 50 ||
844
- actionKeys.has('claudeMd') ||
845
- actionKeys.has('hooks') ||
846
- actionKeys.has('settingsPermissions') ||
847
- actionKeys.has('permissionDeny')
848
- ) {
849
- return `npx nerviq${platFlag} setup`;
850
- }
851
-
852
- if (result.score < 80) {
853
- return `npx nerviq${platFlag} suggest-only`;
854
- }
855
-
856
- return `npx nerviq${platFlag} augment`;
857
- }
858
-
859
- function getPlatformScopeNote(spec, ctx) {
156
+ function getPlatformScopeNote(spec, ctx) {
860
157
  if (spec.platform !== 'codex') {
861
158
  return null;
862
159
  }