@nerviq/cli 1.11.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.
Files changed (62) hide show
  1. package/README.md +216 -124
  2. package/bin/cli.js +620 -183
  3. package/package.json +3 -2
  4. package/src/activity.js +49 -9
  5. package/src/adoption-advisor.js +299 -0
  6. package/src/aider/freshness.js +65 -20
  7. package/src/aider/techniques.js +16 -11
  8. package/src/analyze.js +128 -0
  9. package/src/anti-patterns.js +13 -0
  10. package/src/audit/instruction-files.js +180 -0
  11. package/src/audit/recommendations.js +531 -0
  12. package/src/audit.js +53 -681
  13. package/src/behavioral-drift.js +801 -0
  14. package/src/codex/freshness.js +84 -25
  15. package/src/continuous-ops.js +681 -0
  16. package/src/copilot/freshness.js +57 -20
  17. package/src/cost-tracking.js +61 -0
  18. package/src/cursor/freshness.js +65 -20
  19. package/src/cursor/techniques.js +17 -12
  20. package/src/deep-review.js +83 -0
  21. package/src/diff-only.js +280 -0
  22. package/src/doctor.js +118 -55
  23. package/src/freshness.js +74 -21
  24. package/src/gemini/freshness.js +66 -21
  25. package/src/governance.js +59 -43
  26. package/src/hook-validation.js +342 -0
  27. package/src/index.js +5 -0
  28. package/src/integrations.js +42 -5
  29. package/src/mcp-server.js +95 -59
  30. package/src/mcp-validation.js +337 -0
  31. package/src/opencode/freshness.js +66 -21
  32. package/src/opencode/techniques.js +12 -7
  33. package/src/operating-profile.js +574 -0
  34. package/src/org.js +97 -13
  35. package/src/plans.js +192 -8
  36. package/src/platform-change-manifest.js +86 -0
  37. package/src/policy-layers.js +210 -0
  38. package/src/profiles.js +4 -1
  39. package/src/prompt-injection.js +74 -0
  40. package/src/repo-archetype.js +386 -0
  41. package/src/setup/analysis.js +619 -0
  42. package/src/setup/runtime.js +172 -0
  43. package/src/setup.js +62 -748
  44. package/src/source-urls.js +132 -132
  45. package/src/supplemental-checks.js +13 -12
  46. package/src/techniques/api.js +407 -0
  47. package/src/techniques/automation.js +316 -0
  48. package/src/techniques/compliance.js +257 -0
  49. package/src/techniques/hygiene.js +294 -0
  50. package/src/techniques/instructions.js +243 -0
  51. package/src/techniques/observability.js +226 -0
  52. package/src/techniques/optimization.js +142 -0
  53. package/src/techniques/quality.js +317 -0
  54. package/src/techniques/security.js +237 -0
  55. package/src/techniques/shared.js +443 -0
  56. package/src/techniques/stacks.js +2294 -0
  57. package/src/techniques/tools.js +106 -0
  58. package/src/techniques/workflow.js +413 -0
  59. package/src/techniques.js +78 -5607
  60. package/src/watch.js +18 -0
  61. package/src/windsurf/freshness.js +36 -21
  62. package/src/windsurf/techniques.js +17 -12
@@ -0,0 +1,801 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const { ProjectContext } = require('./context');
4
+ const {
5
+ readSnapshotIndex,
6
+ loadSnapshotPayload,
7
+ writeSnapshotArtifact,
8
+ formatSnapshotTags,
9
+ formatSnapshotMilestone,
10
+ } = require('./activity');
11
+
12
+ const COLORS = {
13
+ reset: '\x1b[0m',
14
+ bold: '\x1b[1m',
15
+ dim: '\x1b[2m',
16
+ red: '\x1b[31m',
17
+ green: '\x1b[32m',
18
+ yellow: '\x1b[33m',
19
+ blue: '\x1b[36m',
20
+ magenta: '\x1b[35m',
21
+ };
22
+
23
+ const c = (text, color) => `${COLORS[color] || ''}${text}${COLORS.reset}`;
24
+
25
+ const BEHAVIORAL_SNAPSHOT_KIND = 'behavioral-drift';
26
+ const SOURCE_EXTENSIONS = new Set([
27
+ '.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs',
28
+ '.py', '.go', '.java', '.kt', '.kts', '.cs',
29
+ '.php', '.rb', '.rs', '.swift', '.dart',
30
+ '.scala', '.lua', '.sh', '.bash',
31
+ '.c', '.cc', '.cpp', '.cxx', '.h', '.hpp',
32
+ ]);
33
+ const IGNORED_DIRS = new Set([
34
+ '.git', '.nerviq', '.next', '.nuxt', '.vercel', '.turbo',
35
+ 'node_modules', 'dist', 'build', 'coverage', 'vendor',
36
+ '__pycache__', '.venv', 'venv', 'Pods', 'DerivedData',
37
+ 'target', 'bin', 'obj',
38
+ ]);
39
+
40
+ const SCOPE_CONTRACT = {
41
+ mode: 'behavioral-drift',
42
+ optIn: true,
43
+ evidenceBased: true,
44
+ inScope: [
45
+ 'Module size distribution',
46
+ 'Utility-vs-service balance',
47
+ 'Dependency fan-out hotspots',
48
+ 'Responsibility concentration',
49
+ 'Lightweight layering-break heuristics',
50
+ 'Intent-vs-outcome mismatch against repo instruction surfaces',
51
+ ],
52
+ outOfScope: [
53
+ 'Full semantic architecture review',
54
+ 'Agent attribution without explicit evidence',
55
+ 'Runtime performance analysis',
56
+ 'Security vulnerability scanning or SAST claims',
57
+ 'Business-logic correctness',
58
+ ],
59
+ disclaimers: [
60
+ 'Behavioral drift mode is heuristic and repository-level. It highlights suspicious patterns, not absolute truth.',
61
+ 'Confidence increases when instruction surfaces explicitly state architectural intent.',
62
+ 'Large generated files, vendored code, and framework conventions can skew the signals.',
63
+ ],
64
+ confidenceGuide: {
65
+ low: 'Weak signal or sparse evidence. Treat as a prompt to inspect.',
66
+ medium: 'Multiple supporting indicators, but still heuristic.',
67
+ high: 'Clear instruction intent plus strong repository evidence.',
68
+ },
69
+ };
70
+
71
+ function safeReadDir(dir) {
72
+ try {
73
+ return fs.readdirSync(dir, { withFileTypes: true });
74
+ } catch {
75
+ return [];
76
+ }
77
+ }
78
+
79
+ function normalizeSlashes(value) {
80
+ return `${value || ''}`.replace(/\\/g, '/');
81
+ }
82
+
83
+ function lineCount(content) {
84
+ if (!content) return 0;
85
+ return content.split(/\r?\n/).length;
86
+ }
87
+
88
+ function buildFileKind(relativePath) {
89
+ const normalized = normalizeSlashes(relativePath).toLowerCase();
90
+ if (/(^|\/)(utils?|helpers?|common|shared|lib)(\/|\.|$)/.test(normalized)) return 'utility';
91
+ if (/(^|\/)(services?|controllers?|handlers?|routes?|resolvers?|repositories?|repos?)(\/|\.|$)/.test(normalized)) return 'service';
92
+ if (/(^|\/)(components?|ui|views?|screens?|pages?)(\/|\.|$)/.test(normalized)) return 'ui';
93
+ if (/(^|\/)(infra|db|database|storage|adapters?|prisma|sql|orm)(\/|\.|$)/.test(normalized)) return 'infra';
94
+ if (/(^|\/)(domain|entities?|models?)(\/|\.|$)/.test(normalized)) return 'domain';
95
+ return 'general';
96
+ }
97
+
98
+ function walkSourceFiles(rootDir, options = {}) {
99
+ const maxFiles = options.maxFiles || 400;
100
+ const maxFileBytes = options.maxFileBytes || 200 * 1024;
101
+ const files = [];
102
+ const meta = {
103
+ visitedFiles: 0,
104
+ skippedLargeFiles: 0,
105
+ skippedUnsupportedFiles: 0,
106
+ truncatedByLimit: false,
107
+ };
108
+
109
+ function visit(currentDir) {
110
+ if (files.length >= maxFiles) {
111
+ meta.truncatedByLimit = true;
112
+ return;
113
+ }
114
+
115
+ for (const entry of safeReadDir(currentDir)) {
116
+ if (files.length >= maxFiles) {
117
+ meta.truncatedByLimit = true;
118
+ return;
119
+ }
120
+
121
+ const fullPath = path.join(currentDir, entry.name);
122
+ const relativePath = path.relative(rootDir, fullPath);
123
+
124
+ if (entry.isDirectory()) {
125
+ if (IGNORED_DIRS.has(entry.name)) continue;
126
+ if (entry.name.startsWith('.') && entry.name !== '.claude' && entry.name !== '.codex') continue;
127
+ visit(fullPath);
128
+ continue;
129
+ }
130
+
131
+ if (!entry.isFile()) continue;
132
+ meta.visitedFiles += 1;
133
+
134
+ const extension = path.extname(entry.name).toLowerCase();
135
+ if (!SOURCE_EXTENSIONS.has(extension)) {
136
+ meta.skippedUnsupportedFiles += 1;
137
+ continue;
138
+ }
139
+
140
+ let stat;
141
+ try {
142
+ stat = fs.statSync(fullPath);
143
+ } catch {
144
+ continue;
145
+ }
146
+ if (stat.size > maxFileBytes) {
147
+ meta.skippedLargeFiles += 1;
148
+ continue;
149
+ }
150
+
151
+ let content;
152
+ try {
153
+ content = fs.readFileSync(fullPath, 'utf8');
154
+ } catch {
155
+ continue;
156
+ }
157
+
158
+ const lines = lineCount(content);
159
+ files.push({
160
+ path: normalizeSlashes(relativePath),
161
+ extension,
162
+ lines,
163
+ sizeBytes: stat.size,
164
+ kind: buildFileKind(relativePath),
165
+ content,
166
+ });
167
+ }
168
+ }
169
+
170
+ visit(rootDir);
171
+ return { files, meta };
172
+ }
173
+
174
+ function extractImportTargets(file) {
175
+ const targets = new Set();
176
+ const content = file.content || '';
177
+ const patterns = [
178
+ /\bfrom\s+['"]([^'"]+)['"]/g,
179
+ /\brequire\(\s*['"]([^'"]+)['"]\s*\)/g,
180
+ /\bimport\s+['"]([^'"]+)['"]/g,
181
+ /\busing\s+([A-Za-z0-9_.]+)/g,
182
+ ];
183
+
184
+ for (const pattern of patterns) {
185
+ for (const match of content.matchAll(pattern)) {
186
+ const target = (match[1] || '').trim();
187
+ if (!target) continue;
188
+ targets.add(target);
189
+ }
190
+ }
191
+
192
+ return [...targets];
193
+ }
194
+
195
+ function extractIntentEvidence(text, pattern) {
196
+ const lines = `${text || ''}`.split(/\r?\n/);
197
+ const evidence = [];
198
+ for (const line of lines) {
199
+ if (pattern.test(line)) {
200
+ evidence.push(line.trim().slice(0, 180));
201
+ if (evidence.length >= 4) break;
202
+ }
203
+ pattern.lastIndex = 0;
204
+ }
205
+ return evidence;
206
+ }
207
+
208
+ function collectIntentSignals(dir) {
209
+ const ctx = new ProjectContext(dir);
210
+ const surfaces = [];
211
+
212
+ const directFiles = ['CLAUDE.md', '.claude/CLAUDE.md', 'AGENTS.md'];
213
+ for (const filePath of directFiles) {
214
+ const content = ctx.fileContent(filePath);
215
+ if (content) surfaces.push({ filePath, content });
216
+ }
217
+
218
+ for (const folder of ['.claude/rules', '.claude/commands']) {
219
+ if (!ctx.hasDir(folder)) continue;
220
+ for (const fileName of ctx.dirFiles(folder)) {
221
+ const relativePath = normalizeSlashes(path.join(folder, fileName));
222
+ const content = ctx.fileContent(relativePath);
223
+ if (content) surfaces.push({ filePath: relativePath, content });
224
+ }
225
+ }
226
+
227
+ const joined = surfaces.map((item) => item.content).join('\n');
228
+ const intentDefinitions = [
229
+ {
230
+ key: 'small-modules',
231
+ label: 'small modules',
232
+ pattern: /(small modules?|small files?|small functions?|keep (modules?|files?) small|avoid giant files?|avoid large modules?|under \d+\s+lines?)/i,
233
+ },
234
+ {
235
+ key: 'thin-services',
236
+ label: 'thin services',
237
+ pattern: /(thin services?|service layer thin|lightweight services?|keep services? thin)/i,
238
+ },
239
+ {
240
+ key: 'avoid-utility-accretion',
241
+ label: 'avoid utility accretion',
242
+ pattern: /(avoid (fat|giant) utils?|avoid utility accretion|avoid helper dumping|don't dump .*utils?|no utility dumping)/i,
243
+ },
244
+ {
245
+ key: 'layered-architecture',
246
+ label: 'layered architecture',
247
+ pattern: /(layered architecture|controller[- /]service[- /]repository|service[- /]repository|separation of concerns|domain layer|infrastructure layer)/i,
248
+ },
249
+ {
250
+ key: 'composition-over-inheritance',
251
+ label: 'composition over inheritance',
252
+ pattern: /(composition over inheritance|prefer composition|avoid inheritance)/i,
253
+ },
254
+ ];
255
+
256
+ const detected = {};
257
+ for (const intent of intentDefinitions) {
258
+ const present = intent.pattern.test(joined);
259
+ intent.pattern.lastIndex = 0;
260
+ if (!present) continue;
261
+ const evidence = [];
262
+ for (const surface of surfaces) {
263
+ evidence.push(...extractIntentEvidence(surface.content, intent.pattern).map((line) => `${surface.filePath}: ${line}`));
264
+ intent.pattern.lastIndex = 0;
265
+ if (evidence.length >= 4) break;
266
+ }
267
+ detected[intent.key] = {
268
+ key: intent.key,
269
+ label: intent.label,
270
+ evidence: evidence.slice(0, 4),
271
+ };
272
+ }
273
+
274
+ return {
275
+ surfaces: surfaces.map((item) => item.filePath),
276
+ detected,
277
+ };
278
+ }
279
+
280
+ function calculateLayerBreaks(fileEntries) {
281
+ const examples = [];
282
+ let count = 0;
283
+
284
+ for (const file of fileEntries) {
285
+ const fileKind = file.kind;
286
+ if (!['ui', 'service', 'general'].includes(fileKind)) continue;
287
+ const imports = extractImportTargets(file);
288
+ for (const target of imports) {
289
+ const normalized = normalizeSlashes(target).toLowerCase();
290
+ const sourcePath = file.path.toLowerCase();
291
+ const suspiciousTarget = /(db|database|sql|prisma|repository|repos?|infra|storage)/.test(normalized);
292
+ const uiIntoInfra = fileKind === 'ui' && suspiciousTarget;
293
+ const routeIntoInfra = /(routes?|controllers?|pages?)/.test(sourcePath) && suspiciousTarget;
294
+ if (!uiIntoInfra && !routeIntoInfra) continue;
295
+ count += 1;
296
+ if (examples.length < 5) {
297
+ examples.push({
298
+ source: file.path,
299
+ target,
300
+ });
301
+ }
302
+ }
303
+ }
304
+
305
+ return { count, examples };
306
+ }
307
+
308
+ function buildStructuralSignals(dir, options = {}) {
309
+ const { files, meta } = walkSourceFiles(dir, options);
310
+ const totalLines = files.reduce((sum, file) => sum + file.lines, 0);
311
+ const utilityFiles = files.filter((file) => file.kind === 'utility');
312
+ const serviceFiles = files.filter((file) => file.kind === 'service');
313
+ const veryLargeFiles = files.filter((file) => file.lines >= 500).sort((a, b) => b.lines - a.lines);
314
+ const largeFiles = files.filter((file) => file.lines >= 250).sort((a, b) => b.lines - a.lines);
315
+ const importCounts = files.map((file) => ({
316
+ path: file.path,
317
+ importCount: new Set(extractImportTargets(file)).size,
318
+ kind: file.kind,
319
+ })).sort((a, b) => b.importCount - a.importCount);
320
+
321
+ const byDirectory = new Map();
322
+ for (const file of files) {
323
+ const dirKey = normalizeSlashes(path.dirname(file.path));
324
+ byDirectory.set(dirKey, (byDirectory.get(dirKey) || 0) + file.lines);
325
+ }
326
+ const directoryHotspots = [...byDirectory.entries()]
327
+ .map(([directory, lines]) => ({ directory: directory === '.' ? '(root)' : directory, lines }))
328
+ .sort((a, b) => b.lines - a.lines);
329
+ const largestDirectoryShare = totalLines > 0 && directoryHotspots[0]
330
+ ? Math.round((directoryHotspots[0].lines / totalLines) * 100)
331
+ : 0;
332
+
333
+ const utilityLines = utilityFiles.reduce((sum, file) => sum + file.lines, 0);
334
+ const serviceLines = serviceFiles.reduce((sum, file) => sum + file.lines, 0);
335
+ const layerBreaks = calculateLayerBreaks(files);
336
+
337
+ const inheritanceHits = files
338
+ .map((file) => ({
339
+ path: file.path,
340
+ count: (file.content.match(/\bextends\s+[A-Z][A-Za-z0-9_]*/g) || []).length,
341
+ }))
342
+ .filter((item) => item.count > 0)
343
+ .sort((a, b) => b.count - a.count);
344
+
345
+ return {
346
+ sourceFiles: files.length,
347
+ totalLines,
348
+ scanMeta: meta,
349
+ moduleSize: {
350
+ small: files.filter((file) => file.lines < 120).length,
351
+ medium: files.filter((file) => file.lines >= 120 && file.lines < 250).length,
352
+ large: files.filter((file) => file.lines >= 250 && file.lines < 500).length,
353
+ veryLarge: veryLargeFiles.length,
354
+ largestFiles: largeFiles.slice(0, 5).map((file) => ({
355
+ path: file.path,
356
+ lines: file.lines,
357
+ kind: file.kind,
358
+ })),
359
+ },
360
+ utilityBalance: {
361
+ utilityFiles: utilityFiles.length,
362
+ utilityLines,
363
+ utilityShare: totalLines > 0 ? Math.round((utilityLines / totalLines) * 100) : 0,
364
+ serviceFiles: serviceFiles.length,
365
+ serviceLines,
366
+ serviceShare: totalLines > 0 ? Math.round((serviceLines / totalLines) * 100) : 0,
367
+ },
368
+ dependencyFanOut: {
369
+ averageImportsPerFile: files.length > 0
370
+ ? Number((importCounts.reduce((sum, file) => sum + file.importCount, 0) / files.length).toFixed(1))
371
+ : 0,
372
+ hotspots: importCounts.filter((item) => item.importCount >= 6).slice(0, 5),
373
+ },
374
+ responsibilityConcentration: {
375
+ largestDirectoryShare,
376
+ hotspotDirectories: directoryHotspots.slice(0, 5),
377
+ },
378
+ layering: layerBreaks,
379
+ inheritance: {
380
+ count: inheritanceHits.reduce((sum, item) => sum + item.count, 0),
381
+ hotspots: inheritanceHits.slice(0, 5),
382
+ },
383
+ };
384
+ }
385
+
386
+ function buildFinding({
387
+ key,
388
+ severity,
389
+ title,
390
+ summary,
391
+ evidence = [],
392
+ whyItMatters,
393
+ suggestedNextStep,
394
+ confidence,
395
+ category,
396
+ }) {
397
+ return {
398
+ key,
399
+ severity,
400
+ title,
401
+ summary,
402
+ evidence,
403
+ whyItMatters,
404
+ suggestedNextStep,
405
+ confidence,
406
+ category,
407
+ };
408
+ }
409
+
410
+ function deriveBehavioralFindings(structuralSignals, intentSignals) {
411
+ const findings = [];
412
+ const labels = [];
413
+ const intents = intentSignals.detected || {};
414
+ const largestFile = structuralSignals.moduleSize.largestFiles[0] || null;
415
+
416
+ if (structuralSignals.moduleSize.veryLarge > 0) {
417
+ labels.push('large-module-drift');
418
+ findings.push(buildFinding({
419
+ key: 'large-module-drift',
420
+ severity: structuralSignals.moduleSize.veryLarge >= 2 ? 'high' : 'medium',
421
+ title: 'Very large modules are carrying too much responsibility',
422
+ summary: structuralSignals.moduleSize.veryLarge >= 2
423
+ ? `${structuralSignals.moduleSize.veryLarge} files are above 500 lines.`
424
+ : `${largestFile ? largestFile.path : 'A module'} is above 500 lines.`,
425
+ evidence: structuralSignals.moduleSize.largestFiles.slice(0, 3).map((file) => `${file.path} (${file.lines} lines, ${file.kind})`),
426
+ whyItMatters: 'Large modules make agent output locally coherent but globally unstable. They attract unrelated changes and hide responsibility drift.',
427
+ suggestedNextStep: 'Split the largest file by responsibility boundary and move the first extraction behind a named module boundary rather than another shared util.',
428
+ confidence: intents['small-modules'] ? 'high' : 'medium',
429
+ category: intents['small-modules'] ? 'intent-outcome-mismatch' : 'structural-signal',
430
+ }));
431
+ }
432
+
433
+ const utilityShare = structuralSignals.utilityBalance.utilityShare;
434
+ const serviceShare = structuralSignals.utilityBalance.serviceShare;
435
+ if (utilityShare >= 30 || (utilityShare >= 20 && utilityShare > serviceShare + 8)) {
436
+ labels.push('utility-gravity');
437
+ findings.push(buildFinding({
438
+ key: 'utility-gravity',
439
+ severity: utilityShare >= 35 ? 'high' : 'medium',
440
+ title: 'Utility modules are absorbing too much of the codebase',
441
+ summary: `Utility-coded files account for ${utilityShare}% of analyzed source lines while service-oriented files account for ${serviceShare}%.`,
442
+ evidence: structuralSignals.moduleSize.largestFiles
443
+ .filter((file) => file.kind === 'utility')
444
+ .slice(0, 3)
445
+ .map((file) => `${file.path} (${file.lines} lines)`),
446
+ whyItMatters: 'This is a common outcome-layer failure mode: agents keep making individually sensible helper additions until shared utility modules become the system.',
447
+ suggestedNextStep: 'Move one oversized utility cluster into a service/domain module with an explicit owner and review the import paths that currently pull it everywhere.',
448
+ confidence: intents['thin-services'] || intents['avoid-utility-accretion'] ? 'high' : 'medium',
449
+ category: (intents['thin-services'] || intents['avoid-utility-accretion']) ? 'intent-outcome-mismatch' : 'structural-signal',
450
+ }));
451
+ }
452
+
453
+ if (structuralSignals.layering.count > 0) {
454
+ labels.push('layering-erosion');
455
+ findings.push(buildFinding({
456
+ key: 'layering-erosion',
457
+ severity: structuralSignals.layering.count >= 3 ? 'high' : 'medium',
458
+ title: 'Layer boundaries show direct reach-through imports',
459
+ summary: `${structuralSignals.layering.count} imports cross directly into infra/data paths from UI or route/controller surfaces.`,
460
+ evidence: structuralSignals.layering.examples.map((item) => `${item.source} -> ${item.target}`),
461
+ whyItMatters: 'Even when configs align, architecture can still drift if top-layer files start reaching into storage or infra directly.',
462
+ suggestedNextStep: 'Insert a service/domain seam for the first direct infra import and make routes or UI files depend on that seam instead of database/storage modules.',
463
+ confidence: intents['layered-architecture'] ? 'high' : 'medium',
464
+ category: intents['layered-architecture'] ? 'intent-outcome-mismatch' : 'structural-signal',
465
+ }));
466
+ }
467
+
468
+ if (structuralSignals.responsibilityConcentration.largestDirectoryShare >= 60) {
469
+ labels.push('responsibility-concentration');
470
+ findings.push(buildFinding({
471
+ key: 'responsibility-concentration',
472
+ severity: structuralSignals.responsibilityConcentration.largestDirectoryShare >= 75 ? 'high' : 'medium',
473
+ title: 'One directory is carrying most of the code volume',
474
+ summary: `${structuralSignals.responsibilityConcentration.hotspotDirectories[0]?.directory || '(root)'} holds ${structuralSignals.responsibilityConcentration.largestDirectoryShare}% of analyzed source lines.`,
475
+ evidence: structuralSignals.responsibilityConcentration.hotspotDirectories.slice(0, 3).map((item) => `${item.directory} (${item.lines} lines)`),
476
+ whyItMatters: 'Responsibility concentration is often an early sign that new work is being absorbed into the easiest existing location instead of the right boundary.',
477
+ suggestedNextStep: 'Pick one hotspot directory and document the modules that should no longer accept unrelated changes before the next agent-heavy batch lands.',
478
+ confidence: 'medium',
479
+ category: 'structural-signal',
480
+ }));
481
+ }
482
+
483
+ if (intents['composition-over-inheritance'] && structuralSignals.inheritance.count >= 3) {
484
+ labels.push('inheritance-drift');
485
+ findings.push(buildFinding({
486
+ key: 'inheritance-drift',
487
+ severity: structuralSignals.inheritance.count >= 6 ? 'medium' : 'low',
488
+ title: 'Inheritance usage is drifting against the stated composition preference',
489
+ summary: `${structuralSignals.inheritance.count} inheritance markers were found in analyzed files.`,
490
+ evidence: structuralSignals.inheritance.hotspots.map((item) => `${item.path} (${item.count} extends)`),
491
+ whyItMatters: 'This is a classic intent-vs-outcome mismatch: the repo says one thing, but incremental agent edits normalize another pattern.',
492
+ suggestedNextStep: 'Review the hottest inheritance chain and convert the next new behavior to composition before the pattern spreads further.',
493
+ confidence: 'high',
494
+ category: 'intent-outcome-mismatch',
495
+ }));
496
+ }
497
+
498
+ return {
499
+ findings,
500
+ labels: [...new Set(labels)],
501
+ };
502
+ }
503
+
504
+ function buildBehavioralScore(structuralSignals, findings) {
505
+ let score = 100;
506
+
507
+ const largePenalty = Math.min(22, structuralSignals.moduleSize.veryLarge * 8);
508
+ const utilityPenalty = structuralSignals.utilityBalance.utilityShare >= 35
509
+ ? 16
510
+ : structuralSignals.utilityBalance.utilityShare >= 25
511
+ ? 8
512
+ : 0;
513
+ const layeringPenalty = Math.min(18, structuralSignals.layering.count * 5);
514
+ const concentrationPenalty = structuralSignals.responsibilityConcentration.largestDirectoryShare >= 70
515
+ ? 12
516
+ : structuralSignals.responsibilityConcentration.largestDirectoryShare >= 60
517
+ ? 6
518
+ : 0;
519
+
520
+ score -= largePenalty + utilityPenalty + layeringPenalty + concentrationPenalty;
521
+
522
+ for (const finding of findings) {
523
+ if (finding.severity === 'high') score -= 10;
524
+ else if (finding.severity === 'medium') score -= 6;
525
+ else if (finding.severity === 'low') score -= 3;
526
+ }
527
+
528
+ return Math.max(0, Math.min(100, score));
529
+ }
530
+
531
+ function buildBehavioralNextSteps(findings) {
532
+ return findings.slice(0, 3).map((finding) => ({
533
+ key: finding.key,
534
+ title: finding.title,
535
+ action: finding.suggestedNextStep,
536
+ confidence: finding.confidence,
537
+ }));
538
+ }
539
+
540
+ function getBehavioralHistory(dir, limit = 10) {
541
+ return readSnapshotIndex(dir)
542
+ .filter((entry) => entry.snapshotKind === BEHAVIORAL_SNAPSHOT_KIND)
543
+ .sort((a, b) => {
544
+ const dateDiff = new Date(b.createdAt) - new Date(a.createdAt);
545
+ if (dateDiff !== 0) return dateDiff;
546
+ return (b.id || '').localeCompare(a.id || '');
547
+ })
548
+ .slice(0, limit);
549
+ }
550
+
551
+ function loadBehavioralSnapshotPayload(dir, entry) {
552
+ const payload = loadSnapshotPayload(dir, entry);
553
+ return payload && payload.mode === 'behavioral-drift' ? payload : null;
554
+ }
555
+
556
+ function compareBehavioralLatest(dir) {
557
+ const history = getBehavioralHistory(dir, 2);
558
+ if (history.length < 2) return null;
559
+
560
+ const current = history[0];
561
+ const previous = history[1];
562
+ const currentPayload = loadBehavioralSnapshotPayload(dir, current);
563
+ const previousPayload = loadBehavioralSnapshotPayload(dir, previous);
564
+ if (!currentPayload || !previousPayload) return null;
565
+
566
+ const currentKeys = new Set((currentPayload.findings || []).map((item) => item.key));
567
+ const previousKeys = new Set((previousPayload.findings || []).map((item) => item.key));
568
+
569
+ return {
570
+ scoreType: 'behavioral-alignment-score',
571
+ current: {
572
+ date: current.createdAt,
573
+ score: current.summary?.score ?? currentPayload.score,
574
+ findingCount: current.summary?.findingCount ?? currentPayload.findings.length,
575
+ tags: current.tags || [],
576
+ milestone: current.milestone || null,
577
+ },
578
+ previous: {
579
+ date: previous.createdAt,
580
+ score: previous.summary?.score ?? previousPayload.score,
581
+ findingCount: previous.summary?.findingCount ?? previousPayload.findings.length,
582
+ tags: previous.tags || [],
583
+ milestone: previous.milestone || null,
584
+ },
585
+ delta: {
586
+ score: (current.summary?.score ?? currentPayload.score ?? 0) - (previous.summary?.score ?? previousPayload.score ?? 0),
587
+ findings: (current.summary?.findingCount ?? currentPayload.findings.length) - (previous.summary?.findingCount ?? previousPayload.findings.length),
588
+ },
589
+ regressions: [...currentKeys].filter((key) => !previousKeys.has(key)),
590
+ resolved: [...previousKeys].filter((key) => !currentKeys.has(key)),
591
+ trend: (current.summary?.score ?? currentPayload.score ?? 0) > (previous.summary?.score ?? previousPayload.score ?? 0)
592
+ ? 'improving'
593
+ : (current.summary?.score ?? currentPayload.score ?? 0) < (previous.summary?.score ?? previousPayload.score ?? 0)
594
+ ? 'regressing'
595
+ : 'stable',
596
+ };
597
+ }
598
+
599
+ function formatBehavioralBootstrap(dir, goal = 'report') {
600
+ const historyCount = getBehavioralHistory(dir, 20).length;
601
+ const lines = [];
602
+
603
+ if (goal === 'history') {
604
+ lines.push(historyCount === 0
605
+ ? 'No behavioral drift snapshots found yet.'
606
+ : 'Behavioral drift history exists, but compare still needs one more snapshot.');
607
+ } else {
608
+ lines.push(historyCount === 0
609
+ ? 'Behavioral compare needs 2 behavioral snapshots.'
610
+ : 'Behavioral compare needs one more behavioral snapshot.');
611
+ }
612
+
613
+ lines.push(` Current state: ${historyCount} behavioral snapshot(s).`);
614
+ lines.push(' Bootstrap it with:');
615
+ lines.push(' 1. Run `nerviq deep-review --behavioral --snapshot --milestone baseline --tag "behavioral-baseline"`.');
616
+ lines.push(' 2. Make a meaningful architectural or workflow change.');
617
+ lines.push(' 3. Run `nerviq deep-review --behavioral --snapshot --milestone release --tag "after-change"`.');
618
+ lines.push(goal === 'history'
619
+ ? ' Then rerun `nerviq deep-review --behavioral --history`.'
620
+ : ' Then rerun `nerviq deep-review --behavioral --compare`.');
621
+ return lines.join('\n');
622
+ }
623
+
624
+ function formatBehavioralHistory(dir) {
625
+ const history = getBehavioralHistory(dir, 10);
626
+ if (history.length === 0) return formatBehavioralBootstrap(dir, 'history');
627
+
628
+ const lines = [
629
+ 'Behavioral drift snapshot history (most recent first):',
630
+ ' Score type: behavioral alignment snapshots only.',
631
+ '',
632
+ ];
633
+
634
+ for (const entry of history) {
635
+ const date = entry.createdAt?.split('T')[0] || '?';
636
+ const score = entry.summary?.score ?? '?';
637
+ const findingCount = entry.summary?.findingCount ?? '?';
638
+ lines.push(` ${date} snapshot${formatSnapshotMilestone(entry.milestone)}${formatSnapshotTags(entry.tags)} ${score}/100 (${findingCount} findings)`);
639
+ }
640
+
641
+ const comparison = compareBehavioralLatest(dir);
642
+ if (comparison) {
643
+ lines.push('');
644
+ lines.push(` Latest snapshot trend: ${comparison.trend} (${comparison.delta.score >= 0 ? '+' : ''}${comparison.delta.score} since previous snapshot)`);
645
+ if (comparison.resolved.length > 0) {
646
+ lines.push(` Resolved drift labels: ${comparison.resolved.join(', ')}`);
647
+ }
648
+ if (comparison.regressions.length > 0) {
649
+ lines.push(` New drift labels: ${comparison.regressions.join(', ')}`);
650
+ }
651
+ }
652
+
653
+ if (history.length === 1) {
654
+ lines.push('');
655
+ lines.push(formatBehavioralBootstrap(dir, 'history'));
656
+ }
657
+
658
+ return lines.join('\n');
659
+ }
660
+
661
+ function formatBehavioralCompare(dir) {
662
+ const comparison = compareBehavioralLatest(dir);
663
+ if (!comparison) return formatBehavioralBootstrap(dir, 'compare');
664
+
665
+ const lines = [
666
+ 'Behavioral drift comparison:',
667
+ ` Previous snapshot: ${comparison.previous.score}/100 (${comparison.previous.date?.split('T')[0]})${formatSnapshotMilestone(comparison.previous.milestone)}${formatSnapshotTags(comparison.previous.tags)}`,
668
+ ` Current snapshot: ${comparison.current.score}/100 (${comparison.current.date?.split('T')[0]})${formatSnapshotMilestone(comparison.current.milestone)}${formatSnapshotTags(comparison.current.tags)}`,
669
+ ` Alignment delta: ${comparison.delta.score >= 0 ? '+' : ''}${comparison.delta.score} points`,
670
+ ` Finding delta: ${comparison.delta.findings >= 0 ? '+' : ''}${comparison.delta.findings} findings`,
671
+ ` Trend: ${comparison.trend}`,
672
+ ];
673
+
674
+ if (comparison.resolved.length > 0) {
675
+ lines.push(` Resolved drift labels: ${comparison.resolved.join(', ')}`);
676
+ }
677
+ if (comparison.regressions.length > 0) {
678
+ lines.push(` New drift labels: ${comparison.regressions.join(', ')}`);
679
+ }
680
+
681
+ return lines.join('\n');
682
+ }
683
+
684
+ function analyzeBehavioralDrift(dir, options = {}) {
685
+ const structuralSignals = buildStructuralSignals(dir, options);
686
+ const intentSignals = collectIntentSignals(dir);
687
+ const { findings, labels } = deriveBehavioralFindings(structuralSignals, intentSignals);
688
+ const score = buildBehavioralScore(structuralSignals, findings);
689
+
690
+ return {
691
+ mode: 'behavioral-drift',
692
+ scoreType: 'behavioral-alignment-score',
693
+ score,
694
+ scope: SCOPE_CONTRACT,
695
+ repoSummary: {
696
+ project: path.basename(dir),
697
+ sourceFiles: structuralSignals.sourceFiles,
698
+ totalLines: structuralSignals.totalLines,
699
+ instructionSurfaces: intentSignals.surfaces,
700
+ scanMeta: structuralSignals.scanMeta,
701
+ },
702
+ structuralSignals,
703
+ intentSignals,
704
+ driftLabels: labels,
705
+ findings,
706
+ nextSteps: buildBehavioralNextSteps(findings),
707
+ };
708
+ }
709
+
710
+ function writeBehavioralSnapshot(dir, report, meta = {}) {
711
+ return writeSnapshotArtifact(dir, BEHAVIORAL_SNAPSHOT_KIND, report, meta);
712
+ }
713
+
714
+ function formatBehavioralReport(report, options = {}) {
715
+ const lines = [];
716
+ const scoreColor = report.score >= 75 ? 'green' : report.score >= 55 ? 'yellow' : 'red';
717
+
718
+ lines.push('');
719
+ lines.push(c(' nerviq behavioral drift review', 'bold'));
720
+ lines.push(c(' ═══════════════════════════════════════', 'dim'));
721
+ lines.push(c(` Alignment score: ${report.score}/100`, scoreColor));
722
+ lines.push(c(' Opt-in local heuristics only. No source code leaves the machine.', 'dim'));
723
+ lines.push('');
724
+
725
+ lines.push(c(' Scope', 'bold'));
726
+ lines.push(` In scope: ${report.scope.inScope.slice(0, 3).join('; ')}.`);
727
+ lines.push(` Out of scope: ${report.scope.outOfScope.slice(0, 3).join('; ')}.`);
728
+ lines.push('');
729
+
730
+ lines.push(c(' Structural Signals', 'bold'));
731
+ lines.push(` Source files analyzed: ${report.repoSummary.sourceFiles}`);
732
+ lines.push(` Very large files (500+ lines): ${report.structuralSignals.moduleSize.veryLarge}`);
733
+ lines.push(` Utility share: ${report.structuralSignals.utilityBalance.utilityShare}% | Service share: ${report.structuralSignals.utilityBalance.serviceShare}%`);
734
+ lines.push(` Layer-break imports: ${report.structuralSignals.layering.count}`);
735
+ lines.push(` Largest directory share: ${report.structuralSignals.responsibilityConcentration.largestDirectoryShare}%`);
736
+ if (report.structuralSignals.moduleSize.largestFiles.length > 0) {
737
+ lines.push(` Largest file: ${report.structuralSignals.moduleSize.largestFiles[0].path} (${report.structuralSignals.moduleSize.largestFiles[0].lines} lines)`);
738
+ }
739
+ lines.push('');
740
+
741
+ lines.push(c(' Intent Signals', 'bold'));
742
+ if (Object.keys(report.intentSignals.detected).length === 0) {
743
+ lines.push(' No explicit architectural intent was detected in instruction surfaces.');
744
+ } else {
745
+ for (const signal of Object.values(report.intentSignals.detected)) {
746
+ lines.push(` - ${signal.label}`);
747
+ for (const evidence of signal.evidence.slice(0, 2)) {
748
+ lines.push(` Evidence: ${evidence}`);
749
+ }
750
+ }
751
+ }
752
+ lines.push('');
753
+
754
+ lines.push(c(' Findings', 'bold'));
755
+ if (report.findings.length === 0) {
756
+ lines.push(c(' ✅ No clear behavioral drift signals found in the sampled source set.', 'green'));
757
+ } else {
758
+ for (const finding of report.findings) {
759
+ const severityColor = finding.severity === 'high' ? 'red' : finding.severity === 'medium' ? 'yellow' : 'blue';
760
+ lines.push(c(` [${finding.severity.toUpperCase()}] ${finding.title}`, severityColor));
761
+ lines.push(` ${finding.summary}`);
762
+ lines.push(` Why: ${finding.whyItMatters}`);
763
+ lines.push(` Confidence: ${finding.confidence}`);
764
+ if (finding.evidence.length > 0) {
765
+ lines.push(` Evidence: ${finding.evidence[0]}`);
766
+ }
767
+ lines.push(` Next: ${finding.suggestedNextStep}`);
768
+ }
769
+ }
770
+ lines.push('');
771
+
772
+ lines.push(c(' Guardrails', 'bold'));
773
+ for (const disclaimer of report.scope.disclaimers) {
774
+ lines.push(` - ${disclaimer}`);
775
+ }
776
+
777
+ if (options.snapshotArtifact) {
778
+ lines.push('');
779
+ lines.push(` Snapshot saved: ${options.snapshotArtifact.relativePath}`);
780
+ lines.push(` Snapshot index: ${options.snapshotArtifact.indexPath}`);
781
+ }
782
+
783
+ lines.push('');
784
+ return lines.join('\n');
785
+ }
786
+
787
+ module.exports = {
788
+ BEHAVIORAL_SNAPSHOT_KIND,
789
+ SCOPE_CONTRACT,
790
+ analyzeBehavioralDrift,
791
+ buildStructuralSignals,
792
+ collectIntentSignals,
793
+ deriveBehavioralFindings,
794
+ getBehavioralHistory,
795
+ compareBehavioralLatest,
796
+ formatBehavioralBootstrap,
797
+ formatBehavioralHistory,
798
+ formatBehavioralCompare,
799
+ formatBehavioralReport,
800
+ writeBehavioralSnapshot,
801
+ };