@nerviq/cli 1.20.0 → 1.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (185) hide show
  1. package/LICENSE +23 -23
  2. package/README.md +2 -2
  3. package/bin/cli.js +1 -0
  4. package/package.json +2 -1
  5. package/src/activity.js +1039 -1039
  6. package/src/adoption-advisor.js +299 -299
  7. package/src/aider/config-parser.js +166 -166
  8. package/src/aider/context.js +6 -2
  9. package/src/aider/deep-review.js +316 -316
  10. package/src/aider/domain-packs.js +303 -303
  11. package/src/aider/freshness.js +93 -93
  12. package/src/aider/governance.js +253 -253
  13. package/src/aider/interactive.js +334 -334
  14. package/src/aider/mcp-packs.js +329 -329
  15. package/src/aider/patch.js +214 -214
  16. package/src/aider/plans.js +186 -186
  17. package/src/aider/premium.js +360 -360
  18. package/src/aider/setup.js +404 -404
  19. package/src/aider/techniques.js +312 -67
  20. package/src/analyze.js +951 -951
  21. package/src/anti-patterns.js +485 -485
  22. package/src/audit/instruction-files.js +180 -180
  23. package/src/audit/recommendations.js +577 -577
  24. package/src/auto-suggest.js +154 -154
  25. package/src/badge.js +13 -13
  26. package/src/behavioral-drift.js +801 -801
  27. package/src/benchmark.js +67 -67
  28. package/src/catalog.js +103 -103
  29. package/src/certification.js +128 -128
  30. package/src/codex/config-parser.js +183 -183
  31. package/src/codex/context.js +223 -223
  32. package/src/codex/deep-review.js +493 -493
  33. package/src/codex/domain-packs.js +394 -394
  34. package/src/codex/freshness.js +84 -84
  35. package/src/codex/governance.js +192 -192
  36. package/src/codex/interactive.js +618 -618
  37. package/src/codex/mcp-packs.js +914 -914
  38. package/src/codex/patch.js +209 -209
  39. package/src/codex/plans.js +251 -251
  40. package/src/codex/premium.js +614 -614
  41. package/src/codex/setup.js +591 -591
  42. package/src/context.js +10 -4
  43. package/src/continuous-ops.js +681 -681
  44. package/src/copilot/activity.js +309 -309
  45. package/src/copilot/deep-review.js +346 -346
  46. package/src/copilot/domain-packs.js +372 -372
  47. package/src/copilot/freshness.js +57 -57
  48. package/src/copilot/governance.js +222 -222
  49. package/src/copilot/interactive.js +406 -406
  50. package/src/copilot/mcp-packs.js +826 -826
  51. package/src/copilot/plans.js +253 -253
  52. package/src/copilot/premium.js +451 -451
  53. package/src/copilot/setup.js +488 -488
  54. package/src/cost-tracking.js +61 -61
  55. package/src/cursor/activity.js +301 -301
  56. package/src/cursor/config-parser.js +265 -265
  57. package/src/cursor/context.js +256 -256
  58. package/src/cursor/deep-review.js +334 -334
  59. package/src/cursor/domain-packs.js +368 -368
  60. package/src/cursor/freshness.js +65 -65
  61. package/src/cursor/governance.js +229 -229
  62. package/src/cursor/interactive.js +391 -391
  63. package/src/cursor/mcp-packs.js +828 -828
  64. package/src/cursor/plans.js +254 -254
  65. package/src/cursor/premium.js +469 -469
  66. package/src/cursor/setup.js +488 -488
  67. package/src/dashboard.js +493 -493
  68. package/src/deep-review.js +428 -428
  69. package/src/deprecation.js +98 -98
  70. package/src/diff-only.js +280 -280
  71. package/src/doctor.js +119 -119
  72. package/src/domain-pack-expansion.js +1033 -1033
  73. package/src/domain-packs.js +387 -387
  74. package/src/feedback.js +178 -178
  75. package/src/fix-engine.js +783 -783
  76. package/src/fix-prompts.js +122 -122
  77. package/src/formatters/sarif.js +115 -115
  78. package/src/freshness.js +74 -74
  79. package/src/gemini/config-parser.js +275 -275
  80. package/src/gemini/deep-review.js +559 -559
  81. package/src/gemini/domain-packs.js +393 -393
  82. package/src/gemini/freshness.js +66 -66
  83. package/src/gemini/governance.js +201 -201
  84. package/src/gemini/interactive.js +860 -860
  85. package/src/gemini/mcp-packs.js +915 -915
  86. package/src/gemini/plans.js +269 -269
  87. package/src/gemini/premium.js +760 -760
  88. package/src/gemini/setup.js +692 -692
  89. package/src/governance.js +72 -72
  90. package/src/harmony/add.js +68 -68
  91. package/src/harmony/advisor.js +333 -333
  92. package/src/harmony/canon.js +565 -565
  93. package/src/harmony/cli.js +591 -591
  94. package/src/harmony/drift.js +401 -401
  95. package/src/harmony/governance.js +313 -313
  96. package/src/harmony/memory.js +239 -239
  97. package/src/harmony/sync.js +475 -475
  98. package/src/harmony/watch.js +370 -370
  99. package/src/hook-validation.js +342 -342
  100. package/src/index.js +271 -271
  101. package/src/init.js +184 -184
  102. package/src/instruction-surfaces.js +185 -185
  103. package/src/integrations.js +144 -144
  104. package/src/interactive.js +118 -118
  105. package/src/locales/en.json +1 -1
  106. package/src/locales/es.json +1 -1
  107. package/src/mcp-packs.js +830 -830
  108. package/src/mcp-server.js +726 -726
  109. package/src/mcp-validation.js +337 -337
  110. package/src/nerviq-sync.json +7 -7
  111. package/src/opencode/config-parser.js +109 -109
  112. package/src/opencode/context.js +247 -247
  113. package/src/opencode/deep-review.js +313 -313
  114. package/src/opencode/domain-packs.js +262 -262
  115. package/src/opencode/freshness.js +66 -66
  116. package/src/opencode/governance.js +159 -159
  117. package/src/opencode/interactive.js +392 -392
  118. package/src/opencode/mcp-packs.js +705 -705
  119. package/src/opencode/patch.js +184 -184
  120. package/src/opencode/plans.js +231 -231
  121. package/src/opencode/premium.js +413 -413
  122. package/src/opencode/setup.js +449 -449
  123. package/src/opencode/techniques.js +27 -27
  124. package/src/operating-profile.js +574 -574
  125. package/src/org.js +152 -152
  126. package/src/permission-rules.js +218 -218
  127. package/src/plans.js +839 -839
  128. package/src/platform-change-manifest.js +86 -86
  129. package/src/plugins.js +110 -110
  130. package/src/policy-layers.js +210 -210
  131. package/src/profiles.js +124 -124
  132. package/src/prompt-injection.js +74 -74
  133. package/src/public-api.js +173 -173
  134. package/src/recommendation-rules.js +84 -84
  135. package/src/repo-archetype.js +386 -386
  136. package/src/secret-patterns.js +39 -39
  137. package/src/server.js +527 -527
  138. package/src/setup/analysis.js +607 -607
  139. package/src/setup/runtime.js +172 -172
  140. package/src/setup.js +677 -677
  141. package/src/shared/capabilities.js +194 -194
  142. package/src/source-urls.js +132 -132
  143. package/src/stack-checks.js +565 -565
  144. package/src/supplemental-checks.js +13 -13
  145. package/src/synergy/adaptive.js +261 -261
  146. package/src/synergy/compensation.js +137 -137
  147. package/src/synergy/evidence.js +193 -193
  148. package/src/synergy/learning.js +199 -199
  149. package/src/synergy/patterns.js +227 -227
  150. package/src/synergy/ranking.js +83 -83
  151. package/src/synergy/report.js +165 -165
  152. package/src/synergy/routing.js +146 -146
  153. package/src/techniques/api.js +407 -407
  154. package/src/techniques/automation.js +316 -316
  155. package/src/techniques/compliance.js +257 -257
  156. package/src/techniques/hygiene.js +294 -294
  157. package/src/techniques/instructions.js +243 -243
  158. package/src/techniques/observability.js +226 -226
  159. package/src/techniques/optimization.js +142 -142
  160. package/src/techniques/quality.js +318 -318
  161. package/src/techniques/security.js +237 -237
  162. package/src/techniques/shared.js +443 -443
  163. package/src/techniques/stacks.js +2294 -2294
  164. package/src/techniques/tools.js +106 -106
  165. package/src/techniques/workflow.js +413 -413
  166. package/src/techniques.js +81 -81
  167. package/src/terminology.js +73 -73
  168. package/src/token-estimate.js +35 -35
  169. package/src/usage-patterns.js +99 -99
  170. package/src/verification-metadata.js +145 -145
  171. package/src/watch.js +247 -247
  172. package/src/windsurf/activity.js +302 -302
  173. package/src/windsurf/config-parser.js +267 -267
  174. package/src/windsurf/context.js +120 -10
  175. package/src/windsurf/deep-review.js +337 -337
  176. package/src/windsurf/domain-packs.js +370 -370
  177. package/src/windsurf/freshness.js +36 -36
  178. package/src/windsurf/governance.js +231 -231
  179. package/src/windsurf/interactive.js +388 -388
  180. package/src/windsurf/mcp-packs.js +792 -792
  181. package/src/windsurf/plans.js +247 -247
  182. package/src/windsurf/premium.js +468 -468
  183. package/src/windsurf/setup.js +471 -471
  184. package/src/windsurf/techniques.js +155 -33
  185. package/src/workspace.js +375 -375
@@ -1,681 +1,681 @@
1
- 'use strict';
2
-
3
- const fs = require('fs');
4
- const path = require('path');
5
- const { version } = require('../package.json');
6
- const {
7
- ensureProjectStateDir,
8
- resolveProjectStateReadPath,
9
- resolveProjectStatePath,
10
- } = require('./state-paths');
11
-
12
- const WATCH_CLASS_DEFS = {
13
- 'config-drift': {
14
- key: 'config-drift',
15
- label: 'Config drift',
16
- disposition: 'block',
17
- description: 'Repo instructions, config, hooks, rules, or verification surfaces drifted away from the managed baseline.',
18
- },
19
- 'policy-drift': {
20
- key: 'policy-drift',
21
- label: 'Policy drift',
22
- disposition: 'block',
23
- description: 'Safety, permissions, secrets, or trust controls drifted and should be treated as blocking.',
24
- },
25
- 'platform-drift': {
26
- key: 'platform-drift',
27
- label: 'Platform drift',
28
- disposition: 'warn',
29
- description: 'The active tool/platform posture changed and should be reviewed before it silently alters repo behavior.',
30
- },
31
- 'maturity-opportunity': {
32
- key: 'maturity-opportunity',
33
- label: 'Maturity opportunity',
34
- disposition: 'suggest',
35
- description: 'A safe improvement is available, but it should not block delivery.',
36
- },
37
- };
38
-
39
- const CONTINUOUS_CLASS_ORDER = ['policy-drift', 'config-drift', 'platform-drift', 'maturity-opportunity'];
40
- const CONTINUOUS_DISPOSITION_ORDER = { block: 3, warn: 2, suggest: 1 };
41
- const IMPACT_ORDER = { critical: 4, high: 3, medium: 2, low: 1 };
42
- const EXCEPTION_SCOPES = ['all', 'ci', 'watch', 'pr'];
43
-
44
- const MANAGED_BASELINE_DIR = 'managed';
45
- const EXCEPTIONS_DIR = 'exceptions';
46
- const MANAGED_BASELINE_FILE = 'baseline.json';
47
- const EXCEPTIONS_INDEX_FILE = 'index.json';
48
-
49
- const POLICY_CATEGORIES = new Set(['security', 'trust']);
50
- const CONFIG_CATEGORIES = new Set([
51
- 'memory',
52
- 'instructions',
53
- 'config',
54
- 'rules',
55
- 'hooks',
56
- 'workflow',
57
- 'automation',
58
- 'quality',
59
- 'quality-deep',
60
- 'git',
61
- 'tools',
62
- 'mcp',
63
- 'local',
64
- 'review',
65
- 'hygiene',
66
- 'devops',
67
- ]);
68
- const PLATFORM_CATEGORIES = new Set(['features', 'freshness']);
69
- const MATURITY_CATEGORIES = new Set(['skills', 'agents', 'design', 'performance', 'prompting']);
70
-
71
- function timestampId() {
72
- return new Date().toISOString().replace(/[:.]/g, '-');
73
- }
74
-
75
- function writeJson(filePath, payload) {
76
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
77
- fs.writeFileSync(filePath, JSON.stringify(payload, null, 2), 'utf8');
78
- }
79
-
80
- function readJsonSafe(filePath) {
81
- if (!fs.existsSync(filePath)) return null;
82
- try {
83
- return JSON.parse(fs.readFileSync(filePath, 'utf8'));
84
- } catch {
85
- return null;
86
- }
87
- }
88
-
89
- function ensureManagedDir(dir) {
90
- return ensureProjectStateDir(dir, MANAGED_BASELINE_DIR);
91
- }
92
-
93
- function ensureExceptionsDir(dir) {
94
- return ensureProjectStateDir(dir, EXCEPTIONS_DIR);
95
- }
96
-
97
- function getManagedBaselinePath(dir) {
98
- return resolveProjectStatePath(dir, MANAGED_BASELINE_DIR, MANAGED_BASELINE_FILE);
99
- }
100
-
101
- function getExceptionsIndexPath(dir) {
102
- return resolveProjectStatePath(dir, EXCEPTIONS_DIR, EXCEPTIONS_INDEX_FILE);
103
- }
104
-
105
- function normalizeExceptionScope(value) {
106
- const normalized = `${value || 'all'}`.trim().toLowerCase();
107
- if (!EXCEPTION_SCOPES.includes(normalized)) {
108
- throw new Error(`exception scope must be one of: ${EXCEPTION_SCOPES.join(', ')}`);
109
- }
110
- return normalized;
111
- }
112
-
113
- function normalizeExpiry(value) {
114
- const raw = `${value || ''}`.trim();
115
- if (!raw) {
116
- throw new Error('exception expires value is required');
117
- }
118
-
119
- const date = new Date(raw);
120
- if (Number.isNaN(date.getTime())) {
121
- throw new Error('exception expires must be a valid ISO date or date-time');
122
- }
123
-
124
- return date.toISOString();
125
- }
126
-
127
- function isExpired(record, now = new Date()) {
128
- if (!record || !record.expiresAt) return false;
129
- const expiry = new Date(record.expiresAt);
130
- if (Number.isNaN(expiry.getTime())) return false;
131
- return expiry.getTime() < now.getTime();
132
- }
133
-
134
- function getExceptionStatus(record, now = new Date()) {
135
- return isExpired(record, now) ? 'expired' : 'active';
136
- }
137
-
138
- function normalizeExceptionRecord(record, now = new Date()) {
139
- if (!record || typeof record !== 'object') return null;
140
- return {
141
- ...record,
142
- scope: normalizeExceptionScope(record.scope || 'all'),
143
- status: getExceptionStatus(record, now),
144
- };
145
- }
146
-
147
- function readManagedBaseline(dir) {
148
- const filePath = resolveProjectStateReadPath(dir, MANAGED_BASELINE_DIR, MANAGED_BASELINE_FILE);
149
- const payload = readJsonSafe(filePath);
150
- return payload && typeof payload === 'object' ? payload : null;
151
- }
152
-
153
- function writeManagedBaseline(dir, payload) {
154
- ensureManagedDir(dir);
155
- const filePath = getManagedBaselinePath(dir);
156
- writeJson(filePath, payload);
157
- return {
158
- filePath,
159
- relativePath: path.relative(dir, filePath),
160
- payload,
161
- };
162
- }
163
-
164
- function listExceptions(dir, now = new Date()) {
165
- const filePath = resolveProjectStateReadPath(dir, EXCEPTIONS_DIR, EXCEPTIONS_INDEX_FILE);
166
- const entries = readJsonSafe(filePath);
167
- if (!Array.isArray(entries)) return [];
168
- return entries
169
- .map((record) => normalizeExceptionRecord(record, now))
170
- .filter(Boolean)
171
- .sort((a, b) => new Date(a.createdAt || 0) - new Date(b.createdAt || 0));
172
- }
173
-
174
- function writeExceptions(dir, records) {
175
- ensureExceptionsDir(dir);
176
- const filePath = getExceptionsIndexPath(dir);
177
- writeJson(filePath, records);
178
- return {
179
- filePath,
180
- relativePath: path.relative(dir, filePath),
181
- };
182
- }
183
-
184
- function addException(dir, payload, now = new Date()) {
185
- const key = `${payload.key || ''}`.trim();
186
- const watchClass = `${payload.watchClass || ''}`.trim().toLowerCase();
187
- if (!key && !watchClass) {
188
- throw new Error('exception add requires --key or --class');
189
- }
190
- if (watchClass && !WATCH_CLASS_DEFS[watchClass]) {
191
- throw new Error(`exception class must be one of: ${Object.keys(WATCH_CLASS_DEFS).join(', ')}`);
192
- }
193
-
194
- const owner = `${payload.owner || ''}`.trim();
195
- const reason = `${payload.reason || ''}`.trim();
196
- if (!owner) throw new Error('exception add requires --owner');
197
- if (!reason) throw new Error('exception add requires --reason');
198
-
199
- const record = {
200
- id: timestampId(),
201
- createdAt: now.toISOString(),
202
- createdBy: payload.createdBy || 'unknown:unknown',
203
- key: key || null,
204
- watchClass: watchClass || null,
205
- scope: normalizeExceptionScope(payload.scope || 'all'),
206
- owner,
207
- reason,
208
- expiresAt: normalizeExpiry(payload.expiresAt),
209
- };
210
-
211
- const records = listExceptions(dir, now).map((item) => ({
212
- id: item.id,
213
- createdAt: item.createdAt,
214
- createdBy: item.createdBy,
215
- key: item.key || null,
216
- watchClass: item.watchClass || null,
217
- scope: item.scope || 'all',
218
- owner: item.owner,
219
- reason: item.reason,
220
- expiresAt: item.expiresAt,
221
- }));
222
- records.push(record);
223
- const writeResult = writeExceptions(dir, records);
224
- return {
225
- record: normalizeExceptionRecord(record, now),
226
- ...writeResult,
227
- };
228
- }
229
-
230
- function pruneExpiredExceptions(dir, now = new Date()) {
231
- const records = listExceptions(dir, now);
232
- const kept = records.filter((record) => record.status !== 'expired').map((item) => ({
233
- id: item.id,
234
- createdAt: item.createdAt,
235
- createdBy: item.createdBy,
236
- key: item.key || null,
237
- watchClass: item.watchClass || null,
238
- scope: item.scope || 'all',
239
- owner: item.owner,
240
- reason: item.reason,
241
- expiresAt: item.expiresAt,
242
- }));
243
- const expired = records.filter((record) => record.status === 'expired');
244
- const writeResult = writeExceptions(dir, kept);
245
- return {
246
- removedCount: expired.length,
247
- keptCount: kept.length,
248
- removed: expired,
249
- ...writeResult,
250
- };
251
- }
252
-
253
- function formatExceptionTarget(record) {
254
- if (record.key && record.watchClass) {
255
- return `${record.key} + ${record.watchClass}`;
256
- }
257
- return record.key || record.watchClass || 'unknown';
258
- }
259
-
260
- function formatExceptionsList(records) {
261
- if (!Array.isArray(records) || records.length === 0) {
262
- return 'No Nerviq exceptions recorded. Use `nerviq exception add --key permissionDeny --owner team --reason "migration in progress" --expires 2026-05-01`.';
263
- }
264
-
265
- const lines = [
266
- 'Nerviq exceptions:',
267
- '',
268
- ];
269
-
270
- for (const record of records) {
271
- lines.push(` ${record.status === 'active' ? '•' : '!' } ${formatExceptionTarget(record)} [${record.status}]`);
272
- lines.push(` owner=${record.owner} | scope=${record.scope} | expires=${record.expiresAt}`);
273
- lines.push(` reason=${record.reason}`);
274
- }
275
-
276
- return lines.join('\n');
277
- }
278
-
279
- function buildManagedBaselineRecord({
280
- dir,
281
- platform,
282
- auditResult,
283
- analysisReport,
284
- snapshotArtifact,
285
- currentPlatforms = [],
286
- }) {
287
- const operatingProfile = analysisReport?.recommendedOperatingProfile || {};
288
- const adoptionGuidance = analysisReport?.adoptionGuidance || {};
289
- return {
290
- schemaVersion: 1,
291
- artifactType: 'managed-baseline',
292
- generatedBy: `nerviq@${version}`,
293
- createdAt: new Date().toISOString(),
294
- directory: dir,
295
- platform,
296
- detectedPlatforms: currentPlatforms,
297
- projectSummary: analysisReport?.projectSummary || {
298
- name: path.basename(dir),
299
- score: auditResult?.score ?? null,
300
- operatingProfile: operatingProfile.label || null,
301
- adoptionPlan: adoptionGuidance?.summary?.label || null,
302
- },
303
- baselineAudit: {
304
- scoreType: 'audit-snapshot-score',
305
- score: auditResult?.score ?? null,
306
- organicScore: auditResult?.organicScore ?? null,
307
- passed: auditResult?.passed ?? null,
308
- failed: auditResult?.failed ?? null,
309
- checkCount: auditResult?.checkCount ?? null,
310
- snapshotId: snapshotArtifact?.id || null,
311
- snapshotPath: snapshotArtifact?.relativePath || null,
312
- milestone: 'baseline',
313
- tags: ['baseline'],
314
- },
315
- operatingProfile: {
316
- label: operatingProfile.label || null,
317
- permissionProfile: operatingProfile.permissionProfile?.key || null,
318
- governancePack: operatingProfile.governancePack?.key || null,
319
- ciShape: operatingProfile.ciShape?.key || null,
320
- hookKeys: Array.isArray(operatingProfile.hooks) ? operatingProfile.hooks.map((item) => item.key) : [],
321
- verification: operatingProfile.verification?.required || [],
322
- },
323
- adoptionPlan: adoptionGuidance?.summary?.label || null,
324
- repoArchetype: analysisReport?.repoArchetype?.key || analysisReport?.projectSummary?.archetype || null,
325
- watchContract: {
326
- blockingClasses: ['policy-drift', 'config-drift'],
327
- warningClasses: ['platform-drift'],
328
- suggestionClasses: ['maturity-opportunity'],
329
- },
330
- };
331
- }
332
-
333
- function formatManagedBaselineStatus(dir, baseline = readManagedBaseline(dir)) {
334
- if (!baseline) {
335
- return [
336
- 'No managed Nerviq baseline exists yet.',
337
- ' Next:',
338
- ' 1. Run `nerviq baseline init` to lock the first managed checkpoint.',
339
- ' 2. Use `nerviq audit --diff-only --drift-mode ci` in PRs/CI.',
340
- ' 3. Use `nerviq watch` locally for continuous drift monitoring.',
341
- ].join('\n');
342
- }
343
-
344
- const lines = [
345
- 'Managed Nerviq baseline:',
346
- ` Project: ${baseline.projectSummary?.name || path.basename(dir)}`,
347
- ` Score: ${baseline.baselineAudit?.score ?? '?'} / 100`,
348
- ` Snapshot: ${baseline.baselineAudit?.snapshotPath || 'n/a'}`,
349
- ` Operating profile: ${baseline.operatingProfile?.label || 'n/a'}`,
350
- ` Adoption plan: ${baseline.adoptionPlan || 'n/a'}`,
351
- ` Active platforms at baseline: ${(baseline.detectedPlatforms || []).join(', ') || 'none detected'}`,
352
- ` Blocking classes: ${(baseline.watchContract?.blockingClasses || []).join(', ')}`,
353
- ` Warning classes: ${(baseline.watchContract?.warningClasses || []).join(', ')}`,
354
- ` Suggestion classes: ${(baseline.watchContract?.suggestionClasses || []).join(', ')}`,
355
- ];
356
-
357
- return lines.join('\n');
358
- }
359
-
360
- function classifyContinuousItem(item) {
361
- const key = `${item?.key || ''}`.toLowerCase();
362
- const category = `${item?.category || ''}`.toLowerCase();
363
- const name = `${item?.name || ''}`.toLowerCase();
364
- const fix = `${item?.fix || ''}`.toLowerCase();
365
-
366
- if (
367
- POLICY_CATEGORIES.has(category) ||
368
- /\b(permission|deny|secret|trust|sandbox|approval|security|protect)\b/.test(key) ||
369
- /\b(secret|permission|deny|trust|approval|security)\b/.test(name) ||
370
- /\b(secret|permission|deny|trust|approval|security)\b/.test(fix)
371
- ) {
372
- return 'policy-drift';
373
- }
374
-
375
- if (
376
- PLATFORM_CATEGORIES.has(category) ||
377
- /\b(freshness|deprecated|legacy|migration|platform)\b/.test(key) ||
378
- /\b(freshness|deprecated|legacy|migration|platform)\b/.test(name)
379
- ) {
380
- return 'platform-drift';
381
- }
382
-
383
- if (
384
- MATURITY_CATEGORIES.has(category) ||
385
- /\b(skill|agent|subagent|fewshot|mermaid|role|context|compaction|design)\b/.test(key) ||
386
- /\b(skill|agent|subagent|architecture diagram|context management|design)\b/.test(name)
387
- ) {
388
- return 'maturity-opportunity';
389
- }
390
-
391
- if (CONFIG_CATEGORIES.has(category)) {
392
- return 'config-drift';
393
- }
394
-
395
- return item?.impact === 'low' ? 'maturity-opportunity' : 'config-drift';
396
- }
397
-
398
- function getContinuousSourceItems(auditResult) {
399
- if (Array.isArray(auditResult?.topNextActions) && auditResult.topNextActions.length > 0) {
400
- return auditResult.topNextActions.map((item) => ({
401
- key: item.key,
402
- name: item.name,
403
- impact: item.impact,
404
- category: item.category,
405
- fix: item.fix,
406
- source: 'top-next-action',
407
- }));
408
- }
409
-
410
- return (auditResult?.results || [])
411
- .filter((item) => item && item.passed === false)
412
- .sort((a, b) => (IMPACT_ORDER[b.impact] || 0) - (IMPACT_ORDER[a.impact] || 0))
413
- .slice(0, 10)
414
- .map((item) => ({
415
- key: item.key,
416
- name: item.name,
417
- impact: item.impact,
418
- category: item.category,
419
- fix: item.fix,
420
- source: 'failed-check',
421
- }));
422
- }
423
-
424
- function buildPlatformDriftItems(baseline, currentPlatforms = []) {
425
- if (!baseline) return [];
426
- const previous = new Set(baseline.detectedPlatforms || []);
427
- const current = new Set(currentPlatforms || []);
428
- const added = [...current].filter((item) => !previous.has(item));
429
- const removed = [...previous].filter((item) => !current.has(item));
430
- if (added.length === 0 && removed.length === 0) return [];
431
-
432
- return [{
433
- key: 'platformSetChanged',
434
- name: 'Active platform set changed since the managed baseline',
435
- impact: 'medium',
436
- category: 'freshness',
437
- fix: `Baseline platforms: ${(baseline.detectedPlatforms || []).join(', ') || 'none'}; current: ${currentPlatforms.join(', ') || 'none'}. Review Harmony and refresh the managed baseline if this is intentional.`,
438
- source: 'managed-baseline',
439
- watchClass: 'platform-drift',
440
- }];
441
- }
442
-
443
- function buildBaselineMissingItem() {
444
- return {
445
- key: 'managedBaselineMissing',
446
- name: 'Managed Nerviq baseline has not been initialized yet',
447
- impact: 'medium',
448
- category: 'workflow',
449
- fix: 'Run `nerviq baseline init` so CI/PR drift mode has a stable operational reference.',
450
- source: 'continuous-ops',
451
- watchClass: 'maturity-opportunity',
452
- };
453
- }
454
-
455
- function matchesException(record, item, mode) {
456
- if (!record || record.status !== 'active') return false;
457
- if (record.scope !== 'all' && record.scope !== mode) return false;
458
- if (record.key && record.key === item.key) return true;
459
- if (record.watchClass && record.watchClass === item.watchClass) return true;
460
- return false;
461
- }
462
-
463
- function dedupeItems(items) {
464
- const seen = new Set();
465
- const ordered = [];
466
- for (const item of items) {
467
- const key = `${item.watchClass}:${item.key}`;
468
- if (seen.has(key)) continue;
469
- seen.add(key);
470
- ordered.push(item);
471
- }
472
- return ordered;
473
- }
474
-
475
- function groupContinuousItems(items) {
476
- const groups = CONTINUOUS_CLASS_ORDER.map((key) => ({
477
- ...WATCH_CLASS_DEFS[key],
478
- count: 0,
479
- effectiveCount: 0,
480
- exceptedCount: 0,
481
- items: [],
482
- }));
483
- const byKey = new Map(groups.map((group) => [group.key, group]));
484
-
485
- for (const item of items) {
486
- const group = byKey.get(item.watchClass || 'config-drift');
487
- if (!group) continue;
488
- group.count += 1;
489
- if (item.exception) {
490
- group.exceptedCount += 1;
491
- } else {
492
- group.effectiveCount += 1;
493
- }
494
- group.items.push(item);
495
- }
496
-
497
- for (const group of groups) {
498
- group.items.sort((a, b) => {
499
- if ((a.exception ? 1 : 0) !== (b.exception ? 1 : 0)) {
500
- return (a.exception ? 1 : 0) - (b.exception ? 1 : 0);
501
- }
502
- return (IMPACT_ORDER[b.impact] || 0) - (IMPACT_ORDER[a.impact] || 0);
503
- });
504
- }
505
-
506
- return groups.filter((group) => group.count > 0);
507
- }
508
-
509
- function selectSuggestedCampaigns(campaigns = [], groups = []) {
510
- const activeFocus = new Set(
511
- groups
512
- .filter((group) => group.effectiveCount > 0)
513
- .map((group) => group.key),
514
- );
515
-
516
- if (activeFocus.size === 0) return [];
517
-
518
- return campaigns.filter((campaign) => {
519
- const focusAreas = Array.isArray(campaign.focusAreas) ? campaign.focusAreas : [];
520
- return focusAreas.some((key) => activeFocus.has(key));
521
- });
522
- }
523
-
524
- function buildContinuousStatus({
525
- dir,
526
- auditResult,
527
- mode = 'watch',
528
- baseline = readManagedBaseline(dir),
529
- exceptions = listExceptions(dir),
530
- currentPlatforms = [],
531
- campaigns = [],
532
- }) {
533
- const normalizedMode = ['ci', 'pr', 'watch'].includes(mode) ? mode : 'watch';
534
- const activeExceptions = exceptions.filter((record) => record.status === 'active');
535
- const expiredExceptions = exceptions.filter((record) => record.status === 'expired');
536
-
537
- const sourceItems = getContinuousSourceItems(auditResult).map((item) => ({
538
- ...item,
539
- watchClass: classifyContinuousItem(item),
540
- }));
541
- const platformItems = buildPlatformDriftItems(baseline, currentPlatforms);
542
- const items = baseline
543
- ? [...sourceItems, ...platformItems]
544
- : [buildBaselineMissingItem(), ...sourceItems, ...platformItems];
545
-
546
- const withExceptions = dedupeItems(items).map((item) => {
547
- const exception = activeExceptions.find((record) => matchesException(record, item, normalizedMode));
548
- return exception ? { ...item, exception } : item;
549
- });
550
-
551
- const groups = groupContinuousItems(withExceptions);
552
- const suggestedCampaigns = selectSuggestedCampaigns(campaigns, groups);
553
- const blockingCount = groups
554
- .filter((group) => group.disposition === 'block')
555
- .reduce((sum, group) => sum + group.effectiveCount, 0);
556
- const warningCount = groups
557
- .filter((group) => group.disposition === 'warn')
558
- .reduce((sum, group) => sum + group.effectiveCount, 0);
559
- const suggestionCount = groups
560
- .filter((group) => group.disposition === 'suggest')
561
- .reduce((sum, group) => sum + group.effectiveCount, 0);
562
-
563
- let gate = 'pass';
564
- if (blockingCount > 0 || expiredExceptions.length > 0) {
565
- gate = 'fail';
566
- } else if (warningCount > 0 || !baseline) {
567
- gate = 'warn';
568
- }
569
-
570
- const gateLabel = gate === 'fail'
571
- ? 'blocking drift detected'
572
- : gate === 'warn'
573
- ? 'review recommended'
574
- : 'managed posture stable';
575
-
576
- return {
577
- mode: normalizedMode,
578
- gate,
579
- gateLabel,
580
- baselinePresent: Boolean(baseline),
581
- baseline: baseline ? {
582
- createdAt: baseline.createdAt,
583
- score: baseline.baselineAudit?.score ?? null,
584
- snapshotPath: baseline.baselineAudit?.snapshotPath || null,
585
- operatingProfile: baseline.operatingProfile?.label || null,
586
- } : null,
587
- blockingCount,
588
- warningCount,
589
- suggestionCount,
590
- appliedExceptionCount: withExceptions.filter((item) => item.exception).length,
591
- expiredExceptionCount: expiredExceptions.length,
592
- expiredExceptions,
593
- classes: groups,
594
- suggestedCampaigns: suggestedCampaigns.map((campaign) => ({
595
- key: campaign.key,
596
- label: campaign.label,
597
- summary: campaign.summary,
598
- proposalIds: campaign.proposalIds,
599
- })),
600
- nextSteps: [
601
- !baseline ? 'Run `nerviq baseline init` to create the first managed checkpoint.' : null,
602
- gate === 'fail' ? 'Run `nerviq plan --campaign governance-hardening --campaign verification-closure` or review the blocking drift items manually.' : null,
603
- gate !== 'fail' && suggestedCampaigns.length > 0 ? `Consider \`${suggestedCampaigns.slice(0, 2).map((campaign) => `nerviq plan --campaign ${campaign.key}`).join('` and `')}\`.` : null,
604
- expiredExceptions.length > 0 ? 'Run `nerviq exception prune` or renew the expired exception with a fresh owner/reason/expiry.' : null,
605
- ].filter(Boolean),
606
- };
607
- }
608
-
609
- function formatContinuousStatus(report, options = {}) {
610
- if (!report) return '';
611
- if (options.compact) {
612
- const parts = [
613
- `gate=${report.gate}`,
614
- `block=${report.blockingCount}`,
615
- `warn=${report.warningCount}`,
616
- `suggest=${report.suggestionCount}`,
617
- ];
618
- if (report.appliedExceptionCount > 0) {
619
- parts.push(`excepted=${report.appliedExceptionCount}`);
620
- }
621
- if (report.expiredExceptionCount > 0) {
622
- parts.push(`expired-exceptions=${report.expiredExceptionCount}`);
623
- }
624
- return ` Continuous status (${report.mode}): ${parts.join(' | ')}`;
625
- }
626
-
627
- const lines = [
628
- ` Continuous operating mode (${report.mode})`,
629
- ' ─────────────────────────────────────',
630
- ` Gate: ${report.gate.toUpperCase()} — ${report.gateLabel}`,
631
- report.baselinePresent
632
- ? ` Managed baseline: ${report.baseline.score ?? '?'} / 100 (${report.baseline.snapshotPath || 'snapshot unavailable'})`
633
- : ' Managed baseline: missing',
634
- ];
635
-
636
- for (const group of report.classes) {
637
- lines.push(` ${group.label}: ${group.effectiveCount}/${group.count} active (${group.disposition})`);
638
- for (const item of group.items.slice(0, 4)) {
639
- const suffix = item.exception
640
- ? ` [excepted by ${item.exception.owner} until ${item.exception.expiresAt.split('T')[0]}]`
641
- : '';
642
- lines.push(` - ${item.key} [${item.impact || 'n/a'}]${suffix}`);
643
- }
644
- }
645
-
646
- if (report.expiredExceptionCount > 0) {
647
- lines.push(` Expired exceptions: ${report.expiredExceptionCount}`);
648
- }
649
-
650
- if (Array.isArray(report.suggestedCampaigns) && report.suggestedCampaigns.length > 0) {
651
- lines.push(' Suggested campaigns:');
652
- for (const campaign of report.suggestedCampaigns.slice(0, 3)) {
653
- lines.push(` - ${campaign.key}: ${campaign.summary}`);
654
- }
655
- }
656
-
657
- if (report.nextSteps.length > 0) {
658
- lines.push(' Next:');
659
- for (const step of report.nextSteps) {
660
- lines.push(` - ${step}`);
661
- }
662
- }
663
-
664
- return lines.join('\n');
665
- }
666
-
667
- module.exports = {
668
- WATCH_CLASS_DEFS,
669
- CONTINUOUS_CLASS_ORDER,
670
- buildManagedBaselineRecord,
671
- readManagedBaseline,
672
- writeManagedBaseline,
673
- formatManagedBaselineStatus,
674
- listExceptions,
675
- addException,
676
- pruneExpiredExceptions,
677
- formatExceptionsList,
678
- buildContinuousStatus,
679
- formatContinuousStatus,
680
- normalizeExceptionScope,
681
- };
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const { version } = require('../package.json');
6
+ const {
7
+ ensureProjectStateDir,
8
+ resolveProjectStateReadPath,
9
+ resolveProjectStatePath,
10
+ } = require('./state-paths');
11
+
12
+ const WATCH_CLASS_DEFS = {
13
+ 'config-drift': {
14
+ key: 'config-drift',
15
+ label: 'Config drift',
16
+ disposition: 'block',
17
+ description: 'Repo instructions, config, hooks, rules, or verification surfaces drifted away from the managed baseline.',
18
+ },
19
+ 'policy-drift': {
20
+ key: 'policy-drift',
21
+ label: 'Policy drift',
22
+ disposition: 'block',
23
+ description: 'Safety, permissions, secrets, or trust controls drifted and should be treated as blocking.',
24
+ },
25
+ 'platform-drift': {
26
+ key: 'platform-drift',
27
+ label: 'Platform drift',
28
+ disposition: 'warn',
29
+ description: 'The active tool/platform posture changed and should be reviewed before it silently alters repo behavior.',
30
+ },
31
+ 'maturity-opportunity': {
32
+ key: 'maturity-opportunity',
33
+ label: 'Maturity opportunity',
34
+ disposition: 'suggest',
35
+ description: 'A safe improvement is available, but it should not block delivery.',
36
+ },
37
+ };
38
+
39
+ const CONTINUOUS_CLASS_ORDER = ['policy-drift', 'config-drift', 'platform-drift', 'maturity-opportunity'];
40
+ const CONTINUOUS_DISPOSITION_ORDER = { block: 3, warn: 2, suggest: 1 };
41
+ const IMPACT_ORDER = { critical: 4, high: 3, medium: 2, low: 1 };
42
+ const EXCEPTION_SCOPES = ['all', 'ci', 'watch', 'pr'];
43
+
44
+ const MANAGED_BASELINE_DIR = 'managed';
45
+ const EXCEPTIONS_DIR = 'exceptions';
46
+ const MANAGED_BASELINE_FILE = 'baseline.json';
47
+ const EXCEPTIONS_INDEX_FILE = 'index.json';
48
+
49
+ const POLICY_CATEGORIES = new Set(['security', 'trust']);
50
+ const CONFIG_CATEGORIES = new Set([
51
+ 'memory',
52
+ 'instructions',
53
+ 'config',
54
+ 'rules',
55
+ 'hooks',
56
+ 'workflow',
57
+ 'automation',
58
+ 'quality',
59
+ 'quality-deep',
60
+ 'git',
61
+ 'tools',
62
+ 'mcp',
63
+ 'local',
64
+ 'review',
65
+ 'hygiene',
66
+ 'devops',
67
+ ]);
68
+ const PLATFORM_CATEGORIES = new Set(['features', 'freshness']);
69
+ const MATURITY_CATEGORIES = new Set(['skills', 'agents', 'design', 'performance', 'prompting']);
70
+
71
+ function timestampId() {
72
+ return new Date().toISOString().replace(/[:.]/g, '-');
73
+ }
74
+
75
+ function writeJson(filePath, payload) {
76
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
77
+ fs.writeFileSync(filePath, JSON.stringify(payload, null, 2), 'utf8');
78
+ }
79
+
80
+ function readJsonSafe(filePath) {
81
+ if (!fs.existsSync(filePath)) return null;
82
+ try {
83
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
84
+ } catch {
85
+ return null;
86
+ }
87
+ }
88
+
89
+ function ensureManagedDir(dir) {
90
+ return ensureProjectStateDir(dir, MANAGED_BASELINE_DIR);
91
+ }
92
+
93
+ function ensureExceptionsDir(dir) {
94
+ return ensureProjectStateDir(dir, EXCEPTIONS_DIR);
95
+ }
96
+
97
+ function getManagedBaselinePath(dir) {
98
+ return resolveProjectStatePath(dir, MANAGED_BASELINE_DIR, MANAGED_BASELINE_FILE);
99
+ }
100
+
101
+ function getExceptionsIndexPath(dir) {
102
+ return resolveProjectStatePath(dir, EXCEPTIONS_DIR, EXCEPTIONS_INDEX_FILE);
103
+ }
104
+
105
+ function normalizeExceptionScope(value) {
106
+ const normalized = `${value || 'all'}`.trim().toLowerCase();
107
+ if (!EXCEPTION_SCOPES.includes(normalized)) {
108
+ throw new Error(`exception scope must be one of: ${EXCEPTION_SCOPES.join(', ')}`);
109
+ }
110
+ return normalized;
111
+ }
112
+
113
+ function normalizeExpiry(value) {
114
+ const raw = `${value || ''}`.trim();
115
+ if (!raw) {
116
+ throw new Error('exception expires value is required');
117
+ }
118
+
119
+ const date = new Date(raw);
120
+ if (Number.isNaN(date.getTime())) {
121
+ throw new Error('exception expires must be a valid ISO date or date-time');
122
+ }
123
+
124
+ return date.toISOString();
125
+ }
126
+
127
+ function isExpired(record, now = new Date()) {
128
+ if (!record || !record.expiresAt) return false;
129
+ const expiry = new Date(record.expiresAt);
130
+ if (Number.isNaN(expiry.getTime())) return false;
131
+ return expiry.getTime() < now.getTime();
132
+ }
133
+
134
+ function getExceptionStatus(record, now = new Date()) {
135
+ return isExpired(record, now) ? 'expired' : 'active';
136
+ }
137
+
138
+ function normalizeExceptionRecord(record, now = new Date()) {
139
+ if (!record || typeof record !== 'object') return null;
140
+ return {
141
+ ...record,
142
+ scope: normalizeExceptionScope(record.scope || 'all'),
143
+ status: getExceptionStatus(record, now),
144
+ };
145
+ }
146
+
147
+ function readManagedBaseline(dir) {
148
+ const filePath = resolveProjectStateReadPath(dir, MANAGED_BASELINE_DIR, MANAGED_BASELINE_FILE);
149
+ const payload = readJsonSafe(filePath);
150
+ return payload && typeof payload === 'object' ? payload : null;
151
+ }
152
+
153
+ function writeManagedBaseline(dir, payload) {
154
+ ensureManagedDir(dir);
155
+ const filePath = getManagedBaselinePath(dir);
156
+ writeJson(filePath, payload);
157
+ return {
158
+ filePath,
159
+ relativePath: path.relative(dir, filePath),
160
+ payload,
161
+ };
162
+ }
163
+
164
+ function listExceptions(dir, now = new Date()) {
165
+ const filePath = resolveProjectStateReadPath(dir, EXCEPTIONS_DIR, EXCEPTIONS_INDEX_FILE);
166
+ const entries = readJsonSafe(filePath);
167
+ if (!Array.isArray(entries)) return [];
168
+ return entries
169
+ .map((record) => normalizeExceptionRecord(record, now))
170
+ .filter(Boolean)
171
+ .sort((a, b) => new Date(a.createdAt || 0) - new Date(b.createdAt || 0));
172
+ }
173
+
174
+ function writeExceptions(dir, records) {
175
+ ensureExceptionsDir(dir);
176
+ const filePath = getExceptionsIndexPath(dir);
177
+ writeJson(filePath, records);
178
+ return {
179
+ filePath,
180
+ relativePath: path.relative(dir, filePath),
181
+ };
182
+ }
183
+
184
+ function addException(dir, payload, now = new Date()) {
185
+ const key = `${payload.key || ''}`.trim();
186
+ const watchClass = `${payload.watchClass || ''}`.trim().toLowerCase();
187
+ if (!key && !watchClass) {
188
+ throw new Error('exception add requires --key or --class');
189
+ }
190
+ if (watchClass && !WATCH_CLASS_DEFS[watchClass]) {
191
+ throw new Error(`exception class must be one of: ${Object.keys(WATCH_CLASS_DEFS).join(', ')}`);
192
+ }
193
+
194
+ const owner = `${payload.owner || ''}`.trim();
195
+ const reason = `${payload.reason || ''}`.trim();
196
+ if (!owner) throw new Error('exception add requires --owner');
197
+ if (!reason) throw new Error('exception add requires --reason');
198
+
199
+ const record = {
200
+ id: timestampId(),
201
+ createdAt: now.toISOString(),
202
+ createdBy: payload.createdBy || 'unknown:unknown',
203
+ key: key || null,
204
+ watchClass: watchClass || null,
205
+ scope: normalizeExceptionScope(payload.scope || 'all'),
206
+ owner,
207
+ reason,
208
+ expiresAt: normalizeExpiry(payload.expiresAt),
209
+ };
210
+
211
+ const records = listExceptions(dir, now).map((item) => ({
212
+ id: item.id,
213
+ createdAt: item.createdAt,
214
+ createdBy: item.createdBy,
215
+ key: item.key || null,
216
+ watchClass: item.watchClass || null,
217
+ scope: item.scope || 'all',
218
+ owner: item.owner,
219
+ reason: item.reason,
220
+ expiresAt: item.expiresAt,
221
+ }));
222
+ records.push(record);
223
+ const writeResult = writeExceptions(dir, records);
224
+ return {
225
+ record: normalizeExceptionRecord(record, now),
226
+ ...writeResult,
227
+ };
228
+ }
229
+
230
+ function pruneExpiredExceptions(dir, now = new Date()) {
231
+ const records = listExceptions(dir, now);
232
+ const kept = records.filter((record) => record.status !== 'expired').map((item) => ({
233
+ id: item.id,
234
+ createdAt: item.createdAt,
235
+ createdBy: item.createdBy,
236
+ key: item.key || null,
237
+ watchClass: item.watchClass || null,
238
+ scope: item.scope || 'all',
239
+ owner: item.owner,
240
+ reason: item.reason,
241
+ expiresAt: item.expiresAt,
242
+ }));
243
+ const expired = records.filter((record) => record.status === 'expired');
244
+ const writeResult = writeExceptions(dir, kept);
245
+ return {
246
+ removedCount: expired.length,
247
+ keptCount: kept.length,
248
+ removed: expired,
249
+ ...writeResult,
250
+ };
251
+ }
252
+
253
+ function formatExceptionTarget(record) {
254
+ if (record.key && record.watchClass) {
255
+ return `${record.key} + ${record.watchClass}`;
256
+ }
257
+ return record.key || record.watchClass || 'unknown';
258
+ }
259
+
260
+ function formatExceptionsList(records) {
261
+ if (!Array.isArray(records) || records.length === 0) {
262
+ return 'No Nerviq exceptions recorded. Use `nerviq exception add --key permissionDeny --owner team --reason "migration in progress" --expires 2026-05-01`.';
263
+ }
264
+
265
+ const lines = [
266
+ 'Nerviq exceptions:',
267
+ '',
268
+ ];
269
+
270
+ for (const record of records) {
271
+ lines.push(` ${record.status === 'active' ? '•' : '!' } ${formatExceptionTarget(record)} [${record.status}]`);
272
+ lines.push(` owner=${record.owner} | scope=${record.scope} | expires=${record.expiresAt}`);
273
+ lines.push(` reason=${record.reason}`);
274
+ }
275
+
276
+ return lines.join('\n');
277
+ }
278
+
279
+ function buildManagedBaselineRecord({
280
+ dir,
281
+ platform,
282
+ auditResult,
283
+ analysisReport,
284
+ snapshotArtifact,
285
+ currentPlatforms = [],
286
+ }) {
287
+ const operatingProfile = analysisReport?.recommendedOperatingProfile || {};
288
+ const adoptionGuidance = analysisReport?.adoptionGuidance || {};
289
+ return {
290
+ schemaVersion: 1,
291
+ artifactType: 'managed-baseline',
292
+ generatedBy: `nerviq@${version}`,
293
+ createdAt: new Date().toISOString(),
294
+ directory: dir,
295
+ platform,
296
+ detectedPlatforms: currentPlatforms,
297
+ projectSummary: analysisReport?.projectSummary || {
298
+ name: path.basename(dir),
299
+ score: auditResult?.score ?? null,
300
+ operatingProfile: operatingProfile.label || null,
301
+ adoptionPlan: adoptionGuidance?.summary?.label || null,
302
+ },
303
+ baselineAudit: {
304
+ scoreType: 'audit-snapshot-score',
305
+ score: auditResult?.score ?? null,
306
+ organicScore: auditResult?.organicScore ?? null,
307
+ passed: auditResult?.passed ?? null,
308
+ failed: auditResult?.failed ?? null,
309
+ checkCount: auditResult?.checkCount ?? null,
310
+ snapshotId: snapshotArtifact?.id || null,
311
+ snapshotPath: snapshotArtifact?.relativePath || null,
312
+ milestone: 'baseline',
313
+ tags: ['baseline'],
314
+ },
315
+ operatingProfile: {
316
+ label: operatingProfile.label || null,
317
+ permissionProfile: operatingProfile.permissionProfile?.key || null,
318
+ governancePack: operatingProfile.governancePack?.key || null,
319
+ ciShape: operatingProfile.ciShape?.key || null,
320
+ hookKeys: Array.isArray(operatingProfile.hooks) ? operatingProfile.hooks.map((item) => item.key) : [],
321
+ verification: operatingProfile.verification?.required || [],
322
+ },
323
+ adoptionPlan: adoptionGuidance?.summary?.label || null,
324
+ repoArchetype: analysisReport?.repoArchetype?.key || analysisReport?.projectSummary?.archetype || null,
325
+ watchContract: {
326
+ blockingClasses: ['policy-drift', 'config-drift'],
327
+ warningClasses: ['platform-drift'],
328
+ suggestionClasses: ['maturity-opportunity'],
329
+ },
330
+ };
331
+ }
332
+
333
+ function formatManagedBaselineStatus(dir, baseline = readManagedBaseline(dir)) {
334
+ if (!baseline) {
335
+ return [
336
+ 'No managed Nerviq baseline exists yet.',
337
+ ' Next:',
338
+ ' 1. Run `nerviq baseline init` to lock the first managed checkpoint.',
339
+ ' 2. Use `nerviq audit --diff-only --drift-mode ci` in PRs/CI.',
340
+ ' 3. Use `nerviq watch` locally for continuous drift monitoring.',
341
+ ].join('\n');
342
+ }
343
+
344
+ const lines = [
345
+ 'Managed Nerviq baseline:',
346
+ ` Project: ${baseline.projectSummary?.name || path.basename(dir)}`,
347
+ ` Score: ${baseline.baselineAudit?.score ?? '?'} / 100`,
348
+ ` Snapshot: ${baseline.baselineAudit?.snapshotPath || 'n/a'}`,
349
+ ` Operating profile: ${baseline.operatingProfile?.label || 'n/a'}`,
350
+ ` Adoption plan: ${baseline.adoptionPlan || 'n/a'}`,
351
+ ` Active platforms at baseline: ${(baseline.detectedPlatforms || []).join(', ') || 'none detected'}`,
352
+ ` Blocking classes: ${(baseline.watchContract?.blockingClasses || []).join(', ')}`,
353
+ ` Warning classes: ${(baseline.watchContract?.warningClasses || []).join(', ')}`,
354
+ ` Suggestion classes: ${(baseline.watchContract?.suggestionClasses || []).join(', ')}`,
355
+ ];
356
+
357
+ return lines.join('\n');
358
+ }
359
+
360
+ function classifyContinuousItem(item) {
361
+ const key = `${item?.key || ''}`.toLowerCase();
362
+ const category = `${item?.category || ''}`.toLowerCase();
363
+ const name = `${item?.name || ''}`.toLowerCase();
364
+ const fix = `${item?.fix || ''}`.toLowerCase();
365
+
366
+ if (
367
+ POLICY_CATEGORIES.has(category) ||
368
+ /\b(permission|deny|secret|trust|sandbox|approval|security|protect)\b/.test(key) ||
369
+ /\b(secret|permission|deny|trust|approval|security)\b/.test(name) ||
370
+ /\b(secret|permission|deny|trust|approval|security)\b/.test(fix)
371
+ ) {
372
+ return 'policy-drift';
373
+ }
374
+
375
+ if (
376
+ PLATFORM_CATEGORIES.has(category) ||
377
+ /\b(freshness|deprecated|legacy|migration|platform)\b/.test(key) ||
378
+ /\b(freshness|deprecated|legacy|migration|platform)\b/.test(name)
379
+ ) {
380
+ return 'platform-drift';
381
+ }
382
+
383
+ if (
384
+ MATURITY_CATEGORIES.has(category) ||
385
+ /\b(skill|agent|subagent|fewshot|mermaid|role|context|compaction|design)\b/.test(key) ||
386
+ /\b(skill|agent|subagent|architecture diagram|context management|design)\b/.test(name)
387
+ ) {
388
+ return 'maturity-opportunity';
389
+ }
390
+
391
+ if (CONFIG_CATEGORIES.has(category)) {
392
+ return 'config-drift';
393
+ }
394
+
395
+ return item?.impact === 'low' ? 'maturity-opportunity' : 'config-drift';
396
+ }
397
+
398
+ function getContinuousSourceItems(auditResult) {
399
+ if (Array.isArray(auditResult?.topNextActions) && auditResult.topNextActions.length > 0) {
400
+ return auditResult.topNextActions.map((item) => ({
401
+ key: item.key,
402
+ name: item.name,
403
+ impact: item.impact,
404
+ category: item.category,
405
+ fix: item.fix,
406
+ source: 'top-next-action',
407
+ }));
408
+ }
409
+
410
+ return (auditResult?.results || [])
411
+ .filter((item) => item && item.passed === false)
412
+ .sort((a, b) => (IMPACT_ORDER[b.impact] || 0) - (IMPACT_ORDER[a.impact] || 0))
413
+ .slice(0, 10)
414
+ .map((item) => ({
415
+ key: item.key,
416
+ name: item.name,
417
+ impact: item.impact,
418
+ category: item.category,
419
+ fix: item.fix,
420
+ source: 'failed-check',
421
+ }));
422
+ }
423
+
424
+ function buildPlatformDriftItems(baseline, currentPlatforms = []) {
425
+ if (!baseline) return [];
426
+ const previous = new Set(baseline.detectedPlatforms || []);
427
+ const current = new Set(currentPlatforms || []);
428
+ const added = [...current].filter((item) => !previous.has(item));
429
+ const removed = [...previous].filter((item) => !current.has(item));
430
+ if (added.length === 0 && removed.length === 0) return [];
431
+
432
+ return [{
433
+ key: 'platformSetChanged',
434
+ name: 'Active platform set changed since the managed baseline',
435
+ impact: 'medium',
436
+ category: 'freshness',
437
+ fix: `Baseline platforms: ${(baseline.detectedPlatforms || []).join(', ') || 'none'}; current: ${currentPlatforms.join(', ') || 'none'}. Review Harmony and refresh the managed baseline if this is intentional.`,
438
+ source: 'managed-baseline',
439
+ watchClass: 'platform-drift',
440
+ }];
441
+ }
442
+
443
+ function buildBaselineMissingItem() {
444
+ return {
445
+ key: 'managedBaselineMissing',
446
+ name: 'Managed Nerviq baseline has not been initialized yet',
447
+ impact: 'medium',
448
+ category: 'workflow',
449
+ fix: 'Run `nerviq baseline init` so CI/PR drift mode has a stable operational reference.',
450
+ source: 'continuous-ops',
451
+ watchClass: 'maturity-opportunity',
452
+ };
453
+ }
454
+
455
+ function matchesException(record, item, mode) {
456
+ if (!record || record.status !== 'active') return false;
457
+ if (record.scope !== 'all' && record.scope !== mode) return false;
458
+ if (record.key && record.key === item.key) return true;
459
+ if (record.watchClass && record.watchClass === item.watchClass) return true;
460
+ return false;
461
+ }
462
+
463
+ function dedupeItems(items) {
464
+ const seen = new Set();
465
+ const ordered = [];
466
+ for (const item of items) {
467
+ const key = `${item.watchClass}:${item.key}`;
468
+ if (seen.has(key)) continue;
469
+ seen.add(key);
470
+ ordered.push(item);
471
+ }
472
+ return ordered;
473
+ }
474
+
475
+ function groupContinuousItems(items) {
476
+ const groups = CONTINUOUS_CLASS_ORDER.map((key) => ({
477
+ ...WATCH_CLASS_DEFS[key],
478
+ count: 0,
479
+ effectiveCount: 0,
480
+ exceptedCount: 0,
481
+ items: [],
482
+ }));
483
+ const byKey = new Map(groups.map((group) => [group.key, group]));
484
+
485
+ for (const item of items) {
486
+ const group = byKey.get(item.watchClass || 'config-drift');
487
+ if (!group) continue;
488
+ group.count += 1;
489
+ if (item.exception) {
490
+ group.exceptedCount += 1;
491
+ } else {
492
+ group.effectiveCount += 1;
493
+ }
494
+ group.items.push(item);
495
+ }
496
+
497
+ for (const group of groups) {
498
+ group.items.sort((a, b) => {
499
+ if ((a.exception ? 1 : 0) !== (b.exception ? 1 : 0)) {
500
+ return (a.exception ? 1 : 0) - (b.exception ? 1 : 0);
501
+ }
502
+ return (IMPACT_ORDER[b.impact] || 0) - (IMPACT_ORDER[a.impact] || 0);
503
+ });
504
+ }
505
+
506
+ return groups.filter((group) => group.count > 0);
507
+ }
508
+
509
+ function selectSuggestedCampaigns(campaigns = [], groups = []) {
510
+ const activeFocus = new Set(
511
+ groups
512
+ .filter((group) => group.effectiveCount > 0)
513
+ .map((group) => group.key),
514
+ );
515
+
516
+ if (activeFocus.size === 0) return [];
517
+
518
+ return campaigns.filter((campaign) => {
519
+ const focusAreas = Array.isArray(campaign.focusAreas) ? campaign.focusAreas : [];
520
+ return focusAreas.some((key) => activeFocus.has(key));
521
+ });
522
+ }
523
+
524
+ function buildContinuousStatus({
525
+ dir,
526
+ auditResult,
527
+ mode = 'watch',
528
+ baseline = readManagedBaseline(dir),
529
+ exceptions = listExceptions(dir),
530
+ currentPlatforms = [],
531
+ campaigns = [],
532
+ }) {
533
+ const normalizedMode = ['ci', 'pr', 'watch'].includes(mode) ? mode : 'watch';
534
+ const activeExceptions = exceptions.filter((record) => record.status === 'active');
535
+ const expiredExceptions = exceptions.filter((record) => record.status === 'expired');
536
+
537
+ const sourceItems = getContinuousSourceItems(auditResult).map((item) => ({
538
+ ...item,
539
+ watchClass: classifyContinuousItem(item),
540
+ }));
541
+ const platformItems = buildPlatformDriftItems(baseline, currentPlatforms);
542
+ const items = baseline
543
+ ? [...sourceItems, ...platformItems]
544
+ : [buildBaselineMissingItem(), ...sourceItems, ...platformItems];
545
+
546
+ const withExceptions = dedupeItems(items).map((item) => {
547
+ const exception = activeExceptions.find((record) => matchesException(record, item, normalizedMode));
548
+ return exception ? { ...item, exception } : item;
549
+ });
550
+
551
+ const groups = groupContinuousItems(withExceptions);
552
+ const suggestedCampaigns = selectSuggestedCampaigns(campaigns, groups);
553
+ const blockingCount = groups
554
+ .filter((group) => group.disposition === 'block')
555
+ .reduce((sum, group) => sum + group.effectiveCount, 0);
556
+ const warningCount = groups
557
+ .filter((group) => group.disposition === 'warn')
558
+ .reduce((sum, group) => sum + group.effectiveCount, 0);
559
+ const suggestionCount = groups
560
+ .filter((group) => group.disposition === 'suggest')
561
+ .reduce((sum, group) => sum + group.effectiveCount, 0);
562
+
563
+ let gate = 'pass';
564
+ if (blockingCount > 0 || expiredExceptions.length > 0) {
565
+ gate = 'fail';
566
+ } else if (warningCount > 0 || !baseline) {
567
+ gate = 'warn';
568
+ }
569
+
570
+ const gateLabel = gate === 'fail'
571
+ ? 'blocking drift detected'
572
+ : gate === 'warn'
573
+ ? 'review recommended'
574
+ : 'managed posture stable';
575
+
576
+ return {
577
+ mode: normalizedMode,
578
+ gate,
579
+ gateLabel,
580
+ baselinePresent: Boolean(baseline),
581
+ baseline: baseline ? {
582
+ createdAt: baseline.createdAt,
583
+ score: baseline.baselineAudit?.score ?? null,
584
+ snapshotPath: baseline.baselineAudit?.snapshotPath || null,
585
+ operatingProfile: baseline.operatingProfile?.label || null,
586
+ } : null,
587
+ blockingCount,
588
+ warningCount,
589
+ suggestionCount,
590
+ appliedExceptionCount: withExceptions.filter((item) => item.exception).length,
591
+ expiredExceptionCount: expiredExceptions.length,
592
+ expiredExceptions,
593
+ classes: groups,
594
+ suggestedCampaigns: suggestedCampaigns.map((campaign) => ({
595
+ key: campaign.key,
596
+ label: campaign.label,
597
+ summary: campaign.summary,
598
+ proposalIds: campaign.proposalIds,
599
+ })),
600
+ nextSteps: [
601
+ !baseline ? 'Run `nerviq baseline init` to create the first managed checkpoint.' : null,
602
+ gate === 'fail' ? 'Run `nerviq plan --campaign governance-hardening --campaign verification-closure` or review the blocking drift items manually.' : null,
603
+ gate !== 'fail' && suggestedCampaigns.length > 0 ? `Consider \`${suggestedCampaigns.slice(0, 2).map((campaign) => `nerviq plan --campaign ${campaign.key}`).join('` and `')}\`.` : null,
604
+ expiredExceptions.length > 0 ? 'Run `nerviq exception prune` or renew the expired exception with a fresh owner/reason/expiry.' : null,
605
+ ].filter(Boolean),
606
+ };
607
+ }
608
+
609
+ function formatContinuousStatus(report, options = {}) {
610
+ if (!report) return '';
611
+ if (options.compact) {
612
+ const parts = [
613
+ `gate=${report.gate}`,
614
+ `block=${report.blockingCount}`,
615
+ `warn=${report.warningCount}`,
616
+ `suggest=${report.suggestionCount}`,
617
+ ];
618
+ if (report.appliedExceptionCount > 0) {
619
+ parts.push(`excepted=${report.appliedExceptionCount}`);
620
+ }
621
+ if (report.expiredExceptionCount > 0) {
622
+ parts.push(`expired-exceptions=${report.expiredExceptionCount}`);
623
+ }
624
+ return ` Continuous status (${report.mode}): ${parts.join(' | ')}`;
625
+ }
626
+
627
+ const lines = [
628
+ ` Continuous operating mode (${report.mode})`,
629
+ ' ─────────────────────────────────────',
630
+ ` Gate: ${report.gate.toUpperCase()} — ${report.gateLabel}`,
631
+ report.baselinePresent
632
+ ? ` Managed baseline: ${report.baseline.score ?? '?'} / 100 (${report.baseline.snapshotPath || 'snapshot unavailable'})`
633
+ : ' Managed baseline: missing',
634
+ ];
635
+
636
+ for (const group of report.classes) {
637
+ lines.push(` ${group.label}: ${group.effectiveCount}/${group.count} active (${group.disposition})`);
638
+ for (const item of group.items.slice(0, 4)) {
639
+ const suffix = item.exception
640
+ ? ` [excepted by ${item.exception.owner} until ${item.exception.expiresAt.split('T')[0]}]`
641
+ : '';
642
+ lines.push(` - ${item.key} [${item.impact || 'n/a'}]${suffix}`);
643
+ }
644
+ }
645
+
646
+ if (report.expiredExceptionCount > 0) {
647
+ lines.push(` Expired exceptions: ${report.expiredExceptionCount}`);
648
+ }
649
+
650
+ if (Array.isArray(report.suggestedCampaigns) && report.suggestedCampaigns.length > 0) {
651
+ lines.push(' Suggested campaigns:');
652
+ for (const campaign of report.suggestedCampaigns.slice(0, 3)) {
653
+ lines.push(` - ${campaign.key}: ${campaign.summary}`);
654
+ }
655
+ }
656
+
657
+ if (report.nextSteps.length > 0) {
658
+ lines.push(' Next:');
659
+ for (const step of report.nextSteps) {
660
+ lines.push(` - ${step}`);
661
+ }
662
+ }
663
+
664
+ return lines.join('\n');
665
+ }
666
+
667
+ module.exports = {
668
+ WATCH_CLASS_DEFS,
669
+ CONTINUOUS_CLASS_ORDER,
670
+ buildManagedBaselineRecord,
671
+ readManagedBaseline,
672
+ writeManagedBaseline,
673
+ formatManagedBaselineStatus,
674
+ listExceptions,
675
+ addException,
676
+ pruneExpiredExceptions,
677
+ formatExceptionsList,
678
+ buildContinuousStatus,
679
+ formatContinuousStatus,
680
+ normalizeExceptionScope,
681
+ };