@chappibunny/repolens 0.7.0 β†’ 0.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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,19 @@
2
2
 
3
3
  All notable changes to RepoLens will be documented in this file.
4
4
 
5
+ ## 0.8.0
6
+
7
+ ### ✨ New Features
8
+ - **GraphQL Schema Detection** (`src/analyzers/graphql-analyzer.js`): Detects `.graphql`/`.gql` schema files, inline SDL via gql tagged templates, 11 library patterns (Apollo, Yoga, Mercurius, Nexus, Pothos, type-graphql, Relay, urql, etc.), and resolver patterns. Parses queries, mutations, subscriptions, object types, enums, inputs, interfaces, unions, scalars, and directives.
9
+ - **TypeScript Type Graph Analysis** (`src/analyzers/typescript-analyzer.js`): Parses interfaces (with extends), type aliases (with reference extraction), classes (extends + implements), enums, and generic constraints. Builds relationship graph with deduplication, filtering to project-declared types only.
10
+ - **Dependency Graph with Cycle Detection** (`src/analyzers/dependency-graph.js`): Parses ES imports, dynamic imports, CommonJS require, and re-exports. Builds directed adjacency graph with cycle detection via iterative DFS (3-color marking). Tracks hub modules, orphan files, and external dependencies.
11
+ - **Architecture Drift Detection** (`src/analyzers/drift-detector.js`): Compares current architecture against stored baseline snapshots. Detects changes across 8 categories (modules, APIs, pages, dependencies, frameworks, circular deps, GraphQL types, file count). Categorizes drifts by severity: πŸ”΄ critical, 🟑 warning, 🟒 info. Baselines auto-saved to `.repolens/architecture-baseline.json`.
12
+ - **Extended Analysis Renderers** (`src/renderers/renderAnalysis.js`): Markdown renderers for all 4 new document types with tables, Unicode relationship trees, and severity-grouped reports.
13
+ - **4 New Document Types**: `graphql_schema`, `type_graph`, `dependency_graph`, `architecture_drift` β€” bringing total to 15 audience-aware documents.
14
+
15
+ ### πŸ§ͺ Tests
16
+ - Added 31 new tests for extended analysis features (121 tests across 12 files)
17
+
5
18
  ## 0.7.0
6
19
 
7
20
  ### ✨ New Features
package/README.md CHANGED
@@ -16,7 +16,7 @@
16
16
 
17
17
  AI-assisted documentation intelligence system that generates architecture docs for engineers AND readable system docs for stakeholders
18
18
 
19
- **Current Status**: v0.7.0 β€” Polish & Reliability
19
+ **Current Status**: v0.8.0 β€” Extended Analysis
20
20
 
21
21
  RepoLens automatically generates and maintains living architecture documentation by analyzing your repository structure, extracting meaningful insights from your package.json, and creating visual dependency graphs. Run it once, or let it auto-update on every push.
22
22
 
@@ -133,6 +133,10 @@ RepoLens automatically detects:
133
133
  βœ… **Interactive Setup** - Step-by-step configuration wizard (NEW in v0.7.0)
134
134
  βœ… **Performance Metrics** - Timing breakdown for scan/render/publish (NEW in v0.7.0)
135
135
  βœ… **Actionable Errors** - Enhanced error messages with fix guidance (NEW in v0.7.0)
136
+ βœ… **GraphQL Schema Detection** - Discover types, queries, mutations, and resolvers (NEW in v0.8.0)
137
+ βœ… **TypeScript Type Graph** - Map interfaces, classes, and type relationships (NEW in v0.8.0)
138
+ βœ… **Dependency Graph** - Import analysis with circular dependency detection (NEW in v0.8.0)
139
+ βœ… **Architecture Drift** - Track structural changes against a baseline (NEW in v0.8.0)
136
140
 
137
141
  ---
138
142
 
@@ -224,7 +228,7 @@ npm link
224
228
  Install from a specific version:
225
229
 
226
230
  ```bash
227
- npm install https://github.com/CHAPIBUNNY/repolens/releases/download/v0.7.0/chappibunny-repolens-0.7.0.tgz
231
+ npm install https://github.com/CHAPIBUNNY/repolens/releases/download/v0.8.0/chappibunny-repolens-0.8.0.tgz
228
232
  ```
229
233
  </details>
230
234
 
@@ -1077,7 +1081,7 @@ Simulates the full user installation experience:
1077
1081
  npm pack
1078
1082
 
1079
1083
  # Install globally from tarball
1080
- npm install -g chappibunny-repolens-0.7.0.tgz
1084
+ npm install -g chappibunny-repolens-0.8.0.tgz
1081
1085
 
1082
1086
  # Verify
1083
1087
  repolens --version
@@ -1101,9 +1105,13 @@ repolens/
1101
1105
  β”‚ β”‚ β”œβ”€β”€ diff.js # Git diff operations
1102
1106
  β”‚ β”‚ └── scan.js # Repository scanning + metadata extraction
1103
1107
  β”‚ β”œβ”€β”€ analyzers/
1104
- β”‚ β”‚ β”œβ”€β”€ domain-inference.js # Business domain mapping
1105
- β”‚ β”‚ β”œβ”€β”€ context-builder.js # Structured AI context assembly
1106
- β”‚ β”‚ └── flow-inference.js # Data flow detection
1108
+ β”‚ β”‚ β”œβ”€β”€ domain-inference.js # Business domain mapping
1109
+ β”‚ β”‚ β”œβ”€β”€ context-builder.js # Structured AI context assembly
1110
+ β”‚ β”‚ β”œβ”€β”€ flow-inference.js # Data flow detection
1111
+ β”‚ β”‚ β”œβ”€β”€ graphql-analyzer.js # GraphQL schema detection
1112
+ β”‚ β”‚ β”œβ”€β”€ typescript-analyzer.js # TypeScript type graph analysis
1113
+ β”‚ β”‚ β”œβ”€β”€ dependency-graph.js # Import graph with cycle detection
1114
+ β”‚ β”‚ └── drift-detector.js # Architecture drift detection
1107
1115
  β”‚ β”œβ”€β”€ ai/
1108
1116
  β”‚ β”‚ β”œβ”€β”€ provider.js # Provider-agnostic AI generation
1109
1117
  β”‚ β”‚ β”œβ”€β”€ prompts.js # Strict prompt templates
@@ -1113,9 +1121,10 @@ repolens/
1113
1121
  β”‚ β”‚ β”œβ”€β”€ generate-doc-set.js # Document generation orchestration
1114
1122
  β”‚ β”‚ └── write-doc-set.js # Write docs to disk
1115
1123
  β”‚ β”œβ”€β”€ renderers/
1116
- β”‚ β”‚ β”œβ”€β”€ render.js # System overview, catalog, API, routes
1117
- β”‚ β”‚ β”œβ”€β”€ renderDiff.js # Architecture diff rendering
1118
- β”‚ β”‚ └── renderMap.js # Unicode dependency diagrams
1124
+ β”‚ β”‚ β”œβ”€β”€ render.js # System overview, catalog, API, routes
1125
+ β”‚ β”‚ β”œβ”€β”€ renderDiff.js # Architecture diff rendering
1126
+ β”‚ β”‚ β”œβ”€β”€ renderMap.js # Unicode dependency diagrams
1127
+ β”‚ β”‚ └── renderAnalysis.js # Extended analysis renderers
1119
1128
  β”‚ β”œβ”€β”€ publishers/
1120
1129
  β”‚ β”‚ β”œβ”€β”€ index.js # Publisher orchestration + branch filtering
1121
1130
  β”‚ β”‚ β”œβ”€β”€ publish.js # Publishing pipeline
@@ -1137,7 +1146,7 @@ repolens/
1137
1146
  β”‚ β”œβ”€β”€ telemetry.js # Opt-in error tracking + performance timers
1138
1147
  β”‚ β”œβ”€β”€ errors.js # Enhanced error messages with guidance
1139
1148
  β”‚ └── update-check.js # Version update notifications
1140
- β”œβ”€β”€ tests/ # Vitest test suite (90 tests across 11 files)
1149
+ β”œβ”€β”€ tests/ # Vitest test suite (121 tests across 12 files)
1141
1150
  β”œβ”€β”€ .repolens.yml # Dogfooding config
1142
1151
  β”œβ”€β”€ package.json
1143
1152
  β”œβ”€β”€ CHANGELOG.md
@@ -1154,13 +1163,13 @@ RepoLens uses automated GitHub Actions releases.
1154
1163
  ### Creating a Release
1155
1164
 
1156
1165
  ```bash
1157
- # Patch version (0.7.0 β†’ 0.7.1) - Bug fixes
1166
+ # Patch version (0.8.0 β†’ 0.8.1) - Bug fixes
1158
1167
  npm run release:patch
1159
1168
 
1160
- # Minor version (0.7.0 β†’ 0.8.0) - New features
1169
+ # Minor version (0.8.0 β†’ 0.9.0) - New features
1161
1170
  npm run release:minor
1162
1171
 
1163
- # Major version (0.7.0 β†’ 1.0.0) - Breaking changes
1172
+ # Major version (0.8.0 β†’ 1.0.0) - Breaking changes
1164
1173
  npm run release:major
1165
1174
 
1166
1175
  # Push the tag to trigger workflow
@@ -1192,7 +1201,7 @@ RepoLens is currently in early access. v1.0 will open for community contribution
1192
1201
 
1193
1202
  ## πŸ—ΊοΈ Roadmap to v1.0
1194
1203
 
1195
- **Current Status:** v0.7.0 β€” Polish & Reliability
1204
+ **Current Status:** v0.8.0 β€” Extended Analysis
1196
1205
 
1197
1206
  ### Completed βœ…
1198
1207
 
@@ -1208,7 +1217,7 @@ RepoLens is currently in early access. v1.0 will open for community contribution
1208
1217
  - [x] GitHub Actions automation (publish + release)
1209
1218
  - [x] PR architecture diff comments
1210
1219
  - [x] Performance guardrails (10k warning, 50k limit)
1211
- - [x] Comprehensive test suite (90 tests across 11 files)
1220
+ - [x] Comprehensive test suite (121 tests across 12 files)
1212
1221
  - [x] Security hardening (secret detection, injection prevention, fuzzing)
1213
1222
  - [x] Discord notifications with rich embeds
1214
1223
  - [x] Documentation coverage & health scoring
@@ -1221,12 +1230,14 @@ RepoLens is currently in early access. v1.0 will open for community contribution
1221
1230
  - [x] Enhanced error messages with actionable guidance
1222
1231
  - [x] Performance monitoring (scan/render/publish timing)
1223
1232
  - [x] Improved documentation coverage scoring
1233
+ - [x] GraphQL schema detection (queries, mutations, types, resolvers)
1234
+ - [x] TypeScript type graph analysis (interfaces, classes, relationships)
1235
+ - [x] Dependency graph with circular dependency detection
1236
+ - [x] Architecture drift detection (baseline comparison)
1224
1237
 
1225
1238
  ### Planned for v1.0 🎯
1226
1239
 
1227
1240
  - [ ] Plugin system for custom renderers
1228
- - [ ] GraphQL schema detection
1229
- - [ ] TypeScript type graph analysis
1230
1241
  - [ ] Additional publishers (GitHub Wiki, Obsidian)
1231
1242
 
1232
1243
  See [ROADMAP.md](./ROADMAP.md) for detailed planning.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chappibunny/repolens",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "AI-assisted documentation intelligence system for technical and non-technical audiences",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -88,6 +88,38 @@ export const DOCUMENT_PLAN = [
88
88
  audience: "technical",
89
89
  ai: true,
90
90
  description: "Quick start guide for new developers"
91
+ },
92
+ {
93
+ key: "graphql_schema",
94
+ filename: "11-graphql-schema.md",
95
+ title: "GraphQL Schema",
96
+ audience: "technical",
97
+ ai: false,
98
+ description: "GraphQL types, queries, mutations, and resolver map"
99
+ },
100
+ {
101
+ key: "type_graph",
102
+ filename: "12-type-graph.md",
103
+ title: "TypeScript Type Graph",
104
+ audience: "technical",
105
+ ai: false,
106
+ description: "TypeScript interfaces, types, classes, and relationships"
107
+ },
108
+ {
109
+ key: "dependency_graph",
110
+ filename: "13-dependency-graph.md",
111
+ title: "Dependency Graph",
112
+ audience: "technical",
113
+ ai: false,
114
+ description: "Module dependency analysis with cycle detection"
115
+ },
116
+ {
117
+ key: "architecture_drift",
118
+ filename: "14-architecture-drift.md",
119
+ title: "Architecture Drift",
120
+ audience: "mixed",
121
+ ai: false,
122
+ description: "Structural changes compared to baseline snapshot"
91
123
  }
92
124
  ];
93
125
 
@@ -0,0 +1,254 @@
1
+ // Dependency graph analysis with cycle detection
2
+ // Parses import/require statements, builds a directed graph, detects cycles via DFS
3
+
4
+ import fs from "node:fs/promises";
5
+ import path from "node:path";
6
+ import { info, warn } from "../utils/logger.js";
7
+
8
+ const CODE_EXTENSIONS = new Set([".js", ".ts", ".jsx", ".tsx", ".mjs", ".cjs"]);
9
+
10
+ // Patterns for extracting imports
11
+ const IMPORT_PATTERNS = [
12
+ // ES module: import ... from "..."
13
+ /import\s+(?:[\w*{},\s]+\s+from\s+)?['"]([^'"]+)['"]/g,
14
+ // Dynamic import: import("...")
15
+ /import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,
16
+ // CommonJS: require("...")
17
+ /require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,
18
+ // Re-export: export ... from "..."
19
+ /export\s+(?:[\w*{},\s]+\s+from\s+)?['"]([^'"]+)['"]/g,
20
+ ];
21
+
22
+ async function readFileSafe(filePath) {
23
+ try {
24
+ return await fs.readFile(filePath, "utf8");
25
+ } catch {
26
+ return "";
27
+ }
28
+ }
29
+
30
+ function isRelativeImport(specifier) {
31
+ return specifier.startsWith("./") || specifier.startsWith("../");
32
+ }
33
+
34
+ function resolveImportPath(importerFile, specifier) {
35
+ // Only resolve relative imports β€” skip node_modules / bare specifiers
36
+ if (!isRelativeImport(specifier)) return null;
37
+
38
+ const importerDir = path.dirname(importerFile);
39
+ let resolved = path.posix.join(importerDir, specifier);
40
+
41
+ // Normalize path separators
42
+ resolved = resolved.replace(/\\/g, "/");
43
+
44
+ // Strip known extensions for dedup β€” we normalize to extensionless keys
45
+ resolved = resolved.replace(/\.(js|ts|jsx|tsx|mjs|cjs)$/, "");
46
+
47
+ // Strip /index suffix
48
+ resolved = resolved.replace(/\/index$/, "");
49
+
50
+ return resolved;
51
+ }
52
+
53
+ function normalizeFileKey(file) {
54
+ // Normalize a source file to a key that can match resolved imports
55
+ let key = file.replace(/\\/g, "/");
56
+ key = key.replace(/\.(js|ts|jsx|tsx|mjs|cjs)$/, "");
57
+ key = key.replace(/\/index$/, "");
58
+ return key;
59
+ }
60
+
61
+ export async function analyzeDependencyGraph(files, repoRoot) {
62
+ const result = {
63
+ nodes: [], // { key, file, imports: string[], importedBy: string[] }
64
+ edges: [], // { from, to }
65
+ cycles: [], // [ [a, b, c, a], ... ]
66
+ externalDeps: [],// sorted unique bare-specifier imports
67
+ stats: null,
68
+ summary: null,
69
+ };
70
+
71
+ const codeFiles = files.filter(f => {
72
+ const ext = path.extname(f);
73
+ return CODE_EXTENSIONS.has(ext);
74
+ });
75
+
76
+ if (codeFiles.length === 0) return result;
77
+
78
+ // Build adjacency: fileKey β†’ Set<fileKey>
79
+ const adjacency = new Map();
80
+ const fileKeyToFile = new Map();
81
+ const allFileKeys = new Set();
82
+ const externalSet = new Set();
83
+
84
+ // Register all known file keys
85
+ for (const file of codeFiles) {
86
+ const key = normalizeFileKey(file);
87
+ allFileKeys.add(key);
88
+ fileKeyToFile.set(key, file);
89
+ if (!adjacency.has(key)) adjacency.set(key, new Set());
90
+ }
91
+
92
+ // Parse imports and build edges
93
+ for (const file of codeFiles) {
94
+ const content = await readFileSafe(path.join(repoRoot, file));
95
+ if (!content) continue;
96
+
97
+ const fromKey = normalizeFileKey(file);
98
+
99
+ for (const pattern of IMPORT_PATTERNS) {
100
+ // Reset lastIndex since we reuse regex objects
101
+ const regex = new RegExp(pattern.source, pattern.flags);
102
+ let match;
103
+ while ((match = regex.exec(content)) !== null) {
104
+ const specifier = match[1];
105
+
106
+ if (isRelativeImport(specifier)) {
107
+ const resolved = resolveImportPath(file, specifier);
108
+ if (resolved && allFileKeys.has(resolved)) {
109
+ adjacency.get(fromKey).add(resolved);
110
+ }
111
+ } else if (!specifier.startsWith("node:")) {
112
+ // Bare specifier β†’ external dependency
113
+ // Normalize scoped packages: @scope/pkg/path β†’ @scope/pkg
114
+ const parts = specifier.startsWith("@") ? specifier.split("/").slice(0, 2) : specifier.split("/").slice(0, 1);
115
+ externalSet.add(parts.join("/"));
116
+ }
117
+ }
118
+ }
119
+ }
120
+
121
+ // Build nodes and edges
122
+ const importedByMap = new Map();
123
+ for (const key of allFileKeys) {
124
+ importedByMap.set(key, []);
125
+ }
126
+
127
+ for (const [fromKey, deps] of adjacency) {
128
+ for (const toKey of deps) {
129
+ result.edges.push({ from: fromKey, to: toKey });
130
+ if (importedByMap.has(toKey)) {
131
+ importedByMap.get(toKey).push(fromKey);
132
+ }
133
+ }
134
+ }
135
+
136
+ for (const key of allFileKeys) {
137
+ result.nodes.push({
138
+ key,
139
+ file: fileKeyToFile.get(key) || key,
140
+ imports: [...(adjacency.get(key) || [])],
141
+ importedBy: importedByMap.get(key) || [],
142
+ });
143
+ }
144
+
145
+ result.externalDeps = [...externalSet].sort();
146
+
147
+ // Detect cycles using iterative DFS (Tarjan-lite / coloring)
148
+ result.cycles = detectCycles(adjacency);
149
+
150
+ // Stats
151
+ const totalImports = result.edges.length;
152
+ const orphans = result.nodes.filter(n => n.imports.length === 0 && n.importedBy.length === 0);
153
+ const hubThreshold = Math.max(5, Math.floor(result.nodes.length * 0.1));
154
+ const hubs = result.nodes
155
+ .filter(n => n.importedBy.length >= hubThreshold)
156
+ .sort((a, b) => b.importedBy.length - a.importedBy.length)
157
+ .slice(0, 10)
158
+ .map(n => ({ key: n.key, importedBy: n.importedBy.length }));
159
+
160
+ result.stats = {
161
+ totalFiles: codeFiles.length,
162
+ totalEdges: totalImports,
163
+ externalDeps: result.externalDeps.length,
164
+ cycles: result.cycles.length,
165
+ orphanFiles: orphans.length,
166
+ hubs,
167
+ };
168
+
169
+ result.summary = buildSummary(result);
170
+
171
+ if (result.cycles.length > 0) {
172
+ warn(`Dependency graph: ${result.cycles.length} circular dependency cycle(s) detected`);
173
+ } else {
174
+ info(`Dependency graph: ${totalImports} edges across ${codeFiles.length} files, no cycles`);
175
+ }
176
+
177
+ return result;
178
+ }
179
+
180
+ /**
181
+ * Detect all cycles in a directed graph using DFS with 3-color marking.
182
+ * Returns an array of cycle paths (each path ends where it started).
183
+ */
184
+ function detectCycles(adjacency) {
185
+ const WHITE = 0, GRAY = 1, BLACK = 2;
186
+ const color = new Map();
187
+ const parent = new Map();
188
+ const cycles = [];
189
+
190
+ for (const node of adjacency.keys()) {
191
+ color.set(node, WHITE);
192
+ }
193
+
194
+ for (const startNode of adjacency.keys()) {
195
+ if (color.get(startNode) !== WHITE) continue;
196
+
197
+ // Iterative DFS
198
+ const stack = [{ node: startNode, neighbors: [...(adjacency.get(startNode) || [])], idx: 0 }];
199
+ color.set(startNode, GRAY);
200
+ parent.set(startNode, null);
201
+
202
+ while (stack.length > 0) {
203
+ const frame = stack[stack.length - 1];
204
+
205
+ if (frame.idx >= frame.neighbors.length) {
206
+ // All neighbors processed β€” mark black and backtrack
207
+ color.set(frame.node, BLACK);
208
+ stack.pop();
209
+ continue;
210
+ }
211
+
212
+ const neighbor = frame.neighbors[frame.idx++];
213
+
214
+ if (color.get(neighbor) === GRAY) {
215
+ // Back edge β†’ cycle found. Reconstruct the cycle path.
216
+ const cyclePath = [neighbor];
217
+ for (let i = stack.length - 1; i >= 0; i--) {
218
+ cyclePath.push(stack[i].node);
219
+ if (stack[i].node === neighbor) break;
220
+ }
221
+ cyclePath.reverse();
222
+ // Only keep reasonably short cycles to avoid noise
223
+ if (cyclePath.length <= 20) {
224
+ cycles.push(cyclePath);
225
+ }
226
+ // Cap cycles to prevent runaway in huge graphs
227
+ if (cycles.length >= 50) return cycles;
228
+ } else if (color.get(neighbor) === WHITE) {
229
+ color.set(neighbor, GRAY);
230
+ parent.set(neighbor, frame.node);
231
+ stack.push({ node: neighbor, neighbors: [...(adjacency.get(neighbor) || [])], idx: 0 });
232
+ }
233
+ }
234
+ }
235
+
236
+ return cycles;
237
+ }
238
+
239
+ function buildSummary(result) {
240
+ const parts = [
241
+ `${result.stats.totalFiles} files`,
242
+ `${result.stats.totalEdges} imports`,
243
+ `${result.stats.externalDeps} external packages`,
244
+ ];
245
+ if (result.stats.cycles > 0) {
246
+ parts.push(`⚠️ ${result.stats.cycles} circular dependency cycle(s)`);
247
+ } else {
248
+ parts.push("βœ“ no circular dependencies");
249
+ }
250
+ if (result.stats.orphanFiles > 0) {
251
+ parts.push(`${result.stats.orphanFiles} orphan file(s)`);
252
+ }
253
+ return parts.join(" Β· ");
254
+ }
@@ -0,0 +1,226 @@
1
+ // Architecture drift detection
2
+ // Compares current scan snapshot against a stored reference baseline
3
+ // Flags structural changes: new/removed modules, dependency shifts, API surface changes
4
+
5
+ import fs from "node:fs/promises";
6
+ import path from "node:path";
7
+ import { info, warn } from "../utils/logger.js";
8
+
9
+ const BASELINE_FILENAME = "architecture-baseline.json";
10
+
11
+ /**
12
+ * Save the current architecture state as a baseline for future drift detection.
13
+ * @param {object} snapshot - The architecture snapshot to save
14
+ * @param {string} outputDir - Directory to save the baseline (typically .repolens/)
15
+ */
16
+ export async function saveBaseline(snapshot, outputDir) {
17
+ const baselinePath = path.join(outputDir, BASELINE_FILENAME);
18
+ const baseline = {
19
+ version: 1,
20
+ timestamp: new Date().toISOString(),
21
+ ...snapshot,
22
+ };
23
+ await fs.mkdir(outputDir, { recursive: true });
24
+ await fs.writeFile(baselinePath, JSON.stringify(baseline, null, 2), "utf8");
25
+ info(`Architecture baseline saved to ${baselinePath}`);
26
+ return baselinePath;
27
+ }
28
+
29
+ /**
30
+ * Load a previously saved baseline. Returns null if none exists.
31
+ */
32
+ export async function loadBaseline(outputDir) {
33
+ const baselinePath = path.join(outputDir, BASELINE_FILENAME);
34
+ try {
35
+ const raw = await fs.readFile(baselinePath, "utf8");
36
+ return JSON.parse(raw);
37
+ } catch {
38
+ return null;
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Build an architecture snapshot from scan results and analysis outputs.
44
+ * This is the canonical representation used for drift comparison.
45
+ */
46
+ export function buildSnapshot(scanResult, depGraph, graphqlResult, tsResult) {
47
+ return {
48
+ modules: (scanResult.modules || []).map(m => m.key).sort(),
49
+ moduleFileCounts: Object.fromEntries(
50
+ (scanResult.modules || []).map(m => [m.key, m.fileCount])
51
+ ),
52
+ filesCount: scanResult.filesCount || 0,
53
+ apiEndpoints: (scanResult.api || []).map(a => `${a.methods.join(",")}:${a.path}`).sort(),
54
+ pages: (scanResult.pages || []).map(p => p.path).sort(),
55
+ externalApis: (scanResult.externalApis || []).map(e => e.name).sort(),
56
+ frameworks: scanResult.metadata?.frameworks || [],
57
+ depGraphEdgeCount: depGraph?.edges?.length || 0,
58
+ depGraphCycleCount: depGraph?.cycles?.length || 0,
59
+ externalDeps: depGraph?.externalDeps || [],
60
+ graphqlTypes: graphqlResult?.detected ? graphqlResult.types.map(t => t.name).sort() : [],
61
+ graphqlQueries: graphqlResult?.detected ? graphqlResult.queries.map(q => q.name).sort() : [],
62
+ graphqlMutations: graphqlResult?.detected ? graphqlResult.mutations.map(m => m.name).sort() : [],
63
+ tsInterfaces: tsResult?.detected ? tsResult.interfaces.map(i => i.name).sort() : [],
64
+ tsClasses: tsResult?.detected ? tsResult.classes.map(c => c.name).sort() : [],
65
+ };
66
+ }
67
+
68
+ /**
69
+ * Compare a current snapshot against a stored baseline and produce drift analysis.
70
+ */
71
+ export function detectDrift(baseline, current) {
72
+ if (!baseline) {
73
+ return {
74
+ hasBaseline: false,
75
+ drifts: [],
76
+ summary: "No baseline found. Run `repolens publish` once to establish a baseline.",
77
+ };
78
+ }
79
+
80
+ const drifts = [];
81
+
82
+ // Module drift
83
+ const baseModules = new Set(baseline.modules || []);
84
+ const currModules = new Set(current.modules || []);
85
+ const addedModules = [...currModules].filter(m => !baseModules.has(m));
86
+ const removedModules = [...baseModules].filter(m => !currModules.has(m));
87
+ if (addedModules.length > 0) {
88
+ drifts.push({ category: "modules", type: "added", items: addedModules, severity: "info" });
89
+ }
90
+ if (removedModules.length > 0) {
91
+ drifts.push({ category: "modules", type: "removed", items: removedModules, severity: "warning" });
92
+ }
93
+
94
+ // Significant module size changes (>50% file count change)
95
+ for (const mod of current.modules || []) {
96
+ const baseCount = baseline.moduleFileCounts?.[mod] || 0;
97
+ const currCount = current.moduleFileCounts?.[mod] || 0;
98
+ if (baseCount > 0 && currCount > 0) {
99
+ const changeRatio = Math.abs(currCount - baseCount) / baseCount;
100
+ if (changeRatio > 0.5) {
101
+ drifts.push({
102
+ category: "modules",
103
+ type: "size-change",
104
+ items: [`${mod}: ${baseCount} β†’ ${currCount} files (${changeRatio > 0 ? "+" : ""}${Math.round(changeRatio * 100)}%)`],
105
+ severity: changeRatio > 1.0 ? "warning" : "info",
106
+ });
107
+ }
108
+ }
109
+ }
110
+
111
+ // API endpoint drift
112
+ const baseApis = new Set(baseline.apiEndpoints || []);
113
+ const currApis = new Set(current.apiEndpoints || []);
114
+ const addedApis = [...currApis].filter(a => !baseApis.has(a));
115
+ const removedApis = [...baseApis].filter(a => !currApis.has(a));
116
+ if (addedApis.length > 0) {
117
+ drifts.push({ category: "api", type: "added", items: addedApis, severity: "info" });
118
+ }
119
+ if (removedApis.length > 0) {
120
+ drifts.push({ category: "api", type: "removed", items: removedApis, severity: "warning" });
121
+ }
122
+
123
+ // Page drift
124
+ const basePages = new Set(baseline.pages || []);
125
+ const currPages = new Set(current.pages || []);
126
+ const addedPages = [...currPages].filter(p => !basePages.has(p));
127
+ const removedPages = [...basePages].filter(p => !currPages.has(p));
128
+ if (addedPages.length > 0) {
129
+ drifts.push({ category: "pages", type: "added", items: addedPages, severity: "info" });
130
+ }
131
+ if (removedPages.length > 0) {
132
+ drifts.push({ category: "pages", type: "removed", items: removedPages, severity: "warning" });
133
+ }
134
+
135
+ // External dependency drift
136
+ const baseDeps = new Set(baseline.externalDeps || []);
137
+ const currDeps = new Set(current.externalDeps || []);
138
+ const addedDeps = [...currDeps].filter(d => !baseDeps.has(d));
139
+ const removedDeps = [...baseDeps].filter(d => !currDeps.has(d));
140
+ if (addedDeps.length > 0) {
141
+ drifts.push({ category: "dependencies", type: "added", items: addedDeps, severity: "info" });
142
+ }
143
+ if (removedDeps.length > 0) {
144
+ drifts.push({ category: "dependencies", type: "removed", items: removedDeps, severity: "warning" });
145
+ }
146
+
147
+ // Framework changes
148
+ const baseFrameworks = new Set(baseline.frameworks || []);
149
+ const currFrameworks = new Set(current.frameworks || []);
150
+ const addedFrameworks = [...currFrameworks].filter(f => !baseFrameworks.has(f));
151
+ const removedFrameworks = [...baseFrameworks].filter(f => !currFrameworks.has(f));
152
+ if (addedFrameworks.length > 0) {
153
+ drifts.push({ category: "frameworks", type: "added", items: addedFrameworks, severity: "info" });
154
+ }
155
+ if (removedFrameworks.length > 0) {
156
+ drifts.push({ category: "frameworks", type: "removed", items: removedFrameworks, severity: "critical" });
157
+ }
158
+
159
+ // Circular dependency drift
160
+ const baseCycles = baseline.depGraphCycleCount || 0;
161
+ const currCycles = current.depGraphCycleCount || 0;
162
+ if (currCycles > baseCycles) {
163
+ drifts.push({
164
+ category: "cycles",
165
+ type: "increased",
166
+ items: [`${baseCycles} β†’ ${currCycles} circular dependencies`],
167
+ severity: "warning",
168
+ });
169
+ } else if (currCycles < baseCycles) {
170
+ drifts.push({
171
+ category: "cycles",
172
+ type: "decreased",
173
+ items: [`${baseCycles} β†’ ${currCycles} circular dependencies`],
174
+ severity: "info",
175
+ });
176
+ }
177
+
178
+ // GraphQL schema drift
179
+ const baseGqlTypes = new Set(baseline.graphqlTypes || []);
180
+ const currGqlTypes = new Set(current.graphqlTypes || []);
181
+ const addedTypes = [...currGqlTypes].filter(t => !baseGqlTypes.has(t));
182
+ const removedTypes = [...baseGqlTypes].filter(t => !currGqlTypes.has(t));
183
+ if (addedTypes.length > 0 || removedTypes.length > 0) {
184
+ drifts.push({
185
+ category: "graphql",
186
+ type: "schema-changed",
187
+ items: [
188
+ ...(addedTypes.length ? [`+${addedTypes.length} types: ${addedTypes.join(", ")}`] : []),
189
+ ...(removedTypes.length ? [`-${removedTypes.length} types: ${removedTypes.join(", ")}`] : []),
190
+ ],
191
+ severity: removedTypes.length > 0 ? "warning" : "info",
192
+ });
193
+ }
194
+
195
+ // Overall file count change
196
+ const baseFiles = baseline.filesCount || 0;
197
+ const currFiles = current.filesCount || 0;
198
+ if (baseFiles > 0 && currFiles > 0) {
199
+ const fileChange = Math.abs(currFiles - baseFiles) / baseFiles;
200
+ if (fileChange > 0.2) {
201
+ drifts.push({
202
+ category: "scale",
203
+ type: "file-count-change",
204
+ items: [`${baseFiles} β†’ ${currFiles} files (${currFiles > baseFiles ? "+" : ""}${Math.round(fileChange * 100)}%)`],
205
+ severity: fileChange > 0.5 ? "warning" : "info",
206
+ });
207
+ }
208
+ }
209
+
210
+ const summary = drifts.length === 0
211
+ ? "No architecture drift detected since last baseline."
212
+ : `${drifts.length} drift(s) detected: ${drifts.filter(d => d.severity === "critical").length} critical, ${drifts.filter(d => d.severity === "warning").length} warning(s), ${drifts.filter(d => d.severity === "info").length} informational`;
213
+
214
+ if (drifts.length > 0) {
215
+ warn(`Architecture drift: ${summary}`);
216
+ } else {
217
+ info("Architecture drift: no drift detected");
218
+ }
219
+
220
+ return {
221
+ hasBaseline: true,
222
+ baselineTimestamp: baseline.timestamp,
223
+ drifts,
224
+ summary,
225
+ };
226
+ }