tribunal-kit 4.4.1 → 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 (44) hide show
  1. package/.agent/history/architecture-graph.yaml +140 -0
  2. package/.agent/history/graph-cache.json +262 -0
  3. package/.agent/history/snapshots/bin__tribunal-kit.js.json +19 -0
  4. package/.agent/history/snapshots/eslint.config.js.json +9 -0
  5. package/.agent/history/snapshots/migrate_refs.js.json +11 -0
  6. package/.agent/history/snapshots/scripts__changelog.js.json +13 -0
  7. package/.agent/history/snapshots/scripts__sync-version.js.json +12 -0
  8. package/.agent/history/snapshots/scripts__validate-payload.js.json +12 -0
  9. package/.agent/history/snapshots/test__integration__bridges.test.js.json +14 -0
  10. package/.agent/history/snapshots/test__integration__init.test.js.json +14 -0
  11. package/.agent/history/snapshots/test__integration__routing.test.js.json +12 -0
  12. package/.agent/history/snapshots/test__integration__swarm_dispatcher.test.js.json +14 -0
  13. package/.agent/history/snapshots/test__integration__wave2.test.js.json +14 -0
  14. package/.agent/history/snapshots/test__unit__args.test.js.json +20 -0
  15. package/.agent/history/snapshots/test__unit__case_law_manager.test.js.json +11 -0
  16. package/.agent/history/snapshots/test__unit__context_broker.test.js.json +11 -0
  17. package/.agent/history/snapshots/test__unit__copyDir.test.js.json +23 -0
  18. package/.agent/history/snapshots/test__unit__graph_tools.test.js.json +12 -0
  19. package/.agent/history/snapshots/test__unit__inner_loop_validator.test.js.json +11 -0
  20. package/.agent/history/snapshots/test__unit__selfInstall.test.js.json +23 -0
  21. package/.agent/history/snapshots/test__unit__semver.test.js.json +20 -0
  22. package/.agent/history/snapshots/test__unit__swarm_dispatcher.test.js.json +12 -0
  23. package/.agent/scripts/_colors.js +170 -18
  24. package/.agent/scripts/_utils.js +244 -42
  25. package/.agent/scripts/bundle_analyzer.js +261 -290
  26. package/.agent/scripts/case_law_manager.js +1 -7
  27. package/.agent/scripts/checklist.js +278 -266
  28. package/.agent/scripts/colors.js +11 -17
  29. package/.agent/scripts/context_broker.js +1 -7
  30. package/.agent/scripts/dependency_analyzer.js +234 -272
  31. package/.agent/scripts/graph_builder.js +46 -18
  32. package/.agent/scripts/graph_visualizer.js +10 -4
  33. package/.agent/scripts/graph_zoom.js +6 -4
  34. package/.agent/scripts/inner_loop_validator.js +2 -8
  35. package/.agent/scripts/lint_runner.js +186 -187
  36. package/.agent/scripts/schema_validator.js +8 -25
  37. package/.agent/scripts/security_scan.js +276 -303
  38. package/.agent/scripts/session_manager.js +1 -7
  39. package/.agent/scripts/skill_evolution.js +1 -8
  40. package/.agent/scripts/skill_integrator.js +1 -7
  41. package/.agent/scripts/test_runner.js +186 -193
  42. package/.agent/scripts/utils.js +17 -32
  43. package/.agent/scripts/verify_all.js +248 -257
  44. package/package.json +1 -1
@@ -1,272 +1,234 @@
1
- #!/usr/bin/env node
2
- /**
3
- * dependency_analyzer.js — Dependency health checker for the Tribunal Agent Kit.
4
- *
5
- * Analyzes project dependencies for:
6
- * - Unused packages (in package.json but never imported)
7
- * - Phantom imports (imported but not in package.json)
8
- * - npm audit / pip-audit results
9
- * - Duplicate/overlapping packages
10
- *
11
- * Usage:
12
- * node .agent/scripts/dependency_analyzer.js .
13
- * node .agent/scripts/dependency_analyzer.js . --audit
14
- * node .agent/scripts/dependency_analyzer.js . --check-unused
15
- */
16
-
17
- 'use strict';
18
-
19
- const fs = require('fs');
20
- const path = require('path');
21
- const { spawnSync } = require('child_process');
22
-
23
- const { RED, GREEN, YELLOW, BLUE, BOLD, RESET } = require('./colors.js');
24
-
25
- const SOURCE_EXTENSIONS = new Set([".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"]);
26
- const SKIP_DIRS = new Set(["node_modules", ".git", "dist", "build", ".next", ".agent", "__pycache__", "test", "tests", "__tests__"]);
27
-
28
- const NODE_BUILTINS = new Set([
29
- "fs", "path", "os", "crypto", "http", "https", "url", "util",
30
- "stream", "events", "child_process", "cluster", "net", "dns",
31
- "tls", "readline", "zlib", "buffer", "querystring", "string_decoder",
32
- "assert", "perf_hooks", "worker_threads", "timers", "v8",
33
- "node:fs", "node:path", "node:os", "node:crypto", "node:http",
34
- "node:https", "node:url", "node:util", "node:stream", "node:events",
35
- "node:child_process", "node:net", "node:dns", "node:tls",
36
- "node:readline", "node:zlib", "node:buffer", "node:assert",
37
- "node:perf_hooks", "node:worker_threads", "node:timers"
38
- ]);
39
-
40
- function header(title) {
41
- console.log(`\n${BOLD}${BLUE}━━━ ${title} ━━━${RESET}`);
42
- }
43
-
44
- function ok(msg) {
45
- console.log(` ${GREEN}✅ ${msg}${RESET}`);
46
- }
47
-
48
- function fail(msg) {
49
- console.log(` ${RED}❌ ${msg}${RESET}`);
50
- }
51
-
52
- function warn(msg) {
53
- console.log(` ${YELLOW}⚠️ ${msg}${RESET}`);
54
- }
55
-
56
- function skip(msg) {
57
- console.log(` ${YELLOW}⏭️ ${msg}${RESET}`);
58
- }
59
-
60
- function loadPackageJson(projectRoot) {
61
- const pkgPath = path.resolve(projectRoot, "package.json");
62
- if (!fs.existsSync(pkgPath)) return null;
63
- try {
64
- return JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
65
- } catch {
66
- return null;
67
- }
68
- }
69
-
70
- function extractImports(projectRoot) {
71
- const imports = new Set();
72
- const importPatterns = [
73
- /(?:import|export)\s+.*?\s+from\s+["']([^"'.][^"']*)["']/g,
74
- /require\s*\(\s*["']([^"'.][^"']*)["']/g,
75
- /import\s*\(\s*["']([^"'.][^"']*)["']/g
76
- ];
77
-
78
- function walk(dir) {
79
- let items;
80
- try {
81
- items = fs.readdirSync(dir, { withFileTypes: true });
82
- } catch {
83
- return;
84
- }
85
-
86
- for (const item of items) {
87
- if (item.isDirectory()) {
88
- if (!SKIP_DIRS.has(item.name)) walk(path.join(dir, item.name));
89
- } else {
90
- const ext = path.extname(item.name);
91
- if (SOURCE_EXTENSIONS.has(ext)) {
92
- try {
93
- const content = fs.readFileSync(path.join(dir, item.name), 'utf8');
94
- for (const pattern of importPatterns) {
95
- let match;
96
- while ((match = pattern.exec(content)) !== null) {
97
- let pkg = match[1];
98
- if (pkg.startsWith("@")) {
99
- const parts = pkg.split("/");
100
- pkg = parts.length >= 2 ? `${parts[0]}/${parts[1]}` : pkg;
101
- } else {
102
- pkg = pkg.split("/")[0];
103
- }
104
- imports.add(pkg);
105
- }
106
- }
107
- } catch {}
108
- }
109
- }
110
- }
111
- }
112
-
113
- walk(projectRoot);
114
- return imports;
115
- }
116
-
117
- function checkUnused(pkg, usedImports) {
118
- const allDeps = new Set([
119
- ...Object.keys(pkg.dependencies || {}),
120
- ...Object.keys(pkg.devDependencies || {})
121
- ]);
122
-
123
- const implicitPackages = new Set([
124
- "typescript", "eslint", "prettier", "vitest", "jest", "ts-node",
125
- "@types/node", "@types/react", "tailwindcss", "postcss", "autoprefixer",
126
- "nodemon", "tsx", "vite", "next", "webpack", "babel", "@babel/core"
127
- ]);
128
-
129
- const unused = [];
130
- for (const d of allDeps) {
131
- if (!implicitPackages.has(d) && !d.startsWith("@types/") && !usedImports.has(d)) {
132
- unused.push(d);
133
- }
134
- }
135
- return unused.sort();
136
- }
137
-
138
- function checkPhantom(pkg, usedImports) {
139
- const allDeps = new Set([
140
- ...Object.keys(pkg.dependencies || {}),
141
- ...Object.keys(pkg.devDependencies || {})
142
- ]);
143
-
144
- const phantom = [];
145
- for (const imp of usedImports) {
146
- if (!NODE_BUILTINS.has(imp) && !allDeps.has(imp)) {
147
- phantom.push(imp);
148
- }
149
- }
150
- return phantom.sort();
151
- }
152
-
153
- function runNpmAudit(projectRoot) {
154
- try {
155
- const executable = process.platform === 'win32' ? 'npm.cmd' : 'npm';
156
- const result = spawnSync(executable, ["audit", "--json"], {
157
- cwd: projectRoot,
158
- encoding: 'utf8',
159
- timeout: 60000,
160
- shell: process.platform === 'win32'
161
- });
162
-
163
- try {
164
- const auditData = JSON.parse(result.stdout);
165
- const vulns = (auditData.metadata && auditData.metadata.vulnerabilities) || {};
166
- const critical = vulns.critical || 0;
167
- const high = vulns.high || 0;
168
- const moderate = vulns.moderate || 0;
169
- const low = vulns.low || 0;
170
-
171
- if (critical + high > 0) {
172
- fail(`npm audit: ${critical} critical, ${high} high, ${moderate} moderate, ${low} low`);
173
- return false;
174
- } else if (moderate + low > 0) {
175
- warn(`npm audit: ${moderate} moderate, ${low} low vulnerabilities`);
176
- return true;
177
- } else {
178
- ok("npm audit no known vulnerabilities");
179
- return true;
180
- }
181
- } catch {
182
- if (result.status === 0) {
183
- ok("npm audit — clean");
184
- return true;
185
- }
186
- fail("npm audit returned errors");
187
- return false;
188
- }
189
- } catch {
190
- skip("npm not installed — skipping audit");
191
- return true;
192
- }
193
- }
194
-
195
- function main() {
196
- const args = process.argv.slice(2);
197
- let targetPath = null;
198
- let auditFlag = false;
199
- let checkUnusedFlag = false;
200
-
201
- for (let i = 0; i < args.length; i++) {
202
- if (args[i] === '--audit') auditFlag = true;
203
- else if (args[i] === '--check-unused') checkUnusedFlag = true;
204
- else if (args[i] === '-h' || args[i] === '--help') {
205
- console.log("Usage: node dependency_analyzer.js <path> [--audit] [--check-unused]");
206
- process.exit(0);
207
- } else if (!args[i].startsWith('-') && !targetPath) {
208
- targetPath = args[i];
209
- }
210
- }
211
-
212
- if (!targetPath) {
213
- console.log("Usage: node dependency_analyzer.js <path> [--audit] [--check-unused]");
214
- process.exit(1);
215
- }
216
-
217
- const projectRoot = path.resolve(targetPath);
218
- if (!fs.existsSync(projectRoot) || !fs.statSync(projectRoot).isDirectory()) {
219
- fail(`Directory not found: ${projectRoot}`);
220
- process.exit(1);
221
- }
222
-
223
- console.log(`${BOLD}Tribunal dependency_analyzer.js${RESET}`);
224
- console.log(`Project: ${projectRoot}`);
225
-
226
- const pkg = loadPackageJson(projectRoot);
227
- if (!pkg) {
228
- skip("No package.json found — dependency analysis requires a Node.js project");
229
- process.exit(0);
230
- }
231
-
232
- let issues = 0;
233
- const usedImports = extractImports(projectRoot);
234
- console.log(`\n Found ${usedImports.size} unique external imports in source code`);
235
-
236
- if (!checkUnusedFlag) {
237
- header("Phantom Imports (not in package.json)");
238
- const phantom = checkPhantom(pkg, usedImports);
239
- if (phantom.length > 0) {
240
- for (const p of phantom) fail(`'${p}' is imported but not in package.json — possible hallucination`);
241
- issues += phantom.length;
242
- } else {
243
- ok("All imports found in package.json");
244
- }
245
- }
246
-
247
- header("Unused Dependencies");
248
- const unused = checkUnused(pkg, usedImports);
249
- if (unused.length > 0) {
250
- for (const u of unused) warn(`'${u}' is in package.json but never imported — may be unused`);
251
- } else {
252
- ok("No obviously unused dependencies found");
253
- }
254
-
255
- if (auditFlag) {
256
- header("Vulnerability Audit");
257
- if (!runNpmAudit(projectRoot)) issues += 1;
258
- }
259
-
260
- console.log(`\n${BOLD}━━━ Dependency Analysis Summary ━━━${RESET}`);
261
- if (issues === 0) {
262
- ok("All dependency checks passed");
263
- } else {
264
- fail(`${issues} issue(s) found — review above`);
265
- }
266
-
267
- process.exit(issues > 0 ? 1 : 0);
268
- }
269
-
270
- if (require.main === module) {
271
- main();
272
- }
1
+ #!/usr/bin/env node
2
+ /**
3
+ * dependency_analyzer.js — Dependency health checker for the Tribunal Agent Kit.
4
+ *
5
+ * Analyzes project dependencies for:
6
+ * - Unused packages (in package.json but never imported)
7
+ * - Phantom imports (imported but not in package.json)
8
+ * - npm audit / pip-audit results
9
+ * - Duplicate/overlapping packages
10
+ *
11
+ * Usage:
12
+ * node .agent/scripts/dependency_analyzer.js .
13
+ * node .agent/scripts/dependency_analyzer.js . --audit
14
+ * node .agent/scripts/dependency_analyzer.js . --check-unused
15
+ */
16
+
17
+ 'use strict';
18
+
19
+ const fs = require('fs');
20
+ const path = require('path');
21
+
22
+ const {
23
+ RED, GREEN, YELLOW, BLUE, BOLD, DIM, CYAN, RESET,
24
+ banner, sectionHeader, timer, formatMs,
25
+ ok, fail, warn, skip,
26
+ } = require('./_colors');
27
+
28
+ const { walkDir, loadJson, runCommand } = require('./_utils');
29
+
30
+ const SOURCE_EXTENSIONS = new Set([".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"]);
31
+
32
+ const NODE_BUILTINS = new Set([
33
+ "fs", "path", "os", "crypto", "http", "https", "url", "util",
34
+ "stream", "events", "child_process", "cluster", "net", "dns",
35
+ "tls", "readline", "zlib", "buffer", "querystring", "string_decoder",
36
+ "assert", "perf_hooks", "worker_threads", "timers", "v8",
37
+ "node:fs", "node:path", "node:os", "node:crypto", "node:http",
38
+ "node:https", "node:url", "node:util", "node:stream", "node:events",
39
+ "node:child_process", "node:net", "node:dns", "node:tls",
40
+ "node:readline", "node:zlib", "node:buffer", "node:assert",
41
+ "node:perf_hooks", "node:worker_threads", "node:timers"
42
+ ]);
43
+
44
+ function extractImports(projectRoot) {
45
+ const imports = new Set();
46
+ const importPatterns = [
47
+ /(?:import|export)\s+.*?\s+from\s+["']([^"'.][^"']*)["']/g,
48
+ /require\s*\(\s*["']([^"'.][^"']*)["']/g,
49
+ /import\s*\(\s*["']([^"'.][^"']*)["']/g
50
+ ];
51
+
52
+ // Use shared walkDir from _utils.js
53
+ const files = walkDir(projectRoot, { extensions: SOURCE_EXTENSIONS });
54
+
55
+ for (const fullPath of files) {
56
+ let content;
57
+ try { content = fs.readFileSync(fullPath, 'utf8'); } catch { continue; }
58
+
59
+ for (const pattern of importPatterns) {
60
+ // Reset regex state for each file
61
+ pattern.lastIndex = 0;
62
+ let match;
63
+ while ((match = pattern.exec(content)) !== null) {
64
+ let pkg = match[1];
65
+ if (pkg.startsWith("@")) {
66
+ const parts = pkg.split("/");
67
+ pkg = parts.length >= 2 ? `${parts[0]}/${parts[1]}` : pkg;
68
+ } else {
69
+ pkg = pkg.split("/")[0];
70
+ }
71
+ imports.add(pkg);
72
+ }
73
+ }
74
+ }
75
+
76
+ return imports;
77
+ }
78
+
79
+ function checkUnused(pkg, usedImports) {
80
+ const allDeps = new Set([
81
+ ...Object.keys(pkg.dependencies || {}),
82
+ ...Object.keys(pkg.devDependencies || {})
83
+ ]);
84
+
85
+ const implicitPackages = new Set([
86
+ "typescript", "eslint", "prettier", "vitest", "jest", "ts-node",
87
+ "@types/node", "@types/react", "tailwindcss", "postcss", "autoprefixer",
88
+ "nodemon", "tsx", "vite", "next", "webpack", "babel", "@babel/core"
89
+ ]);
90
+
91
+ const unused = [];
92
+ for (const d of allDeps) {
93
+ if (!implicitPackages.has(d) && !d.startsWith("@types/") && !usedImports.has(d)) {
94
+ unused.push(d);
95
+ }
96
+ }
97
+ return unused.sort();
98
+ }
99
+
100
+ function checkPhantom(pkg, usedImports) {
101
+ const allDeps = new Set([
102
+ ...Object.keys(pkg.dependencies || {}),
103
+ ...Object.keys(pkg.devDependencies || {})
104
+ ]);
105
+
106
+ const phantom = [];
107
+ for (const imp of usedImports) {
108
+ if (!NODE_BUILTINS.has(imp) && !allDeps.has(imp)) {
109
+ phantom.push(imp);
110
+ }
111
+ }
112
+ return phantom.sort();
113
+ }
114
+
115
+ function runNpmAudit(projectRoot) {
116
+ const result = runCommand('npm', ['audit', '--json'], {
117
+ cwd: projectRoot,
118
+ timeout: 60000,
119
+ });
120
+
121
+ if (result.status === null && !result.stdout) {
122
+ skip("npm not installed — skipping audit");
123
+ return true;
124
+ }
125
+
126
+ try {
127
+ const auditData = JSON.parse(result.stdout);
128
+ const vulns = (auditData.metadata && auditData.metadata.vulnerabilities) || {};
129
+ const critical = vulns.critical || 0;
130
+ const high = vulns.high || 0;
131
+ const moderate = vulns.moderate || 0;
132
+ const low = vulns.low || 0;
133
+
134
+ if (critical + high > 0) {
135
+ fail(`npm audit: ${critical} critical, ${high} high, ${moderate} moderate, ${low} low`);
136
+ return false;
137
+ } else if (moderate + low > 0) {
138
+ warn(`npm audit: ${moderate} moderate, ${low} low vulnerabilities`);
139
+ return true;
140
+ } else {
141
+ ok("npm audit — no known vulnerabilities");
142
+ return true;
143
+ }
144
+ } catch {
145
+ if (result.ok) {
146
+ ok("npm audit — clean");
147
+ return true;
148
+ }
149
+ fail("npm audit returned errors");
150
+ return false;
151
+ }
152
+ }
153
+
154
+ function main() {
155
+ const args = process.argv.slice(2);
156
+ let targetPath = null;
157
+ let auditFlag = false;
158
+ let checkUnusedFlag = false;
159
+
160
+ for (let i = 0; i < args.length; i++) {
161
+ if (args[i] === '--audit') auditFlag = true;
162
+ else if (args[i] === '--check-unused') checkUnusedFlag = true;
163
+ else if (args[i] === '-h' || args[i] === '--help') {
164
+ console.log("Usage: node dependency_analyzer.js <path> [--audit] [--check-unused]");
165
+ process.exit(0);
166
+ } else if (!args[i].startsWith('-') && !targetPath) {
167
+ targetPath = args[i];
168
+ }
169
+ }
170
+
171
+ if (!targetPath) {
172
+ console.log("Usage: node dependency_analyzer.js <path> [--audit] [--check-unused]");
173
+ process.exit(1);
174
+ }
175
+
176
+ const projectRoot = path.resolve(targetPath);
177
+ if (!fs.existsSync(projectRoot) || !fs.statSync(projectRoot).isDirectory()) {
178
+ fail(`Directory not found: ${projectRoot}`);
179
+ process.exit(1);
180
+ }
181
+
182
+ console.log(banner('dependency_analyzer.js', { Project: projectRoot }));
183
+
184
+ const pkg = loadJson(path.join(projectRoot, 'package.json'));
185
+ if (!pkg) {
186
+ skip("No package.json found — dependency analysis requires a Node.js project");
187
+ process.exit(0);
188
+ }
189
+
190
+ let issues = 0;
191
+ const elapsed = timer();
192
+ const usedImports = extractImports(projectRoot);
193
+ const scanMs = elapsed();
194
+
195
+ console.log(`\n ${DIM}Found ${usedImports.size} unique external imports in ${formatMs(scanMs)}${RESET}`);
196
+
197
+ if (!checkUnusedFlag) {
198
+ console.log(sectionHeader('Phantom Imports (not in package.json)'));
199
+ const phantom = checkPhantom(pkg, usedImports);
200
+ if (phantom.length > 0) {
201
+ for (const p of phantom) fail(`'${p}' is imported but not in package.json — possible hallucination`);
202
+ issues += phantom.length;
203
+ } else {
204
+ ok("All imports found in package.json");
205
+ }
206
+ }
207
+
208
+ console.log(sectionHeader('Unused Dependencies'));
209
+ const unused = checkUnused(pkg, usedImports);
210
+ if (unused.length > 0) {
211
+ for (const u of unused) warn(`'${u}' is in package.json but never imported — may be unused`);
212
+ } else {
213
+ ok("No obviously unused dependencies found");
214
+ }
215
+
216
+ if (auditFlag) {
217
+ console.log(sectionHeader('Vulnerability Audit'));
218
+ if (!runNpmAudit(projectRoot)) issues += 1;
219
+ }
220
+
221
+ console.log(`\n${BOLD}${CYAN}━━━ Dependency Analysis Summary ━━━${RESET}`);
222
+ if (issues === 0) {
223
+ ok("All dependency checks passed");
224
+ } else {
225
+ fail(`${issues} issue(s) found — review above`);
226
+ }
227
+ console.log();
228
+
229
+ process.exit(issues > 0 ? 1 : 0);
230
+ }
231
+
232
+ if (require.main === module) {
233
+ main();
234
+ }
@@ -10,6 +10,9 @@
10
10
 
11
11
  const fs = require('fs');
12
12
  const path = require('path');
13
+ const crypto = require('crypto');
14
+
15
+ const { RED, GREEN, BOLD, DIM, CYAN, RESET, timer, formatMs } = require('./_colors');
13
16
 
14
17
  const AGENT_DIR = path.join(process.cwd(), '.agent');
15
18
  const HISTORY_DIR = path.join(AGENT_DIR, 'history');
@@ -45,6 +48,12 @@ function isExcluded(filePath) {
45
48
  return false;
46
49
  }
47
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
+
48
57
  // ── Traversal ─────────────────────────────────────────────────────────────────
49
58
  function walkDir(dir, fileList = []) {
50
59
  if (!fs.existsSync(dir) || isExcluded(dir)) return fileList;
@@ -151,7 +160,7 @@ function generateYAML(data) {
151
160
  // ── Main Execution ────────────────────────────────────────────────────────────
152
161
  function main() {
153
162
  if (!fs.existsSync(AGENT_DIR)) {
154
- console.error('\x1b[31m✖ Error: .agent directory not found.\x1b[0m');
163
+ console.error(`${RED}✖ Error: .agent directory not found.${RESET}`);
155
164
  process.exit(1);
156
165
  }
157
166
 
@@ -162,18 +171,23 @@ function main() {
162
171
  try { cache = JSON.parse(fs.readFileSync(CACHE_FILE, 'utf8')); } catch { /* ignore */ }
163
172
  }
164
173
 
165
- console.log('\x1b[96m✦ Building Architecture Graph...\x1b[0m');
174
+ const totalTimer = timer();
175
+ console.log(`${CYAN}✦ Building Architecture Graph...${RESET}`);
166
176
  const files = walkDir(process.cwd());
167
177
  const graphData = {};
168
178
 
169
179
  let parsedCount = 0;
170
180
  let cachedCount = 0;
181
+ const changedFiles = new Set();
171
182
 
172
183
  for (const file of files) {
173
- const stat = fs.statSync(file);
174
184
  const relativePath = path.relative(process.cwd(), file).replace(/\\/g, '/');
185
+ let fileHash;
186
+ try {
187
+ fileHash = getFileHash(file);
188
+ } catch { continue; }
175
189
 
176
- if (cache[relativePath] && cache[relativePath].mtimeMs === stat.mtimeMs) {
190
+ if (cache[relativePath] && cache[relativePath].hash === fileHash) {
177
191
  graphData[relativePath] = { imports: cache[relativePath].imports, exports: cache[relativePath].exports };
178
192
  cachedCount++;
179
193
  } else {
@@ -183,11 +197,12 @@ function main() {
183
197
  graphData[relativePath] = parsed;
184
198
 
185
199
  cache[relativePath] = {
186
- mtimeMs: stat.mtimeMs,
200
+ hash: fileHash,
187
201
  imports: parsed.imports,
188
202
  exports: parsed.exports
189
203
  };
190
204
  parsedCount++;
205
+ changedFiles.add(relativePath);
191
206
  } catch { /* ignore */ }
192
207
  }
193
208
  }
@@ -247,24 +262,35 @@ function main() {
247
262
  fs.writeFileSync(CACHE_FILE, JSON.stringify(cache, null, 2));
248
263
  fs.writeFileSync(GRAPH_FILE, generateYAML(graphData));
249
264
 
250
- // ── Pre-Computed Context Snapshots (Option C) ───────────────────────────
265
+ // ── Pre-Computed Context Snapshots (Incremental) ─────────────────────────
251
266
  const SNAPSHOTS_DIR = path.join(HISTORY_DIR, 'snapshots');
252
267
  if (!fs.existsSync(SNAPSHOTS_DIR)) {
253
268
  fs.mkdirSync(SNAPSHOTS_DIR, { recursive: true });
254
- } else {
255
- // Clear stale snapshots
256
- try {
257
- const oldSnapshots = fs.readdirSync(SNAPSHOTS_DIR);
258
- for (const f of oldSnapshots) fs.unlinkSync(path.join(SNAPSHOTS_DIR, f));
259
- } catch { /* ignore */ }
260
269
  }
261
270
 
262
- console.log('\x1b[96m✦ Generating Context Snapshots...\x1b[0m');
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;
263
283
  for (const file of fileKeys) {
264
284
  const info = graphData[file];
265
285
  const snapshotFile = file.replace(/[\\/]/g, '__') + '.json';
266
286
  const snapshotPath = path.join(SNAPSHOTS_DIR, snapshotFile);
267
287
 
288
+ // Skip unchanged files that already have a snapshot
289
+ if (!changedFiles.has(file) && fs.existsSync(snapshotPath)) {
290
+ snapshotSkipped++;
291
+ continue;
292
+ }
293
+
268
294
  let content = '';
269
295
  try {
270
296
  content = fs.readFileSync(path.join(process.cwd(), file), 'utf8');
@@ -298,15 +324,17 @@ function main() {
298
324
  }
299
325
 
300
326
  fs.writeFileSync(snapshotPath, JSON.stringify(snapshot, null, 2));
327
+ snapshotWritten++;
301
328
  }
302
- console.log(` \x1b[2mSaved ${fileKeys.length} snapshots to: ${SNAPSHOTS_DIR}\x1b[0m`);
329
+ console.log(` ${DIM}Snapshots: ${snapshotWritten} written | ${snapshotSkipped} cached${RESET}`);
303
330
 
304
- console.log(`\n\x1b[32m✔ Graph successfully built.\x1b[0m`);
305
- console.log(` \x1b[2mParsed: ${parsedCount} files | Cached: ${cachedCount} files\x1b[0m`);
306
- console.log(` \x1b[2mSaved to: ${GRAPH_FILE}\x1b[0m`);
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}`);
307
335
  }
308
336
  // ── Exports (for testing & programmatic use) ─────────────────────────────────
309
- module.exports = { parseFile, generateYAML, walkDir, isExcluded, main };
337
+ module.exports = { parseFile, generateYAML, walkDir, isExcluded, getFileHash, main };
310
338
 
311
339
  if (require.main === module) {
312
340
  main();