contextos-agents 2.0.0-beta.2 → 2.0.0-beta.3

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.
@@ -0,0 +1,525 @@
1
+ /**
2
+ * .agents/rules/rule-catalog.js
3
+ * ContextOS — Rule Catalog, Instruction Inventory & Enforcement Engine (Milestone 9)
4
+ *
5
+ * Implements:
6
+ * - Comprehensive rule inventory tracking (id, skill, summary, level, enforcement, checker)
7
+ * - Automated checker registry (runtime, linter, scanner, compiler)
8
+ * - Enforcement levels: ENFORCED, PARTIALLY_ENFORCED, PROMPT_GUIDANCE, REFERENCE, EXAMPLE
9
+ * - Invariant check: "A rule existing only in Markdown is NOT ENFORCED (requires automated checker)"
10
+ * - Rule explanation formatting for `ctx explain`
11
+ * - Parity with compiled registry and manifest declarations
12
+ */
13
+
14
+ 'use strict';
15
+
16
+ const fs = require('fs');
17
+ const path = require('path');
18
+
19
+ /**
20
+ * Standard enforcement levels
21
+ */
22
+ const ENFORCEMENT_LEVELS = {
23
+ ENFORCED: 'ENFORCED', // Backed by deterministic runtime/linter checker
24
+ PARTIALLY_ENFORCED: 'PARTIALLY_ENFORCED', // Heuristic checker or partial automated guard
25
+ PROMPT_GUIDANCE: 'PROMPT_GUIDANCE', // Normative natural language prompt instruction
26
+ REFERENCE: 'REFERENCE', // Architecture reference or pattern guide
27
+ EXAMPLE: 'EXAMPLE', // Code snippet or reference illustration
28
+ };
29
+
30
+ /**
31
+ * Normalizes enforcement strings to standard uppercase ENFORCEMENT_LEVELS
32
+ */
33
+ function normalizeEnforcement(val) {
34
+ if (!val) return ENFORCEMENT_LEVELS.PROMPT_GUIDANCE;
35
+ const s = String(val).trim().toUpperCase().replace(/-/g, '_');
36
+ if (s === 'RUNTIME' || s === 'LINTER' || s === 'ENFORCED') return ENFORCEMENT_LEVELS.ENFORCED;
37
+ if (s === 'PARTIAL' || s === 'PARTIALLY_ENFORCED') return ENFORCEMENT_LEVELS.PARTIALLY_ENFORCED;
38
+ if (s === 'PROMPT' || s === 'PROMPT_GUIDANCE' || s === 'GUIDANCE') return ENFORCEMENT_LEVELS.PROMPT_GUIDANCE;
39
+ if (s === 'REFERENCE' || s === 'DOCS') return ENFORCEMENT_LEVELS.REFERENCE;
40
+ if (s === 'EXAMPLE') return ENFORCEMENT_LEVELS.EXAMPLE;
41
+ return ENFORCEMENT_LEVELS.PROMPT_GUIDANCE;
42
+ }
43
+
44
+ /**
45
+ * Registered automated checkers in ContextOS
46
+ */
47
+ const AUTOMATED_CHECKERS = {
48
+ 'workspace-path-policy-v2': {
49
+ id: 'workspace-path-policy-v2',
50
+ name: 'Workspace Path Policy Guard v2',
51
+ description: 'Enforces directory containment, blocks traversal, NUL-bytes, and symlink escapes in safe-path.js',
52
+ type: 'runtime',
53
+ module: '.agents/filesystem/safe-path.js',
54
+ },
55
+ 'project-mutation-lock': {
56
+ id: 'project-mutation-lock',
57
+ name: 'Project Mutation Lock Engine',
58
+ description: 'Enforces cross-process advisory mutation locking preventing concurrent write corruption',
59
+ type: 'runtime',
60
+ module: '.agents/filesystem/project-lock.js',
61
+ },
62
+ 'journaled-transaction-recovery': {
63
+ id: 'journaled-transaction-recovery',
64
+ name: 'Journaled Transaction & Rollback Recovery',
65
+ description: 'Atomically stages file mutations with write-ahead intent log and rollback crash recovery',
66
+ type: 'runtime',
67
+ module: '.agents/filesystem/journaled-transaction.js',
68
+ },
69
+ 'lockfile-cas-integrity': {
70
+ id: 'lockfile-cas-integrity',
71
+ name: 'Lockfile v2 CAS Integrity Checker',
72
+ description: 'Cryptographically verifies Content Addressable Storage hashes for all managed project artifacts',
73
+ type: 'runtime',
74
+ module: '.agents/filesystem/lockfile-v2.js',
75
+ },
76
+ 'secret-scanner': {
77
+ id: 'secret-scanner',
78
+ name: 'Automated Secret & Credential Scanner',
79
+ description: 'Pre-commit and doctor scan detecting private keys, AWS/GCP/OpenAI credentials, and tokens',
80
+ type: 'scanner',
81
+ module: 'scripts/check-secrets.js',
82
+ },
83
+ 'adapter-drift-detector': {
84
+ id: 'adapter-drift-detector',
85
+ name: 'Adapter Output Provenance & Drift Detector',
86
+ description: 'Detects unauthorized manual modifications and upstream drift in generated agent adapter configs',
87
+ type: 'runtime',
88
+ module: '.agents/adapters/drift-detector.js',
89
+ },
90
+ 'manifest-schema-validator': {
91
+ id: 'manifest-schema-validator',
92
+ name: 'Skill Manifest Schema v2 Compiler Validator',
93
+ description: 'Fails closed on schema violations, invalid paths, and frontmatter divergence',
94
+ type: 'compiler',
95
+ module: '.agents/compiler/manifest-compiler.js',
96
+ },
97
+ 'skill-frontmatter-validator': {
98
+ id: 'skill-frontmatter-validator',
99
+ name: 'Skill Frontmatter & COSTAR Quality Validator',
100
+ description: 'Verifies YAML frontmatter integrity, minimum content sizes, and COSTAR formatting in SKILL.md',
101
+ type: 'linter',
102
+ module: '.agents/validate.js',
103
+ },
104
+ 'profile-integrity-validator': {
105
+ id: 'profile-integrity-validator',
106
+ name: 'Profile Integrity & Exclusion Validator',
107
+ description: 'Validates profile definitions, required skills, exclusions, and scoped package configurations',
108
+ type: 'compiler',
109
+ module: '.agents/profiles.js',
110
+ },
111
+ 'watch-coalescing-guard': {
112
+ id: 'watch-coalescing-guard',
113
+ name: 'Watch Event Coalescing & Race Guard',
114
+ description: 'Coalesces rapid file modification bursts and synchronizes compilations under project lock',
115
+ type: 'runtime',
116
+ module: '.agents/watch.js',
117
+ },
118
+ };
119
+
120
+ /**
121
+ * Built-in core normative rules inventory
122
+ */
123
+ const BUILTIN_RULES = [
124
+ {
125
+ id: 'SEC-001',
126
+ sourceSkill: 'security',
127
+ level: 'must',
128
+ enforcement: 'prompt-guidance',
129
+ summary: 'Always validate and sanitize all user input and untrusted external payloads before processing',
130
+ applicability: ['api', 'controllers', 'forms', 'inputs'],
131
+ priority: 90,
132
+ tokenCost: 45,
133
+ duplicates: ['SEC-AGENT-006'],
134
+ conflicts: [],
135
+ },
136
+ {
137
+ id: 'SEC-002',
138
+ sourceSkill: 'security',
139
+ level: 'must',
140
+ enforcement: 'runtime',
141
+ checker: 'secret-scanner',
142
+ summary: 'Zero plaintext credentials, private keys, or API tokens committed to repository',
143
+ applicability: ['all'],
144
+ priority: 100,
145
+ tokenCost: 35,
146
+ duplicates: [],
147
+ conflicts: [],
148
+ },
149
+ {
150
+ id: 'SEC-003',
151
+ sourceSkill: 'security',
152
+ level: 'must',
153
+ enforcement: 'prompt-guidance',
154
+ summary: 'Enforce authentication and authorization checks prior to accessing sensitive resources or data',
155
+ applicability: ['routes', 'services', 'database'],
156
+ priority: 95,
157
+ tokenCost: 40,
158
+ duplicates: [],
159
+ conflicts: [],
160
+ },
161
+ {
162
+ id: 'FS-001',
163
+ sourceSkill: 'filesystem',
164
+ level: 'must',
165
+ enforcement: 'runtime',
166
+ checker: 'workspace-path-policy-v2',
167
+ summary: 'Restrict all filesystem mutations strictly inside project root; prevent directory traversal',
168
+ applicability: ['filesystem', 'adapters', 'init'],
169
+ priority: 100,
170
+ tokenCost: 35,
171
+ duplicates: [],
172
+ conflicts: [],
173
+ },
174
+ {
175
+ id: 'FS-002',
176
+ sourceSkill: 'filesystem',
177
+ level: 'must',
178
+ enforcement: 'runtime',
179
+ checker: 'project-mutation-lock',
180
+ summary: 'Cross-process write operations must acquire project mutation lock to prevent concurrent races',
181
+ applicability: ['cli', 'adapters', 'watch', 'init'],
182
+ priority: 95,
183
+ tokenCost: 35,
184
+ duplicates: [],
185
+ conflicts: [],
186
+ },
187
+ {
188
+ id: 'FS-003',
189
+ sourceSkill: 'filesystem',
190
+ level: 'must',
191
+ enforcement: 'runtime',
192
+ checker: 'journaled-transaction-recovery',
193
+ summary: 'Multi-file modifications must execute within journaled transaction with atomic rollback capability',
194
+ applicability: ['adapters', 'init', 'update'],
195
+ priority: 95,
196
+ tokenCost: 40,
197
+ duplicates: [],
198
+ conflicts: [],
199
+ },
200
+ {
201
+ id: 'ADAPT-001',
202
+ sourceSkill: 'adapters',
203
+ level: 'must',
204
+ enforcement: 'runtime',
205
+ checker: 'adapter-drift-detector',
206
+ summary: 'Adapter compiler must produce deterministic output with provenance headers and detect drift',
207
+ applicability: ['adapters', 'export'],
208
+ priority: 90,
209
+ tokenCost: 40,
210
+ duplicates: [],
211
+ conflicts: [],
212
+ },
213
+ {
214
+ id: 'LOCK-001',
215
+ sourceSkill: 'filesystem',
216
+ level: 'must',
217
+ enforcement: 'runtime',
218
+ checker: 'lockfile-cas-integrity',
219
+ summary: 'Managed files in lockfile must match SHA-256 CAS content hashes with fail-closed integrity',
220
+ applicability: ['lockfile', 'doctor'],
221
+ priority: 95,
222
+ tokenCost: 35,
223
+ duplicates: [],
224
+ conflicts: [],
225
+ },
226
+ {
227
+ id: 'ARCH-001',
228
+ sourceSkill: 'system-design',
229
+ level: 'must',
230
+ enforcement: 'prompt-guidance',
231
+ summary: 'Business domain logic must never reside directly inside API route handlers or UI components',
232
+ applicability: ['routes', 'api', 'controllers'],
233
+ priority: 85,
234
+ tokenCost: 40,
235
+ duplicates: [],
236
+ conflicts: [],
237
+ },
238
+ {
239
+ id: 'ARCH-002',
240
+ sourceSkill: 'decisions',
241
+ level: 'should',
242
+ enforcement: 'reference',
243
+ summary: 'Record significant architectural choices and trade-offs in Architecture Decision Records (docs/decisions/)',
244
+ applicability: ['architecture', 'docs'],
245
+ priority: 70,
246
+ tokenCost: 30,
247
+ duplicates: [],
248
+ conflicts: [],
249
+ },
250
+ {
251
+ id: 'WORK-001',
252
+ sourceSkill: 'engineering-workflow',
253
+ level: 'must',
254
+ enforcement: 'runtime',
255
+ checker: 'manifest-schema-validator',
256
+ summary: 'All skill manifests must strictly conform to schema v2 with fail-closed validation',
257
+ applicability: ['skills', 'manifests'],
258
+ priority: 95,
259
+ tokenCost: 35,
260
+ duplicates: [],
261
+ conflicts: [],
262
+ },
263
+ {
264
+ id: 'WORK-002',
265
+ sourceSkill: 'engineering-workflow',
266
+ level: 'must',
267
+ enforcement: 'prompt-guidance',
268
+ summary: 'Follow risk-based workflows: routine tasks fast-track, standard plan, high requires spec & review',
269
+ applicability: ['workflow', 'all'],
270
+ priority: 90,
271
+ tokenCost: 50,
272
+ duplicates: [],
273
+ conflicts: [],
274
+ },
275
+ {
276
+ id: 'TEST-001',
277
+ sourceSkill: 'testing',
278
+ level: 'must',
279
+ enforcement: 'runtime',
280
+ checker: 'skill-frontmatter-validator',
281
+ summary: 'Zero unverified claims: mandatory proof-of-work with automated test suite and validator execution',
282
+ applicability: ['all'],
283
+ priority: 100,
284
+ tokenCost: 45,
285
+ duplicates: [],
286
+ conflicts: [],
287
+ },
288
+ {
289
+ id: 'PON-001',
290
+ sourceSkill: 'ponytail-mindset',
291
+ level: 'must',
292
+ enforcement: 'prompt-guidance',
293
+ summary: 'Surgical blast radius: modify only files planned for the task; zero unnecessary boilerplate',
294
+ applicability: ['all'],
295
+ priority: 90,
296
+ tokenCost: 35,
297
+ duplicates: [],
298
+ conflicts: [],
299
+ },
300
+ ];
301
+
302
+ /**
303
+ * Class representing the Rule Catalog and Instruction Inventory
304
+ */
305
+ class RuleCatalog {
306
+ constructor(options = {}) {
307
+ this.rootDir = options.rootDir || process.cwd();
308
+ this.checkers = { ...AUTOMATED_CHECKERS, ...(options.customCheckers || {}) };
309
+ this.rules = new Map();
310
+
311
+ // Register builtin rules
312
+ for (const rule of BUILTIN_RULES) {
313
+ this.registerRule(rule);
314
+ }
315
+ }
316
+
317
+ /**
318
+ * Registers a rule in the catalog, validating the enforcement invariant.
319
+ */
320
+ registerRule(rule) {
321
+ if (!rule || !rule.id) {
322
+ throw new Error('Rule registration requires a valid rule object with an "id" property.');
323
+ }
324
+
325
+ const enforcement = normalizeEnforcement(rule.enforcement);
326
+
327
+ // INVARIANT (Section 14.1): A rule existing only in Markdown cannot be ENFORCED.
328
+ if (enforcement === ENFORCEMENT_LEVELS.ENFORCED) {
329
+ if (!rule.checker) {
330
+ throw new Error(`Rule '${rule.id}' cannot be marked ENFORCED without a registered automated checker.`);
331
+ }
332
+ if (!this.checkers[rule.checker]) {
333
+ throw new Error(`Rule '${rule.id}' references unknown checker '${rule.checker}'. Registered checkers: ${Object.keys(this.checkers).join(', ')}`);
334
+ }
335
+ }
336
+
337
+ const normalized = {
338
+ id: rule.id,
339
+ sourceSkill: rule.sourceSkill || 'core',
340
+ level: rule.level || 'must',
341
+ enforcement,
342
+ checker: enforcement === ENFORCEMENT_LEVELS.ENFORCED ? rule.checker : (rule.checker || null),
343
+ summary: rule.summary || '',
344
+ applicability: Array.isArray(rule.applicability) ? rule.applicability : ['all'],
345
+ priority: typeof rule.priority === 'number' ? rule.priority : 50,
346
+ tokenCost: typeof rule.tokenCost === 'number' ? rule.tokenCost : 40,
347
+ duplicates: Array.isArray(rule.duplicates) ? rule.duplicates : [],
348
+ conflicts: Array.isArray(rule.conflicts) ? rule.conflicts : [],
349
+ };
350
+
351
+ this.rules.set(normalized.id, normalized);
352
+ return normalized;
353
+ }
354
+
355
+ /**
356
+ * Loads rules declared inside compiled registry or skills directory
357
+ */
358
+ loadFromRegistry(registry) {
359
+ if (!registry || !registry.skills) return;
360
+
361
+ for (const [skillId, skill] of Object.entries(registry.skills)) {
362
+ if (Array.isArray(skill.rules)) {
363
+ for (const r of skill.rules) {
364
+ try {
365
+ this.registerRule({
366
+ ...r,
367
+ sourceSkill: skillId,
368
+ });
369
+ } catch (err) {
370
+ // Log warning on invalid manifest rule
371
+ }
372
+ }
373
+ }
374
+ }
375
+ }
376
+
377
+ /**
378
+ * Retrieves a rule by ID
379
+ */
380
+ getRule(id) {
381
+ return this.rules.get(id) || null;
382
+ }
383
+
384
+ /**
385
+ * Returns all rules as an array
386
+ */
387
+ getAllRules() {
388
+ return Array.from(this.rules.values());
389
+ }
390
+
391
+ /**
392
+ * Returns all registered automated checkers
393
+ */
394
+ getAllCheckers() {
395
+ return Object.values(this.checkers);
396
+ }
397
+
398
+ /**
399
+ * Formats detailed explanation for a single rule
400
+ */
401
+ explainRule(id) {
402
+ const rule = this.getRule(id);
403
+ if (!rule) {
404
+ return `Rule '${id}' not found in catalog. Run 'contextos explain --rules' to list all rules.`;
405
+ }
406
+
407
+ const lines = [];
408
+ lines.push('\n══════════════════════════════════════════');
409
+ lines.push(` ContextOS — Rule Explanation: ${rule.id}`);
410
+ lines.push('══════════════════════════════════════════\n');
411
+ lines.push(` Rule ID : ${rule.id}`);
412
+ lines.push(` Source Skill : ${rule.sourceSkill}`);
413
+ lines.push(` Level : ${rule.level.toUpperCase()}`);
414
+ lines.push(` Enforcement : ${rule.enforcement}`);
415
+
416
+ if (rule.enforcement === ENFORCEMENT_LEVELS.ENFORCED) {
417
+ const checker = this.checkers[rule.checker];
418
+ lines.push(` Active Checker : [ENFORCED] ${rule.checker}`);
419
+ if (checker) {
420
+ lines.push(` Checker Module : ${checker.module}`);
421
+ lines.push(` Checker Purpose : ${checker.description}`);
422
+ }
423
+ } else {
424
+ lines.push(` Enforcement Note : Governed via agent prompt guidelines (No runtime checker)`);
425
+ }
426
+
427
+ lines.push(` Summary : ${rule.summary}`);
428
+ lines.push(` Applicability : ${rule.applicability.join(', ')}`);
429
+ lines.push(` Estimated Cost : ~${rule.tokenCost} tokens`);
430
+ lines.push(` Priority : ${rule.priority} / 100`);
431
+
432
+ if (rule.duplicates.length > 0) {
433
+ lines.push(` Known Duplicates : ${rule.duplicates.join(', ')} (consolidated)`);
434
+ }
435
+ if (rule.conflicts.length > 0) {
436
+ lines.push(` Conflicts With : ${rule.conflicts.join(', ')}`);
437
+ }
438
+
439
+ lines.push('\n──────────────────────────────────────────\n');
440
+ return lines.join('\n');
441
+ }
442
+
443
+ /**
444
+ * Formats explanation of all rules within a skill
445
+ */
446
+ explainSkill(skillId) {
447
+ const skillRules = this.getAllRules().filter(r => r.sourceSkill === skillId);
448
+ const lines = [];
449
+ lines.push('\n══════════════════════════════════════════');
450
+ lines.push(` ContextOS — Skill Rules: ${skillId}`);
451
+ lines.push('══════════════════════════════════════════\n');
452
+
453
+ if (skillRules.length === 0) {
454
+ lines.push(` No individual rule IDs declared for '${skillId}'.`);
455
+ lines.push(` All guidance is delivered as comprehensive skill instructions.`);
456
+ } else {
457
+ lines.push(` Found ${skillRules.length} declared rule(s):\n`);
458
+ for (const r of skillRules) {
459
+ const checkStr = r.checker ? ` [Checker: ${r.checker}]` : '';
460
+ lines.push(` • ${r.id} (${r.level.toUpperCase()}) — ${r.enforcement}${checkStr}`);
461
+ lines.push(` "${r.summary}" (~${r.tokenCost} tokens)`);
462
+ }
463
+ }
464
+
465
+ lines.push('\n──────────────────────────────────────────\n');
466
+ return lines.join('\n');
467
+ }
468
+
469
+ /**
470
+ * Formats a summary table of all rules
471
+ */
472
+ formatRulesSummary() {
473
+ const lines = [];
474
+ lines.push('\n══════════════════════════════════════════════════════════════════════════════════');
475
+ lines.push(' ContextOS — Instruction Inventory & Rule Enforcement Catalog');
476
+ lines.push('══════════════════════════════════════════════════════════════════════════════════\n');
477
+ lines.push(' RULE ID | SKILL | LEVEL | ENFORCEMENT | CHECKER');
478
+ lines.push(' ──────────┼──────────────┼───────┼─────────────────┼────────────────────────────');
479
+
480
+ for (const r of this.getAllRules()) {
481
+ const id = r.id.padEnd(10);
482
+ const skill = r.sourceSkill.slice(0, 12).padEnd(12);
483
+ const level = r.level.toUpperCase().padEnd(5);
484
+ const enf = r.enforcement.slice(0, 15).padEnd(15);
485
+ const checker = r.checker ? r.checker.slice(0, 26) : '— (prompt guidance)';
486
+ lines.push(` ${id}| ${skill} | ${level} | ${enf} | ${checker}`);
487
+ }
488
+
489
+ lines.push('\n Total rules: ' + this.rules.size);
490
+ const enforcedCount = this.getAllRules().filter(r => r.enforcement === ENFORCEMENT_LEVELS.ENFORCED).length;
491
+ lines.push(` Enforced via code checkers : ${enforcedCount}`);
492
+ lines.push(` Governed via prompt : ${this.rules.size - enforcedCount}`);
493
+ lines.push('\n──────────────────────────────────────────────────────────────────────────────────\n');
494
+ return lines.join('\n');
495
+ }
496
+
497
+ /**
498
+ * Formats summary of automated checkers
499
+ */
500
+ formatCheckersSummary() {
501
+ const lines = [];
502
+ lines.push('\n══════════════════════════════════════════════════════════════════════════════════');
503
+ lines.push(' ContextOS — Registered Automated Enforcement Checkers');
504
+ lines.push('══════════════════════════════════════════════════════════════════════════════════\n');
505
+
506
+ for (const ch of this.getAllCheckers()) {
507
+ lines.push(` • ${ch.id} [${ch.type.toUpperCase()}]`);
508
+ lines.push(` Name : ${ch.name}`);
509
+ lines.push(` Module : ${ch.module}`);
510
+ lines.push(` Role : ${ch.description}\n`);
511
+ }
512
+
513
+ lines.push(` Total active checkers: ${Object.keys(this.checkers).length}`);
514
+ lines.push('──────────────────────────────────────────────────────────────────────────────────\n');
515
+ return lines.join('\n');
516
+ }
517
+ }
518
+
519
+ module.exports = {
520
+ RuleCatalog,
521
+ ENFORCEMENT_LEVELS,
522
+ AUTOMATED_CHECKERS,
523
+ BUILTIN_RULES,
524
+ normalizeEnforcement,
525
+ };