tribunal-kit 4.4.0 → 4.4.2

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 (90) hide show
  1. package/.agent/agents/api-architect.md +66 -66
  2. package/.agent/agents/db-latency-auditor.md +216 -216
  3. package/.agent/agents/precedence-reviewer.md +250 -250
  4. package/.agent/agents/resilience-reviewer.md +88 -88
  5. package/.agent/agents/schema-reviewer.md +67 -67
  6. package/.agent/agents/throughput-optimizer.md +299 -299
  7. package/.agent/agents/ui-ux-auditor.md +292 -292
  8. package/.agent/agents/vitals-reviewer.md +223 -223
  9. package/.agent/history/architecture-graph.yaml +32 -1
  10. package/.agent/history/graph-cache.json +66 -19
  11. package/.agent/history/snapshots/bin__tribunal-kit.js.json +19 -0
  12. package/.agent/history/snapshots/eslint.config.js.json +9 -0
  13. package/.agent/history/snapshots/migrate_refs.js.json +3 -3
  14. package/.agent/history/snapshots/scripts__changelog.js.json +2 -1
  15. package/.agent/history/snapshots/scripts__sync-version.js.json +2 -1
  16. package/.agent/history/snapshots/scripts__validate-payload.js.json +1 -0
  17. package/.agent/history/snapshots/test__integration__bridges.test.js.json +2 -1
  18. package/.agent/history/snapshots/test__integration__init.test.js.json +1 -0
  19. package/.agent/history/snapshots/test__integration__routing.test.js.json +1 -0
  20. package/.agent/history/snapshots/test__integration__swarm_dispatcher.test.js.json +2 -1
  21. package/.agent/history/snapshots/test__integration__wave2.test.js.json +2 -1
  22. package/.agent/history/snapshots/test__unit__args.test.js.json +11 -1
  23. package/.agent/history/snapshots/test__unit__case_law_manager.test.js.json +1 -0
  24. package/.agent/history/snapshots/test__unit__context_broker.test.js.json +11 -0
  25. package/.agent/history/snapshots/test__unit__copyDir.test.js.json +11 -1
  26. package/.agent/history/snapshots/test__unit__graph_tools.test.js.json +1 -0
  27. package/.agent/history/snapshots/test__unit__inner_loop_validator.test.js.json +11 -0
  28. package/.agent/history/snapshots/test__unit__selfInstall.test.js.json +11 -1
  29. package/.agent/history/snapshots/test__unit__semver.test.js.json +11 -1
  30. package/.agent/history/snapshots/test__unit__swarm_dispatcher.test.js.json +1 -0
  31. package/.agent/scripts/_colors.js +154 -2
  32. package/.agent/scripts/_utils.js +205 -3
  33. package/.agent/scripts/append_flow.js +72 -72
  34. package/.agent/scripts/auto_preview.js +197 -197
  35. package/.agent/scripts/bundle_analyzer.js +90 -119
  36. package/.agent/scripts/case_law_manager.js +18 -13
  37. package/.agent/scripts/checklist.js +100 -88
  38. package/.agent/scripts/colors.js +7 -13
  39. package/.agent/scripts/compress_skills.js +141 -141
  40. package/.agent/scripts/consolidate_skills.js +149 -149
  41. package/.agent/scripts/context_broker.js +605 -609
  42. package/.agent/scripts/deep_compress.js +150 -150
  43. package/.agent/scripts/dependency_analyzer.js +68 -106
  44. package/.agent/scripts/graph_builder.js +341 -311
  45. package/.agent/scripts/graph_visualizer.js +390 -384
  46. package/.agent/scripts/graph_zoom.js +6 -4
  47. package/.agent/scripts/inner_loop_validator.js +445 -465
  48. package/.agent/scripts/lint_runner.js +27 -28
  49. package/.agent/scripts/minify_context.js +100 -100
  50. package/.agent/scripts/mutation_runner.js +280 -280
  51. package/.agent/scripts/patch_skills_meta.js +156 -156
  52. package/.agent/scripts/patch_skills_output.js +244 -244
  53. package/.agent/scripts/schema_validator.js +280 -297
  54. package/.agent/scripts/security_scan.js +37 -64
  55. package/.agent/scripts/session_manager.js +270 -276
  56. package/.agent/scripts/skill_evolution.js +637 -644
  57. package/.agent/scripts/skill_integrator.js +307 -313
  58. package/.agent/scripts/strengthen_skills.js +193 -193
  59. package/.agent/scripts/strip_tribunal.js +47 -47
  60. package/.agent/scripts/swarm_dispatcher.js +360 -360
  61. package/.agent/scripts/test_runner.js +32 -39
  62. package/.agent/scripts/utils.js +10 -25
  63. package/.agent/scripts/verify_all.js +84 -92
  64. package/.agent/skills/app-builder/templates/astro-static/TEMPLATE.md +1 -1
  65. package/.agent/skills/app-builder/templates/chrome-extension/TEMPLATE.md +1 -1
  66. package/.agent/skills/app-builder/templates/cli-tool/TEMPLATE.md +1 -1
  67. package/.agent/skills/app-builder/templates/electron-desktop/TEMPLATE.md +1 -1
  68. package/.agent/skills/app-builder/templates/express-api/TEMPLATE.md +1 -1
  69. package/.agent/skills/app-builder/templates/flutter-app/TEMPLATE.md +1 -1
  70. package/.agent/skills/app-builder/templates/monorepo-turborepo/TEMPLATE.md +1 -1
  71. package/.agent/skills/app-builder/templates/nextjs-fullstack/TEMPLATE.md +1 -1
  72. package/.agent/skills/app-builder/templates/nextjs-saas/TEMPLATE.md +1 -1
  73. package/.agent/skills/app-builder/templates/nextjs-static/TEMPLATE.md +1 -1
  74. package/.agent/skills/app-builder/templates/nuxt-app/TEMPLATE.md +1 -1
  75. package/.agent/skills/app-builder/templates/python-fastapi/TEMPLATE.md +1 -1
  76. package/.agent/skills/app-builder/templates/react-native-app/TEMPLATE.md +1 -1
  77. package/.agent/skills/doc.md +1 -1
  78. package/.agent/skills/knowledge-graph/SKILL.md +52 -52
  79. package/.agent/skills/ui-ux-pro-max/SKILL.md +562 -562
  80. package/.agent/workflows/generate.md +183 -183
  81. package/.agent/workflows/tribunal-speed.md +183 -183
  82. package/README.md +1 -1
  83. package/bin/tribunal-kit.js +76 -87
  84. package/package.json +6 -3
  85. package/scripts/changelog.js +167 -167
  86. package/scripts/sync-version.js +81 -81
  87. package/.agent/history/architecture-explorer.html +0 -352
  88. package/.agent/scripts/__pycache__/_colors.cpython-311.pyc +0 -0
  89. package/.agent/scripts/__pycache__/_utils.cpython-311.pyc +0 -0
  90. package/.agent/scripts/__pycache__/case_law_manager.cpython-311.pyc +0 -0
@@ -1,311 +1,341 @@
1
- #!/usr/bin/env node
2
- /**
3
- * graph_builder.js — Tribunal Kit Macro Graph Mapper
4
- * Parses project structure for imports, exports, and dependencies
5
- * using incremental caching and zero external dependencies.
6
- * Now includes Blast Radius calculation and robust token stripping.
7
- */
8
-
9
- 'use strict';
10
-
11
- const fs = require('fs');
12
- const path = require('path');
13
-
14
- const AGENT_DIR = path.join(process.cwd(), '.agent');
15
- const HISTORY_DIR = path.join(AGENT_DIR, 'history');
16
- const CACHE_FILE = path.join(HISTORY_DIR, 'graph-cache.json');
17
- const GRAPH_FILE = path.join(HISTORY_DIR, 'architecture-graph.yaml');
18
-
19
- // ── Exclusions & Safety ───────────────────────────────────────────────────────
20
- const DEFAULT_EXCLUSIONS = new Set([
21
- 'node_modules', '.git', '.next', 'dist', 'build', 'coverage', '.agent', 'artifacts'
22
- ]);
23
-
24
- function loadGitIgnore() {
25
- const gitignorePath = path.join(process.cwd(), '.gitignore');
26
- if (!fs.existsSync(gitignorePath)) return [];
27
-
28
- return fs.readFileSync(gitignorePath, 'utf8')
29
- .split('\n')
30
- .map(line => line.trim())
31
- .filter(line => line && !line.startsWith('#'))
32
- .map(line => line.replace(/\/$/, '').replace(/^\//, ''));
33
- }
34
-
35
- const customExclusions = loadGitIgnore();
36
-
37
- function isExcluded(filePath) {
38
- const parts = filePath.split(path.sep);
39
- if (parts.some(p => DEFAULT_EXCLUSIONS.has(p))) return true;
40
-
41
- const relativePath = path.relative(process.cwd(), filePath).replace(/\\/g, '/');
42
- for (const pattern of customExclusions) {
43
- if (relativePath.includes(pattern)) return true;
44
- }
45
- return false;
46
- }
47
-
48
- // ── Traversal ─────────────────────────────────────────────────────────────────
49
- function walkDir(dir, fileList = []) {
50
- if (!fs.existsSync(dir) || isExcluded(dir)) return fileList;
51
-
52
- let files;
53
- try {
54
- files = fs.readdirSync(dir);
55
- } catch (err) {
56
- return fileList;
57
- }
58
-
59
- for (const file of files) {
60
- const filePath = path.join(dir, file);
61
- if (isExcluded(filePath)) continue;
62
-
63
- if (fs.statSync(filePath).isDirectory()) {
64
- walkDir(filePath, fileList);
65
- } else {
66
- if (/\.(js|jsx|ts|tsx|mjs|cjs)$/.test(file)) {
67
- fileList.push(filePath);
68
- }
69
- }
70
- }
71
- return fileList;
72
- }
73
-
74
- // ── Regex AST Extraction ──────────────────────────────────────────────────────
75
- function parseFile(content) {
76
- const imports = new Set();
77
- const exports = new Set();
78
-
79
- const cleanContent = stripStringsAndComments(content);
80
-
81
- const importRegex = /import(?:(?:[\w*\s{},]*)\sfrom\s+)?([^\s;]+)/g; // Match bare specifier if possible, strings are stripped, but wait...
82
- // WAIT: If I stripped strings, how do I get the import path?
83
- // The previous implementation used strings `['"]([^'"]+)['"]`.
84
- // If I strip strings, the import path is lost!
85
- // Let's rollback that logic or adapt it.
86
- // Instead of stripping all strings, we should only strip strings if they are NOT following 'import ' or 'require('
87
- // To do this simply, let's keep strings, but just be careful.
88
- // Actually, string literals inside `require("...")` are what we want.
89
- // So `parseFile` should probably NOT strip strings, but just use a safer regex.
90
- // The false positive in `dependency_analyzer` was because of `const diff = "import a from 'a'"`.
91
- // Let's use `stripStringsAndComments` but we DO NOT strip strings.
92
- // We only strip comments.
93
-
94
- // I'll define an inner function to just strip comments to be safe for imports.
95
- // Let's stick to the simple `.replace` for comments for now, and rely on regex boundaries.
96
- const semiCleanContent = content.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, '');
97
-
98
- const importRegex2 = /^[\s]*import(?:(?:[\w*\s{},]*)\sfrom\s+)?['"]([^'"]+)['"]/gm;
99
- const requireRegex = /require\(['"]([^'"]+)['"]\)/g;
100
- const dynamicImportRegex = /import\(['"]([^'"]+)['"]\)/g;
101
-
102
- const exportRegex = /^[\s]*export\s+(?:const|let|var|function|class)\s+([a-zA-Z0-9_]+)/gm;
103
- const moduleExportRegex = /module\.exports\s*=\s*\{([^}]+)\}/g;
104
- const defaultExportRegex = /^[\s]*export\s+default\s+([a-zA-Z0-9_]+)/gm;
105
-
106
- let match;
107
- while ((match = importRegex2.exec(semiCleanContent)) !== null) imports.add(match[1]);
108
- while ((match = requireRegex.exec(semiCleanContent)) !== null) imports.add(match[1]);
109
- while ((match = dynamicImportRegex.exec(semiCleanContent)) !== null) imports.add(match[1]);
110
-
111
- while ((match = exportRegex.exec(semiCleanContent)) !== null) exports.add(match[1]);
112
- while ((match = defaultExportRegex.exec(semiCleanContent)) !== null) exports.add(match[1]);
113
-
114
- while ((match = moduleExportRegex.exec(semiCleanContent)) !== null) {
115
- const tokens = match[1].split(',').map(s => s.trim().split(':')[0].trim());
116
- tokens.forEach(t => t && exports.add(t));
117
- }
118
-
119
- return {
120
- imports: Array.from(imports),
121
- exports: Array.from(exports)
122
- };
123
- }
124
-
125
- // ── YAML Generation ───────────────────────────────────────────────────────────
126
- function generateYAML(data) {
127
- let yaml = '# Auto-generated Architecture Graph by Tribunal Kit\n';
128
- yaml += '# DO NOT EDIT MANUALLY - Auto-updates via incremental cache\n\n';
129
-
130
- for (const [file, info] of Object.entries(data)) {
131
- if (info.imports.length === 0 && info.exports.length === 0 && (!info.dependents || info.dependents.length === 0)) continue;
132
-
133
- yaml += `"${file}":\n`;
134
- yaml += ` riskScore: "${info.riskScore || 'Low'}"\n`;
135
- yaml += ` blastRadius: ${info.blastRadius || 0}\n`;
136
-
137
- if (info.imports && info.imports.length > 0) {
138
- yaml += ` imports:\n`;
139
- info.imports.forEach(i => yaml += ` - "${i}"\n`);
140
- }
141
- if (info.exports && info.exports.length > 0) {
142
- yaml += ` exports:\n`;
143
- info.exports.forEach(e => yaml += ` - "${e}"\n`);
144
- }
145
- if (info.dependents && info.dependents.length > 0) {
146
- yaml += ` dependents:\n`;
147
- info.dependents.forEach(d => yaml += ` - "${d}"\n`);
148
- }
149
- }
150
- return yaml;
151
- }
152
-
153
- // ── Main Execution ────────────────────────────────────────────────────────────
154
- function main() {
155
- if (!fs.existsSync(AGENT_DIR)) {
156
- console.error('\x1b[31m✖ Error: .agent directory not found.\x1b[0m');
157
- process.exit(1);
158
- }
159
-
160
- if (!fs.existsSync(HISTORY_DIR)) fs.mkdirSync(HISTORY_DIR, { recursive: true });
161
-
162
- let cache = {};
163
- if (fs.existsSync(CACHE_FILE)) {
164
- try { cache = JSON.parse(fs.readFileSync(CACHE_FILE, 'utf8')); } catch(e) {}
165
- }
166
-
167
- console.log('\x1b[96m✦ Building Architecture Graph...\x1b[0m');
168
- const files = walkDir(process.cwd());
169
- const graphData = {};
170
-
171
- let parsedCount = 0;
172
- let cachedCount = 0;
173
-
174
- for (const file of files) {
175
- const stat = fs.statSync(file);
176
- const relativePath = path.relative(process.cwd(), file).replace(/\\/g, '/');
177
-
178
- if (cache[relativePath] && cache[relativePath].mtimeMs === stat.mtimeMs) {
179
- graphData[relativePath] = { imports: cache[relativePath].imports, exports: cache[relativePath].exports };
180
- cachedCount++;
181
- } else {
182
- try {
183
- const content = fs.readFileSync(file, 'utf8');
184
- const parsed = parseFile(content);
185
- graphData[relativePath] = parsed;
186
-
187
- cache[relativePath] = {
188
- mtimeMs: stat.mtimeMs,
189
- imports: parsed.imports,
190
- exports: parsed.exports
191
- };
192
- parsedCount++;
193
- } catch (err) {}
194
- }
195
- }
196
-
197
- // Compute Dependents
198
- for (const [file, info] of Object.entries(graphData)) info.dependents = [];
199
-
200
- const fileKeys = Object.keys(graphData);
201
- for (const [file, info] of Object.entries(graphData)) {
202
- for (const imp of info.imports) {
203
- if (imp.startsWith('.')) {
204
- let resolved = path.posix.join(path.dirname(file), imp);
205
- // Look for direct match or .js / index.js
206
- let matchingKey = fileKeys.find(k =>
207
- k === resolved || k === resolved + '.js' || k === resolved + '.ts' || k === resolved + '/index.js'
208
- );
209
- if (matchingKey) {
210
- if (!graphData[matchingKey].dependents.includes(file)) {
211
- graphData[matchingKey].dependents.push(file);
212
- }
213
- }
214
- }
215
- }
216
- }
217
-
218
- // Compute Risk Score
219
- function computeRisk(file) {
220
- const visited = new Set();
221
- function visit(node) {
222
- if (visited.has(node)) return;
223
- visited.add(node);
224
- const deps = graphData[node]?.dependents || [];
225
- deps.forEach(visit);
226
- }
227
- visit(file);
228
- const radius = visited.size - 1;
229
- let score = 'Low';
230
- if (radius > 10) score = 'Critical';
231
- else if (radius >= 5) score = 'High';
232
- else if (radius >= 2) score = 'Medium';
233
- return { score, count: Math.max(0, radius) };
234
- }
235
-
236
- for (const file of fileKeys) {
237
- const risk = computeRisk(file);
238
- graphData[file].riskScore = risk.score;
239
- graphData[file].blastRadius = risk.count;
240
-
241
- // Update cache with these values so visualizer can use it
242
- if (cache[file]) {
243
- cache[file].dependents = graphData[file].dependents;
244
- cache[file].riskScore = risk.score;
245
- cache[file].blastRadius = risk.count;
246
- }
247
- }
248
-
249
- fs.writeFileSync(CACHE_FILE, JSON.stringify(cache, null, 2));
250
- fs.writeFileSync(GRAPH_FILE, generateYAML(graphData));
251
-
252
- // ── Pre-Computed Context Snapshots (Option C) ───────────────────────────
253
- const SNAPSHOTS_DIR = path.join(HISTORY_DIR, 'snapshots');
254
- if (!fs.existsSync(SNAPSHOTS_DIR)) {
255
- fs.mkdirSync(SNAPSHOTS_DIR, { recursive: true });
256
- } else {
257
- // Clear stale snapshots
258
- try {
259
- const oldSnapshots = fs.readdirSync(SNAPSHOTS_DIR);
260
- for (const os of oldSnapshots) fs.unlinkSync(path.join(SNAPSHOTS_DIR, os));
261
- } catch (e) {}
262
- }
263
-
264
- console.log('\x1b[96m✦ Generating Context Snapshots...\x1b[0m');
265
- for (const file of fileKeys) {
266
- const info = graphData[file];
267
- const snapshotFile = file.replace(/[\\/]/g, '__') + '.json';
268
- const snapshotPath = path.join(SNAPSHOTS_DIR, snapshotFile);
269
-
270
- let content = '';
271
- try {
272
- content = fs.readFileSync(path.join(process.cwd(), file), 'utf8');
273
- } catch (e) {
274
- continue;
275
- }
276
-
277
- const snapshot = {
278
- file: file,
279
- riskScore: info.riskScore,
280
- blastRadius: info.blastRadius,
281
- imports: {},
282
- dependents: info.dependents || [],
283
- content: content
284
- };
285
-
286
- for (const imp of info.imports) {
287
- if (imp.startsWith('.')) {
288
- let resolved = path.posix.join(path.dirname(file), imp);
289
- let matchingKey = fileKeys.find(k =>
290
- k === resolved || k === resolved + '.js' || k === resolved + '.ts' || k === resolved + '/index.js'
291
- );
292
- if (matchingKey && graphData[matchingKey]) {
293
- snapshot.imports[imp] = graphData[matchingKey].exports;
294
- } else {
295
- snapshot.imports[imp] = [];
296
- }
297
- } else {
298
- snapshot.imports[imp] = [];
299
- }
300
- }
301
-
302
- fs.writeFileSync(snapshotPath, JSON.stringify(snapshot, null, 2));
303
- }
304
- console.log(` \x1b[2mSaved ${fileKeys.length} snapshots to: ${SNAPSHOTS_DIR}\x1b[0m`);
305
-
306
- console.log(`\n\x1b[32m✔ Graph successfully built.\x1b[0m`);
307
- console.log(` \x1b[2mParsed: ${parsedCount} files | Cached: ${cachedCount} files\x1b[0m`);
308
- console.log(` \x1b[2mSaved to: ${GRAPH_FILE}\x1b[0m`);
309
- }
310
-
311
- main();
1
+ #!/usr/bin/env node
2
+ /**
3
+ * graph_builder.js — Tribunal Kit Macro Graph Mapper
4
+ * Parses project structure for imports, exports, and dependencies
5
+ * using incremental caching and zero external dependencies.
6
+ * Now includes Blast Radius calculation and robust token stripping.
7
+ */
8
+
9
+ 'use strict';
10
+
11
+ const fs = require('fs');
12
+ const path = require('path');
13
+ const crypto = require('crypto');
14
+
15
+ const { RED, GREEN, BOLD, DIM, CYAN, RESET, timer, formatMs } = require('./_colors');
16
+
17
+ const AGENT_DIR = path.join(process.cwd(), '.agent');
18
+ const HISTORY_DIR = path.join(AGENT_DIR, 'history');
19
+ const CACHE_FILE = path.join(HISTORY_DIR, 'graph-cache.json');
20
+ const GRAPH_FILE = path.join(HISTORY_DIR, 'architecture-graph.yaml');
21
+
22
+ // ── Exclusions & Safety ───────────────────────────────────────────────────────
23
+ const DEFAULT_EXCLUSIONS = new Set([
24
+ 'node_modules', '.git', '.next', 'dist', 'build', 'coverage', '.agent', 'artifacts'
25
+ ]);
26
+
27
+ function loadGitIgnore() {
28
+ const gitignorePath = path.join(process.cwd(), '.gitignore');
29
+ if (!fs.existsSync(gitignorePath)) return [];
30
+
31
+ return fs.readFileSync(gitignorePath, 'utf8')
32
+ .split('\n')
33
+ .map(line => line.trim())
34
+ .filter(line => line && !line.startsWith('#'))
35
+ .map(line => line.replace(/\/$/, '').replace(/^\//, ''));
36
+ }
37
+
38
+ const customExclusions = loadGitIgnore();
39
+
40
+ function isExcluded(filePath) {
41
+ const parts = filePath.split(path.sep);
42
+ if (parts.some(p => DEFAULT_EXCLUSIONS.has(p))) return true;
43
+
44
+ const relativePath = path.relative(process.cwd(), filePath).replace(/\\/g, '/');
45
+ for (const pattern of customExclusions) {
46
+ if (relativePath.includes(pattern)) return true;
47
+ }
48
+ return false;
49
+ }
50
+
51
+ // ── Content Hashing ───────────────────────────────────────────────────────────
52
+ function getFileHash(filePath) {
53
+ const content = fs.readFileSync(filePath);
54
+ return crypto.createHash('sha1').update(content).digest('hex');
55
+ }
56
+
57
+ // ── Traversal ─────────────────────────────────────────────────────────────────
58
+ function walkDir(dir, fileList = []) {
59
+ if (!fs.existsSync(dir) || isExcluded(dir)) return fileList;
60
+
61
+ let files;
62
+ try {
63
+ files = fs.readdirSync(dir);
64
+ } catch (_err) {
65
+ return fileList;
66
+ }
67
+
68
+ for (const file of files) {
69
+ const filePath = path.join(dir, file);
70
+ if (isExcluded(filePath)) continue;
71
+
72
+ if (fs.statSync(filePath).isDirectory()) {
73
+ walkDir(filePath, fileList);
74
+ } else {
75
+ if (/\.(js|jsx|ts|tsx|mjs|cjs)$/.test(file)) {
76
+ fileList.push(filePath);
77
+ }
78
+ }
79
+ }
80
+ return fileList;
81
+ }
82
+
83
+ // ── Regex AST Extraction ──────────────────────────────────────────────────────
84
+ function parseFile(content) {
85
+ const imports = new Set();
86
+ const exports = new Set();
87
+
88
+ // Parse from semi-cleaned content (comments removed)
89
+ // WAIT: If I stripped strings, how do I get the import path?
90
+ // The previous implementation used strings `['"]([^'"]+)['"]`.
91
+ // If I strip strings, the import path is lost!
92
+ // Let's rollback that logic or adapt it.
93
+ // Instead of stripping all strings, we should only strip strings if they are NOT following 'import ' or 'require('
94
+ // To do this simply, let's keep strings, but just be careful.
95
+ // Actually, string literals inside `require("...")` are what we want.
96
+ // So `parseFile` should probably NOT strip strings, but just use a safer regex.
97
+ // The false positive in `dependency_analyzer` was because of `const diff = "import a from 'a'"`.
98
+ // Let's use `stripStringsAndComments` but we DO NOT strip strings.
99
+ // We only strip comments.
100
+
101
+ // I'll define an inner function to just strip comments to be safe for imports.
102
+ // Let's stick to the simple `.replace` for comments for now, and rely on regex boundaries.
103
+ const semiCleanContent = content.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, '');
104
+
105
+ const importRegex2 = /^[\s]*import(?:(?:[\w*\s{},]*)\sfrom\s+)?['"]([^'"]+)['"]/gm;
106
+ const requireRegex = /require\(['"]([^'"]+)['"]\)/g;
107
+ const dynamicImportRegex = /import\(['"]([^'"]+)['"]\)/g;
108
+
109
+ const exportRegex = /^[\s]*export\s+(?:const|let|var|function|class)\s+([a-zA-Z0-9_]+)/gm;
110
+ const moduleExportRegex = /module\.exports\s*=\s*\{([^}]+)\}/g;
111
+ const defaultExportRegex = /^[\s]*export\s+default\s+([a-zA-Z0-9_]+)/gm;
112
+
113
+ let match;
114
+ while ((match = importRegex2.exec(semiCleanContent)) !== null) imports.add(match[1]);
115
+ while ((match = requireRegex.exec(semiCleanContent)) !== null) imports.add(match[1]);
116
+ while ((match = dynamicImportRegex.exec(semiCleanContent)) !== null) imports.add(match[1]);
117
+
118
+ while ((match = exportRegex.exec(semiCleanContent)) !== null) exports.add(match[1]);
119
+ while ((match = defaultExportRegex.exec(semiCleanContent)) !== null) exports.add(match[1]);
120
+
121
+ while ((match = moduleExportRegex.exec(semiCleanContent)) !== null) {
122
+ const tokens = match[1].split(',').map(s => s.trim().split(':')[0].trim());
123
+ tokens.forEach(t => t && exports.add(t));
124
+ }
125
+
126
+ return {
127
+ imports: Array.from(imports),
128
+ exports: Array.from(exports)
129
+ };
130
+ }
131
+
132
+ // ── YAML Generation ───────────────────────────────────────────────────────────
133
+ function generateYAML(data) {
134
+ let yaml = '# Auto-generated Architecture Graph by Tribunal Kit\n';
135
+ yaml += '# DO NOT EDIT MANUALLY - Auto-updates via incremental cache\n\n';
136
+
137
+ for (const [file, info] of Object.entries(data)) {
138
+ if (info.imports.length === 0 && info.exports.length === 0 && (!info.dependents || info.dependents.length === 0)) continue;
139
+
140
+ yaml += `"${file}":\n`;
141
+ yaml += ` riskScore: "${info.riskScore || 'Low'}"\n`;
142
+ yaml += ` blastRadius: ${info.blastRadius || 0}\n`;
143
+
144
+ if (info.imports && info.imports.length > 0) {
145
+ yaml += ` imports:\n`;
146
+ info.imports.forEach(i => yaml += ` - "${i}"\n`);
147
+ }
148
+ if (info.exports && info.exports.length > 0) {
149
+ yaml += ` exports:\n`;
150
+ info.exports.forEach(e => yaml += ` - "${e}"\n`);
151
+ }
152
+ if (info.dependents && info.dependents.length > 0) {
153
+ yaml += ` dependents:\n`;
154
+ info.dependents.forEach(d => yaml += ` - "${d}"\n`);
155
+ }
156
+ }
157
+ return yaml;
158
+ }
159
+
160
+ // ── Main Execution ────────────────────────────────────────────────────────────
161
+ function main() {
162
+ if (!fs.existsSync(AGENT_DIR)) {
163
+ console.error(`${RED}✖ Error: .agent directory not found.${RESET}`);
164
+ process.exit(1);
165
+ }
166
+
167
+ if (!fs.existsSync(HISTORY_DIR)) fs.mkdirSync(HISTORY_DIR, { recursive: true });
168
+
169
+ let cache = {};
170
+ if (fs.existsSync(CACHE_FILE)) {
171
+ try { cache = JSON.parse(fs.readFileSync(CACHE_FILE, 'utf8')); } catch { /* ignore */ }
172
+ }
173
+
174
+ const totalTimer = timer();
175
+ console.log(`${CYAN}✦ Building Architecture Graph...${RESET}`);
176
+ const files = walkDir(process.cwd());
177
+ const graphData = {};
178
+
179
+ let parsedCount = 0;
180
+ let cachedCount = 0;
181
+ const changedFiles = new Set();
182
+
183
+ for (const file of files) {
184
+ const relativePath = path.relative(process.cwd(), file).replace(/\\/g, '/');
185
+ let fileHash;
186
+ try {
187
+ fileHash = getFileHash(file);
188
+ } catch { continue; }
189
+
190
+ if (cache[relativePath] && cache[relativePath].hash === fileHash) {
191
+ graphData[relativePath] = { imports: cache[relativePath].imports, exports: cache[relativePath].exports };
192
+ cachedCount++;
193
+ } else {
194
+ try {
195
+ const content = fs.readFileSync(file, 'utf8');
196
+ const parsed = parseFile(content);
197
+ graphData[relativePath] = parsed;
198
+
199
+ cache[relativePath] = {
200
+ hash: fileHash,
201
+ imports: parsed.imports,
202
+ exports: parsed.exports
203
+ };
204
+ parsedCount++;
205
+ changedFiles.add(relativePath);
206
+ } catch { /* ignore */ }
207
+ }
208
+ }
209
+
210
+ // Compute Dependents
211
+ for (const [_file, info] of Object.entries(graphData)) info.dependents = [];
212
+
213
+ const fileKeys = Object.keys(graphData);
214
+ for (const [file, info] of Object.entries(graphData)) {
215
+ for (const imp of info.imports) {
216
+ if (imp.startsWith('.')) {
217
+ let resolved = path.posix.join(path.dirname(file), imp);
218
+ // Look for direct match or .js / index.js
219
+ let matchingKey = fileKeys.find(k =>
220
+ k === resolved || k === resolved + '.js' || k === resolved + '.ts' || k === resolved + '/index.js'
221
+ );
222
+ if (matchingKey) {
223
+ if (!graphData[matchingKey].dependents.includes(file)) {
224
+ graphData[matchingKey].dependents.push(file);
225
+ }
226
+ }
227
+ }
228
+ }
229
+ }
230
+
231
+ // Compute Risk Score
232
+ function computeRisk(file) {
233
+ const visited = new Set();
234
+ function visit(node) {
235
+ if (visited.has(node)) return;
236
+ visited.add(node);
237
+ const deps = graphData[node]?.dependents || [];
238
+ deps.forEach(visit);
239
+ }
240
+ visit(file);
241
+ const radius = visited.size - 1;
242
+ let score = 'Low';
243
+ if (radius > 10) score = 'Critical';
244
+ else if (radius >= 5) score = 'High';
245
+ else if (radius >= 2) score = 'Medium';
246
+ return { score, count: Math.max(0, radius) };
247
+ }
248
+
249
+ for (const file of fileKeys) {
250
+ const risk = computeRisk(file);
251
+ graphData[file].riskScore = risk.score;
252
+ graphData[file].blastRadius = risk.count;
253
+
254
+ // Update cache with these values so visualizer can use it
255
+ if (cache[file]) {
256
+ cache[file].dependents = graphData[file].dependents;
257
+ cache[file].riskScore = risk.score;
258
+ cache[file].blastRadius = risk.count;
259
+ }
260
+ }
261
+
262
+ fs.writeFileSync(CACHE_FILE, JSON.stringify(cache, null, 2));
263
+ fs.writeFileSync(GRAPH_FILE, generateYAML(graphData));
264
+
265
+ // ── Pre-Computed Context Snapshots (Incremental) ─────────────────────────
266
+ const SNAPSHOTS_DIR = path.join(HISTORY_DIR, 'snapshots');
267
+ if (!fs.existsSync(SNAPSHOTS_DIR)) {
268
+ fs.mkdirSync(SNAPSHOTS_DIR, { recursive: true });
269
+ }
270
+
271
+ // Clean up snapshots for files that no longer exist
272
+ try {
273
+ const existingSnapshots = fs.readdirSync(SNAPSHOTS_DIR);
274
+ const currentFileSet = new Set(fileKeys.map(f => f.replace(/[\\/]/g, '__') + '.json'));
275
+ for (const snap of existingSnapshots) {
276
+ if (!currentFileSet.has(snap)) fs.unlinkSync(path.join(SNAPSHOTS_DIR, snap));
277
+ }
278
+ } catch { /* ignore */ }
279
+
280
+ console.log(`${CYAN}✦ Generating Context Snapshots...${RESET}`);
281
+ let snapshotWritten = 0;
282
+ let snapshotSkipped = 0;
283
+ for (const file of fileKeys) {
284
+ const info = graphData[file];
285
+ const snapshotFile = file.replace(/[\\/]/g, '__') + '.json';
286
+ const snapshotPath = path.join(SNAPSHOTS_DIR, snapshotFile);
287
+
288
+ // Skip unchanged files that already have a snapshot
289
+ if (!changedFiles.has(file) && fs.existsSync(snapshotPath)) {
290
+ snapshotSkipped++;
291
+ continue;
292
+ }
293
+
294
+ let content = '';
295
+ try {
296
+ content = fs.readFileSync(path.join(process.cwd(), file), 'utf8');
297
+ } catch {
298
+ continue;
299
+ }
300
+
301
+ const snapshot = {
302
+ file: file,
303
+ riskScore: info.riskScore,
304
+ blastRadius: info.blastRadius,
305
+ imports: {},
306
+ dependents: info.dependents || [],
307
+ content: content
308
+ };
309
+
310
+ for (const imp of info.imports) {
311
+ if (imp.startsWith('.')) {
312
+ let resolved = path.posix.join(path.dirname(file), imp);
313
+ let matchingKey = fileKeys.find(k =>
314
+ k === resolved || k === resolved + '.js' || k === resolved + '.ts' || k === resolved + '/index.js'
315
+ );
316
+ if (matchingKey && graphData[matchingKey]) {
317
+ snapshot.imports[imp] = graphData[matchingKey].exports;
318
+ } else {
319
+ snapshot.imports[imp] = [];
320
+ }
321
+ } else {
322
+ snapshot.imports[imp] = [];
323
+ }
324
+ }
325
+
326
+ fs.writeFileSync(snapshotPath, JSON.stringify(snapshot, null, 2));
327
+ snapshotWritten++;
328
+ }
329
+ console.log(` ${DIM}Snapshots: ${snapshotWritten} written | ${snapshotSkipped} cached${RESET}`);
330
+
331
+ const totalMs = totalTimer();
332
+ console.log(`\n${GREEN}${BOLD}✔ Graph successfully built.${RESET}`);
333
+ console.log(` ${DIM}Parsed: ${parsedCount} files | Cached: ${cachedCount} files | ${formatMs(totalMs)}${RESET}`);
334
+ console.log(` ${DIM}Saved to: ${GRAPH_FILE}${RESET}`);
335
+ }
336
+ // ── Exports (for testing & programmatic use) ─────────────────────────────────
337
+ module.exports = { parseFile, generateYAML, walkDir, isExcluded, getFileHash, main };
338
+
339
+ if (require.main === module) {
340
+ main();
341
+ }