tribunal-kit 4.4.5 → 4.5.1

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.
@@ -1,1121 +1,1230 @@
1
1
  #!/usr/bin/env node
2
- /**
3
- * tribunal-kit CLI (alias: tk)
4
- *
5
- * Commands:
6
- * init — Install .agent/ into target project
7
- * update — Re-install to get latest changes
8
- * status — Check if .agent/ is installed
9
- * learn — Evolve project idioms based on git diffs
10
- * case — Manage Case Law precedents
11
- * hook — Install pre-push git hook
12
- * uninstall — Remove .agent/ from project
13
- *
14
- * Usage:
15
- * npx tribunal-kit init
16
- * npx tribunal-kit init --force
17
- * npx tribunal-kit init --path ./myapp
18
- * npx tribunal-kit init --quiet
19
- * npx tribunal-kit init --dry-run
20
- * tribunal-kit update
21
- * tribunal-kit status
22
- * tribunal-kit uninstall
23
- */
24
-
25
- const fs = require('fs');
26
- const path = require('path');
27
- const https = require('https');
28
- const { execSync } = require('child_process');
29
-
30
- const PKG = require(path.resolve(__dirname, '..', 'package.json'));
31
- const CURRENT_VERSION = PKG.version;
32
-
33
- // ── Colors ───────────────────────────────────────────────
34
- const C = {
35
- reset: '\x1b[0m',
36
- bold: '\x1b[1m',
37
- dim: '\x1b[2m',
38
- red: '\x1b[91m',
39
- green: '\x1b[92m',
40
- yellow: '\x1b[93m',
41
- blue: '\x1b[94m',
42
- magenta: '\x1b[95m',
43
- cyan: '\x1b[96m',
44
- white: '\x1b[97m',
45
- gray: '\x1b[90m',
46
- bgCyan: '\x1b[46m',
47
- };
48
-
49
- function colorize(color, text) {
50
- return `${C[color]}${text}${C.reset}`;
51
- }
52
-
53
- function c(color, text) { return `${C[color]}${text}${C.reset}`; }
54
- function bold(text) { return `${C.bold}${text}${C.reset}`; }
55
-
56
- // ── Logging ──────────────────────────────────────────────
57
- let quiet = false;
58
- let verbose = false;
59
-
60
- function log(msg) { if (!quiet) console.log(msg); }
61
- function ok(msg) { if (!quiet) console.log(` ${c('green', '✔')} ${msg}`); }
62
- function warn(msg) { if (!quiet) console.log(` ${c('yellow', '⚠')} ${msg}`); }
63
- function err(msg) { console.error(` ${c('red', '✖')} ${msg}`); }
64
- function dim(msg) { if (!quiet) console.log(` ${c('gray', msg)}`); }
65
- function dbg(msg) { if (verbose) console.log(` ${c('gray', '⊡')} ${c('gray', msg)}`); }
66
-
67
- // ── Arg Parser ───────────────────────────────────────────
68
- function parseArgs(argv) {
69
- const args = { command: null, flags: {} };
70
- const raw = argv.slice(2);
71
-
72
- // First non-flag arg is the command
73
- for (const arg of raw) {
74
- if (!arg.startsWith('--') && !args.command) {
75
- args.command = arg;
76
- continue;
77
- }
78
- if (arg === '--force') { args.flags.force = true; continue; }
79
- if (arg === '--quiet') { args.flags.quiet = true; continue; }
80
- if (arg === '--verbose') { args.flags.verbose = true; continue; }
81
- if (arg === '--dry-run') { args.flags.dryRun = true; continue; }
82
- if (arg === '--minimal') { args.flags.minimal = true; continue; }
83
- if (arg === '--skip-update-check') { args.flags.skipUpdateCheck = true; continue; }
84
- if (arg === '--head') { args.flags.head = true; continue; }
85
- if (arg.startsWith('--path=')) {
86
- args.flags.path = arg.split('=').slice(1).join('=');
87
- }
88
- if (arg === '--path') {
89
- const idx = raw.indexOf('--path');
90
- const nextVal = raw[idx + 1];
91
- if (!nextVal || nextVal.startsWith('--')) {
92
- console.error(` \x1b[91m--path requires a directory argument\x1b[0m`);
93
- process.exit(1);
94
- }
95
- args.flags.path = nextVal;
96
- }
97
- if (arg.startsWith('--branch=')) {
98
- args.flags.branch = arg.split('=').slice(1).join('=');
99
- }
100
- }
101
-
102
- return args;
103
- }
104
-
105
- // ── File Utilities ────────────────────────────────────────
106
-
107
- // Core agents to install in --minimal mode
108
- const CORE_AGENTS = new Set([
109
- 'backend-specialist.md',
110
- 'frontend-specialist.md',
111
- 'database-architect.md',
112
- 'debugger.md',
113
- 'security-auditor.md',
114
- 'logic-reviewer.md',
115
- 'dependency-reviewer.md',
116
- 'type-safety-reviewer.md',
117
- 'performance-reviewer.md',
118
- 'orchestrator.md',
119
- 'explorer-agent.md',
120
- 'project-planner.md',
121
- 'test-engineer.md',
122
- ]);
123
-
124
- // Core skills to install in --minimal mode
125
- const CORE_SKILLS = new Set([
126
- 'clean-code', 'architecture', 'testing-patterns', 'systematic-debugging',
127
- 'frontend-design', 'database-design', 'api-patterns', 'nodejs-best-practices',
128
- 'vulnerability-scanner', 'typescript-advanced', 'python-pro', 'nextjs-react-expert',
129
- 'react-specialist', 'performance-profiling', 'lint-and-validate',
130
- ]);
131
-
132
- function copyDir(src, dest, dryRun = false, filter = null) {
133
- if (!dryRun) {
134
- fs.mkdirSync(dest, { recursive: true });
135
- }
136
-
137
- const entries = fs.readdirSync(src, { withFileTypes: true });
138
- let count = 0;
139
-
140
- for (const entry of entries) {
141
- // Apply filter if provided (for --minimal mode)
142
- if (filter && !filter(entry.name, src)) {
143
- dbg(` skip: ${entry.name}`);
144
- continue;
145
- }
146
-
147
- const srcPath = path.join(src, entry.name);
148
- const destPath = path.join(dest, entry.name);
149
-
150
- if (entry.isDirectory()) {
151
- count += copyDir(srcPath, destPath, dryRun, filter);
152
- } else {
153
- if (!dryRun) {
154
- fs.cpSync(srcPath, destPath, { force: true });
155
- }
156
- dbg(` copy: ${entry.name}`);
157
- count++;
158
- }
159
- }
160
-
161
- return count;
162
- }
163
-
164
- function countDir(dir) {
165
- let count = 0;
166
- const entries = fs.readdirSync(dir, { withFileTypes: true });
167
- for (const e of entries) {
168
- if (e.isDirectory()) count += countDir(path.join(dir, e.name));
169
- else count++;
170
- }
171
- return count;
172
- }
173
-
174
- // ── Version Check & Auto-Update ──────────────────────────
175
-
176
- /**
177
- * Compare two semver strings. Returns:
178
- * 1 if a > b, -1 if a < b, 0 if equal.
179
- */
180
- function compareSemver(a, b) {
181
- const pa = a.replace(/^v/, '').split('.').map(Number);
182
- const pb = b.replace(/^v/, '').split('.').map(Number);
183
- for (let i = 0; i < 3; i++) {
184
- const na = pa[i] || 0;
185
- const nb = pb[i] || 0;
186
- if (na > nb) return 1;
187
- if (na < nb) return -1;
188
- }
189
- return 0;
190
- }
191
-
192
- /**
193
- * Fetch the latest version from npm registry.
194
- * Returns the version string (e.g. '4.0.0') or null on failure.
195
- */
196
- function fetchLatestVersion() {
197
- return new Promise((resolve) => {
198
- const req = https.get(
199
- 'https://registry.npmjs.org/tribunal-kit/latest',
200
- {
201
- headers: {
202
- 'Accept': 'application/json',
203
- 'User-Agent': `tribunal-kit/${CURRENT_VERSION}`
204
- },
205
- timeout: 5000
206
- },
207
- (res) => {
208
- let data = '';
209
- res.on('data', (chunk) => { data += chunk; });
210
- res.on('end', () => {
211
- try {
212
- const json = JSON.parse(data);
213
- const version = json.version || null;
214
- resolve(version);
215
- } catch {
216
- resolve(null);
217
- }
218
- });
219
- }
220
- );
221
- req.on('error', () => resolve(null));
222
- req.on('timeout', () => { req.destroy(); resolve(null); });
223
- });
224
- }
225
-
226
- /**
227
- * Check for a newer version and re-invoke with @latest if found.
228
- * Uses TK_SKIP_UPDATE_CHECK env var as recursion guard.
229
- * Returns true if a re-invoke happened (caller should exit), false otherwise.
230
- */
231
- async function autoUpdateCheck(originalArgs) {
232
- // Recursion guard: if we're already a re-invoked process, skip
233
- if (process.env.TK_SKIP_UPDATE_CHECK === '1') {
234
- return false;
235
- }
236
-
237
- const latestVersion = await fetchLatestVersion();
238
-
239
- if (!latestVersion) {
240
- // Network fail — proceed silently with current version
241
- return false;
242
- }
243
-
244
- if (compareSemver(latestVersion, CURRENT_VERSION) <= 0) {
245
- // Already up to date
246
- dim(`Version ${CURRENT_VERSION} is up to date.`);
247
- return false;
248
- }
249
-
250
- // Newer version available — re-invoke
251
- log('');
252
- log(colorize('cyan', ` ⬆ New version available: ${colorize('bold', CURRENT_VERSION)} → ${colorize('bold', latestVersion)}`));
253
- log(colorize('gray', ' Re-invoking with latest version...'));
254
- log('');
255
-
256
- try {
257
- // Build the command pulling from npm registry
258
- const args = originalArgs.join(' ');
259
- const cmd = `npx -y tribunal-kit@${latestVersion} ${args}`;
260
-
261
- execSync(cmd, {
262
- stdio: 'inherit',
263
- env: { ...process.env, TK_SKIP_UPDATE_CHECK: '1' },
264
- });
265
- return true; // Re-invoke succeeded, caller should exit
266
- } catch (e) {
267
- warn(`Auto-update failed: ${e.message}`);
268
- warn('Continuing with current version...');
269
- return false; // Fall through to current version
270
- }
271
- }
272
-
273
- // ── Kit Source Location ───────────────────────────────────
274
- function getKitAgent() {
275
- // When installed via npm, the .agent/ folder is next to this script's package
276
- const kitRoot = path.resolve(__dirname, '..');
277
- const agentDir = path.join(kitRoot, '.agent');
278
-
279
- if (!fs.existsSync(agentDir)) {
280
- err(`Kit .agent/ folder not found at: ${agentDir}`);
281
- err('The package may be corrupted. Try: npm install -g tribunal-kit');
282
- process.exit(1);
283
- }
284
-
285
- return agentDir;
286
- }
287
-
288
- // ── Self-Install Guard ────────────────────────────────────
289
- /**
290
- * Returns true if the target directory IS the tribunal-kit package itself.
291
- * This prevents `init --force` / `update` from deleting the package's own files
292
- * when run from inside the project directory.
293
- */
294
- function isSelfInstall(targetDir) {
295
- const kitRoot = path.resolve(__dirname, '..');
296
- const resolvedTarget = path.resolve(targetDir);
297
-
298
- // Direct path match
299
- if (resolvedTarget === kitRoot) return true;
300
-
301
- // Check if the target's package.json is this package
302
- const targetPkg = path.join(resolvedTarget, 'package.json');
303
- if (fs.existsSync(targetPkg)) {
304
- try {
305
- const targetName = JSON.parse(fs.readFileSync(targetPkg, 'utf8')).name;
306
- if (targetName === PKG.name) return true;
307
- } catch {
308
- // Unreadable package.json — not a match
309
- }
310
- }
311
-
312
- return false;
313
- }
314
-
315
- // ── Banner ────────────────────────────────────────────────
316
- function banner() {
317
- if (quiet) return;
318
- // Big ASCII art (TRIBUNAL-KIT)
319
- const art = String.raw`
320
- ████████╗██████╗ ██╗██████╗ ██╗ ██╗███╗ ██╗ █████╗ ██╗ ██╗ ██╗██╗████████╗
321
- ╚══██╔══╝██╔══██╗██║██╔══██╗██║ ██║████╗ ██║██╔══██╗██║ ██║ ██╔╝██║╚══██╔══╝
322
- ██║ ██████╔╝██║██████╔╝██║ ██║██╔██╗ ██║███████║██║█████╗█████╔╝ ██║ ██║
323
- ██║ ██╔══██╗██║██╔══██╗██║ ██║██║╚██╗██║██╔══██║██║╚════╝██╔═██╗ ██║ ██║
324
- ██║ ██║ ██║██║██████╔╝╚██████╔╝██║ ╚████║██║ ██║███████╗ ██║ ██╗██║ ██║
325
- ╚═╝ ╚═╝ ╚═╝╚═╝╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ `.split('\n').filter(Boolean);
326
- console.log();
327
- const _maxLen = Math.max(...art.map(line => line.length));
328
- for (const line of art) {
329
- let gradientLine = ' ' + C.bold;
330
- for (let i = 0; i < line.length; i++) {
331
- gradientLine += `\x1b[38;2;255;22;55m${line[i]}`;
332
- }
333
- gradientLine += C.reset;
334
- log(gradientLine);
335
- }
336
- console.log();
337
- // Subtitle strip
338
- const W = 84;
339
- const sub = 'Anti-Hallucination Agent System';
340
- const sp = Math.max(0, W - sub.length);
341
- const centred = ' '.repeat(Math.floor(sp / 2)) + sub + ' '.repeat(Math.ceil(sp / 2));
342
- const RED_ANSI = '\x1b[38;2;255;22;55m';
343
- console.log(` ${RED_ANSI}╔${'═'.repeat(W)}╗${C.reset}`);
344
- console.log(` ${RED_ANSI}║${C.reset}${c('gray', centred)}${RED_ANSI}║${C.reset}`);
345
- console.log(` ${RED_ANSI}╚${'═'.repeat(W)}╝${C.reset}`);
346
- console.log();
347
- }
348
-
349
- // ── Commands ──────────────────────────────────────────────
350
- function cmdInit(flags) {
351
- const agentSrc = getKitAgent();
352
- const targetDir = flags.path ? path.resolve(flags.path) : process.cwd();
353
- const agentDest = path.join(targetDir, '.agent');
354
- const dryRun = flags.dryRun || false;
355
-
356
- // ── Self-install guard ──────────────────────────────────
357
- if (isSelfInstall(targetDir)) {
358
- err('Cannot run init/update inside the tribunal-kit package itself.');
359
- err(`Target: ${targetDir}`);
360
- err(`Package: ${path.resolve(__dirname, '..')}`);
361
- console.log();
362
- dim('This command is designed to install .agent/ into OTHER projects.');
363
- dim('Run it from the root of the project you want to set up:');
364
- dim(' cd /path/to/your-project');
365
- dim(' npx tribunal-kit init');
366
- console.log();
367
- process.exit(1);
368
- }
369
- // ────────────────────────────────────────────────────────
370
-
371
- // ── Backup / Cleanup ────────────────────────────────────
372
- if (!dryRun && fs.existsSync(agentDest) && flags.force) {
373
- // Backup the existing subdirectories before overwriting
374
- const backupDir = path.join(agentDest, '.backups', `backup-${Date.now()}`);
375
- fs.mkdirSync(backupDir, { recursive: true });
376
-
377
- // PRESERVE_DIRS: user-generated content that must survive updates
378
- const _PRESERVE_DIRS = ['history', 'patterns', 'mcp_config.json'];
379
- const subdirs = ['agents', 'workflows', 'skills', 'scripts', '.shared', 'rules'];
380
- for (const sub of subdirs) {
381
- const subPath = path.join(agentDest, sub);
382
- if (fs.existsSync(subPath)) {
383
- // Copy to backup dir
384
- copyDir(subPath, path.join(backupDir, sub), false);
385
- fs.rmSync(subPath, { recursive: true, force: true });
386
- }
387
- }
388
- log(` ${c('gray', '✦ Backed up existing configurations to .agent/.backups/')}`);
389
-
390
-
391
- }
392
- // ────────────────────────────────────────────────────────
393
-
394
- banner();
395
-
396
- if (dryRun) {
397
- log(colorize('yellow', ' DRY RUN — no files will be written'));
398
- console.log();
399
- }
400
-
401
- // Check target exists
402
- if (!fs.existsSync(targetDir)) {
403
- err(`Target directory not found: ${targetDir}`);
404
- process.exit(1);
405
- }
406
-
407
- // Check if .agent already exists
408
- if (fs.existsSync(agentDest) && !flags.force) {
409
- warn('.agent/ already exists in this project.');
410
- log(` ${c('gray', '▸')} To refresh or update it, run: ${colorize('white', 'tribunal-kit init --force')}`);
411
- log(` ${c('gray', '▸')} Or check status with: ${colorize('cyan', 'tribunal-kit status')}`);
412
- console.log();
413
- process.exit(0);
414
- }
415
-
416
- // Ensure history dirs exist (Case Law + Skill Evolution)
417
- if (!dryRun) {
418
- const caseDir = path.join(agentDest, 'history', 'case-law', 'cases');
419
- const evoDir = path.join(agentDest, 'history', 'skill-evolution');
420
- fs.mkdirSync(caseDir, { recursive: true });
421
- fs.mkdirSync(evoDir, { recursive: true });
422
- const gkCase = path.join(caseDir, '.gitkeep');
423
- const gkEvo = path.join(evoDir, '.gitkeep');
424
- if (!fs.existsSync(gkCase)) fs.writeFileSync(gkCase, '');
425
- if (!fs.existsSync(gkEvo)) fs.writeFileSync(gkEvo, '');
426
- }
427
-
428
- // Count what we're installing
429
- const isMinimal = flags.minimal || false;
430
- if (isMinimal) {
431
- log(` ${c('yellow','⚡')} ${bold('Minimal mode')} — installing core agents and skills only`);
432
- console.log();
433
- }
434
- const totalFiles = countDir(agentSrc);
435
- dbg(`Source: ${agentSrc}`);
436
- dbg(`Target: ${agentDest}`);
437
- dbg(`Total source files: ${totalFiles}`);
438
- log(` ${c('gray','▸')} Scanning ${c('white', String(totalFiles))} files ${c('gray','')} ${c('gray', agentDest)}`);
439
-
440
- try {
441
- // Build filter for --minimal mode
442
- const minimalFilter = isMinimal ? (name, parentDir) => {
443
- const parentName = path.basename(parentDir);
444
- if (parentName === 'agents') return CORE_AGENTS.has(name);
445
- if (parentName === 'skills') return CORE_SKILLS.has(name);
446
- return true; // everything else passes
447
- } : null;
448
-
449
- const copied = copyDir(agentSrc, agentDest, dryRun, minimalFilter);
450
-
451
- console.log();
452
- if (dryRun) {
453
- ok(`${bold('DRY RUN')} complete — would install ${c('cyan', String(copied))} files`);
454
- dim(`Target: ${agentDest}`);
455
- } else {
456
- // ── Success card — W=62, rows padded by plain-text length ──
457
- const W = 62;
458
- const agentsCount = fs.readdirSync(path.join(agentDest, 'agents')).length;
459
- const workflowsCount = fs.readdirSync(path.join(agentDest, 'workflows')).length;
460
- const skillsCount = fs.readdirSync(path.join(agentDest, 'skills')).length;
461
- const scriptsCount = fs.readdirSync(path.join(agentDest, 'scripts')).length;
462
-
463
- // Stat rows: compute trailing spaces from plain text so right ║ aligns
464
- const statRow = (icon, label, val, col) => {
465
- // emoji JS .length===2 == terminal display width 2 ✓
466
- const plain = ` ${icon} ${label.padEnd(10)}${String(val).padStart(3)} installed`;
467
- const trail = ' '.repeat(Math.max(0, W - plain.length));
468
- return ` ${c('cyan','║')} ${icon} ${c('white',label.padEnd(10))}${c(col,String(val).padStart(3))} ${c('gray','installed')}${trail}${c('cyan','║')}`;
469
- };
470
- // Plain-text rows (header / blank)
471
- const plainRow = (text, wrapFn) => {
472
- const trail = ' '.repeat(Math.max(0, W - text.length));
473
- return ` ${c('cyan','║')}${wrapFn(text)}${trail}${c('cyan','║')}`;
474
- };
475
- // Next-step rows: fixed cmd column + description
476
- const stepRow = (cmd, desc) => {
477
- const plain = ` ${cmd.padEnd(16)}${desc}`;
478
- const trail = ' '.repeat(Math.max(0, W - plain.length));
479
- return ` ${c('cyan','║')} ${c('white',cmd.padEnd(16))}${c('gray',desc)}${trail}${c('cyan','║')}`;
480
- };
481
-
482
- console.log(` ${c('green','✔')} ${bold(c('green','Installation complete'))} ${c('gray','—')} ${c('white',String(copied))} files`);
483
- console.log(` ${c('gray',' ╰─')} ${c('gray', agentDest)}`);
484
- console.log();
485
- console.log(` ${c('cyan', '╔' + '═'.repeat(W) + '╗')}`);
486
- console.log(plainRow(` What's inside:`, s => c('bold', c('white', s))));
487
- console.log(` ${c('cyan', '╠' + '═'.repeat(W) + '')}`);
488
- console.log(statRow('🤖', 'Agents', agentsCount, 'magenta'));
489
- console.log(statRow('⚡', 'Workflows', workflowsCount, 'yellow'));
490
- console.log(statRow('🧠', 'Skills', skillsCount, 'blue'));
491
- console.log(statRow('🔧', 'Scripts', scriptsCount, 'green'));
492
- console.log(` ${c('cyan', '╠' + '═'.repeat(W) + '╣')}`);
493
- console.log(plainRow('', () => ''));
494
- console.log(plainRow(` Next steps:`, s => c('gray', s)));
495
- console.log(stepRow('/generate', 'Generate code with anti-hallucination'));
496
- console.log(stepRow('/review', 'Audit existing code for issues'));
497
- console.log(stepRow('/tribunal-full', 'Run all 16 reviewers in parallel'));
498
- console.log(plainRow('', () => ''));
499
- console.log(` ${c('cyan', '╚' + '═'.repeat(W) + '╝')}`);
500
- console.log();
501
- log(` ${c('gray', '✦ Generating IDE bridge files...')}`);
502
- generateIDEBridges(targetDir, agentDest, dryRun);
503
- }
504
-
505
- console.log();
506
- } catch (e) {
507
- err(`Failed to install: ${e.message}`);
508
- process.exit(1);
509
- }
510
- }
511
-
512
- // ── IDE Bridge Files ──────────────────────────────────────
513
- // Each AI IDE reads rules from a different location.
514
- // We generate bridge files that point each IDE at .agent/
515
- function generateIDEBridges(targetDir, agentDest, dryRun = false) {
516
- const rulesFile = path.join(agentDest, 'rules', 'GEMINI.md');
517
- let rulesContent = '';
518
- if (fs.existsSync(rulesFile)) {
519
- rulesContent = fs.readFileSync(rulesFile, 'utf8');
520
- }
521
-
522
- // Helper: write a bridge file only if it doesn't already exist
523
- const writeBridge = (filePath, content, label) => {
524
- if (dryRun) {
525
- dbg(` would create: ${filePath}`);
526
- return;
527
- }
528
- const dir = path.dirname(filePath);
529
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
530
- if (fs.existsSync(filePath)) {
531
- dbg(` skip (exists): ${path.basename(filePath)}`);
532
- return;
533
- }
534
- fs.writeFileSync(filePath, content, 'utf8');
535
- ok(`${label} → ${c('gray', path.relative(targetDir, filePath))}`);
536
- };
537
-
538
- // ── 1. Cursor (.cursorrules) ──────────────────────────
539
- const cursorRules = `# Tribunal Kit — Cursor Bridge
540
- # Auto-generated by tribunal-kit init. Do not edit manually.
541
- # Source: .agent/rules/GEMINI.md
542
-
543
- ${rulesContent}
544
- `;
545
- writeBridge(
546
- path.join(targetDir, '.cursorrules'),
547
- cursorRules,
548
- 'Cursor'
549
- );
550
-
551
- // ── 2. Windsurf (.windsurfrules) ─────────────────────
552
- const windsurfRules = `# Tribunal Kit — Windsurf Bridge
553
- # Auto-generated by tribunal-kit init. Do not edit manually.
554
- # Source: .agent/rules/GEMINI.md
555
-
556
- ${rulesContent}
557
- `;
558
- writeBridge(
559
- path.join(targetDir, '.windsurfrules'),
560
- windsurfRules,
561
- 'Windsurf'
562
- );
563
-
564
- // ── 3. Gemini / Antigravity (.gemini/settings.json) ──
565
- const geminiSettings = JSON.stringify({
566
- "$schema": "https://raw.githubusercontent.com/anthropics/anthropic-cookbook/main/.gemini/settings.schema.json",
567
- "rules": [
568
- { "path": "../.agent/rules/GEMINI.md", "trigger": "always_on" }
569
- ],
570
- "agents": { "directory": "../.agent/agents" },
571
- "skills": { "directory": "../.agent/skills" },
572
- "workflows": { "directory": "../.agent/workflows" }
573
- }, null, 2) + '\n';
574
- writeBridge(
575
- path.join(targetDir, '.gemini', 'settings.json'),
576
- geminiSettings,
577
- 'Gemini/Antigravity'
578
- );
579
-
580
- // ── Also create .gemini/GEMINI.md as a direct rules file ──
581
- const geminiRulesBridge = `---
582
- trigger: always_on
583
- ---
584
-
585
- # Tribunal Kit Gemini Bridge
586
- # Auto-generated by tribunal-kit init.
587
- # Full rules: .agent/rules/GEMINI.md
588
-
589
- ${rulesContent}
590
- `;
591
- writeBridge(
592
- path.join(targetDir, '.gemini', 'GEMINI.md'),
593
- geminiRulesBridge,
594
- 'Gemini rules'
595
- );
596
-
597
- // ── 4. GitHub Copilot (.github/copilot-instructions.md) ──
598
- const copilotInstructions = `# Tribunal Kit — Copilot Bridge
599
- # Auto-generated by tribunal-kit init. Do not edit manually.
600
- # Source: .agent/rules/GEMINI.md
601
-
602
- ${rulesContent}
603
- `;
604
- writeBridge(
605
- path.join(targetDir, '.github', 'copilot-instructions.md'),
606
- copilotInstructions,
607
- 'GitHub Copilot'
608
- );
609
-
610
- // ── 5. Claude (.claude/CLAUDE.md) ─────────────────────
611
- const claudeRules = `# Tribunal Kit Claude Bridge
612
- # Auto-generated by tribunal-kit init. Do not edit manually.
613
- # Source: .agent/rules/GEMINI.md
614
-
615
- ${rulesContent}
616
- `;
617
- writeBridge(
618
- path.join(targetDir, '.claude', 'CLAUDE.md'),
619
- claudeRules,
620
- 'Claude'
621
- );
622
-
623
- console.log();
624
- }
625
-
626
- function cmdUpdate(flags) {
627
- // ── Self-install guard (early, before banner) ───────────
628
- const targetDir = flags.path ? path.resolve(flags.path) : process.cwd();
629
- if (isSelfInstall(targetDir)) {
630
- err('Cannot run update inside the tribunal-kit package itself.');
631
- err(`Target: ${targetDir}`);
632
- console.log();
633
- dim('This command is designed to update .agent/ in OTHER projects.');
634
- dim('Run it from the root of the project you want to update:');
635
- dim(' cd /path/to/your-project');
636
- dim(' npx tribunal-kit update');
637
- console.log();
638
- process.exit(1);
639
- }
640
- // ────────────────────────────────────────────────────────
641
-
642
- // Update = init with --force
643
- flags.force = true;
644
- if (!quiet) {
645
- log(` ${c('cyan','↻')} ${bold('Updating')} ${c('white','.agent/')} to latest version...`);
646
- console.log();
647
- }
648
- cmdInit(flags);
649
- }
650
-
651
-
652
- function cmdLearn(flags) {
653
- const targetDir = flags.path ? path.resolve(flags.path) : process.cwd();
654
- const agentDest = path.join(targetDir, '.agent');
655
-
656
- if (!fs.existsSync(agentDest)) {
657
- err('.agent/ not found. Run: npx tribunal-kit init');
658
- process.exit(1);
659
- }
660
-
661
- banner();
662
-
663
- const W = 62;
664
- const title = ' Tribunal Learn — Supreme Court Mode';
665
- const trail = ' '.repeat(Math.max(0, W - title.length));
666
- console.log(` ${c('cyan', '\u2554' + '\u2550'.repeat(W) + '\u2557')}`);
667
- console.log(` ${c('cyan', '\u2551')}${c('bold', c('white', title))}${trail}${c('cyan', '\u2551')}`);
668
- console.log(` ${c('cyan', '\u255a' + '\u2550'.repeat(W) + '\u255d')}`);
669
- console.log();
670
-
671
- const dryRun = flags.dryRun ? '--dry-run' : '';
672
- const useHead = flags.head ? '--head' : '';
673
-
674
-
675
- // Phase 1: Skill Evolution
676
- log(` ${c('cyan', '\u229b')} ${bold('Phase 1')} \u2014 Skill Evolution Forge (auto-generating project idioms)`);
677
- const evoScript = path.join(agentDest, 'scripts', 'skill_evolution.js');
678
- if (!fs.existsSync(evoScript)) {
679
- warn('skill_evolution.js not found \u2014 run: npx tribunal-kit update');
680
- } else {
681
- try {
682
- const cmd = `node "${evoScript}" digest ${dryRun} ${useHead}`.trim();
683
- execSync(cmd, { stdio: 'inherit', cwd: targetDir });
684
- } catch (e) {
685
- warn(`Skill Evolution error: ${e.message}`);
686
- }
687
- }
688
-
689
- console.log();
690
-
691
- // Phase 2: Case Law prompt
692
- log(` ${c('cyan', '\u229b')} ${bold('Phase 2')} \u2014 Case Law Engine (building precedence record)`);
693
- console.log();
694
- log(` ${c('gray','\u25b8')} Record a new rejection precedent:`);
695
- log(` ${c('white', 'npx tribunal-kit case add')}`);
696
- console.log();
697
- log(` ${c('gray','\u25b8')} Search existing case law:`);
698
- log(` ${c('white', 'npx tribunal-kit case search "your query"')}`);
699
- console.log();
700
- log(` ${c('green', '\u2714')} ${bold('Learn cycle complete.')} Your Tribunal grows smarter with every commit.`);
701
- console.log();
702
- }
703
-
704
- // ── Async Main Wrapper ───────────────────────────────────
705
- async function runWithUpdateCheck(command, flags) {
706
- const shouldSkip = flags.skipUpdateCheck || process.env.TK_SKIP_UPDATE_CHECK === '1';
707
-
708
- if (!shouldSkip && (command === 'init' || command === 'update')) {
709
- // Pass through the original args (minus the node/script path)
710
- const originalArgs = process.argv.slice(2);
711
- const didReInvoke = await autoUpdateCheck(originalArgs);
712
- if (didReInvoke) {
713
- process.exit(0); // Latest version handled it
714
- }
715
- }
716
-
717
- // Proceed with current version
718
- switch (command) {
719
- case 'init':
720
- cmdInit(flags);
721
- break;
722
- case 'update':
723
- cmdUpdate(flags);
724
- break;
725
- case 'status':
726
- cmdStatus(flags);
727
- break;
728
- case 'learn':
729
- cmdLearn(flags);
730
- break;
731
- case 'case':
732
- cmdCase(flags);
733
- break;
734
- case 'hook':
735
- cmdHook(flags);
736
- break;
737
- case 'graph':
738
- cmdGraph(flags);
739
- break;
740
- case 'mutate':
741
- cmdMutate(flags);
742
- break;
743
- case 'context':
744
- cmdContext(flags);
745
- break;
746
- case 'marathon':
747
- cmdMarathon(flags);
748
- break;
749
- case 'uninstall':
750
- cmdUninstall(flags);
751
- break;
752
- case 'help':
753
- case '--help':
754
- case '-h':
755
- case null:
756
- cmdHelp();
757
- break;
758
- default:
759
- err(`Unknown command: "${command}"`);
760
- console.log();
761
- dim('Run tribunal-kit --help for usage');
762
- process.exit(1);
763
- }
764
- }
765
-
766
- function cmdCase(flags) {
767
- const targetDir = flags.path ? path.resolve(flags.path) : process.cwd();
768
- const agentDest = path.join(targetDir, '.agent');
769
-
770
- if (!fs.existsSync(agentDest)) {
771
- err('.agent/ not found. Run: npx tribunal-kit init');
772
- process.exit(1);
773
- }
774
-
775
- const args = process.argv.slice(3).join(' ');
776
- if (!args || args === 'help' || args === '--help' || args === '-h') {
777
- banner();
778
- log(` ${c('cyan', '\u2554' + '\u2550'.repeat(60) + '\u2557')}`);
779
- log(` ${c('cyan', '\u2551')}${c('bold', c('white', ' Tribunal Case Law Engine \u2014 Supreme Court '))}${c('cyan', '\u2551')}`);
780
- log(` ${c('cyan', '\u255a' + '\u2550'.repeat(60) + '\u255d')}`);
781
- console.log();
782
- log(` ${c('cyan', 'add'.padEnd(10))} ${c('gray', 'Record a new Case Law rejection pattern')}`);
783
- log(` ${c('cyan', 'search'.padEnd(10))} ${c('gray', 'Search existing cases (e.g., search "query")')}`);
784
- log(` ${c('cyan', 'list'.padEnd(10))} ${c('gray', 'List all recorded case law')}`);
785
- log(` ${c('cyan', 'show'.padEnd(10))} ${c('gray', 'Show full diff for a case (e.g., show --id 1)')}`);
786
- log(` ${c('cyan', 'stats'.padEnd(10))} ${c('gray', 'Show case law stats by domain/verdict')}`);
787
- log(` ${c('cyan', 'export'.padEnd(10))} ${c('gray', 'Export all cases to Markdown')}`);
788
- log(` ${c('cyan', 'overrule'.padEnd(10))} ${c('gray', 'Overrule a past precedent (e.g., overrule --id 1)')}`);
789
- console.log();
790
- process.exit(1);
791
- }
792
-
793
- const caseLawScript = path.join(agentDest, 'scripts', 'case_law_manager.js');
794
-
795
- // Make shorthand aliases
796
- let pyArgs = args;
797
- if (pyArgs.startsWith('add')) pyArgs = pyArgs.replace(/^add/, 'add-case');
798
- if (pyArgs.startsWith('search')) pyArgs = pyArgs.replace(/^search/, 'search-cases');
799
-
800
- try {
801
- const { execSync } = require('child_process');
802
- execSync(`node "${caseLawScript}" ${pyArgs}`, { stdio: 'inherit', cwd: targetDir });
803
- } catch {
804
- process.exit(1); // Script already prints errors
805
- }
806
- }
807
-
808
- function cmdGraph(flags) {
809
- const targetDir = flags.path ? path.resolve(flags.path) : process.cwd();
810
- const agentDest = path.join(targetDir, '.agent');
811
-
812
- if (!fs.existsSync(agentDest)) {
813
- err('.agent/ not found. Run: npx tribunal-kit init');
814
- process.exit(1);
815
- }
816
-
817
- banner();
818
- const { execSync } = require('child_process');
819
- const builderScript = path.join(agentDest, 'scripts', 'graph_builder.js');
820
- const visualizerScript = path.join(agentDest, 'scripts', 'graph_visualizer.js');
821
- const htmlFile = path.join(agentDest, 'history', 'architecture-explorer.html');
822
-
823
- try {
824
- execSync(`node "${builderScript}"`, { stdio: 'inherit', cwd: targetDir });
825
- execSync(`node "${visualizerScript}"`, { stdio: 'inherit', cwd: targetDir });
826
-
827
- log(` ${c('cyan', '▸')} Opening visualizer in browser...`);
828
- const opener = process.platform === 'win32' ? 'start' : process.platform === 'darwin' ? 'open' : 'xdg-open';
829
- execSync(`${opener} "${htmlFile}"`);
830
- } catch (e) {
831
- err(`Graph generation failed: ${e.message}`);
832
- process.exit(1);
833
- }
834
- }
835
-
836
- function cmdHook(flags) {
837
- const targetDir = flags.path ? path.resolve(flags.path) : process.cwd();
838
- const gitDir = path.join(targetDir, '.git');
839
-
840
- if (!fs.existsSync(gitDir)) {
841
- err('Not a git repository. Cannot install git hooks here.');
842
- process.exit(1);
843
- }
844
-
845
- const hooksDir = path.join(gitDir, 'hooks');
846
- if (!fs.existsSync(hooksDir)) {
847
- fs.mkdirSync(hooksDir, { recursive: true });
848
- }
849
-
850
- const prePushPath = path.join(hooksDir, 'pre-push');
851
- const hookScript = `#!/bin/sh\n# Supreme Court - Auto Learn on Push\necho "⚖️ Tribunal Supreme Court: Evolving Skills..."\nnpx tribunal-kit learn --head\n`;
852
-
853
- fs.writeFileSync(prePushPath, hookScript, { mode: 0o755 });
854
-
855
- console.log();
856
- log(` ${c('green', '')} Installed pre-push git hook.`);
857
- log(` ${c('gray', '▸')} Skill Evolution will now run automatically every time you git push.`);
858
- console.log();
859
- }
860
-
861
- function cmdMutate(flags) {
862
- const targetDir = flags.path ? path.resolve(flags.path) : process.cwd();
863
- const agentDest = path.join(targetDir, '.agent');
864
-
865
- if (!fs.existsSync(agentDest)) {
866
- err('.agent/ not found. Run: npx tribunal-kit init');
867
- process.exit(1);
868
- }
869
-
870
- const args = process.argv.slice(3);
871
- if (args.length < 2) {
872
- err('Usage: npx tribunal-kit mutate <target_file> <test_command>');
873
- process.exit(1);
874
- }
875
-
876
- const mutateScript = path.join(agentDest, 'scripts', 'mutation_runner.js');
877
- const { execSync } = require('child_process');
878
- try {
879
- execSync(`node "${mutateScript}" ${args.join(' ')}`, { stdio: 'inherit', cwd: targetDir });
880
- } catch {
881
- process.exit(1);
882
- }
883
- }
884
-
885
- function cmdUninstall(flags) {
886
- const targetDir = flags.path ? path.resolve(flags.path) : process.cwd();
887
- const agentDest = path.join(targetDir, '.agent');
888
-
889
- banner();
890
-
891
- if (!fs.existsSync(agentDest)) {
892
- log(` ${c('yellow','')} ${bold('.agent/')} is not installed in this project.`);
893
- console.log();
894
- return;
895
- }
896
-
897
- if (flags.dryRun) {
898
- log(colorize('yellow', ' DRY RUN — would remove:'));
899
- log(` ${c('gray',' ╰─')} ${agentDest}`);
900
- console.log();
901
- return;
902
- }
903
-
904
- try {
905
- fs.rmSync(agentDest, { recursive: true, force: true });
906
- log(` ${c('green','✔')} ${bold('.agent/')} has been removed from this project.`);
907
- console.log();
908
- log(` ${c('gray','▸')} To reinstall: ${c('cyan','npx tribunal-kit init')}`);
909
- console.log();
910
- } catch (e) {
911
- err(`Failed to remove .agent/: ${e.message}`);
912
- process.exit(1);
913
- }
914
- }
915
-
916
- function cmdStatus(flags) {
917
- const targetDir = flags.path ? path.resolve(flags.path) : process.cwd();
918
- const agentDest = path.join(targetDir, '.agent');
919
-
920
- banner();
921
-
922
- if (!fs.existsSync(agentDest)) {
923
- log(` ${c('red','✖')} ${bold('Not installed')} in this project`);
924
- console.log();
925
- log(` ${c('gray','Run:')} ${c('cyan','npx tribunal-kit init')}`);
926
- console.log();
927
- return;
928
- }
929
-
930
- log(` ${c('green','✔')} ${bold(c('green','Installed'))} ${c('gray','→')} ${c('gray', agentDest)}`);
931
- console.log();
932
-
933
- const icons = { agents: '🤖', workflows: '⚡', skills: '🧠', scripts: '🔧' };
934
- const colors = { agents: 'magenta', workflows: 'yellow', skills: 'blue', scripts: 'green' };
935
- const subdirs = ['agents', 'workflows', 'skills', 'scripts'];
936
- for (const sub of subdirs) {
937
- const subPath = path.join(agentDest, sub);
938
- if (fs.existsSync(subPath)) {
939
- const count = fs.readdirSync(subPath).filter(f => !fs.statSync(path.join(subPath, f)).isDirectory()).length;
940
- log(` ${icons[sub]} ${c(colors[sub], sub.padEnd(12))}${c('white', String(count).padStart(3))} files`);
941
- }
942
- }
943
- console.log();
944
- }
945
-
946
- function cmdHelp() {
947
- banner();
948
- const cmd = (name, desc) => ` ${c('cyan', name.padEnd(10))} ${c('gray', desc)}`;
949
- const opt = (flag, desc) => ` ${c('yellow', flag.padEnd(22))} ${c('gray', desc)}`;
950
- const ex = (s) => ` ${c('gray', '▸')} ${c('white', s)}`;
951
-
952
- log(bold(' Commands'));
953
- log(` ${c('gray','─'.repeat(40))}`);
954
- log(cmd('init', 'Install .agent/ into current project'));
955
- log(cmd('update', 'Re-install to get latest version'));
956
- log(cmd('status', 'Check if .agent/ is installed'));
957
- log(cmd('learn', 'Evolve project idioms based on git diffs'));
958
- log(cmd('case', 'Manage Case Law precedents (add, search, list, show, stats, overrule)'));
959
- log(cmd('graph', 'Build and visualize the architecture graph'));
960
- log(cmd('mutate', 'Run the Mutation Engine to test test-suite reliability'));
961
- log(cmd('context', 'Retrieve a highly-optimized Context Snapshot for a file'));
962
- log(cmd('marathon', 'Long-running agent harness (init, status, next, mark)'));
963
- log(cmd('hook', 'Install pre-push git hook for auto-learning'));
964
- log(cmd('uninstall','Remove .agent/ folder from project'));
965
- console.log();
966
- log(bold(' Options'));
967
- log(` ${c('gray',''.repeat(40))}`);
968
- log(opt('--force', 'Overwrite existing .agent/ folder'));
969
- log(opt('--path <dir>', 'Install in specific directory'));
970
- log(opt('--quiet', 'Suppress all output'));
971
- log(opt('--verbose', 'Show detailed debug logging'));
972
- log(opt('--dry-run', 'Preview actions without executing'));
973
- log(opt('--minimal', 'Install core agents/skills only (~13 agents)'));
974
- log(opt('--skip-update-check', 'Skip auto-update version check'));
975
- log(opt('--head', '(learn) Diff against last commit instead of staged'));
976
- console.log();
977
- log(bold(' Aliases'));
978
- log(` ${c('gray','─'.repeat(40))}`);
979
- log(` ${c('cyan', 'tk')} ${c('gray', 'Shorthand for tribunal-kit (e.g., tk init, tk status)')}`);
980
- console.log();
981
- log(bold(' Examples'));
982
- log(` ${c('gray','─'.repeat(40))}`);
983
- log(ex('npx tribunal-kit init'));
984
- log(ex('tk init --force'));
985
- log(ex('tk init --path ./my-app'));
986
- log(ex('npx tribunal-kit init --dry-run'));
987
- log(ex('tk update'));
988
- log(ex('tk status'));
989
- log(ex('tk learn'));
990
- log(ex('tk learn --dry-run'));
991
- log(ex('tk learn --head'));
992
- log(ex('tk case add'));
993
- log(ex('tk case search "useEffect"'));
994
- log(ex('tk case list'));
995
- log(ex('tk case show --id 1'));
996
- log(ex('tk case stats'));
997
- log(ex('tk case export'));
998
- log(ex('tk case overrule --id 1'));
999
- log(ex('tk graph'));
1000
- log(ex('tk mutate src/utils.js "npm test"'));
1001
- log(ex('tk marathon init "Build a todo app"'));
1002
- log(ex('tk marathon status'));
1003
- log(ex('tk marathon next'));
1004
- log(ex('tk marathon mark 5 pass'));
1005
- log(ex('tk hook'));
1006
- log(ex('tk uninstall'));
1007
- console.log();
1008
- }
1009
-
1010
-
1011
- function cmdMarathon(flags) {
1012
- const targetDir = flags.path ? path.resolve(flags.path) : process.cwd();
1013
- const agentDest = path.join(targetDir, '.agent');
1014
-
1015
- if (!fs.existsSync(agentDest)) {
1016
- err('.agent/ not found. Run: npx tribunal-kit init');
1017
- process.exit(1);
1018
- }
1019
-
1020
- const args = process.argv.slice(3);
1021
- const argsStr = args.join(' ');
1022
- if (args.length === 0 || args[0] === 'help' || args[0] === '--help' || args[0] === '-h') {
1023
- banner();
1024
- log(` ${c('cyan', '╔' + '═'.repeat(60) + '╗')}`);
1025
- log(` ${c('cyan', '║')}${c('bold', c('white', ' Marathon — Long-Running Agent Harness '))}${c('cyan', '║')}`);
1026
- log(` ${c('cyan', '╚' + '═'.repeat(60) + '╝')}`);
1027
- console.log();
1028
- log(` ${c('cyan', 'init'.padEnd(16))} ${c('gray', 'Start a new marathon (init "spec")')}`);
1029
- log(` ${c('cyan', 'status'.padEnd(16))} ${c('gray', 'Show progress dashboard')}`);
1030
- log(` ${c('cyan', 'next'.padEnd(16))} ${c('gray', 'Show next unfinished feature')}`);
1031
- log(` ${c('cyan', 'mark'.padEnd(16))} ${c('gray', 'Mark feature pass/fail (mark <id> pass)')}`);
1032
- log(` ${c('cyan', 'log'.padEnd(16))} ${c('gray', 'Add a progress note')}`);
1033
- log(` ${c('cyan', 'session-start'.padEnd(16))} ${c('gray', 'Begin a new work session')}`);
1034
- log(` ${c('cyan', 'session-end'.padEnd(16))} ${c('gray', 'End session with summary')}`);
1035
- log(` ${c('cyan', 'add-feature'.padEnd(16))} ${c('gray', 'Add feature: "category" "desc" "step1" ...')}`);
1036
- log(` ${c('cyan', 'reset'.padEnd(16))} ${c('gray', 'Archive and start fresh')}`);
1037
- console.log();
1038
- return;
1039
- }
1040
-
1041
- const marathonScript = path.join(agentDest, 'scripts', 'marathon_harness.js');
1042
- try {
1043
- execSync(`node "${marathonScript}" ${argsStr}`, { stdio: 'inherit', cwd: targetDir });
1044
- } catch {
1045
- process.exit(1);
1046
- }
1047
- }
1048
-
1049
- function cmdContext(flags) {
1050
- const targetDir = flags.path ? path.resolve(flags.path) : process.cwd();
1051
- const agentDest = path.join(targetDir, '.agent');
1052
-
1053
- if (!fs.existsSync(agentDest)) {
1054
- err('.agent/ not found. Run: npx tribunal-kit init');
1055
- process.exit(1);
1056
- }
1057
-
1058
- const args = process.argv.slice(3);
1059
- if (args.length === 0 || args[0] === 'help' || args[0] === '--help') {
1060
- console.error('Usage: npx tribunal-kit context <target_file>');
1061
- process.exit(1);
1062
- }
1063
-
1064
- const targetFile = args[0].replace(/\\/g, '/');
1065
- const snapshotName = targetFile.replace(/[\\\/]/g, '__') + '.json';
1066
- const snapshotPath = require('path').join(agentDest, 'history', 'snapshots', snapshotName);
1067
-
1068
- if (!require('fs').existsSync(snapshotPath)) {
1069
- console.error(' \x1b[91m✖\x1b[0m Context Snapshot not found for: ' + targetFile);
1070
- console.log(' Run: npx tribunal-kit graph (to generate snapshots)');
1071
- process.exit(1);
1072
- }
1073
-
1074
- try {
1075
- const snapshot = JSON.parse(require('fs').readFileSync(snapshotPath, 'utf8'));
1076
-
1077
- console.log('\n# Context Snapshot: ' + snapshot.file);
1078
- process.stdout.write('> Size Estimate: ' + (snapshot['estimatedTokens'] || 'Unknown') + '\n');
1079
- console.log('> Risk Score: ' + snapshot.riskScore + ' (Blast Radius: ' + snapshot.blastRadius + ')\n');
1080
-
1081
- if (Object.keys(snapshot.imports).length > 0) {
1082
- console.log('## Imports');
1083
- for (const [imp, exports] of Object.entries(snapshot.imports)) {
1084
- if (exports && exports.length > 0) {
1085
- console.log('- `' + imp + '` (exports: ' + exports.join(', ') + ')');
1086
- } else {
1087
- console.log('- `' + imp + '`');
1088
- }
1089
- }
1090
- console.log();
1091
- }
1092
-
1093
- if (snapshot.dependents && snapshot.dependents.length > 0) {
1094
- console.log('## Dependents');
1095
- for (const dep of snapshot.dependents) {
1096
- console.log('- `' + dep + '`');
1097
- }
1098
- console.log();
1099
- }
1100
-
1101
- console.log('## Source Code');
1102
- console.log('```javascript\n' + snapshot.content + '\n```\n');
1103
-
1104
- } catch (e) {
1105
- console.error('Failed to read snapshot: ' + e.message);
1106
- process.exit(1);
1107
- }
1108
- }
1109
-
1110
- // ── Main ──────────────────────────────────────────────────
1111
- const { command, flags } = parseArgs(process.argv);
1112
-
1113
- if (flags.quiet) quiet = true;
1114
- if (flags.verbose) verbose = true;
1115
-
1116
- runWithUpdateCheck(command, flags);
1117
-
1118
- // -- Exports (for testing) -- do not remove
1119
- if (require.main !== module) {
1120
- module.exports = { parseArgs, compareSemver, copyDir, countDir, isSelfInstall, CORE_AGENTS, CORE_SKILLS, generateIDEBridges, cmdMarathon };
2
+ /**
3
+ * tribunal-kit CLI (alias: tk)
4
+ *
5
+ * Commands:
6
+ * init — Install .agent/ into target project
7
+ * update — Re-install to get latest changes
8
+ * status — Check if .agent/ is installed
9
+ * learn — Evolve project idioms based on git diffs
10
+ * case — Manage Case Law precedents
11
+ * hook — Install pre-push git hook
12
+ * uninstall — Remove .agent/ from project
13
+ *
14
+ * Usage:
15
+ * npx tribunal-kit init
16
+ * npx tribunal-kit init --force
17
+ * npx tribunal-kit init --path ./myapp
18
+ * npx tribunal-kit init --quiet
19
+ * npx tribunal-kit init --dry-run
20
+ * tribunal-kit update
21
+ * tribunal-kit status
22
+ * tribunal-kit uninstall
23
+ */
24
+
25
+ const fs = require('fs');
26
+ const path = require('path');
27
+ const https = require('https');
28
+ const { execSync, spawn } = require('child_process');
29
+
30
+ function runShellAsync(command, options) {
31
+ return new Promise((resolve, reject) => {
32
+ const child = spawn(command, [], { ...options, shell: true });
33
+ child.on('close', code => {
34
+ if (code !== 0) reject(new Error(`Command failed with exit code ${code}`));
35
+ else resolve();
36
+ });
37
+ child.on('error', reject);
38
+ });
39
+ }
40
+
41
+ /**
42
+ * Safely run a Node.js script with arguments as an array.
43
+ * No shell interpolation — immune to injection.
44
+ */
45
+ function runScriptAsync(scriptPath, args = [], options = {}) {
46
+ return new Promise((resolve, reject) => {
47
+ const child = spawn(process.execPath, [scriptPath, ...args], {
48
+ stdio: 'inherit',
49
+ ...options,
50
+ });
51
+ child.on('close', code => {
52
+ if (code !== 0) reject(new Error(`Script failed with exit code ${code}`));
53
+ else resolve();
54
+ });
55
+ child.on('error', reject);
56
+ });
57
+ }
58
+
59
+ const PKG = require(path.resolve(__dirname, '..', 'package.json'));
60
+ const CURRENT_VERSION = PKG.version;
61
+
62
+ // ── Colors ───────────────────────────────────────────────
63
+ const C = {
64
+ reset: '\x1b[0m',
65
+ bold: '\x1b[1m',
66
+ dim: '\x1b[2m',
67
+ red: '\x1b[91m',
68
+ green: '\x1b[92m',
69
+ yellow: '\x1b[93m',
70
+ blue: '\x1b[94m',
71
+ magenta: '\x1b[95m',
72
+ cyan: '\x1b[96m',
73
+ white: '\x1b[97m',
74
+ gray: '\x1b[90m',
75
+ bgCyan: '\x1b[46m',
76
+ };
77
+
78
+ function colorize(color, text) {
79
+ return `${C[color]}${text}${C.reset}`;
80
+ }
81
+
82
+ function c(color, text) { return `${C[color]}${text}${C.reset}`; }
83
+ function bold(text) { return `${C.bold}${text}${C.reset}`; }
84
+
85
+ // ── Logging ──────────────────────────────────────────────
86
+ let quiet = false;
87
+ let verbose = false;
88
+
89
+ function log(msg) { if (!quiet) console.log(msg); }
90
+ function ok(msg) { if (!quiet) console.log(` ${c('green', '✔')} ${msg}`); }
91
+ function warn(msg) { if (!quiet) console.log(` ${c('yellow', '⚠')} ${msg}`); }
92
+ function err(msg) { console.error(` ${c('red', '')} ${msg}`); }
93
+ function dim(msg) { if (!quiet) console.log(` ${c('gray', msg)}`); }
94
+ function dbg(msg) { if (verbose) console.log(` ${c('gray', '⊡')} ${c('gray', msg)}`); }
95
+
96
+ // ── Arg Parser ───────────────────────────────────────────
97
+ function parseArgs(argv) {
98
+ const args = { command: null, flags: {} };
99
+ const raw = argv.slice(2);
100
+
101
+ // First non-flag arg is the command
102
+ for (const arg of raw) {
103
+ if (!arg.startsWith('--') && !args.command) {
104
+ args.command = arg;
105
+ continue;
106
+ }
107
+ if (arg === '--force') { args.flags.force = true; continue; }
108
+ if (arg === '--quiet') { args.flags.quiet = true; continue; }
109
+ if (arg === '--verbose') { args.flags.verbose = true; continue; }
110
+ if (arg === '--dry-run') { args.flags.dryRun = true; continue; }
111
+ if (arg === '--minimal') { args.flags.minimal = true; continue; }
112
+ if (arg === '--skip-update-check') { args.flags.skipUpdateCheck = true; continue; }
113
+ if (arg === '--head') { args.flags.head = true; continue; }
114
+ if (arg.startsWith('--path=')) {
115
+ args.flags.path = arg.split('=').slice(1).join('=');
116
+ }
117
+ if (arg === '--path') {
118
+ const idx = raw.indexOf('--path');
119
+ const nextVal = raw[idx + 1];
120
+ if (!nextVal || nextVal.startsWith('--')) {
121
+ console.error(` \x1b[91m✖ --path requires a directory argument\x1b[0m`);
122
+ process.exit(1);
123
+ }
124
+ args.flags.path = nextVal;
125
+ }
126
+ if (arg.startsWith('--branch=')) {
127
+ args.flags.branch = arg.split('=').slice(1).join('=');
128
+ }
129
+ }
130
+
131
+ return args;
132
+ }
133
+
134
+ // ── File Utilities ────────────────────────────────────────
135
+
136
+ // Core agents to install in --minimal mode
137
+ const CORE_AGENTS = new Set([
138
+ 'backend-specialist.md',
139
+ 'frontend-specialist.md',
140
+ 'database-architect.md',
141
+ 'debugger.md',
142
+ 'security-auditor.md',
143
+ 'logic-reviewer.md',
144
+ 'dependency-reviewer.md',
145
+ 'type-safety-reviewer.md',
146
+ 'performance-reviewer.md',
147
+ 'orchestrator.md',
148
+ 'explorer-agent.md',
149
+ 'project-planner.md',
150
+ 'test-engineer.md',
151
+ ]);
152
+
153
+ // Core skills to install in --minimal mode
154
+ const CORE_SKILLS = new Set([
155
+ 'clean-code', 'architecture', 'testing-patterns', 'systematic-debugging',
156
+ 'frontend-design', 'database-design', 'api-patterns', 'nodejs-best-practices',
157
+ 'vulnerability-scanner', 'typescript-advanced', 'python-pro', 'nextjs-react-expert',
158
+ 'react-specialist', 'performance-profiling', 'lint-and-validate',
159
+ ]);
160
+
161
+ async function copyDir(src, dest, dryRun = false, filter = null) {
162
+ if (!dryRun) {
163
+ await fs.promises.mkdir(dest, { recursive: true });
164
+ }
165
+
166
+ const entries = await fs.promises.readdir(src, { withFileTypes: true });
167
+ let count = 0;
168
+
169
+ for (const entry of entries) {
170
+ // Apply filter if provided (for --minimal mode)
171
+ if (filter && !filter(entry.name, src)) {
172
+ dbg(` skip: ${entry.name}`);
173
+ continue;
174
+ }
175
+
176
+ const srcPath = path.join(src, entry.name);
177
+ const destPath = path.join(dest, entry.name);
178
+
179
+ if (entry.isDirectory()) {
180
+ count += await copyDir(srcPath, destPath, dryRun, filter);
181
+ } else {
182
+ if (!dryRun) {
183
+ await fs.promises.copyFile(srcPath, destPath);
184
+ }
185
+ dbg(` copy: ${entry.name}`);
186
+ count++;
187
+ }
188
+ }
189
+
190
+ return count;
191
+ }
192
+
193
+ async function countDir(dir) {
194
+ let count = 0;
195
+ const entries = await fs.promises.readdir(dir, { withFileTypes: true });
196
+ for (const e of entries) {
197
+ if (e.isDirectory()) count += await countDir(path.join(dir, e.name));
198
+ else count++;
199
+ }
200
+ return count;
201
+ }
202
+
203
+ // ── Version Check & Auto-Update ──────────────────────────
204
+
205
+ /**
206
+ * Compare two semver strings. Returns:
207
+ * 1 if a > b, -1 if a < b, 0 if equal.
208
+ */
209
+ function compareSemver(a, b) {
210
+ const pa = a.replace(/^v/, '').split('.').map(Number);
211
+ const pb = b.replace(/^v/, '').split('.').map(Number);
212
+ for (let i = 0; i < 3; i++) {
213
+ const na = pa[i] || 0;
214
+ const nb = pb[i] || 0;
215
+ if (na > nb) return 1;
216
+ if (na < nb) return -1;
217
+ }
218
+ return 0;
219
+ }
220
+
221
+ /**
222
+ * Fetch the latest version from npm registry.
223
+ * Returns the version string (e.g. '4.0.0') or null on failure.
224
+ */
225
+ function fetchLatestVersion() {
226
+ return new Promise((resolve) => {
227
+ const req = https.get(
228
+ 'https://registry.npmjs.org/tribunal-kit/latest',
229
+ {
230
+ headers: {
231
+ 'Accept': 'application/json',
232
+ 'User-Agent': `tribunal-kit/${CURRENT_VERSION}`
233
+ },
234
+ timeout: 5000
235
+ },
236
+ (res) => {
237
+ let data = '';
238
+ res.on('data', (chunk) => { data += chunk; });
239
+ res.on('end', () => {
240
+ try {
241
+ const json = JSON.parse(data);
242
+ const version = json.version || null;
243
+ resolve(version);
244
+ } catch {
245
+ resolve(null);
246
+ }
247
+ });
248
+ }
249
+ );
250
+ req.on('error', () => resolve(null));
251
+ req.on('timeout', () => { req.destroy(); resolve(null); });
252
+ });
253
+ }
254
+
255
+ /**
256
+ * Check for a newer version and re-invoke with @latest if found.
257
+ * Uses TK_SKIP_UPDATE_CHECK env var as recursion guard.
258
+ * Returns true if a re-invoke happened (caller should exit), false otherwise.
259
+ */
260
+ async function autoUpdateCheck(originalArgs) {
261
+ // Recursion guard: if we're already a re-invoked process, skip
262
+ if (process.env.TK_SKIP_UPDATE_CHECK === '1') {
263
+ return false;
264
+ }
265
+
266
+ log(' Checking for updates...');
267
+ const latestVersion = await fetchLatestVersion();
268
+
269
+ if (!latestVersion) {
270
+ // Network fail — proceed silently with current version
271
+ return false;
272
+ }
273
+
274
+ if (compareSemver(latestVersion, CURRENT_VERSION) <= 0) {
275
+ // Already up to date
276
+ dim(`Version ${CURRENT_VERSION} is up to date.`);
277
+ return false;
278
+ }
279
+
280
+ // Newer version available re-invoke
281
+ log('');
282
+ log(colorize('cyan', ` ⬆ New version available: ${colorize('bold', CURRENT_VERSION)} → ${colorize('bold', latestVersion)}`));
283
+ log(colorize('gray', ' Re-invoking with latest version...'));
284
+ log('');
285
+
286
+ try {
287
+ // Build the command pulling from npm registry
288
+ const args = originalArgs.join(' ');
289
+ const cmd = `npx -y tribunal-kit@${latestVersion} ${args}`;
290
+
291
+ execSync(cmd, {
292
+ stdio: 'inherit',
293
+ env: { ...process.env, TK_SKIP_UPDATE_CHECK: '1' },
294
+ });
295
+ return true; // Re-invoke succeeded, caller should exit
296
+ } catch (e) {
297
+ warn(`Auto-update failed: ${e.message}`);
298
+ warn('Continuing with current version...');
299
+ return false; // Fall through to current version
300
+ }
301
+ }
302
+
303
+ // ── Kit Source Location ───────────────────────────────────
304
+ function getKitAgent() {
305
+ // When installed via npm, the .agent/ folder is next to this script's package
306
+ const kitRoot = path.resolve(__dirname, '..');
307
+ const agentDir = path.join(kitRoot, '.agent');
308
+
309
+ if (!fs.existsSync(agentDir)) {
310
+ err(`Kit .agent/ folder not found at: ${agentDir}`);
311
+ err('The package may be corrupted. Try: npm install -g tribunal-kit');
312
+ process.exit(1);
313
+ }
314
+
315
+ return agentDir;
316
+ }
317
+
318
+ // ── Self-Install Guard ────────────────────────────────────
319
+ /**
320
+ * Returns true if the target directory IS the tribunal-kit package itself.
321
+ * This prevents `init --force` / `update` from deleting the package's own files
322
+ * when run from inside the project directory.
323
+ */
324
+ function isSelfInstall(targetDir) {
325
+ const kitRoot = path.resolve(__dirname, '..');
326
+ const resolvedTarget = path.resolve(targetDir);
327
+
328
+ // Direct path match
329
+ if (resolvedTarget === kitRoot) return true;
330
+
331
+ // Check if the target's package.json is this package
332
+ const targetPkg = path.join(resolvedTarget, 'package.json');
333
+ if (fs.existsSync(targetPkg)) {
334
+ try {
335
+ const targetName = JSON.parse(fs.readFileSync(targetPkg, 'utf8')).name;
336
+ if (targetName === PKG.name) return true;
337
+ } catch {
338
+ // Unreadable package.json — not a match
339
+ }
340
+ }
341
+
342
+ return false;
343
+ }
344
+
345
+ // ── Banner ────────────────────────────────────────────────
346
+ function banner() {
347
+ if (quiet) return;
348
+ // Big ASCII art (TRIBUNAL-KIT)
349
+ const art = String.raw`
350
+ ████████╗██████╗ ██╗██████╗ ██╗ ██╗███╗ ██╗ █████╗ ██╗ ██╗ ██╗██╗████████╗
351
+ ╚══██╔══╝██╔══██╗██║██╔══██╗██║ ██║████╗ ██║██╔══██╗██║ ██║ ██╔╝██║╚══██╔══╝
352
+ ██║ ██████╔╝██║██████╔╝██║ ██║██╔██╗ ██║███████║██║█████╗█████╔╝ ██║ ██║
353
+ ██║ ██╔══██╗██║██╔══██╗██║ ██║██║╚██╗██║██╔══██║██║╚════╝██╔═██╗ ██║ ██║
354
+ ██║ ██║ ██║██║██████╔╝╚██████╔╝██║ ╚████║██║ ██║███████╗ ██║ ██╗██║ ██║
355
+ ╚═╝ ╚═╝ ╚═╝╚═╝╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ `.split('\n').filter(Boolean);
356
+ console.log();
357
+ const _maxLen = Math.max(...art.map(line => line.length));
358
+ for (const line of art) {
359
+ let gradientLine = ' ' + C.bold;
360
+ for (let i = 0; i < line.length; i++) {
361
+ gradientLine += `\x1b[38;2;255;22;55m${line[i]}`;
362
+ }
363
+ gradientLine += C.reset;
364
+ log(gradientLine);
365
+ }
366
+ console.log();
367
+ // Subtitle strip
368
+ const W = 84;
369
+ const sub = 'Anti-Hallucination Agent System';
370
+ const sp = Math.max(0, W - sub.length);
371
+ const centred = ' '.repeat(Math.floor(sp / 2)) + sub + ' '.repeat(Math.ceil(sp / 2));
372
+ const RED_ANSI = '\x1b[38;2;255;22;55m';
373
+ console.log(` ${RED_ANSI}╔${'═'.repeat(W)}╗${C.reset}`);
374
+ console.log(` ${RED_ANSI}║${C.reset}${c('gray', centred)}${RED_ANSI}║${C.reset}`);
375
+ console.log(` ${RED_ANSI}╚${'═'.repeat(W)}╝${C.reset}`);
376
+ console.log();
377
+ }
378
+
379
+ // ── Commands ──────────────────────────────────────────────
380
+ async function cmdInit(flags) {
381
+ const agentSrc = getKitAgent();
382
+ const targetDir = flags.path ? path.resolve(flags.path) : process.cwd();
383
+ const agentDest = path.join(targetDir, '.agent');
384
+ const dryRun = flags.dryRun || false;
385
+
386
+ // ── Self-install guard ──────────────────────────────────
387
+ if (isSelfInstall(targetDir)) {
388
+ err('Cannot run init/update inside the tribunal-kit package itself.');
389
+ err(`Target: ${targetDir}`);
390
+ err(`Package: ${path.resolve(__dirname, '..')}`);
391
+ console.log();
392
+ dim('This command is designed to install .agent/ into OTHER projects.');
393
+ dim('Run it from the root of the project you want to set up:');
394
+ dim(' cd /path/to/your-project');
395
+ dim(' npx tribunal-kit init');
396
+ console.log();
397
+ process.exit(1);
398
+ }
399
+ // ────────────────────────────────────────────────────────
400
+
401
+ // ── Backup / Cleanup ────────────────────────────────────
402
+ if (!dryRun && fs.existsSync(agentDest) && flags.force) {
403
+ // Backup the existing subdirectories before overwriting
404
+ const backupDir = path.join(agentDest, '.backups', `backup-${Date.now()}`);
405
+ fs.mkdirSync(backupDir, { recursive: true });
406
+
407
+ const subdirs = ['agents', 'workflows', 'skills', 'scripts', '.shared', 'rules'];
408
+ for (const sub of subdirs) {
409
+ const subPath = path.join(agentDest, sub);
410
+ if (fs.existsSync(subPath)) {
411
+ // Copy to backup dir
412
+ await copyDir(subPath, path.join(backupDir, sub), false);
413
+ // Removed aggressive deletion so user custom files persist
414
+ }
415
+ }
416
+ log(` ${c('gray', '✦ Backed up existing configurations to .agent/.backups/')}`);
417
+
418
+
419
+ }
420
+ // ────────────────────────────────────────────────────────
421
+
422
+ banner();
423
+
424
+ if (dryRun) {
425
+ log(colorize('yellow', ' DRY RUN — no files will be written'));
426
+ console.log();
427
+ }
428
+
429
+ // Check target exists
430
+ if (!fs.existsSync(targetDir)) {
431
+ err(`Target directory not found: ${targetDir}`);
432
+ process.exit(1);
433
+ }
434
+
435
+ // Check if .agent already exists
436
+ if (fs.existsSync(agentDest) && !flags.force) {
437
+ warn('.agent/ already exists in this project.');
438
+ log(` ${c('gray', '▸')} To refresh or update it, run: ${colorize('white', 'tribunal-kit init --force')}`);
439
+ log(` ${c('gray', '▸')} Or check status with: ${colorize('cyan', 'tribunal-kit status')}`);
440
+ console.log();
441
+ process.exit(0);
442
+ }
443
+
444
+ // Ensure history dirs exist (Case Law + Skill Evolution)
445
+ if (!dryRun) {
446
+ const caseDir = path.join(agentDest, 'history', 'case-law', 'cases');
447
+ const evoDir = path.join(agentDest, 'history', 'skill-evolution');
448
+ fs.mkdirSync(caseDir, { recursive: true });
449
+ fs.mkdirSync(evoDir, { recursive: true });
450
+ const gkCase = path.join(caseDir, '.gitkeep');
451
+ const gkEvo = path.join(evoDir, '.gitkeep');
452
+ if (!fs.existsSync(gkCase)) fs.writeFileSync(gkCase, '');
453
+ if (!fs.existsSync(gkEvo)) fs.writeFileSync(gkEvo, '');
454
+ }
455
+
456
+ // Count what we're installing
457
+ const isMinimal = flags.minimal || false;
458
+ if (isMinimal) {
459
+ log(` ${c('yellow','⚡')} ${bold('Minimal mode')} — installing core agents and skills only`);
460
+ console.log();
461
+ }
462
+ const totalFiles = await countDir(agentSrc);
463
+ dbg(`Source: ${agentSrc}`);
464
+ dbg(`Target: ${agentDest}`);
465
+ dbg(`Total source files: ${totalFiles}`);
466
+ log(` ${c('gray','▸')} Scanning ${c('white', String(totalFiles))} files ${c('gray','→')} ${c('gray', agentDest)}`);
467
+
468
+ try {
469
+ // Build filter for --minimal mode
470
+ const minimalFilter = isMinimal ? (name, parentDir) => {
471
+ const parentName = path.basename(parentDir);
472
+ if (parentName === 'agents') return CORE_AGENTS.has(name);
473
+ if (parentName === 'skills') return CORE_SKILLS.has(name);
474
+ return true; // everything else passes
475
+ } : null;
476
+
477
+ const copied = await copyDir(agentSrc, agentDest, dryRun, minimalFilter);
478
+
479
+ console.log();
480
+ if (dryRun) {
481
+ ok(`${bold('DRY RUN')} complete — would install ${c('cyan', String(copied))} files`);
482
+ dim(`Target: ${agentDest}`);
483
+ } else {
484
+ // ── Success card — W=62, rows padded by plain-text length ──
485
+ const W = 62;
486
+ const agentsCount = fs.readdirSync(path.join(agentDest, 'agents')).length;
487
+ const workflowsCount = fs.readdirSync(path.join(agentDest, 'workflows')).length;
488
+ const skillsCount = fs.readdirSync(path.join(agentDest, 'skills')).length;
489
+ const scriptsCount = fs.readdirSync(path.join(agentDest, 'scripts')).length;
490
+
491
+ // Stat rows: compute trailing spaces from plain text so right ║ aligns
492
+ const statRow = (icon, label, val, col) => {
493
+ // emoji JS .length===2 == terminal display width 2 ✓
494
+ const plain = ` ${icon} ${label.padEnd(10)}${String(val).padStart(3)} installed`;
495
+ const trail = ' '.repeat(Math.max(0, W - plain.length));
496
+ return ` ${c('cyan','║')} ${icon} ${c('white',label.padEnd(10))}${c(col,String(val).padStart(3))} ${c('gray','installed')}${trail}${c('cyan','║')}`;
497
+ };
498
+ // Plain-text rows (header / blank)
499
+ const plainRow = (text, wrapFn) => {
500
+ const trail = ' '.repeat(Math.max(0, W - text.length));
501
+ return ` ${c('cyan','')}${wrapFn(text)}${trail}${c('cyan','║')}`;
502
+ };
503
+ // Next-step rows: fixed cmd column + description
504
+ const stepRow = (cmd, desc) => {
505
+ const plain = ` ${cmd.padEnd(16)}${desc}`;
506
+ const trail = ' '.repeat(Math.max(0, W - plain.length));
507
+ return ` ${c('cyan','║')} ${c('white',cmd.padEnd(16))}${c('gray',desc)}${trail}${c('cyan','║')}`;
508
+ };
509
+
510
+ console.log(` ${c('green','✔')} ${bold(c('green','Installation complete'))} ${c('gray','—')} ${c('white',String(copied))} files`);
511
+ console.log(` ${c('gray',' ╰─')} ${c('gray', agentDest)}`);
512
+ console.log();
513
+ console.log(` ${c('cyan', '╔' + '═'.repeat(W) + '╗')}`);
514
+ console.log(plainRow(` What's inside:`, s => c('bold', c('white', s))));
515
+ console.log(` ${c('cyan', '╠' + '═'.repeat(W) + '╣')}`);
516
+ console.log(statRow('🤖', 'Agents', agentsCount, 'magenta'));
517
+ console.log(statRow('⚡', 'Workflows', workflowsCount, 'yellow'));
518
+ console.log(statRow('🧠', 'Skills', skillsCount, 'blue'));
519
+ console.log(statRow('🔧', 'Scripts', scriptsCount, 'green'));
520
+ console.log(` ${c('cyan', '╠' + '═'.repeat(W) + '╣')}`);
521
+ console.log(plainRow('', () => ''));
522
+ console.log(plainRow(` Next steps:`, s => c('gray', s)));
523
+ console.log(stepRow('/generate', 'Generate code with anti-hallucination'));
524
+ console.log(stepRow('/review', 'Audit existing code for issues'));
525
+ console.log(stepRow('/tribunal-full', 'Run all 16 reviewers in parallel'));
526
+ console.log(plainRow('', () => ''));
527
+ console.log(` ${c('cyan', '╚' + '═'.repeat(W) + '╝')}`);
528
+ console.log();
529
+ log(` ${c('gray', '✦ Updating .gitignore...')}`);
530
+ await updateGitignore(targetDir, dryRun);
531
+ log(` ${c('gray', '✦ Generating IDE bridge files...')}`);
532
+ await generateIDEBridges(targetDir, agentDest, dryRun);
533
+ }
534
+
535
+ console.log();
536
+ } catch (e) {
537
+ err(`Failed to install: ${e.message}`);
538
+ process.exit(1);
539
+ }
540
+ }
541
+
542
+ // ── Gitignore Management ──────────────────────────────────
543
+ async function updateGitignore(targetDir, dryRun = false) {
544
+ if (dryRun) return;
545
+ const gitignorePath = path.join(targetDir, '.gitignore');
546
+ const entries = ['.agent/.backups/', '.agent/history/'];
547
+ let content = '';
548
+ try {
549
+ content = await fs.promises.readFile(gitignorePath, 'utf8');
550
+ } catch (err) {
551
+ if (err.code !== 'ENOENT') throw err;
552
+ }
553
+ let appended = false;
554
+ for (const entry of entries) {
555
+ if (!content.includes(entry)) {
556
+ content += (content.length > 0 && !content.endsWith('\n') ? '\n' : '') + entry + '\n';
557
+ appended = true;
558
+ }
559
+ }
560
+ if (appended) {
561
+ await fs.promises.writeFile(gitignorePath, content, 'utf8');
562
+ dbg(' Updated .gitignore');
563
+ }
564
+ }
565
+
566
+ // ── IDE Bridge Files ──────────────────────────────────────
567
+ // Each AI IDE reads rules from a different location.
568
+ // We generate bridge files that point each IDE at .agent/
569
+ async function generateIDEBridges(targetDir, agentDest, dryRun = false) {
570
+ const rulesFile = path.join(agentDest, 'rules', 'GEMINI.md');
571
+ let rulesContent = '';
572
+ try {
573
+ rulesContent = await fs.promises.readFile(rulesFile, 'utf8');
574
+ } catch {
575
+ // rules file doesn't exist
576
+ }
577
+
578
+ // Helper: write a bridge file or merge it if it exists
579
+ const writeBridge = async (filePath, content, label, isJson = false) => {
580
+ if (dryRun) {
581
+ dbg(` would create/update: ${filePath}`);
582
+ return;
583
+ }
584
+ const dir = path.dirname(filePath);
585
+ await fs.promises.mkdir(dir, { recursive: true });
586
+
587
+ try {
588
+ const existingContent = await fs.promises.readFile(filePath, 'utf8');
589
+ if (isJson) {
590
+ try {
591
+ const existingData = JSON.parse(existingContent);
592
+ const newData = JSON.parse(content);
593
+
594
+ if (!existingData.rules) existingData.rules = [];
595
+ const rulePath = newData.rules[0].path;
596
+ const ruleExists = existingData.rules.some(r => r.path === rulePath);
597
+ if (!ruleExists) {
598
+ existingData.rules.push(newData.rules[0]);
599
+ }
600
+
601
+ existingData.agents = { ...existingData.agents, ...newData.agents };
602
+ existingData.skills = { ...existingData.skills, ...newData.skills };
603
+ existingData.workflows = { ...existingData.workflows, ...newData.workflows };
604
+
605
+ await fs.promises.writeFile(filePath, JSON.stringify(existingData, null, 2) + '\n', 'utf8');
606
+ ok(`${label} (merged) → ${c('gray', path.relative(targetDir, filePath))}`);
607
+ } catch (e) {
608
+ warn(`Failed to merge ${label}: ${e.message}`);
609
+ }
610
+ } else {
611
+ if (!existingContent.includes('Tribunal Kit') && (!rulesContent || !existingContent.includes(rulesContent.slice(0, 50)))) {
612
+ await fs.promises.appendFile(filePath, '\n' + content, 'utf8');
613
+ ok(`${label} (appended) → ${c('gray', path.relative(targetDir, filePath))}`);
614
+ } else {
615
+ dbg(` skip (rules exist): ${path.basename(filePath)}`);
616
+ }
617
+ }
618
+ } catch (err) {
619
+ if (err.code === 'ENOENT') {
620
+ await fs.promises.writeFile(filePath, content, 'utf8');
621
+ ok(`${label} → ${c('gray', path.relative(targetDir, filePath))}`);
622
+ }
623
+ }
624
+ };
625
+
626
+ // ── 1. Cursor (.cursorrules) ──────────────────────────
627
+ const cursorRules = `# Tribunal Kit Cursor Bridge
628
+ # Auto-generated by tribunal-kit init. Do not edit manually.
629
+ # Source: .agent/rules/GEMINI.md
630
+
631
+ ${rulesContent}
632
+ `;
633
+ await writeBridge(
634
+ path.join(targetDir, '.cursorrules'),
635
+ cursorRules,
636
+ 'Cursor'
637
+ );
638
+
639
+ // ── 2. Windsurf (.windsurfrules) ─────────────────────
640
+ const windsurfRules = `# Tribunal Kit — Windsurf Bridge
641
+ # Auto-generated by tribunal-kit init. Do not edit manually.
642
+ # Source: .agent/rules/GEMINI.md
643
+
644
+ ${rulesContent}
645
+ `;
646
+ await writeBridge(
647
+ path.join(targetDir, '.windsurfrules'),
648
+ windsurfRules,
649
+ 'Windsurf'
650
+ );
651
+
652
+ // ── 3. Gemini / Antigravity (.gemini/settings.json) ──
653
+ const geminiSettings = JSON.stringify({
654
+ "rules": [
655
+ { "path": "../.agent/rules/GEMINI.md", "trigger": "always_on" }
656
+ ],
657
+ "agents": { "directory": "../.agent/agents" },
658
+ "skills": { "directory": "../.agent/skills" },
659
+ "workflows": { "directory": "../.agent/workflows" }
660
+ }, null, 2) + '\n';
661
+ await writeBridge(
662
+ path.join(targetDir, '.gemini', 'settings.json'),
663
+ geminiSettings,
664
+ 'Gemini/Antigravity',
665
+ true
666
+ );
667
+
668
+ // ── Also create .gemini/GEMINI.md as a direct rules file ──
669
+ const geminiRulesBridge = `---
670
+ trigger: always_on
671
+ ---
672
+
673
+ # Tribunal Kit — Gemini Bridge
674
+ # Auto-generated by tribunal-kit init.
675
+ # Full rules: .agent/rules/GEMINI.md
676
+
677
+ ${rulesContent}
678
+ `;
679
+ await writeBridge(
680
+ path.join(targetDir, '.gemini', 'GEMINI.md'),
681
+ geminiRulesBridge,
682
+ 'Gemini rules'
683
+ );
684
+
685
+ // ── 4. GitHub Copilot (.github/copilot-instructions.md) ──
686
+ const copilotInstructions = `# Tribunal Kit — Copilot Bridge
687
+ # Auto-generated by tribunal-kit init. Do not edit manually.
688
+ # Source: .agent/rules/GEMINI.md
689
+
690
+ ${rulesContent}
691
+ `;
692
+ await writeBridge(
693
+ path.join(targetDir, '.github', 'copilot-instructions.md'),
694
+ copilotInstructions,
695
+ 'GitHub Copilot'
696
+ );
697
+
698
+ // ── 5. Claude (.claude/CLAUDE.md) ─────────────────────
699
+ const claudeRules = `# Tribunal Kit — Claude Bridge
700
+ # Auto-generated by tribunal-kit init. Do not edit manually.
701
+ # Source: .agent/rules/GEMINI.md
702
+
703
+ ${rulesContent}
704
+ `;
705
+ await writeBridge(
706
+ path.join(targetDir, '.claude', 'CLAUDE.md'),
707
+ claudeRules,
708
+ 'Claude'
709
+ );
710
+
711
+ console.log();
712
+ }
713
+
714
+ async function cmdSync(args) {
715
+ console.log(`\n╭─ ${c('bold', 'Tribunal IDE Sync')} ──────────────────`);
716
+ console.log('│');
717
+ console.log(`│ ${c('gray', '✦ Regenerating IDE bridge files...')}`);
718
+ const cwd = process.cwd();
719
+ const agentDest = path.join(cwd, '.agent');
720
+ if (!fs.existsSync(agentDest)) {
721
+ console.error(`│ ${c('red', '✖ Error: .agent/ directory not found.')}`);
722
+ console.error(`│ ${c('gray', 'Run `tk init` first.')}`);
723
+ process.exit(1);
724
+ }
725
+ await generateIDEBridges(cwd, agentDest, false);
726
+ console.log(`│ ${c('green', '✔ Sync complete.')}`);
727
+ console.log('╰────────────────────────────────────────\n');
728
+ }
729
+
730
+ async function cmdUpdate(flags) {
731
+ // ── Self-install guard (early, before banner) ───────────
732
+ const targetDir = flags.path ? path.resolve(flags.path) : process.cwd();
733
+ if (isSelfInstall(targetDir)) {
734
+ err('Cannot run update inside the tribunal-kit package itself.');
735
+ err(`Target: ${targetDir}`);
736
+ console.log();
737
+ dim('This command is designed to update .agent/ in OTHER projects.');
738
+ dim('Run it from the root of the project you want to update:');
739
+ dim(' cd /path/to/your-project');
740
+ dim(' npx tribunal-kit update');
741
+ console.log();
742
+ process.exit(1);
743
+ }
744
+ // ────────────────────────────────────────────────────────
745
+
746
+ // Update = init with --force
747
+ flags.force = true;
748
+ if (!quiet) {
749
+ log(` ${c('cyan','↻')} ${bold('Updating')} ${c('white','.agent/')} to latest version...`);
750
+ console.log();
751
+ }
752
+ await cmdInit(flags);
753
+ }
754
+
755
+
756
+ async function cmdLearn(flags) {
757
+ const targetDir = flags.path ? path.resolve(flags.path) : process.cwd();
758
+ const agentDest = path.join(targetDir, '.agent');
759
+
760
+ if (!fs.existsSync(agentDest)) {
761
+ err('.agent/ not found. Run: npx tribunal-kit init');
762
+ process.exit(1);
763
+ }
764
+
765
+ banner();
766
+
767
+ const W = 62;
768
+ const title = ' Tribunal Learn — Supreme Court Mode';
769
+ const trail = ' '.repeat(Math.max(0, W - title.length));
770
+ console.log(` ${c('cyan', '\u2554' + '\u2550'.repeat(W) + '\u2557')}`);
771
+ console.log(` ${c('cyan', '\u2551')}${c('bold', c('white', title))}${trail}${c('cyan', '\u2551')}`);
772
+ console.log(` ${c('cyan', '\u255a' + '\u2550'.repeat(W) + '\u255d')}`);
773
+ console.log();
774
+
775
+ const evoArgs = ['digest'];
776
+ if (flags.dryRun) evoArgs.push('--dry-run');
777
+ if (flags.head) evoArgs.push('--head');
778
+
779
+
780
+ // Phase 1: Skill Evolution
781
+ log(` ${c('cyan', '\u229b')} ${bold('Phase 1')} \u2014 Skill Evolution Forge (auto-generating project idioms)`);
782
+ const evoScript = path.join(agentDest, 'scripts', 'skill_evolution.js');
783
+ if (!fs.existsSync(evoScript)) {
784
+ warn('skill_evolution.js not found \u2014 run: npx tribunal-kit update');
785
+ } else {
786
+ try {
787
+ await runScriptAsync(evoScript, evoArgs, { cwd: targetDir });
788
+ } catch (e) {
789
+ warn(`Skill Evolution error: ${e.message}`);
790
+ }
791
+ }
792
+
793
+ console.log();
794
+
795
+ // Phase 2: Case Law prompt
796
+ log(` ${c('cyan', '\u229b')} ${bold('Phase 2')} \u2014 Case Law Engine (building precedence record)`);
797
+ console.log();
798
+ log(` ${c('gray','\u25b8')} Record a new rejection precedent:`);
799
+ log(` ${c('white', 'npx tribunal-kit case add')}`);
800
+ console.log();
801
+ log(` ${c('gray','\u25b8')} Search existing case law:`);
802
+ log(` ${c('white', 'npx tribunal-kit case search "your query"')}`);
803
+ console.log();
804
+ log(` ${c('green', '\u2714')} ${bold('Learn cycle complete.')} Your Tribunal grows smarter with every commit.`);
805
+ console.log();
806
+ }
807
+
808
+ // ── Async Main Wrapper ───────────────────────────────────
809
+ async function runWithUpdateCheck(command, flags) {
810
+ const shouldSkip = flags.skipUpdateCheck || process.env.TK_SKIP_UPDATE_CHECK === '1';
811
+
812
+ if (!shouldSkip && (command === 'init' || command === 'update')) {
813
+ // Pass through the original args (minus the node/script path)
814
+ const originalArgs = process.argv.slice(2);
815
+ const didReInvoke = await autoUpdateCheck(originalArgs);
816
+ if (didReInvoke) {
817
+ process.exit(0); // Latest version handled it
818
+ }
819
+ }
820
+
821
+ // Proceed with current version
822
+ switch (command) {
823
+ case 'init':
824
+ await cmdInit(flags);
825
+ break;
826
+ case 'update':
827
+ await cmdUpdate(flags);
828
+ break;
829
+ case 'status':
830
+ cmdStatus(flags);
831
+ break;
832
+ case 'learn':
833
+ await cmdLearn(flags);
834
+ break;
835
+ case 'case':
836
+ await cmdCase(flags);
837
+ break;
838
+ case 'hook':
839
+ cmdHook(flags);
840
+ break;
841
+ case 'graph':
842
+ await cmdGraph(flags);
843
+ break;
844
+ case 'mutate':
845
+ await cmdMutate(flags);
846
+ break;
847
+ case 'context':
848
+ cmdContext(flags);
849
+ break;
850
+ case 'sync':
851
+ await cmdSync();
852
+ break;
853
+ case 'marathon':
854
+ await cmdMarathon(flags);
855
+ break;
856
+ case 'uninstall':
857
+ cmdUninstall(flags);
858
+ break;
859
+ case 'help':
860
+ case '--help':
861
+ case '-h':
862
+ case null:
863
+ cmdHelp();
864
+ break;
865
+ default:
866
+ err(`Unknown command: "${command}"`);
867
+ console.log();
868
+ dim('Run tribunal-kit --help for usage');
869
+ process.exit(1);
870
+ }
871
+ }
872
+
873
+ async function cmdCase(flags) {
874
+ const targetDir = flags.path ? path.resolve(flags.path) : process.cwd();
875
+ const agentDest = path.join(targetDir, '.agent');
876
+
877
+ if (!fs.existsSync(agentDest)) {
878
+ err('.agent/ not found. Run: npx tribunal-kit init');
879
+ process.exit(1);
880
+ }
881
+
882
+ const args = process.argv.slice(3);
883
+ if (args.length === 0 || args[0] === 'help' || args[0] === '--help' || args[0] === '-h') {
884
+ banner();
885
+ log(` ${c('cyan', '\u2554' + '\u2550'.repeat(60) + '\u2557')}`);
886
+ log(` ${c('cyan', '\u2551')}${c('bold', c('white', ' Tribunal Case Law Engine \u2014 Supreme Court '))}${c('cyan', '\u2551')}`);
887
+ log(` ${c('cyan', '\u255a' + '\u2550'.repeat(60) + '\u255d')}`);
888
+ console.log();
889
+ log(` ${c('cyan', 'add'.padEnd(10))} ${c('gray', 'Record a new Case Law rejection pattern')}`);
890
+ log(` ${c('cyan', 'search'.padEnd(10))} ${c('gray', 'Search existing cases (e.g., search "query")')}`);
891
+ log(` ${c('cyan', 'list'.padEnd(10))} ${c('gray', 'List all recorded case law')}`);
892
+ log(` ${c('cyan', 'show'.padEnd(10))} ${c('gray', 'Show full diff for a case (e.g., show --id 1)')}`);
893
+ log(` ${c('cyan', 'stats'.padEnd(10))} ${c('gray', 'Show case law stats by domain/verdict')}`);
894
+ log(` ${c('cyan', 'export'.padEnd(10))} ${c('gray', 'Export all cases to Markdown')}`);
895
+ log(` ${c('cyan', 'overrule'.padEnd(10))} ${c('gray', 'Overrule a past precedent (e.g., overrule --id 1)')}`);
896
+ console.log();
897
+ process.exit(1);
898
+ }
899
+
900
+ const caseLawScript = path.join(agentDest, 'scripts', 'case_law_manager.js');
901
+
902
+ // Make shorthand aliases for the subcommand (first arg only)
903
+ const caseArgs = [...args];
904
+ if (caseArgs[0] === 'add') caseArgs[0] = 'add-case';
905
+ if (caseArgs[0] === 'search') caseArgs[0] = 'search-cases';
906
+
907
+ try {
908
+ await runScriptAsync(caseLawScript, caseArgs, { cwd: targetDir });
909
+ } catch {
910
+ process.exit(1); // Script already prints errors
911
+ }
912
+ }
913
+
914
+ async function cmdGraph(flags) {
915
+ const targetDir = flags.path ? path.resolve(flags.path) : process.cwd();
916
+ const agentDest = path.join(targetDir, '.agent');
917
+
918
+ if (!fs.existsSync(agentDest)) {
919
+ err('.agent/ not found. Run: npx tribunal-kit init');
920
+ process.exit(1);
921
+ }
922
+
923
+ banner();
924
+ const builderScript = path.join(agentDest, 'scripts', 'graph_builder.js');
925
+ const visualizerScript = path.join(agentDest, 'scripts', 'graph_visualizer.js');
926
+ const htmlFile = path.join(agentDest, 'history', 'architecture-explorer.html');
927
+
928
+ try {
929
+ await runScriptAsync(builderScript, [], { cwd: targetDir });
930
+ await runScriptAsync(visualizerScript, [], { cwd: targetDir });
931
+
932
+ log(` ${c('cyan', '▸')} Opening visualizer in browser...`);
933
+ // Open browser safely without shell interpolation
934
+ const { opener, openerArgs } = (() => {
935
+ if (process.platform === 'win32') return { opener: 'cmd', openerArgs: ['/c', 'start', '', htmlFile] };
936
+ if (process.platform === 'darwin') return { opener: 'open', openerArgs: [htmlFile] };
937
+ return { opener: 'xdg-open', openerArgs: [htmlFile] };
938
+ })();
939
+ spawn(opener, openerArgs, { stdio: 'ignore', detached: true }).unref();
940
+ } catch (e) {
941
+ err(`Graph generation failed: ${e.message}`);
942
+ process.exit(1);
943
+ }
944
+ }
945
+
946
+ function cmdHook(flags) {
947
+ const targetDir = flags.path ? path.resolve(flags.path) : process.cwd();
948
+ const gitDir = path.join(targetDir, '.git');
949
+
950
+ if (!fs.existsSync(gitDir)) {
951
+ err('Not a git repository. Cannot install git hooks here.');
952
+ process.exit(1);
953
+ }
954
+
955
+ const hooksDir = path.join(gitDir, 'hooks');
956
+ if (!fs.existsSync(hooksDir)) {
957
+ fs.mkdirSync(hooksDir, { recursive: true });
958
+ }
959
+
960
+ const prePushPath = path.join(hooksDir, 'pre-push');
961
+ const hookScript = `#!/bin/sh\n# Supreme Court - Auto Learn on Push\necho "⚖️ Tribunal Supreme Court: Evolving Skills..."\nnpx tribunal-kit learn --head\necho "✦ Synchronizing IDE bridges..."\nnpx tribunal-kit sync\n`;
962
+
963
+ fs.writeFileSync(prePushPath, hookScript, { mode: 0o755 });
964
+
965
+ console.log();
966
+ log(` ${c('green', '✔')} Installed pre-push git hook.`);
967
+ log(` ${c('gray', '')} Skill Evolution and IDE Sync will now run automatically every time you git push.`);
968
+ console.log();
969
+ }
970
+
971
+ async function cmdMutate(flags) {
972
+ const targetDir = flags.path ? path.resolve(flags.path) : process.cwd();
973
+ const agentDest = path.join(targetDir, '.agent');
974
+
975
+ if (!fs.existsSync(agentDest)) {
976
+ err('.agent/ not found. Run: npx tribunal-kit init');
977
+ process.exit(1);
978
+ }
979
+
980
+ const args = process.argv.slice(3);
981
+ if (args.length < 2) {
982
+ err('Usage: npx tribunal-kit mutate <target_file> <test_command>');
983
+ process.exit(1);
984
+ }
985
+
986
+ const mutateScript = path.join(agentDest, 'scripts', 'mutation_runner.js');
987
+ try {
988
+ await runScriptAsync(mutateScript, args, { cwd: targetDir });
989
+ } catch {
990
+ process.exit(1);
991
+ }
992
+ }
993
+
994
+ function cmdUninstall(flags) {
995
+ const targetDir = flags.path ? path.resolve(flags.path) : process.cwd();
996
+ const agentDest = path.join(targetDir, '.agent');
997
+
998
+ banner();
999
+
1000
+ if (!fs.existsSync(agentDest)) {
1001
+ log(` ${c('yellow','⚠')} ${bold('.agent/')} is not installed in this project.`);
1002
+ console.log();
1003
+ return;
1004
+ }
1005
+
1006
+ if (flags.dryRun) {
1007
+ log(colorize('yellow', ' DRY RUN — would remove:'));
1008
+ log(` ${c('gray',' ╰─')} ${agentDest}`);
1009
+ console.log();
1010
+ return;
1011
+ }
1012
+
1013
+ try {
1014
+ fs.rmSync(agentDest, { recursive: true, force: true });
1015
+ log(` ${c('green','✔')} ${bold('.agent/')} has been removed from this project.`);
1016
+ console.log();
1017
+ log(` ${c('gray','▸')} To reinstall: ${c('cyan','npx tribunal-kit init')}`);
1018
+ console.log();
1019
+ } catch (e) {
1020
+ err(`Failed to remove .agent/: ${e.message}`);
1021
+ process.exit(1);
1022
+ }
1023
+ }
1024
+
1025
+ function cmdStatus(flags) {
1026
+ const targetDir = flags.path ? path.resolve(flags.path) : process.cwd();
1027
+ const agentDest = path.join(targetDir, '.agent');
1028
+
1029
+ banner();
1030
+
1031
+ if (!fs.existsSync(agentDest)) {
1032
+ log(` ${c('red','')} ${bold('Not installed')} in this project`);
1033
+ console.log();
1034
+ log(` ${c('gray','Run:')} ${c('cyan','npx tribunal-kit init')}`);
1035
+ console.log();
1036
+ return;
1037
+ }
1038
+
1039
+ log(` ${c('green','✔')} ${bold(c('green','Installed'))} ${c('gray','→')} ${c('gray', agentDest)}`);
1040
+ console.log();
1041
+
1042
+ const icons = { agents: '🤖', workflows: '⚡', skills: '🧠', scripts: '🔧' };
1043
+ const colors = { agents: 'magenta', workflows: 'yellow', skills: 'blue', scripts: 'green' };
1044
+ const subdirs = ['agents', 'workflows', 'skills', 'scripts'];
1045
+ for (const sub of subdirs) {
1046
+ const subPath = path.join(agentDest, sub);
1047
+ if (fs.existsSync(subPath)) {
1048
+ const count = fs.readdirSync(subPath).filter(f => !fs.statSync(path.join(subPath, f)).isDirectory()).length;
1049
+ log(` ${icons[sub]} ${c(colors[sub], sub.padEnd(12))}${c('white', String(count).padStart(3))} files`);
1050
+ }
1051
+ }
1052
+ console.log();
1053
+ }
1054
+
1055
+ function cmdHelp() {
1056
+ banner();
1057
+ const cmd = (name, desc) => ` ${c('cyan', name.padEnd(10))} ${c('gray', desc)}`;
1058
+ const opt = (flag, desc) => ` ${c('yellow', flag.padEnd(22))} ${c('gray', desc)}`;
1059
+ const ex = (s) => ` ${c('gray', '')} ${c('white', s)}`;
1060
+
1061
+ log(bold(' Commands'));
1062
+ log(` ${c('gray','─'.repeat(40))}`);
1063
+ log(cmd('init', 'Install .agent/ into current project'));
1064
+ log(cmd('update', 'Re-install to get latest version'));
1065
+ log(cmd('status', 'Check if .agent/ is installed'));
1066
+ log(cmd('learn', 'Evolve project idioms based on git diffs'));
1067
+ log(cmd('case', 'Manage Case Law precedents (add, search, list, show, stats, overrule)'));
1068
+ log(cmd('graph', 'Build and visualize the architecture graph'));
1069
+ log(cmd('mutate', 'Run the Mutation Engine to test test-suite reliability'));
1070
+ log(cmd('context', 'Retrieve a highly-optimized Context Snapshot for a file'));
1071
+ log(cmd('sync', 'Synchronize IDE bridge files with current rules'));
1072
+ log(cmd('marathon', 'Long-running agent harness (init, status, next, mark)'));
1073
+ log(cmd('hook', 'Install pre-push git hook for auto-learning'));
1074
+ log(cmd('uninstall','Remove .agent/ folder from project'));
1075
+ console.log();
1076
+ log(bold(' Options'));
1077
+ log(` ${c('gray','─'.repeat(40))}`);
1078
+ log(opt('--force', 'Overwrite existing .agent/ folder'));
1079
+ log(opt('--path <dir>', 'Install in specific directory'));
1080
+ log(opt('--quiet', 'Suppress all output'));
1081
+ log(opt('--verbose', 'Show detailed debug logging'));
1082
+ log(opt('--dry-run', 'Preview actions without executing'));
1083
+ log(opt('--minimal', 'Install core agents/skills only (~13 agents)'));
1084
+ log(opt('--skip-update-check', 'Skip auto-update version check'));
1085
+ log(opt('--head', '(learn) Diff against last commit instead of staged'));
1086
+ console.log();
1087
+ log(bold(' Aliases'));
1088
+ log(` ${c('gray','─'.repeat(40))}`);
1089
+ log(` ${c('cyan', 'tk')} ${c('gray', 'Shorthand for tribunal-kit (e.g., tk init, tk status)')}`);
1090
+ console.log();
1091
+ log(bold(' Examples'));
1092
+ log(` ${c('gray','─'.repeat(40))}`);
1093
+ log(ex('npx tribunal-kit init'));
1094
+ log(ex('tk init --force'));
1095
+ log(ex('tk init --path ./my-app'));
1096
+ log(ex('npx tribunal-kit init --dry-run'));
1097
+ log(ex('tk update'));
1098
+ log(ex('tk status'));
1099
+ log(ex('tk learn'));
1100
+ log(ex('tk learn --dry-run'));
1101
+ log(ex('tk learn --head'));
1102
+ log(ex('tk case add'));
1103
+ log(ex('tk case search "useEffect"'));
1104
+ log(ex('tk case list'));
1105
+ log(ex('tk case show --id 1'));
1106
+ log(ex('tk case stats'));
1107
+ log(ex('tk case export'));
1108
+ log(ex('tk case overrule --id 1'));
1109
+ log(ex('tk graph'));
1110
+ log(ex('tk mutate src/utils.js "npm test"'));
1111
+ log(ex('tk marathon init "Build a todo app"'));
1112
+ log(ex('tk marathon status'));
1113
+ log(ex('tk marathon next'));
1114
+ log(ex('tk marathon mark 5 pass'));
1115
+ log(ex('tk hook'));
1116
+ log(ex('tk uninstall'));
1117
+ console.log();
1118
+ }
1119
+
1120
+
1121
+ async function cmdMarathon(flags) {
1122
+ const targetDir = flags.path ? path.resolve(flags.path) : process.cwd();
1123
+ const agentDest = path.join(targetDir, '.agent');
1124
+
1125
+ if (!fs.existsSync(agentDest)) {
1126
+ err('.agent/ not found. Run: npx tribunal-kit init');
1127
+ process.exit(1);
1128
+ }
1129
+
1130
+ const args = process.argv.slice(3);
1131
+ if (args.length === 0 || args[0] === 'help' || args[0] === '--help' || args[0] === '-h') {
1132
+ banner();
1133
+ log(` ${c('cyan', '╔' + '═'.repeat(60) + '╗')}`);
1134
+ log(` ${c('cyan', '║')}${c('bold', c('white', ' Marathon — Long-Running Agent Harness '))}${c('cyan', '║')}`);
1135
+ log(` ${c('cyan', '╚' + '═'.repeat(60) + '╝')}`);
1136
+ console.log();
1137
+ log(` ${c('cyan', 'init'.padEnd(16))} ${c('gray', 'Start a new marathon (init "spec")')}`);
1138
+ log(` ${c('cyan', 'status'.padEnd(16))} ${c('gray', 'Show progress dashboard')}`);
1139
+ log(` ${c('cyan', 'next'.padEnd(16))} ${c('gray', 'Show next unfinished feature')}`);
1140
+ log(` ${c('cyan', 'mark'.padEnd(16))} ${c('gray', 'Mark feature pass/fail (mark <id> pass)')}`);
1141
+ log(` ${c('cyan', 'log'.padEnd(16))} ${c('gray', 'Add a progress note')}`);
1142
+ log(` ${c('cyan', 'session-start'.padEnd(16))} ${c('gray', 'Begin a new work session')}`);
1143
+ log(` ${c('cyan', 'session-end'.padEnd(16))} ${c('gray', 'End session with summary')}`);
1144
+ log(` ${c('cyan', 'add-feature'.padEnd(16))} ${c('gray', 'Add feature: "category" "desc" "step1" ...')}`);
1145
+ log(` ${c('cyan', 'reset'.padEnd(16))} ${c('gray', 'Archive and start fresh')}`);
1146
+ console.log();
1147
+ return;
1148
+ }
1149
+
1150
+ const marathonScript = path.join(agentDest, 'scripts', 'marathon_harness.js');
1151
+ try {
1152
+ await runScriptAsync(marathonScript, args, { cwd: targetDir });
1153
+ } catch {
1154
+ process.exit(1);
1155
+ }
1156
+ }
1157
+
1158
+ function cmdContext(flags) {
1159
+ const targetDir = flags.path ? path.resolve(flags.path) : process.cwd();
1160
+ const agentDest = path.join(targetDir, '.agent');
1161
+
1162
+ if (!fs.existsSync(agentDest)) {
1163
+ err('.agent/ not found. Run: npx tribunal-kit init');
1164
+ process.exit(1);
1165
+ }
1166
+
1167
+ const args = process.argv.slice(3);
1168
+ if (args.length === 0 || args[0] === 'help' || args[0] === '--help') {
1169
+ console.error('Usage: npx tribunal-kit context <target_file>');
1170
+ process.exit(1);
1171
+ }
1172
+
1173
+ const targetFile = args[0].replace(/\\/g, '/');
1174
+ const snapshotName = targetFile.replace(/[\\\/]/g, '__') + '.json';
1175
+ const snapshotPath = require('path').join(agentDest, 'history', 'snapshots', snapshotName);
1176
+
1177
+ if (!require('fs').existsSync(snapshotPath)) {
1178
+ console.error(' \x1b[91m✖\x1b[0m Context Snapshot not found for: ' + targetFile);
1179
+ console.log(' Run: npx tribunal-kit graph (to generate snapshots)');
1180
+ process.exit(1);
1181
+ }
1182
+
1183
+ try {
1184
+ const snapshot = JSON.parse(require('fs').readFileSync(snapshotPath, 'utf8'));
1185
+
1186
+ console.log('\n# Context Snapshot: ' + snapshot.file);
1187
+ process.stdout.write('> Size Estimate: ' + (snapshot['estimatedTokens'] || 'Unknown') + '\n');
1188
+ console.log('> Risk Score: ' + snapshot.riskScore + ' (Blast Radius: ' + snapshot.blastRadius + ')\n');
1189
+
1190
+ if (Object.keys(snapshot.imports).length > 0) {
1191
+ console.log('## Imports');
1192
+ for (const [imp, exports] of Object.entries(snapshot.imports)) {
1193
+ if (exports && exports.length > 0) {
1194
+ console.log('- `' + imp + '` (exports: ' + exports.join(', ') + ')');
1195
+ } else {
1196
+ console.log('- `' + imp + '`');
1197
+ }
1198
+ }
1199
+ console.log();
1200
+ }
1201
+
1202
+ if (snapshot.dependents && snapshot.dependents.length > 0) {
1203
+ console.log('## Dependents');
1204
+ for (const dep of snapshot.dependents) {
1205
+ console.log('- `' + dep + '`');
1206
+ }
1207
+ console.log();
1208
+ }
1209
+
1210
+ console.log('## Source Code');
1211
+ console.log('```javascript\n' + snapshot.content + '\n```\n');
1212
+
1213
+ } catch (e) {
1214
+ console.error('Failed to read snapshot: ' + e.message);
1215
+ process.exit(1);
1216
+ }
1217
+ }
1218
+
1219
+ // ── Main ──────────────────────────────────────────────────
1220
+ const { command, flags } = parseArgs(process.argv);
1221
+
1222
+ if (flags.quiet) quiet = true;
1223
+ if (flags.verbose) verbose = true;
1224
+
1225
+ runWithUpdateCheck(command, flags);
1226
+
1227
+ // -- Exports (for testing) -- do not remove
1228
+ if (require.main !== module) {
1229
+ module.exports = { parseArgs, compareSemver, copyDir, countDir, isSelfInstall, CORE_AGENTS, CORE_SKILLS, generateIDEBridges, cmdMarathon };
1121
1230
  }