tribunal-kit 5.7.0 → 5.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/.agent/ARCHITECTURE.md +6 -7
  2. package/.agent/agents/frontend-reviewer.md +13 -0
  3. package/.agent/agents/frontend-specialist.md +14 -0
  4. package/.agent/agents/logic-reviewer.md +11 -0
  5. package/.agent/agents/orchestrator.md +15 -0
  6. package/.agent/agents/security-auditor.md +13 -0
  7. package/.agent/agents/ui-ux-auditor.md +7 -31
  8. package/.agent/history/memory/.memory.idx +766 -0
  9. package/.agent/history/memory/MEMORY.md +62 -0
  10. package/.agent/routing_index.json +694 -714
  11. package/.agent/rules/GEMINI.md +58 -8
  12. package/.agent/scripts/_colors.js +131 -89
  13. package/.agent/scripts/_utils.js +163 -128
  14. package/.agent/scripts/auto_preview.js +207 -197
  15. package/.agent/scripts/bundle_analyzer.js +227 -192
  16. package/.agent/scripts/case_law_manager.js +991 -689
  17. package/.agent/scripts/checklist.js +233 -190
  18. package/.agent/scripts/context_broker.js +930 -605
  19. package/.agent/scripts/dependency_analyzer.js +275 -184
  20. package/.agent/scripts/graph_builder.js +412 -341
  21. package/.agent/scripts/graph_visualizer.js +392 -390
  22. package/.agent/scripts/graph_zoom.js +198 -156
  23. package/.agent/scripts/inner_loop_validator.js +523 -445
  24. package/.agent/scripts/lint_runner.js +199 -157
  25. package/.agent/scripts/marathon_harness.js +819 -661
  26. package/.agent/scripts/minify_context.js +115 -100
  27. package/.agent/scripts/mutation_runner.js +321 -280
  28. package/.agent/scripts/prompt_compiler.js +62 -42
  29. package/.agent/scripts/schema_validator.js +373 -280
  30. package/.agent/scripts/security_scan.js +333 -190
  31. package/.agent/scripts/session_manager.js +306 -270
  32. package/.agent/scripts/skill_evolution.js +810 -637
  33. package/.agent/scripts/skill_integrator.js +327 -307
  34. package/.agent/scripts/strengthen_skills.js +203 -193
  35. package/.agent/scripts/swarm_dispatcher.js +558 -457
  36. package/.agent/scripts/test_runner.js +178 -152
  37. package/.agent/scripts/verify_all.js +200 -168
  38. package/.agent/skills/fabel-protocol/SKILL.md +235 -0
  39. package/.agent/skills/thinking-protocol/SKILL.md +27 -0
  40. package/.agent/workflows/generate.md +1 -1
  41. package/.agent/workflows/tribunal-speed.md +1 -1
  42. package/README.md +53 -53
  43. package/bin/mcp-server.js +460 -175
  44. package/bin/tribunal-kit.js +1245 -987
  45. package/bin/wrapper.js +104 -74
  46. package/dist/cli.js +31 -0
  47. package/dist/commands/case.js +23 -0
  48. package/dist/commands/compile.js +84 -0
  49. package/dist/commands/init.js +42 -0
  50. package/dist/commands/learn.js +57 -0
  51. package/dist/commands/memory.js +456 -0
  52. package/package.json +2 -2
  53. package/scripts/benchmark.js +162 -125
  54. package/scripts/changelog.js +196 -168
  55. package/scripts/sync-version.js +94 -81
  56. package/scripts/validate-payload.js +85 -78
@@ -1,689 +1,991 @@
1
- #!/usr/bin/env node
2
- /**
3
- * case_law_manager.js — Tribunal Kit Case Law Engine
4
- * =====================================================
5
- * Records rejected code patterns as "Cases" and surfaces them as
6
- * binding Legal Precedence during future Tribunal reviews.
7
- *
8
- * Usage:
9
- * node .agent/scripts/case_law_manager.js add-case
10
- * node .agent/scripts/case_law_manager.js search-cases --query "forEach side effects"
11
- * node .agent/scripts/case_law_manager.js list
12
- * node .agent/scripts/case_law_manager.js show --id 7
13
- * node .agent/scripts/case_law_manager.js export
14
- * node .agent/scripts/case_law_manager.js stats
15
- *
16
- * Storage:
17
- * .agent/history/case-law/index.json ← master index of all cases
18
- * .agent/history/case-law/cases/ ← one JSON file per case
19
- */
20
-
21
- 'use strict';
22
-
23
- const fs = require('fs');
24
- const path = require('path');
25
- const crypto = require('crypto');
26
- const readline = require('readline');
27
-
28
- // ── Colours ──────────────────────────────────────────────────────────────────
29
- const { GREEN, YELLOW, CYAN, RED, BOLD, DIM, RESET } = require('./_colors');
30
-
31
- // ── Find .agent directory ─────────────────────────────────────────────────────
32
- function findAgentDir() {
33
- let current = path.resolve(process.cwd());
34
- const root = path.parse(current).root;
35
- while (current !== root) {
36
- const candidate = path.join(current, '.agent');
37
- if (fs.existsSync(candidate) && fs.statSync(candidate).isDirectory()) return candidate;
38
- current = path.dirname(current);
39
- }
40
- console.error(`${RED}✖ Error: '.agent' directory not found. Please run 'npx tribunal-kit init' first.${RESET}`);
41
- process.exit(1);
42
- }
43
-
44
- // ── Lazy path resolution (avoids side effects at require-time) ───────────────
45
- let _paths = null;
46
- function getPaths() {
47
- if (_paths) return _paths;
48
- const agentDir = findAgentDir();
49
- const historyDir = path.join(agentDir, 'history', 'case-law');
50
- const casesDir = path.join(historyDir, 'cases');
51
- const indexFile = path.join(historyDir, 'index.json');
52
- _paths = { AGENT_DIR: agentDir, HISTORY_DIR: historyDir, CASES_DIR: casesDir, INDEX_FILE: indexFile };
53
- return _paths;
54
- }
55
-
56
- const VALID_DOMAINS = new Set(['backend', 'frontend', 'database', 'security', 'performance', 'mobile', 'testing', 'devops', 'general']);
57
- const VALID_VERDICTS = new Set(['REJECTED', 'APPROVED_WITH_CONDITIONS', 'PRECEDENT_SET', 'OVERRULED']);
58
-
59
- // ── Noise filter ────────────────────────────────────────────────────────────
60
- const NOISE_PATTERNS = [
61
- /\bformatting\b/i, /\bwhitespace\b/i, /\bindent(ation)?\b/i,
62
- /\bimport\s+order\b/i, /\btrailing\s+(comma|space|whitespace)\b/i,
63
- /\bsemicolon\b/i, /\bprettier\b/i, /\beslint.*fix\b/i, /\blint.*only\b/i,
64
- ];
65
-
66
- function isNoiseRejection(reason) {
67
- const lower = reason.toLowerCase();
68
- return NOISE_PATTERNS.some(p => p.test(lower));
69
- }
70
-
71
- // ── Trivial-change filter (Semantic Delta) ────────────────────────────────────
72
- const TRIVIAL_PATTERNS = [
73
- /^\s*$/, // blank lines
74
- /^\s*\/\/.*$/, // comment-only lines
75
- /^\s*#.*$/, // python comments
76
- /^\s*\*.*$/, // JSDoc lines
77
- /^\s*import\b.*$/, // imports
78
- ];
79
-
80
- function isTrivialLine(line) {
81
- return TRIVIAL_PATTERNS.some(p => p.test(line));
82
- }
83
-
84
- function semanticDelta(diffText) {
85
- const lines = diffText.split('\n');
86
- const meaningful = [];
87
- for (const line of lines) {
88
- if (line.startsWith('+++') || line.startsWith('---') || line.startsWith('@@')) {
89
- meaningful.push(line);
90
- continue;
91
- }
92
- if (line.startsWith('+') || line.startsWith('-')) {
93
- const codePart = line.slice(1);
94
- if (!isTrivialLine(codePart)) meaningful.push(line);
95
- } else {
96
- meaningful.push(line);
97
- }
98
- }
99
- let filtered = meaningful.join('\n');
100
- filtered = filtered.replace(/(\n[ ]?\n){3,}/g, '\n\n');
101
- return filtered.trim();
102
- }
103
-
104
- function contentHash(text) {
105
- const cleaned = semanticDelta(text);
106
- return crypto.createHash('sha256').update(cleaned).digest('hex').slice(0, 8);
107
- }
108
-
109
- // ── Index helpers ─────────────────────────────────────────────────────────────
110
- function ensureDirs() {
111
- const { HISTORY_DIR, CASES_DIR } = getPaths();
112
- fs.mkdirSync(HISTORY_DIR, { recursive: true });
113
- fs.mkdirSync(CASES_DIR, { recursive: true });
114
- }
115
-
116
- function loadIndex() {
117
- ensureDirs();
118
- const { INDEX_FILE } = getPaths();
119
- if (fs.existsSync(INDEX_FILE)) {
120
- try { return JSON.parse(fs.readFileSync(INDEX_FILE, 'utf8')); } catch { /* fallthrough */ }
121
- }
122
- return { version: '1.0', cases: [], next_id: 1 };
123
- }
124
-
125
- function saveIndex(index) {
126
- ensureDirs();
127
- const { INDEX_FILE } = getPaths();
128
- const tmp = INDEX_FILE + '.tmp';
129
- fs.writeFileSync(tmp, JSON.stringify(index, null, 2), 'utf8');
130
- fs.renameSync(tmp, INDEX_FILE);
131
- }
132
-
133
- function loadCase(caseId) {
134
- const { CASES_DIR } = getPaths();
135
- const p = path.join(CASES_DIR, `case-${String(caseId).padStart(4, '0')}.json`);
136
- if (!fs.existsSync(p)) return null;
137
- try { return JSON.parse(fs.readFileSync(p, 'utf8')); } catch { return null; }
138
- }
139
-
140
- function saveCase(caseRecord) {
141
- const { CASES_DIR } = getPaths();
142
- const p = path.join(CASES_DIR, `case-${String(caseRecord.id).padStart(4, '0')}.json`);
143
- fs.writeFileSync(p, JSON.stringify(caseRecord, null, 2), 'utf8');
144
- }
145
-
146
- // ── Keyword/tag extraction ─────────────────────────────────────────────────────
147
- function extractTags(text) {
148
- const tokens = text.match(/\b[a-zA-Z_][a-zA-Z0-9_]{2,}\b/g) || [];
149
- const stopWords = new Set([
150
- 'the', 'and', 'for', 'was', 'this', 'with', 'that', 'has', 'a', 'an',
151
- 'from', 'are', 'not', 'use', 'but', 'also', 'code',
152
- 'have', 'will', 'should', 'must', 'can', 'may', 'any',
153
- 'all', 'new', 'old', 'add', 'get', 'set', 'var', 'let',
154
- 'const', 'function', 'return', 'import', 'export', 'class',
155
- 'async', 'await', 'true', 'false', 'null', 'undefined',
156
- ]);
157
- const seen = new Set();
158
- const tags = [];
159
- for (const token of tokens) {
160
- const lower = token.toLowerCase();
161
- if (!stopWords.has(lower) && !seen.has(lower)) {
162
- seen.add(lower);
163
- tags.push(lower);
164
- }
165
- if (tags.length >= 20) break;
166
- }
167
- return tags;
168
- }
169
-
170
- // ── Version-Aware Case Filtering ──────────────────────────────────────────────
171
- // FIX: Prevents stale cases (e.g., React 17 rejections) from blocking valid code
172
- // once the project has upgraded frameworks. Uses simple numeric comparison.
173
- //
174
- // Version filter string format: "react=19,node=22,next=15"
175
- // Case stack_version format: "react>=18,node>=20" (>=, >, =, <, <=)
176
-
177
- /**
178
- * Parse a version filter string into a map of { lib -> number }.
179
- * Input: "react=19,node=22"
180
- * Output: { react: 19, node: 22 }
181
- * @param {string} filterStr
182
- * @returns {Object<string, number>}
183
- */
184
- function parseVersionFilter(filterStr) {
185
- const result = {};
186
- if (!filterStr) return result;
187
- for (const segment of filterStr.split(',')) {
188
- const m = segment.trim().match(/^([a-zA-Z0-9_.-]+)\s*(?:>=|>|<=|<|=)?\s*(\d+(?:\.\d+)?)/);
189
- if (m) result[m[1].toLowerCase()] = parseFloat(m[2]);
190
- }
191
- return result;
192
- }
193
-
194
- /**
195
- * Returns true if the case either has no stack_version constraint,
196
- * OR all of its version constraints are satisfied by the provided filter.
197
- *
198
- * A case with stack_version "react>=18,node>=20" will be SKIPPED (return false)
199
- * when the version filter says react=19,node=22 → both constraints met → case IS relevant.
200
- *
201
- * The logic: if a case's constraint is NOT met by the current version filter,
202
- * that case is from a different version context → skip it.
203
- *
204
- * @param {{ stack_version?: string }} caseEntry
205
- * @param {Object<string, number>} versionFilter
206
- * @returns {boolean} true = case is eligible for this version context
207
- */
208
- function caseMatchesVersionFilter(caseEntry, versionFilter) {
209
- if (!caseEntry.stack_version) return true; // No constraint → always eligible
210
- if (!versionFilter || !Object.keys(versionFilter).length) return true;
211
-
212
- // Parse the case's own version constraint
213
- const caseConstraints = [];
214
- for (const segment of caseEntry.stack_version.split(',')) {
215
- const m = segment.trim().match(/^([a-zA-Z0-9_.-]+)\s*(>=|>|<=|<|=)\s*(\d+(?:\.\d+)?)/);
216
- if (m) caseConstraints.push({ lib: m[1].toLowerCase(), op: m[2], ver: parseFloat(m[3]) });
217
- }
218
-
219
- // Check each constraint against the version filter
220
- for (const { lib, op, ver } of caseConstraints) {
221
- const projectVer = versionFilter[lib];
222
- if (projectVer === undefined) continue; // Unknown lib → don't filter on it
223
-
224
- const satisfied = (
225
- op === '>=' ? projectVer >= ver :
226
- op === '>' ? projectVer > ver :
227
- op === '<=' ? projectVer <= ver :
228
- op === '<' ? projectVer < ver :
229
- /* = */ projectVer === ver
230
- );
231
- if (!satisfied) return false; // This case's version context doesn't match
232
- }
233
- return true;
234
- }
235
-
236
- // ── Similarity scoring (TF-IDF Cosine — token-free) ──────────────────────────
237
-
238
- function buildIdf(corpus) {
239
- const n = corpus.length;
240
- if (n === 0) return {};
241
- const docFreq = {};
242
- for (const tags of corpus) {
243
- const unique = new Set(tags);
244
- for (const tag of unique) {
245
- docFreq[tag] = (docFreq[tag] || 0) + 1;
246
- }
247
- }
248
- const idf = {};
249
- for (const [term, df] of Object.entries(docFreq)) {
250
- idf[term] = Math.log((n + 1) / (df + 1)) + 1.0;
251
- }
252
- return idf;
253
- }
254
-
255
- function tfidfCosineSimilarity(queryTags, caseTags, idf) {
256
- if (!queryTags.length || !caseTags.length) return 0.0;
257
- const tfQ = {};
258
- for (const t of queryTags) tfQ[t] = (tfQ[t] || 0) + 1;
259
- const tfC = {};
260
- for (const t of caseTags) tfC[t] = (tfC[t] || 0) + 1;
261
- const allTerms = new Set([...Object.keys(tfQ), ...Object.keys(tfC)]);
262
- let dot = 0, magQ = 0, magC = 0;
263
- for (const term of allTerms) {
264
- const wQ = (tfQ[term] || 0) * (idf[term] || 1.0);
265
- const wC = (tfC[term] || 0) * (idf[term] || 1.0);
266
- dot += wQ * wC;
267
- magQ += wQ * wQ;
268
- magC += wC * wC;
269
- }
270
- if (magQ === 0 || magC === 0) return 0.0;
271
- return dot / (Math.sqrt(magQ) * Math.sqrt(magC));
272
- }
273
-
274
- // ── Input helpers ─────────────────────────────────────────────────────────────
275
- function createRl() {
276
- return readline.createInterface({ input: process.stdin, output: process.stdout });
277
- }
278
-
279
- function ask(rl, prompt) {
280
- return new Promise(resolve => rl.question(` ${BOLD}${prompt}${RESET} `, resolve));
281
- }
282
-
283
- function askMultiline(rl, prompt, sentinel) {
284
- return new Promise(resolve => {
285
- console.log(` ${BOLD}${prompt}${RESET}`);
286
- console.log(` ${DIM}(Type or paste content. Type '${sentinel}' on its own line when done.)${RESET}`);
287
- const lines = [];
288
- const listener = (line) => {
289
- if (line.trim() === sentinel) {
290
- rl.removeListener('line', listener);
291
- resolve(lines.join('\n'));
292
- } else {
293
- lines.push(line);
294
- }
295
- };
296
- rl.on('line', listener);
297
- });
298
- }
299
-
300
- function askChoice(rl, label, choices, defaultVal) {
301
- return new Promise(resolve => {
302
- const opts = choices.map(c => c === defaultVal ? `${BOLD}${c}${RESET}` : c).join(' / ');
303
- rl.question(` ${BOLD}${label}${RESET} [${opts}] (default: ${defaultVal}): `, answer => {
304
- const val = (answer || '').trim().toLowerCase();
305
- resolve(val && choices.includes(val) ? val : defaultVal);
306
- });
307
- });
308
- }
309
-
310
- // ── Commands ──────────────────────────────────────────────────────────────────
311
- async function cmdAddCase() {
312
- console.log(`\n${BOLD}${CYAN}━━━ Recording New Case ━━━━━━━━━━━━━━━━━━━━━━━━━━━━${RESET}`);
313
- const rl = createRl();
314
-
315
- const diffText = await askMultiline(rl, 'Paste the REJECTED diff (code snippet):', 'END_DIFF');
316
- if (!diffText.trim()) { console.log(`${RED}✖ Diff cannot be empty. Aborting.${RESET}`); rl.close(); process.exit(1); }
317
-
318
- const reason = await ask(rl, 'Rejection reason (1-2 sentences):');
319
- if (!reason.trim()) { console.log(`${RED}✖ Reason cannot be empty. Aborting.${RESET}`); rl.close(); process.exit(1); }
320
-
321
- const domain = await askChoice(rl, 'Domain', [...VALID_DOMAINS].sort(), 'general');
322
- const verdict = await askChoice(rl, 'Verdict', [...VALID_VERDICTS].sort(), 'REJECTED');
323
- const prRef = (await ask(rl, 'PR / commit reference (optional, e.g. PR-404):')).trim() || null;
324
- const reviewer = (await ask(rl, 'Reviewer agent (optional, e.g. security-auditor):')).trim() || null;
325
-
326
- // FIX: stack_version — prevents stale cases from blocking valid code after
327
- // framework upgrades. Format: "react>=19, node>=20" or leave blank for all.
328
- const stackVersionRaw = (await ask(rl, 'Stack version constraint (optional, e.g. react>=18, node>=20):')).trim();
329
- const stackVersion = stackVersionRaw || null;
330
- rl.close();
331
-
332
- const delta = semanticDelta(diffText);
333
- const fingerprint = contentHash(diffText);
334
- const tags = extractTags(diffText + ' ' + reason);
335
-
336
- const index = loadIndex();
337
- const caseId = index.next_id;
338
- const now = new Date().toISOString().slice(0, 19);
339
-
340
- const caseRecord = {
341
- id: caseId, fingerprint, timestamp: now, domain, verdict,
342
- reason: reason.trim(), pr_ref: prRef, reviewer, tags,
343
- stack_version: stackVersion,
344
- diff_raw: diffText.trim(), diff_delta: delta,
345
- };
346
-
347
- saveCase(caseRecord);
348
- index.cases.push({
349
- id: caseId, fingerprint, domain, verdict, tags,
350
- timestamp: now, reason_summary: reason.trim().slice(0, 120),
351
- stack_version: stackVersion,
352
- });
353
- index.next_id = caseId + 1;
354
- saveIndex(index);
355
-
356
- console.log(`\n${GREEN}✔ Case #${String(caseId).padStart(4, '0')} recorded${RESET}`);
357
- console.log(` ${DIM}Fingerprint : ${fingerprint}${RESET}`);
358
- console.log(` ${DIM}Domain : ${domain}${RESET}`);
359
- console.log(` ${DIM}Tags : ${tags.slice(0, 8).join(', ')}${RESET}`);
360
- if (stackVersion) console.log(` ${DIM}Stack version : ${stackVersion}${RESET}`);
361
- console.log();
362
- }
363
-
364
- function cmdSearchCases(args) {
365
- let query = args.filter(a => !a.startsWith('--')).join(' ');
366
- if (!query) {
367
- const qi = process.argv.indexOf('--query');
368
- if (qi !== -1) query = process.argv.slice(qi + 1).filter(a => !a.startsWith('--')).join(' ');
369
- }
370
- if (!query) { console.log(`${RED}✖ Provide a search query: search-cases --query "forEach side effects"${RESET}`); process.exit(1); }
371
-
372
- // FIX: --version-filter skips cases whose stack_version constraint doesn't
373
- // match the specified versions. Prevents stale React 17/18 cases blocking React 19 code.
374
- // Usage: search-cases "useEffect" --version-filter "react=19,node=22"
375
- const vfIdx = args.indexOf('--version-filter');
376
- const versionFilter = vfIdx !== -1 && args[vfIdx + 1]
377
- ? parseVersionFilter(args[vfIdx + 1])
378
- : null;
379
-
380
- const queryTags = extractTags(query);
381
- const index = loadIndex();
382
- if (!index.cases.length) { console.log(`${YELLOW}No cases recorded yet. Use 'add-case' to record your first rejection.${RESET}`); return; }
383
-
384
- // Apply version filter before scoring
385
- const eligibleCases = versionFilter
386
- ? index.cases.filter(e => caseMatchesVersionFilter(e, versionFilter))
387
- : index.cases;
388
-
389
- const skipped = index.cases.length - eligibleCases.length;
390
-
391
- const corpus = eligibleCases.map(e => e.tags || []);
392
- const idf = buildIdf(corpus);
393
-
394
- const scored = [];
395
- for (const entry of eligibleCases) {
396
- const score = tfidfCosineSimilarity(queryTags, entry.tags || [], idf);
397
- if (score > 0.0) scored.push({ score, entry });
398
- }
399
- scored.sort((a, b) => b.score - a.score);
400
- const top = scored.slice(0, 5);
401
-
402
- if (!top.length) {
403
- console.log(`${YELLOW}No matching cases found for: "${query}"${RESET}`);
404
- if (skipped > 0) console.log(` ${DIM}${skipped} case(s) skipped by version filter: ${args[vfIdx + 1]}${RESET}`);
405
- console.log(` ${DIM}Try broader terms or check 'list' for available cases.${RESET}`);
406
- return;
407
- }
408
-
409
- console.log(`\n${BOLD}${CYAN}━━━ Case Law Search Results ━━━━━━━━━━━━━━━━━━━━━━━${RESET}`);
410
- console.log(` Query : ${BOLD}${query}${RESET}`);
411
- console.log(` Matches: ${top.length} of ${index.cases.length} cases` +
412
- (skipped > 0 ? ` ${DIM}(${skipped} skipped by version filter)${RESET}` : '') + '\n');
413
-
414
- for (const { score, entry } of top) {
415
- const vc = entry.verdict === 'REJECTED' ? RED : YELLOW;
416
- console.log(` ${BOLD}Case #${String(entry.id).padStart(4, '0')}${RESET} ${vc}[${entry.verdict}]${RESET} ${DIM}${(entry.timestamp || '').slice(0, 10)}${RESET} score=${score.toFixed(2)}`);
417
- console.log(` ${DIM}Domain: ${entry.domain}${RESET}`);
418
- console.log(` ${entry.reason_summary}`);
419
- console.log(` ${DIM}Tags: ${(entry.tags || []).slice(0, 8).join(', ')}${RESET}\n`);
420
- }
421
- console.log(` ${DIM}Run 'show --id <N>' to see the full diff for any case.${RESET}`);
422
- console.log(`${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${RESET}\n`);
423
- }
424
-
425
- function cmdList(args) {
426
- const index = loadIndex();
427
- const cases = index.cases || [];
428
- if (!cases.length) { console.log(`${YELLOW}No cases recorded yet.${RESET}`); return; }
429
-
430
- let domainFilter = null;
431
- const di = args.indexOf('--domain');
432
- if (di !== -1 && args[di + 1]) domainFilter = args[di + 1].toLowerCase();
433
-
434
- const filtered = domainFilter ? cases.filter(c => c.domain === domainFilter) : cases;
435
- const total = filtered.length;
436
-
437
- console.log(`\n${BOLD}${CYAN}━━━ Case Law Index (${total} cases) ━━━━━━━━━━━━━━━━━━━━${RESET}`);
438
- if (domainFilter) console.log(` ${DIM}Filtered by domain: ${domainFilter}${RESET}\n`);
439
-
440
- const last20 = filtered.slice(-20).reverse();
441
- for (const entry of last20) {
442
- const vc = entry.verdict === 'REJECTED' ? RED : YELLOW;
443
- console.log(` ${BOLD}#${String(entry.id).padStart(4, '0')}${RESET} ${vc}[${entry.verdict}]${RESET} ${DIM}${(entry.domain || '').toUpperCase()}${RESET} ${(entry.timestamp || '').slice(0, 10)}`);
444
- console.log(` ${(entry.reason_summary || '').slice(0, 80)}`);
445
- }
446
- if (total > 20) console.log(`\n ${YELLOW}... showing last 20 of ${total}. Use 'export' for full history.${RESET}`);
447
- console.log(`${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${RESET}\n`);
448
- }
449
-
450
- function cmdShow(args) {
451
- let caseId = null;
452
- const ii = args.indexOf('--id');
453
- if (ii !== -1 && args[ii + 1]) caseId = parseInt(args[ii + 1], 10);
454
- if (caseId == null || isNaN(caseId)) { console.log(`${RED}✖ Provide a case ID: show --id 7${RESET}`); process.exit(1); }
455
-
456
- const caseRecord = loadCase(caseId);
457
- if (!caseRecord) { console.log(`${RED}✖ Case #${String(caseId).padStart(4, '0')} not found.${RESET}`); process.exit(1); }
458
-
459
- const vc = caseRecord.verdict === 'REJECTED' ? RED : YELLOW;
460
- console.log(`\n${BOLD}${CYAN}━━━ Case #${String(caseRecord.id).padStart(4, '0')} ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${RESET}`);
461
- console.log(` Verdict : ${vc}${BOLD}${caseRecord.verdict}${RESET}`);
462
- console.log(` Domain : ${caseRecord.domain}`);
463
- console.log(` Recorded : ${caseRecord.timestamp}`);
464
- if (caseRecord.pr_ref) console.log(` PR / Ref : ${caseRecord.pr_ref}`);
465
- if (caseRecord.reviewer) console.log(` Reviewer : ${caseRecord.reviewer}`);
466
- console.log(`\n ${BOLD}Reason:${RESET}`);
467
- console.log(` ${caseRecord.reason}`);
468
- console.log(`\n ${BOLD}Semantic Delta (meaningful changes only):${RESET}`);
469
- console.log(` ${DIM}─────────────────────────────────────────${RESET}`);
470
- const deltaLines = (caseRecord.diff_delta || caseRecord.diff_raw).split('\n').slice(0, 40);
471
- for (const line of deltaLines) {
472
- if (line.startsWith('+')) console.log(` ${GREEN}${line}${RESET}`);
473
- else if (line.startsWith('-')) console.log(` ${RED}${line}${RESET}`);
474
- else console.log(` ${DIM}${line}${RESET}`);
475
- }
476
- console.log(`\n ${BOLD}Tags:${RESET} ${(caseRecord.tags || []).join(', ')}`);
477
- console.log(`${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${RESET}\n`);
478
- }
479
-
480
- function cmdExport(args) {
481
- const toStdout = args.includes('--stdout');
482
- const index = loadIndex();
483
- const cases = index.cases || [];
484
- if (!cases.length) { console.log(`${YELLOW}No cases to export.${RESET}`); return; }
485
-
486
- const now = new Date().toISOString().slice(0, 19);
487
- const lines = [
488
- '# Tribunal Case Law — Full Export\n',
489
- `Generated: ${now}`, `Total Cases: ${cases.length}\n`, '---\n',
490
- ];
491
- for (const entry of cases) {
492
- const caseRecord = loadCase(entry.id) || entry;
493
- const badge = `[${caseRecord.verdict || 'REJECTED'}]`;
494
- lines.push(`## Case #${String(entry.id).padStart(4, '0')} ${badge}`);
495
- lines.push(`**Domain:** ${entry.domain} `);
496
- lines.push(`**Recorded:** ${(entry.timestamp || '').slice(0, 10)} `);
497
- if (caseRecord.pr_ref) lines.push(`**PR/Ref:** ${caseRecord.pr_ref} `);
498
- lines.push(`\n**Reason:** ${entry.reason_summary}\n`);
499
- lines.push(`**Tags:** \`${(entry.tags || []).slice(0, 8).join(', ')}\`\n`);
500
- lines.push('---\n');
501
- }
502
- const content = lines.join('\n');
503
- if (toStdout) { console.log(content); return; }
504
-
505
- const outPath = path.join(getPaths().HISTORY_DIR, 'case-law-export.md');
506
- fs.writeFileSync(outPath, content, 'utf8');
507
- console.log(`${GREEN}✔ Exported ${cases.length} cases to ${outPath}${RESET}`);
508
- }
509
-
510
- function cmdStats() {
511
- const index = loadIndex();
512
- const cases = index.cases || [];
513
- const domainCounts = {};
514
- const verdictCounts = {};
515
- for (const c of cases) {
516
- domainCounts[c.domain] = (domainCounts[c.domain] || 0) + 1;
517
- verdictCounts[c.verdict] = (verdictCounts[c.verdict] || 0) + 1;
518
- }
519
-
520
- console.log(`\n${BOLD}${CYAN}━━━ Case Law Statistics ━━━━━━━━━━━━━━━━━━━━━━━━━━━${RESET}`);
521
- console.log(` Total cases: ${BOLD}${cases.length}${RESET}`);
522
- console.log(`\n ${BOLD}By Verdict:${RESET}`);
523
- for (const v of Object.keys(verdictCounts).sort()) {
524
- const color = v === 'REJECTED' ? RED : YELLOW;
525
- console.log(` ${color}${v.padEnd(30)}${RESET} ${verdictCounts[v]}`);
526
- }
527
- console.log(`\n ${BOLD}By Domain:${RESET}`);
528
- for (const [d, c] of Object.entries(domainCounts).sort((a, b) => b[1] - a[1])) {
529
- console.log(` ${CYAN}${d.padEnd(20)}${RESET} ${c}`);
530
- }
531
- console.log(`${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${RESET}\n`);
532
- }
533
-
534
- function cmdAutoRecord() {
535
- function getFlag(name) {
536
- const flag = `--${name}`;
537
- const idx = process.argv.indexOf(flag);
538
- return (idx !== -1 && process.argv[idx + 1]) ? process.argv[idx + 1] : '';
539
- }
540
-
541
- const diffText = getFlag('diff');
542
- const reason = getFlag('reason');
543
- let domain = getFlag('domain') || 'general';
544
- let verdict = getFlag('verdict') || 'REJECTED';
545
- const reviewer = getFlag('reviewer') || null;
546
- const prRef = getFlag('pr-ref') || null;
547
- // FIX: --stack-version persists version context with the case record so
548
- // future searches can skip it when the project has moved past that version.
549
- // Example: --stack-version "react=18,next=14"
550
- const stackVersion = getFlag('stack-version') || null;
551
-
552
- if (!diffText || !reason) {
553
- console.log(`${RED}✖ auto-record requires --diff and --reason flags.${RESET}`);
554
- console.log(` Usage: auto-record --diff "code" --reason "why" --domain security --reviewer agent-name --stack-version "react=18"`);
555
- process.exit(1);
556
- }
557
-
558
- if (isNoiseRejection(reason)) { console.log(`${DIM}⊘ Skipped: trivial rejection (noise filter matched).${RESET}`); return; }
559
- if (!VALID_DOMAINS.has(domain)) domain = 'general';
560
- if (!VALID_VERDICTS.has(verdict)) verdict = 'REJECTED';
561
-
562
- const fingerprint = contentHash(diffText);
563
- const index = loadIndex();
564
- for (const existing of index.cases) {
565
- if (existing.fingerprint === fingerprint) {
566
- console.log(`${YELLOW}⊘ Duplicate: Case #${String(existing.id).padStart(4, '0')} already records this pattern.${RESET}`);
567
- return;
568
- }
569
- }
570
-
571
- const delta = semanticDelta(diffText);
572
- const tags = extractTags(diffText + ' ' + reason);
573
- const caseId = index.next_id;
574
- const now = new Date().toISOString().slice(0, 19);
575
-
576
- const caseRecord = {
577
- id: caseId, fingerprint, timestamp: now, domain, verdict,
578
- reason: reason.trim(), pr_ref: prRef, reviewer, tags,
579
- stack_version: stackVersion,
580
- diff_raw: diffText.trim(), diff_delta: delta, auto_recorded: true,
581
- };
582
-
583
- saveCase(caseRecord);
584
- index.cases.push({
585
- id: caseId, fingerprint, domain, verdict, tags,
586
- timestamp: now, reason_summary: reason.trim().slice(0, 120),
587
- stack_version: stackVersion,
588
- });
589
- index.next_id = caseId + 1;
590
- saveIndex(index);
591
- console.log(`${GREEN} Auto-recorded Case #${String(caseId).padStart(4, '0')}${RESET} [${verdict}] domain=${domain}`);
592
- console.log(` ${DIM}Reason: ${reason.slice(0, 80)}${RESET}`);
593
- if (stackVersion) console.log(` ${DIM}Stack version: ${stackVersion}${RESET}`);
594
- }
595
-
596
- async function cmdOverrule(args) {
597
- let caseId = null;
598
- const ii = args.indexOf('--id');
599
- if (ii !== -1 && args[ii + 1]) caseId = parseInt(args[ii + 1], 10);
600
- if (caseId == null || isNaN(caseId)) { console.log(`${RED}✖ Provide a case ID: overrule --id 7${RESET}`); process.exit(1); }
601
-
602
- const caseRecord = loadCase(caseId);
603
- if (!caseRecord) { console.log(`${RED}✖ Case #${String(caseId).padStart(4, '0')} not found.${RESET}`); process.exit(1); }
604
- if (caseRecord.verdict === 'OVERRULED') { console.log(`${YELLOW}Case #${String(caseId).padStart(4, '0')} is already OVERRULED.${RESET}`); return; }
605
-
606
- let reason = null;
607
- const ri = args.indexOf('--reason');
608
- if (ri !== -1 && args[ri + 1]) reason = args[ri + 1];
609
-
610
- if (!reason) {
611
- const rl = createRl();
612
- reason = await ask(rl, 'Reason for overruling this precedent:');
613
- rl.close();
614
- }
615
- if (!reason || !reason.trim()) { console.log(`${RED}✖ An overrule reason is required.${RESET}`); process.exit(1); }
616
-
617
- const oldVerdict = caseRecord.verdict;
618
- caseRecord.verdict = 'OVERRULED';
619
- caseRecord.overruled_at = new Date().toISOString().slice(0, 19);
620
- caseRecord.overrule_reason = reason.trim();
621
- caseRecord.previous_verdict = oldVerdict;
622
- saveCase(caseRecord);
623
-
624
- const index = loadIndex();
625
- for (const entry of index.cases) {
626
- if (entry.id === caseId) { entry.verdict = 'OVERRULED'; break; }
627
- }
628
- saveIndex(index);
629
-
630
- console.log(`\n${GREEN}✔ Case #${String(caseId).padStart(4, '0')} OVERRULED${RESET}`);
631
- console.log(` ${DIM}Previous verdict : ${oldVerdict}${RESET}`);
632
- console.log(` ${DIM}Overrule reason : ${reason.trim()}${RESET}`);
633
- console.log(` ${DIM}The case is preserved in history but no longer blocks reviews.${RESET}\n`);
634
- }
635
-
636
- // ── Main ──────────────────────────────────────────────────────────────────────
637
- const COMMANDS = {
638
- 'add-case': cmdAddCase,
639
- 'auto-record': cmdAutoRecord,
640
- 'search-cases': cmdSearchCases,
641
- 'list': cmdList,
642
- 'show': cmdShow,
643
- 'overrule': cmdOverrule,
644
- 'export': cmdExport,
645
- 'stats': cmdStats,
646
- };
647
-
648
- async function main() {
649
- const argv = process.argv.slice(2);
650
- if (!argv.length || ['-h', '--help', 'help'].includes(argv[0])) {
651
- console.log(`
652
- ${BOLD}case_law_manager.js${RESET} Tribunal Case Law Engine
653
-
654
- ${BOLD}Commands:${RESET}
655
- add-case Record a new rejected pattern (interactive)
656
- auto-record --diff --reason Record a rejection (non-interactive, for AI agents)
657
- search-cases --query <text> Find relevant precedents (TF-IDF cosine, token-free)
658
- list [--domain <domain>] List all recorded cases
659
- show --id <N> Show full diff for a case
660
- overrule --id <N> Formally overrule a past precedent
661
- export [--stdout] Export all cases to Markdown
662
- stats Show breakdown by domain/verdict
663
-
664
- ${BOLD}Domains:${RESET} ${[...VALID_DOMAINS].sort().join(', ')}
665
- ${BOLD}Verdicts:${RESET} ${[...VALID_VERDICTS].sort().join(', ')}
666
- `);
667
- return;
668
- }
669
-
670
- const cmd = argv[0];
671
- const rest = argv.slice(1);
672
- if (!COMMANDS[cmd]) {
673
- console.log(`${RED}✖ Unknown command: '${cmd}'${RESET}`);
674
- console.log(` Valid: ${Object.keys(COMMANDS).join(', ')}`);
675
- process.exit(1);
676
- }
677
- await COMMANDS[cmd](rest);
678
- }
679
-
680
- // ── Exports ──────────────────────────────────────────────────────────────────
681
- module.exports = {
682
- contentHash, semanticDelta, extractTags, loadIndex, saveIndex,
683
- loadCase, saveCase, tfidfCosineSimilarity, buildIdf, findAgentDir,
684
- isNoiseRejection, isTrivialLine,
685
- };
686
-
687
- if (require.main === module) {
688
- main().catch(err => { console.error(err); process.exit(1); });
689
- }
1
+ #!/usr/bin/env node
2
+ /**
3
+ * case_law_manager.js — Tribunal Kit Case Law Engine
4
+ * =====================================================
5
+ * Records rejected code patterns as "Cases" and surfaces them as
6
+ * binding Legal Precedence during future Tribunal reviews.
7
+ *
8
+ * Usage:
9
+ * node .agent/scripts/case_law_manager.js add-case
10
+ * node .agent/scripts/case_law_manager.js search-cases --query "forEach side effects"
11
+ * node .agent/scripts/case_law_manager.js list
12
+ * node .agent/scripts/case_law_manager.js show --id 7
13
+ * node .agent/scripts/case_law_manager.js export
14
+ * node .agent/scripts/case_law_manager.js stats
15
+ *
16
+ * Storage:
17
+ * .agent/history/case-law/index.json ← master index of all cases
18
+ * .agent/history/case-law/cases/ ← one JSON file per case
19
+ */
20
+
21
+ "use strict";
22
+
23
+ const fs = require("fs");
24
+ const path = require("path");
25
+ const crypto = require("crypto");
26
+ const readline = require("readline");
27
+
28
+ // ── Colours ──────────────────────────────────────────────────────────────────
29
+ const { GREEN, YELLOW, CYAN, RED, BOLD, DIM, RESET } = require("./_colors");
30
+
31
+ // ── Find .agent directory ─────────────────────────────────────────────────────
32
+ function findAgentDir() {
33
+ let current = path.resolve(process.cwd());
34
+ const root = path.parse(current).root;
35
+ while (current !== root) {
36
+ const candidate = path.join(current, ".agent");
37
+ if (fs.existsSync(candidate) && fs.statSync(candidate).isDirectory())
38
+ return candidate;
39
+ current = path.dirname(current);
40
+ }
41
+ console.error(
42
+ `${RED}✖ Error: '.agent' directory not found. Please run 'npx tribunal-kit init' first.${RESET}`,
43
+ );
44
+ process.exit(1);
45
+ }
46
+
47
+ // ── Lazy path resolution (avoids side effects at require-time) ───────────────
48
+ let _paths = null;
49
+ function getPaths() {
50
+ if (_paths) return _paths;
51
+ const agentDir = findAgentDir();
52
+ const historyDir = path.join(agentDir, "history", "case-law");
53
+ const casesDir = path.join(historyDir, "cases");
54
+ const indexFile = path.join(historyDir, "index.json");
55
+ _paths = {
56
+ AGENT_DIR: agentDir,
57
+ HISTORY_DIR: historyDir,
58
+ CASES_DIR: casesDir,
59
+ INDEX_FILE: indexFile,
60
+ };
61
+ return _paths;
62
+ }
63
+
64
+ const VALID_DOMAINS = new Set([
65
+ "backend",
66
+ "frontend",
67
+ "database",
68
+ "security",
69
+ "performance",
70
+ "mobile",
71
+ "testing",
72
+ "devops",
73
+ "general",
74
+ ]);
75
+ const VALID_VERDICTS = new Set([
76
+ "REJECTED",
77
+ "APPROVED_WITH_CONDITIONS",
78
+ "PRECEDENT_SET",
79
+ "OVERRULED",
80
+ ]);
81
+
82
+ // ── Noise filter ────────────────────────────────────────────────────────────
83
+ const NOISE_PATTERNS = [
84
+ /\bformatting\b/i,
85
+ /\bwhitespace\b/i,
86
+ /\bindent(ation)?\b/i,
87
+ /\bimport\s+order\b/i,
88
+ /\btrailing\s+(comma|space|whitespace)\b/i,
89
+ /\bsemicolon\b/i,
90
+ /\bprettier\b/i,
91
+ /\beslint.*fix\b/i,
92
+ /\blint.*only\b/i,
93
+ ];
94
+
95
+ function isNoiseRejection(reason) {
96
+ const lower = reason.toLowerCase();
97
+ return NOISE_PATTERNS.some((p) => p.test(lower));
98
+ }
99
+
100
+ // ── Trivial-change filter (Semantic Delta) ────────────────────────────────────
101
+ const TRIVIAL_PATTERNS = [
102
+ /^\s*$/, // blank lines
103
+ /^\s*\/\/.*$/, // comment-only lines
104
+ /^\s*#.*$/, // python comments
105
+ /^\s*\*.*$/, // JSDoc lines
106
+ /^\s*import\b.*$/, // imports
107
+ ];
108
+
109
+ function isTrivialLine(line) {
110
+ return TRIVIAL_PATTERNS.some((p) => p.test(line));
111
+ }
112
+
113
+ function semanticDelta(diffText) {
114
+ const lines = diffText.split("\n");
115
+ const meaningful = [];
116
+ for (const line of lines) {
117
+ if (
118
+ line.startsWith("+++") ||
119
+ line.startsWith("---") ||
120
+ line.startsWith("@@")
121
+ ) {
122
+ meaningful.push(line);
123
+ continue;
124
+ }
125
+ if (line.startsWith("+") || line.startsWith("-")) {
126
+ const codePart = line.slice(1);
127
+ if (!isTrivialLine(codePart)) meaningful.push(line);
128
+ } else {
129
+ meaningful.push(line);
130
+ }
131
+ }
132
+ let filtered = meaningful.join("\n");
133
+ filtered = filtered.replace(/(\n[ ]?\n){3,}/g, "\n\n");
134
+ return filtered.trim();
135
+ }
136
+
137
+ function contentHash(text) {
138
+ const cleaned = semanticDelta(text);
139
+ return crypto.createHash("sha256").update(cleaned).digest("hex").slice(0, 8);
140
+ }
141
+
142
+ // ── Index helpers ─────────────────────────────────────────────────────────────
143
+ function ensureDirs() {
144
+ const { HISTORY_DIR, CASES_DIR } = getPaths();
145
+ fs.mkdirSync(HISTORY_DIR, { recursive: true });
146
+ fs.mkdirSync(CASES_DIR, { recursive: true });
147
+ }
148
+
149
+ function loadIndex() {
150
+ ensureDirs();
151
+ const { INDEX_FILE } = getPaths();
152
+ if (fs.existsSync(INDEX_FILE)) {
153
+ try {
154
+ return JSON.parse(fs.readFileSync(INDEX_FILE, "utf8"));
155
+ } catch {
156
+ /* fallthrough */
157
+ }
158
+ }
159
+ return { version: "1.0", cases: [], next_id: 1 };
160
+ }
161
+
162
+ function saveIndex(index) {
163
+ ensureDirs();
164
+ const { INDEX_FILE } = getPaths();
165
+ const tmp = INDEX_FILE + ".tmp";
166
+ fs.writeFileSync(tmp, JSON.stringify(index, null, 2), "utf8");
167
+ fs.renameSync(tmp, INDEX_FILE);
168
+ }
169
+
170
+ function loadCase(caseId) {
171
+ const { CASES_DIR } = getPaths();
172
+ const p = path.join(
173
+ CASES_DIR,
174
+ `case-${String(caseId).padStart(4, "0")}.json`,
175
+ );
176
+ if (!fs.existsSync(p)) return null;
177
+ try {
178
+ return JSON.parse(fs.readFileSync(p, "utf8"));
179
+ } catch {
180
+ return null;
181
+ }
182
+ }
183
+
184
+ function saveCase(caseRecord) {
185
+ const { CASES_DIR } = getPaths();
186
+ const p = path.join(
187
+ CASES_DIR,
188
+ `case-${String(caseRecord.id).padStart(4, "0")}.json`,
189
+ );
190
+ fs.writeFileSync(p, JSON.stringify(caseRecord, null, 2), "utf8");
191
+ }
192
+
193
+ // ── Keyword/tag extraction ─────────────────────────────────────────────────────
194
+ function extractTags(text) {
195
+ const tokens = text.match(/\b[a-zA-Z_][a-zA-Z0-9_]{2,}\b/g) || [];
196
+ const stopWords = new Set([
197
+ "the",
198
+ "and",
199
+ "for",
200
+ "was",
201
+ "this",
202
+ "with",
203
+ "that",
204
+ "has",
205
+ "a",
206
+ "an",
207
+ "from",
208
+ "are",
209
+ "not",
210
+ "use",
211
+ "but",
212
+ "also",
213
+ "code",
214
+ "have",
215
+ "will",
216
+ "should",
217
+ "must",
218
+ "can",
219
+ "may",
220
+ "any",
221
+ "all",
222
+ "new",
223
+ "old",
224
+ "add",
225
+ "get",
226
+ "set",
227
+ "var",
228
+ "let",
229
+ "const",
230
+ "function",
231
+ "return",
232
+ "import",
233
+ "export",
234
+ "class",
235
+ "async",
236
+ "await",
237
+ "true",
238
+ "false",
239
+ "null",
240
+ "undefined",
241
+ ]);
242
+ const seen = new Set();
243
+ const tags = [];
244
+ for (const token of tokens) {
245
+ const lower = token.toLowerCase();
246
+ if (!stopWords.has(lower) && !seen.has(lower)) {
247
+ seen.add(lower);
248
+ tags.push(lower);
249
+ }
250
+ if (tags.length >= 20) break;
251
+ }
252
+ return tags;
253
+ }
254
+
255
+ // ── Version-Aware Case Filtering ──────────────────────────────────────────────
256
+ // FIX: Prevents stale cases (e.g., React 17 rejections) from blocking valid code
257
+ // once the project has upgraded frameworks. Uses simple numeric comparison.
258
+ //
259
+ // Version filter string format: "react=19,node=22,next=15"
260
+ // Case stack_version format: "react>=18,node>=20" (>=, >, =, <, <=)
261
+
262
+ /**
263
+ * Parse a version filter string into a map of { lib -> number }.
264
+ * Input: "react=19,node=22"
265
+ * Output: { react: 19, node: 22 }
266
+ * @param {string} filterStr
267
+ * @returns {Object<string, number>}
268
+ */
269
+ function parseVersionFilter(filterStr) {
270
+ const result = {};
271
+ if (!filterStr) return result;
272
+ for (const segment of filterStr.split(",")) {
273
+ const m = segment
274
+ .trim()
275
+ .match(/^([a-zA-Z0-9_.-]+)\s*(?:>=|>|<=|<|=)?\s*(\d+(?:\.\d+)?)/);
276
+ if (m) result[m[1].toLowerCase()] = parseFloat(m[2]);
277
+ }
278
+ return result;
279
+ }
280
+
281
+ /**
282
+ * Returns true if the case either has no stack_version constraint,
283
+ * OR all of its version constraints are satisfied by the provided filter.
284
+ *
285
+ * A case with stack_version "react>=18,node>=20" will be SKIPPED (return false)
286
+ * when the version filter says react=19,node=22 both constraints met → case IS relevant.
287
+ *
288
+ * The logic: if a case's constraint is NOT met by the current version filter,
289
+ * that case is from a different version context → skip it.
290
+ *
291
+ * @param {{ stack_version?: string }} caseEntry
292
+ * @param {Object<string, number>} versionFilter
293
+ * @returns {boolean} true = case is eligible for this version context
294
+ */
295
+ function caseMatchesVersionFilter(caseEntry, versionFilter) {
296
+ if (!caseEntry.stack_version) return true; // No constraint → always eligible
297
+ if (!versionFilter || !Object.keys(versionFilter).length) return true;
298
+
299
+ // Parse the case's own version constraint
300
+ const caseConstraints = [];
301
+ for (const segment of caseEntry.stack_version.split(",")) {
302
+ const m = segment
303
+ .trim()
304
+ .match(/^([a-zA-Z0-9_.-]+)\s*(>=|>|<=|<|=)\s*(\d+(?:\.\d+)?)/);
305
+ if (m)
306
+ caseConstraints.push({
307
+ lib: m[1].toLowerCase(),
308
+ op: m[2],
309
+ ver: parseFloat(m[3]),
310
+ });
311
+ }
312
+
313
+ // Check each constraint against the version filter
314
+ for (const { lib, op, ver } of caseConstraints) {
315
+ const projectVer = versionFilter[lib];
316
+ if (projectVer === undefined) continue; // Unknown lib don't filter on it
317
+
318
+ const satisfied =
319
+ op === ">="
320
+ ? projectVer >= ver
321
+ : op === ">"
322
+ ? projectVer > ver
323
+ : op === "<="
324
+ ? projectVer <= ver
325
+ : op === "<"
326
+ ? projectVer < ver
327
+ : /* = */ projectVer === ver;
328
+ if (!satisfied) return false; // This case's version context doesn't match
329
+ }
330
+ return true;
331
+ }
332
+
333
+ // ── Similarity scoring (TF-IDF Cosine — token-free) ──────────────────────────
334
+
335
+ function buildIdf(corpus) {
336
+ const n = corpus.length;
337
+ if (n === 0) return {};
338
+ const docFreq = {};
339
+ for (const tags of corpus) {
340
+ const unique = new Set(tags);
341
+ for (const tag of unique) {
342
+ docFreq[tag] = (docFreq[tag] || 0) + 1;
343
+ }
344
+ }
345
+ const idf = {};
346
+ for (const [term, df] of Object.entries(docFreq)) {
347
+ idf[term] = Math.log((n + 1) / (df + 1)) + 1.0;
348
+ }
349
+ return idf;
350
+ }
351
+
352
+ function tfidfCosineSimilarity(queryTags, caseTags, idf) {
353
+ if (!queryTags.length || !caseTags.length) return 0.0;
354
+ const tfQ = {};
355
+ for (const t of queryTags) tfQ[t] = (tfQ[t] || 0) + 1;
356
+ const tfC = {};
357
+ for (const t of caseTags) tfC[t] = (tfC[t] || 0) + 1;
358
+ const allTerms = new Set([...Object.keys(tfQ), ...Object.keys(tfC)]);
359
+ let dot = 0,
360
+ magQ = 0,
361
+ magC = 0;
362
+ for (const term of allTerms) {
363
+ const wQ = (tfQ[term] || 0) * (idf[term] || 1.0);
364
+ const wC = (tfC[term] || 0) * (idf[term] || 1.0);
365
+ dot += wQ * wC;
366
+ magQ += wQ * wQ;
367
+ magC += wC * wC;
368
+ }
369
+ if (magQ === 0 || magC === 0) return 0.0;
370
+ return dot / (Math.sqrt(magQ) * Math.sqrt(magC));
371
+ }
372
+
373
+ // ── Input helpers ─────────────────────────────────────────────────────────────
374
+ function createRl() {
375
+ return readline.createInterface({
376
+ input: process.stdin,
377
+ output: process.stdout,
378
+ });
379
+ }
380
+
381
+ function ask(rl, prompt) {
382
+ return new Promise((resolve) =>
383
+ rl.question(` ${BOLD}${prompt}${RESET} `, resolve),
384
+ );
385
+ }
386
+
387
+ function askMultiline(rl, prompt, sentinel) {
388
+ return new Promise((resolve) => {
389
+ console.log(` ${BOLD}${prompt}${RESET}`);
390
+ console.log(
391
+ ` ${DIM}(Type or paste content. Type '${sentinel}' on its own line when done.)${RESET}`,
392
+ );
393
+ const lines = [];
394
+ const listener = (line) => {
395
+ if (line.trim() === sentinel) {
396
+ rl.removeListener("line", listener);
397
+ resolve(lines.join("\n"));
398
+ } else {
399
+ lines.push(line);
400
+ }
401
+ };
402
+ rl.on("line", listener);
403
+ });
404
+ }
405
+
406
+ function askChoice(rl, label, choices, defaultVal) {
407
+ return new Promise((resolve) => {
408
+ const opts = choices
409
+ .map((c) => (c === defaultVal ? `${BOLD}${c}${RESET}` : c))
410
+ .join(" / ");
411
+ rl.question(
412
+ ` ${BOLD}${label}${RESET} [${opts}] (default: ${defaultVal}): `,
413
+ (answer) => {
414
+ const val = (answer || "").trim().toLowerCase();
415
+ resolve(val && choices.includes(val) ? val : defaultVal);
416
+ },
417
+ );
418
+ });
419
+ }
420
+
421
+ // ── Commands ──────────────────────────────────────────────────────────────────
422
+ async function cmdAddCase() {
423
+ console.log(
424
+ `\n${BOLD}${CYAN}━━━ Recording New Case ━━━━━━━━━━━━━━━━━━━━━━━━━━━━${RESET}`,
425
+ );
426
+ const rl = createRl();
427
+
428
+ const diffText = await askMultiline(
429
+ rl,
430
+ "Paste the REJECTED diff (code snippet):",
431
+ "END_DIFF",
432
+ );
433
+ if (!diffText.trim()) {
434
+ console.log(`${RED}✖ Diff cannot be empty. Aborting.${RESET}`);
435
+ rl.close();
436
+ process.exit(1);
437
+ }
438
+
439
+ const reason = await ask(rl, "Rejection reason (1-2 sentences):");
440
+ if (!reason.trim()) {
441
+ console.log(`${RED}✖ Reason cannot be empty. Aborting.${RESET}`);
442
+ rl.close();
443
+ process.exit(1);
444
+ }
445
+
446
+ const domain = await askChoice(
447
+ rl,
448
+ "Domain",
449
+ [...VALID_DOMAINS].sort(),
450
+ "general",
451
+ );
452
+ const verdict = await askChoice(
453
+ rl,
454
+ "Verdict",
455
+ [...VALID_VERDICTS].sort(),
456
+ "REJECTED",
457
+ );
458
+ const prRef =
459
+ (await ask(rl, "PR / commit reference (optional, e.g. PR-404):")).trim() ||
460
+ null;
461
+ const reviewer =
462
+ (
463
+ await ask(rl, "Reviewer agent (optional, e.g. security-auditor):")
464
+ ).trim() || null;
465
+
466
+ // FIX: stack_version — prevents stale cases from blocking valid code after
467
+ // framework upgrades. Format: "react>=19, node>=20" or leave blank for all.
468
+ const stackVersionRaw = (
469
+ await ask(
470
+ rl,
471
+ "Stack version constraint (optional, e.g. react>=18, node>=20):",
472
+ )
473
+ ).trim();
474
+ const stackVersion = stackVersionRaw || null;
475
+ rl.close();
476
+
477
+ const delta = semanticDelta(diffText);
478
+ const fingerprint = contentHash(diffText);
479
+ const tags = extractTags(diffText + " " + reason);
480
+
481
+ const index = loadIndex();
482
+ const caseId = index.next_id;
483
+ const now = new Date().toISOString().slice(0, 19);
484
+
485
+ const caseRecord = {
486
+ id: caseId,
487
+ fingerprint,
488
+ timestamp: now,
489
+ domain,
490
+ verdict,
491
+ reason: reason.trim(),
492
+ pr_ref: prRef,
493
+ reviewer,
494
+ tags,
495
+ stack_version: stackVersion,
496
+ diff_raw: diffText.trim(),
497
+ diff_delta: delta,
498
+ };
499
+
500
+ saveCase(caseRecord);
501
+ index.cases.push({
502
+ id: caseId,
503
+ fingerprint,
504
+ domain,
505
+ verdict,
506
+ tags,
507
+ timestamp: now,
508
+ reason_summary: reason.trim().slice(0, 120),
509
+ stack_version: stackVersion,
510
+ });
511
+ index.next_id = caseId + 1;
512
+ saveIndex(index);
513
+
514
+ console.log(
515
+ `\n${GREEN}✔ Case #${String(caseId).padStart(4, "0")} recorded${RESET}`,
516
+ );
517
+ console.log(` ${DIM}Fingerprint : ${fingerprint}${RESET}`);
518
+ console.log(` ${DIM}Domain : ${domain}${RESET}`);
519
+ console.log(` ${DIM}Tags : ${tags.slice(0, 8).join(", ")}${RESET}`);
520
+ if (stackVersion)
521
+ console.log(` ${DIM}Stack version : ${stackVersion}${RESET}`);
522
+ console.log();
523
+ }
524
+
525
+ function cmdSearchCases(args) {
526
+ let query = args.filter((a) => !a.startsWith("--")).join(" ");
527
+ if (!query) {
528
+ const qi = process.argv.indexOf("--query");
529
+ if (qi !== -1)
530
+ query = process.argv
531
+ .slice(qi + 1)
532
+ .filter((a) => !a.startsWith("--"))
533
+ .join(" ");
534
+ }
535
+ if (!query) {
536
+ console.log(
537
+ `${RED}✖ Provide a search query: search-cases --query "forEach side effects"${RESET}`,
538
+ );
539
+ process.exit(1);
540
+ }
541
+
542
+ // FIX: --version-filter skips cases whose stack_version constraint doesn't
543
+ // match the specified versions. Prevents stale React 17/18 cases blocking React 19 code.
544
+ // Usage: search-cases "useEffect" --version-filter "react=19,node=22"
545
+ const vfIdx = args.indexOf("--version-filter");
546
+ const versionFilter =
547
+ vfIdx !== -1 && args[vfIdx + 1]
548
+ ? parseVersionFilter(args[vfIdx + 1])
549
+ : null;
550
+
551
+ const queryTags = extractTags(query);
552
+ const index = loadIndex();
553
+ if (!index.cases.length) {
554
+ console.log(
555
+ `${YELLOW}No cases recorded yet. Use 'add-case' to record your first rejection.${RESET}`,
556
+ );
557
+ return;
558
+ }
559
+
560
+ // Apply version filter before scoring
561
+ const eligibleCases = versionFilter
562
+ ? index.cases.filter((e) => caseMatchesVersionFilter(e, versionFilter))
563
+ : index.cases;
564
+
565
+ const skipped = index.cases.length - eligibleCases.length;
566
+
567
+ const corpus = eligibleCases.map((e) => e.tags || []);
568
+ const idf = buildIdf(corpus);
569
+
570
+ const scored = [];
571
+ for (const entry of eligibleCases) {
572
+ const score = tfidfCosineSimilarity(queryTags, entry.tags || [], idf);
573
+ if (score > 0.0) scored.push({ score, entry });
574
+ }
575
+ scored.sort((a, b) => b.score - a.score);
576
+ const top = scored.slice(0, 5);
577
+
578
+ if (!top.length) {
579
+ console.log(`${YELLOW}No matching cases found for: "${query}"${RESET}`);
580
+ if (skipped > 0)
581
+ console.log(
582
+ ` ${DIM}${skipped} case(s) skipped by version filter: ${args[vfIdx + 1]}${RESET}`,
583
+ );
584
+ console.log(
585
+ ` ${DIM}Try broader terms or check 'list' for available cases.${RESET}`,
586
+ );
587
+ return;
588
+ }
589
+
590
+ console.log(
591
+ `\n${BOLD}${CYAN}━━━ Case Law Search Results ━━━━━━━━━━━━━━━━━━━━━━━${RESET}`,
592
+ );
593
+ console.log(` Query : ${BOLD}${query}${RESET}`);
594
+ console.log(
595
+ ` Matches: ${top.length} of ${index.cases.length} cases` +
596
+ (skipped > 0
597
+ ? ` ${DIM}(${skipped} skipped by version filter)${RESET}`
598
+ : "") +
599
+ "\n",
600
+ );
601
+
602
+ for (const { score, entry } of top) {
603
+ const vc = entry.verdict === "REJECTED" ? RED : YELLOW;
604
+ console.log(
605
+ ` ${BOLD}Case #${String(entry.id).padStart(4, "0")}${RESET} ${vc}[${entry.verdict}]${RESET} ${DIM}${(entry.timestamp || "").slice(0, 10)}${RESET} score=${score.toFixed(2)}`,
606
+ );
607
+ console.log(` ${DIM}Domain: ${entry.domain}${RESET}`);
608
+ console.log(` ${entry.reason_summary}`);
609
+ console.log(
610
+ ` ${DIM}Tags: ${(entry.tags || []).slice(0, 8).join(", ")}${RESET}\n`,
611
+ );
612
+ }
613
+ console.log(
614
+ ` ${DIM}Run 'show --id <N>' to see the full diff for any case.${RESET}`,
615
+ );
616
+ console.log(
617
+ `${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${RESET}\n`,
618
+ );
619
+ }
620
+
621
+ function cmdList(args) {
622
+ const index = loadIndex();
623
+ const cases = index.cases || [];
624
+ if (!cases.length) {
625
+ console.log(`${YELLOW}No cases recorded yet.${RESET}`);
626
+ return;
627
+ }
628
+
629
+ let domainFilter = null;
630
+ const di = args.indexOf("--domain");
631
+ if (di !== -1 && args[di + 1]) domainFilter = args[di + 1].toLowerCase();
632
+
633
+ const filtered = domainFilter
634
+ ? cases.filter((c) => c.domain === domainFilter)
635
+ : cases;
636
+ const total = filtered.length;
637
+
638
+ console.log(
639
+ `\n${BOLD}${CYAN}━━━ Case Law Index (${total} cases) ━━━━━━━━━━━━━━━━━━━━${RESET}`,
640
+ );
641
+ if (domainFilter)
642
+ console.log(` ${DIM}Filtered by domain: ${domainFilter}${RESET}\n`);
643
+
644
+ const last20 = filtered.slice(-20).reverse();
645
+ for (const entry of last20) {
646
+ const vc = entry.verdict === "REJECTED" ? RED : YELLOW;
647
+ console.log(
648
+ ` ${BOLD}#${String(entry.id).padStart(4, "0")}${RESET} ${vc}[${entry.verdict}]${RESET} ${DIM}${(entry.domain || "").toUpperCase()}${RESET} ${(entry.timestamp || "").slice(0, 10)}`,
649
+ );
650
+ console.log(` ${(entry.reason_summary || "").slice(0, 80)}`);
651
+ }
652
+ if (total > 20)
653
+ console.log(
654
+ `\n ${YELLOW}... showing last 20 of ${total}. Use 'export' for full history.${RESET}`,
655
+ );
656
+ console.log(
657
+ `${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${RESET}\n`,
658
+ );
659
+ }
660
+
661
+ function cmdShow(args) {
662
+ let caseId = null;
663
+ const ii = args.indexOf("--id");
664
+ if (ii !== -1 && args[ii + 1]) caseId = parseInt(args[ii + 1], 10);
665
+ if (caseId == null || isNaN(caseId)) {
666
+ console.log(`${RED}✖ Provide a case ID: show --id 7${RESET}`);
667
+ process.exit(1);
668
+ }
669
+
670
+ const caseRecord = loadCase(caseId);
671
+ if (!caseRecord) {
672
+ console.log(
673
+ `${RED}✖ Case #${String(caseId).padStart(4, "0")} not found.${RESET}`,
674
+ );
675
+ process.exit(1);
676
+ }
677
+
678
+ const vc = caseRecord.verdict === "REJECTED" ? RED : YELLOW;
679
+ console.log(
680
+ `\n${BOLD}${CYAN}━━━ Case #${String(caseRecord.id).padStart(4, "0")} ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${RESET}`,
681
+ );
682
+ console.log(` Verdict : ${vc}${BOLD}${caseRecord.verdict}${RESET}`);
683
+ console.log(` Domain : ${caseRecord.domain}`);
684
+ console.log(` Recorded : ${caseRecord.timestamp}`);
685
+ if (caseRecord.pr_ref) console.log(` PR / Ref : ${caseRecord.pr_ref}`);
686
+ if (caseRecord.reviewer) console.log(` Reviewer : ${caseRecord.reviewer}`);
687
+ console.log(`\n ${BOLD}Reason:${RESET}`);
688
+ console.log(` ${caseRecord.reason}`);
689
+ console.log(`\n ${BOLD}Semantic Delta (meaningful changes only):${RESET}`);
690
+ console.log(` ${DIM}─────────────────────────────────────────${RESET}`);
691
+ const deltaLines = (caseRecord.diff_delta || caseRecord.diff_raw)
692
+ .split("\n")
693
+ .slice(0, 40);
694
+ for (const line of deltaLines) {
695
+ if (line.startsWith("+")) console.log(` ${GREEN}${line}${RESET}`);
696
+ else if (line.startsWith("-")) console.log(` ${RED}${line}${RESET}`);
697
+ else console.log(` ${DIM}${line}${RESET}`);
698
+ }
699
+ console.log(`\n ${BOLD}Tags:${RESET} ${(caseRecord.tags || []).join(", ")}`);
700
+ console.log(
701
+ `${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${RESET}\n`,
702
+ );
703
+ }
704
+
705
+ function cmdExport(args) {
706
+ const toStdout = args.includes("--stdout");
707
+ const index = loadIndex();
708
+ const cases = index.cases || [];
709
+ if (!cases.length) {
710
+ console.log(`${YELLOW}No cases to export.${RESET}`);
711
+ return;
712
+ }
713
+
714
+ const now = new Date().toISOString().slice(0, 19);
715
+ const lines = [
716
+ "# Tribunal Case Law — Full Export\n",
717
+ `Generated: ${now}`,
718
+ `Total Cases: ${cases.length}\n`,
719
+ "---\n",
720
+ ];
721
+ for (const entry of cases) {
722
+ const caseRecord = loadCase(entry.id) || entry;
723
+ const badge = `[${caseRecord.verdict || "REJECTED"}]`;
724
+ lines.push(`## Case #${String(entry.id).padStart(4, "0")} ${badge}`);
725
+ lines.push(`**Domain:** ${entry.domain} `);
726
+ lines.push(`**Recorded:** ${(entry.timestamp || "").slice(0, 10)} `);
727
+ if (caseRecord.pr_ref) lines.push(`**PR/Ref:** ${caseRecord.pr_ref} `);
728
+ lines.push(`\n**Reason:** ${entry.reason_summary}\n`);
729
+ lines.push(`**Tags:** \`${(entry.tags || []).slice(0, 8).join(", ")}\`\n`);
730
+ lines.push("---\n");
731
+ }
732
+ const content = lines.join("\n");
733
+ if (toStdout) {
734
+ console.log(content);
735
+ return;
736
+ }
737
+
738
+ const outPath = path.join(getPaths().HISTORY_DIR, "case-law-export.md");
739
+ fs.writeFileSync(outPath, content, "utf8");
740
+ console.log(`${GREEN}✔ Exported ${cases.length} cases to ${outPath}${RESET}`);
741
+ }
742
+
743
+ function cmdStats() {
744
+ const index = loadIndex();
745
+ const cases = index.cases || [];
746
+ const domainCounts = {};
747
+ const verdictCounts = {};
748
+ for (const c of cases) {
749
+ domainCounts[c.domain] = (domainCounts[c.domain] || 0) + 1;
750
+ verdictCounts[c.verdict] = (verdictCounts[c.verdict] || 0) + 1;
751
+ }
752
+
753
+ console.log(
754
+ `\n${BOLD}${CYAN}━━━ Case Law Statistics ━━━━━━━━━━━━━━━━━━━━━━━━━━━${RESET}`,
755
+ );
756
+ console.log(` Total cases: ${BOLD}${cases.length}${RESET}`);
757
+ console.log(`\n ${BOLD}By Verdict:${RESET}`);
758
+ for (const v of Object.keys(verdictCounts).sort()) {
759
+ const color = v === "REJECTED" ? RED : YELLOW;
760
+ console.log(` ${color}${v.padEnd(30)}${RESET} ${verdictCounts[v]}`);
761
+ }
762
+ console.log(`\n ${BOLD}By Domain:${RESET}`);
763
+ for (const [d, c] of Object.entries(domainCounts).sort(
764
+ (a, b) => b[1] - a[1],
765
+ )) {
766
+ console.log(` ${CYAN}${d.padEnd(20)}${RESET} ${c}`);
767
+ }
768
+ console.log(
769
+ `${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${RESET}\n`,
770
+ );
771
+ }
772
+
773
+ function cmdAutoRecord() {
774
+ function getFlag(name) {
775
+ const flag = `--${name}`;
776
+ const idx = process.argv.indexOf(flag);
777
+ return idx !== -1 && process.argv[idx + 1] ? process.argv[idx + 1] : "";
778
+ }
779
+
780
+ const diffText = getFlag("diff");
781
+ const reason = getFlag("reason");
782
+ let domain = getFlag("domain") || "general";
783
+ let verdict = getFlag("verdict") || "REJECTED";
784
+ const reviewer = getFlag("reviewer") || null;
785
+ const prRef = getFlag("pr-ref") || null;
786
+ // FIX: --stack-version persists version context with the case record so
787
+ // future searches can skip it when the project has moved past that version.
788
+ // Example: --stack-version "react=18,next=14"
789
+ const stackVersion = getFlag("stack-version") || null;
790
+
791
+ if (!diffText || !reason) {
792
+ console.log(
793
+ `${RED}✖ auto-record requires --diff and --reason flags.${RESET}`,
794
+ );
795
+ console.log(
796
+ ` Usage: auto-record --diff "code" --reason "why" --domain security --reviewer agent-name --stack-version "react=18"`,
797
+ );
798
+ process.exit(1);
799
+ }
800
+
801
+ if (isNoiseRejection(reason)) {
802
+ console.log(
803
+ `${DIM}⊘ Skipped: trivial rejection (noise filter matched).${RESET}`,
804
+ );
805
+ return;
806
+ }
807
+ if (!VALID_DOMAINS.has(domain)) domain = "general";
808
+ if (!VALID_VERDICTS.has(verdict)) verdict = "REJECTED";
809
+
810
+ const fingerprint = contentHash(diffText);
811
+ const index = loadIndex();
812
+ for (const existing of index.cases) {
813
+ if (existing.fingerprint === fingerprint) {
814
+ console.log(
815
+ `${YELLOW}⊘ Duplicate: Case #${String(existing.id).padStart(4, "0")} already records this pattern.${RESET}`,
816
+ );
817
+ return;
818
+ }
819
+ }
820
+
821
+ const delta = semanticDelta(diffText);
822
+ const tags = extractTags(diffText + " " + reason);
823
+ const caseId = index.next_id;
824
+ const now = new Date().toISOString().slice(0, 19);
825
+
826
+ const caseRecord = {
827
+ id: caseId,
828
+ fingerprint,
829
+ timestamp: now,
830
+ domain,
831
+ verdict,
832
+ reason: reason.trim(),
833
+ pr_ref: prRef,
834
+ reviewer,
835
+ tags,
836
+ stack_version: stackVersion,
837
+ diff_raw: diffText.trim(),
838
+ diff_delta: delta,
839
+ auto_recorded: true,
840
+ };
841
+
842
+ saveCase(caseRecord);
843
+ index.cases.push({
844
+ id: caseId,
845
+ fingerprint,
846
+ domain,
847
+ verdict,
848
+ tags,
849
+ timestamp: now,
850
+ reason_summary: reason.trim().slice(0, 120),
851
+ stack_version: stackVersion,
852
+ });
853
+ index.next_id = caseId + 1;
854
+ saveIndex(index);
855
+ console.log(
856
+ `${GREEN}✔ Auto-recorded Case #${String(caseId).padStart(4, "0")}${RESET} [${verdict}] domain=${domain}`,
857
+ );
858
+ console.log(` ${DIM}Reason: ${reason.slice(0, 80)}${RESET}`);
859
+ if (stackVersion)
860
+ console.log(` ${DIM}Stack version: ${stackVersion}${RESET}`);
861
+ }
862
+
863
+ async function cmdOverrule(args) {
864
+ let caseId = null;
865
+ const ii = args.indexOf("--id");
866
+ if (ii !== -1 && args[ii + 1]) caseId = parseInt(args[ii + 1], 10);
867
+ if (caseId == null || isNaN(caseId)) {
868
+ console.log(`${RED}✖ Provide a case ID: overrule --id 7${RESET}`);
869
+ process.exit(1);
870
+ }
871
+
872
+ const caseRecord = loadCase(caseId);
873
+ if (!caseRecord) {
874
+ console.log(
875
+ `${RED}✖ Case #${String(caseId).padStart(4, "0")} not found.${RESET}`,
876
+ );
877
+ process.exit(1);
878
+ }
879
+ if (caseRecord.verdict === "OVERRULED") {
880
+ console.log(
881
+ `${YELLOW}Case #${String(caseId).padStart(4, "0")} is already OVERRULED.${RESET}`,
882
+ );
883
+ return;
884
+ }
885
+
886
+ let reason = null;
887
+ const ri = args.indexOf("--reason");
888
+ if (ri !== -1 && args[ri + 1]) reason = args[ri + 1];
889
+
890
+ if (!reason) {
891
+ const rl = createRl();
892
+ reason = await ask(rl, "Reason for overruling this precedent:");
893
+ rl.close();
894
+ }
895
+ if (!reason || !reason.trim()) {
896
+ console.log(`${RED}✖ An overrule reason is required.${RESET}`);
897
+ process.exit(1);
898
+ }
899
+
900
+ const oldVerdict = caseRecord.verdict;
901
+ caseRecord.verdict = "OVERRULED";
902
+ caseRecord.overruled_at = new Date().toISOString().slice(0, 19);
903
+ caseRecord.overrule_reason = reason.trim();
904
+ caseRecord.previous_verdict = oldVerdict;
905
+ saveCase(caseRecord);
906
+
907
+ const index = loadIndex();
908
+ for (const entry of index.cases) {
909
+ if (entry.id === caseId) {
910
+ entry.verdict = "OVERRULED";
911
+ break;
912
+ }
913
+ }
914
+ saveIndex(index);
915
+
916
+ console.log(
917
+ `\n${GREEN}✔ Case #${String(caseId).padStart(4, "0")} OVERRULED${RESET}`,
918
+ );
919
+ console.log(` ${DIM}Previous verdict : ${oldVerdict}${RESET}`);
920
+ console.log(` ${DIM}Overrule reason : ${reason.trim()}${RESET}`);
921
+ console.log(
922
+ ` ${DIM}The case is preserved in history but no longer blocks reviews.${RESET}\n`,
923
+ );
924
+ }
925
+
926
+ // ── Main ──────────────────────────────────────────────────────────────────────
927
+ const COMMANDS = {
928
+ "add-case": cmdAddCase,
929
+ "auto-record": cmdAutoRecord,
930
+ "search-cases": cmdSearchCases,
931
+ list: cmdList,
932
+ show: cmdShow,
933
+ overrule: cmdOverrule,
934
+ export: cmdExport,
935
+ stats: cmdStats,
936
+ };
937
+
938
+ async function main() {
939
+ const argv = process.argv.slice(2);
940
+ if (!argv.length || ["-h", "--help", "help"].includes(argv[0])) {
941
+ console.log(`
942
+ ${BOLD}case_law_manager.js${RESET} — Tribunal Case Law Engine
943
+
944
+ ${BOLD}Commands:${RESET}
945
+ add-case Record a new rejected pattern (interactive)
946
+ auto-record --diff --reason Record a rejection (non-interactive, for AI agents)
947
+ search-cases --query <text> Find relevant precedents (TF-IDF cosine, token-free)
948
+ list [--domain <domain>] List all recorded cases
949
+ show --id <N> Show full diff for a case
950
+ overrule --id <N> Formally overrule a past precedent
951
+ export [--stdout] Export all cases to Markdown
952
+ stats Show breakdown by domain/verdict
953
+
954
+ ${BOLD}Domains:${RESET} ${[...VALID_DOMAINS].sort().join(", ")}
955
+ ${BOLD}Verdicts:${RESET} ${[...VALID_VERDICTS].sort().join(", ")}
956
+ `);
957
+ return;
958
+ }
959
+
960
+ const cmd = argv[0];
961
+ const rest = argv.slice(1);
962
+ if (!COMMANDS[cmd]) {
963
+ console.log(`${RED}✖ Unknown command: '${cmd}'${RESET}`);
964
+ console.log(` Valid: ${Object.keys(COMMANDS).join(", ")}`);
965
+ process.exit(1);
966
+ }
967
+ await COMMANDS[cmd](rest);
968
+ }
969
+
970
+ // ── Exports ──────────────────────────────────────────────────────────────────
971
+ module.exports = {
972
+ contentHash,
973
+ semanticDelta,
974
+ extractTags,
975
+ loadIndex,
976
+ saveIndex,
977
+ loadCase,
978
+ saveCase,
979
+ tfidfCosineSimilarity,
980
+ buildIdf,
981
+ findAgentDir,
982
+ isNoiseRejection,
983
+ isTrivialLine,
984
+ };
985
+
986
+ if (require.main === module) {
987
+ main().catch((err) => {
988
+ console.error(err);
989
+ process.exit(1);
990
+ });
991
+ }