cto-ai-cli 1.3.0 → 3.0.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/DOCS.md +351 -0
- package/README.md +189 -263
- package/dist/action/index.js +25730 -0
- package/dist/api/dashboard.js +2073 -0
- package/dist/api/dashboard.js.map +1 -0
- package/dist/api/server.js +3401 -0
- package/dist/api/server.js.map +1 -0
- package/dist/cli/score.js +1971 -0
- package/dist/cli/v2/index.d.ts +2 -0
- package/dist/cli/v2/index.js +3496 -0
- package/dist/cli/v2/index.js.map +1 -0
- package/dist/engine/index.d.ts +816 -0
- package/dist/engine/index.js +4997 -0
- package/dist/engine/index.js.map +1 -0
- package/dist/govern/index.d.ts +261 -0
- package/dist/govern/index.js +662 -0
- package/dist/govern/index.js.map +1 -0
- package/dist/interact/index.d.ts +234 -0
- package/dist/interact/index.js +1343 -0
- package/dist/interact/index.js.map +1 -0
- package/dist/mcp/v2.d.ts +2 -0
- package/dist/mcp/v2.js +18289 -0
- package/dist/mcp/v2.js.map +1 -0
- package/package.json +55 -25
|
@@ -0,0 +1,2073 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/api/dashboard.ts
|
|
4
|
+
import { resolve as resolve5, join as join5 } from "path";
|
|
5
|
+
import { writeFile, mkdir, readFile as readFile5 } from "fs/promises";
|
|
6
|
+
|
|
7
|
+
// src/engine/analyzer.ts
|
|
8
|
+
import { readFile as readFile2, readdir, stat as stat2 } from "fs/promises";
|
|
9
|
+
import { join as join2, extname, relative as relative2, resolve as resolve2, basename as basename2 } from "path";
|
|
10
|
+
import { createHash } from "crypto";
|
|
11
|
+
|
|
12
|
+
// src/types/engine.ts
|
|
13
|
+
var DEFAULT_RISK_WEIGHTS = {
|
|
14
|
+
hub: 30,
|
|
15
|
+
typeProvider: 25,
|
|
16
|
+
complexity: 15,
|
|
17
|
+
recency: 15,
|
|
18
|
+
config: 10,
|
|
19
|
+
churn: 5
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
// src/types/config.ts
|
|
23
|
+
var DEFAULT_CONFIG = {
|
|
24
|
+
version: "2.0",
|
|
25
|
+
analysis: {
|
|
26
|
+
extensions: {
|
|
27
|
+
code: ["ts", "tsx", "js", "jsx", "py", "go", "rs", "java", "kt", "rb", "php", "c", "cpp", "h", "hpp", "cs"],
|
|
28
|
+
config: ["json", "yml", "yaml", "toml"],
|
|
29
|
+
docs: ["md", "txt", "rst"]
|
|
30
|
+
},
|
|
31
|
+
ignore: {
|
|
32
|
+
dirs: ["node_modules", "dist", "build", ".git", "coverage", "__pycache__", ".next", "vendor", ".cto"],
|
|
33
|
+
patterns: ["*.min.js", "*.map", "*.lock", "*.generated.*"]
|
|
34
|
+
},
|
|
35
|
+
maxDepth: 20
|
|
36
|
+
},
|
|
37
|
+
risk: {
|
|
38
|
+
weights: {
|
|
39
|
+
hub: 30,
|
|
40
|
+
typeProvider: 25,
|
|
41
|
+
complexity: 15,
|
|
42
|
+
recency: 15,
|
|
43
|
+
config: 10,
|
|
44
|
+
churn: 5
|
|
45
|
+
}
|
|
46
|
+
},
|
|
47
|
+
interaction: {
|
|
48
|
+
defaultBudget: 5e4,
|
|
49
|
+
defaultModel: "claude-sonnet-4"
|
|
50
|
+
},
|
|
51
|
+
tokens: {
|
|
52
|
+
method: "chars4"
|
|
53
|
+
},
|
|
54
|
+
governance: {
|
|
55
|
+
auditEnabled: true,
|
|
56
|
+
secretDetection: true,
|
|
57
|
+
retentionDays: 90
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
// src/engine/tokenizer.ts
|
|
62
|
+
import { encodingForModel } from "js-tiktoken";
|
|
63
|
+
import { readFile, stat } from "fs/promises";
|
|
64
|
+
var CHARS_PER_TOKEN = 4;
|
|
65
|
+
var encoder = null;
|
|
66
|
+
function getEncoder() {
|
|
67
|
+
if (!encoder) {
|
|
68
|
+
encoder = encodingForModel("claude-3-5-sonnet-20241022");
|
|
69
|
+
}
|
|
70
|
+
return encoder;
|
|
71
|
+
}
|
|
72
|
+
function countTokensTiktoken(text) {
|
|
73
|
+
try {
|
|
74
|
+
const enc = getEncoder();
|
|
75
|
+
const tokens = enc.encode(text);
|
|
76
|
+
return tokens.length;
|
|
77
|
+
} catch {
|
|
78
|
+
return Math.ceil(text.length / CHARS_PER_TOKEN);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
function countTokensChars4(sizeInBytes) {
|
|
82
|
+
return Math.ceil(sizeInBytes / CHARS_PER_TOKEN);
|
|
83
|
+
}
|
|
84
|
+
function estimateTokens(content, sizeInBytes, method = "chars4") {
|
|
85
|
+
if (method === "tiktoken") {
|
|
86
|
+
return countTokensTiktoken(content);
|
|
87
|
+
}
|
|
88
|
+
return countTokensChars4(sizeInBytes);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// src/engine/graph.ts
|
|
92
|
+
import { Project, SyntaxKind } from "ts-morph";
|
|
93
|
+
import { resolve, relative, dirname, join } from "path";
|
|
94
|
+
import { existsSync } from "fs";
|
|
95
|
+
var TS_EXTENSIONS = /* @__PURE__ */ new Set(["ts", "tsx", "js", "jsx", "mts", "mjs", "cts", "cjs"]);
|
|
96
|
+
function createProject(projectPath, filePaths) {
|
|
97
|
+
const tsConfigPath = join(projectPath, "tsconfig.json");
|
|
98
|
+
const hasTsConfig = existsSync(tsConfigPath);
|
|
99
|
+
const project = new Project({
|
|
100
|
+
tsConfigFilePath: hasTsConfig ? tsConfigPath : void 0,
|
|
101
|
+
skipAddingFilesFromTsConfig: true,
|
|
102
|
+
compilerOptions: hasTsConfig ? void 0 : {
|
|
103
|
+
allowJs: true,
|
|
104
|
+
jsx: 4,
|
|
105
|
+
// JsxEmit.ReactJSX
|
|
106
|
+
esModuleInterop: true,
|
|
107
|
+
moduleResolution: 100
|
|
108
|
+
// Bundler
|
|
109
|
+
}
|
|
110
|
+
});
|
|
111
|
+
const tsFiles = filePaths.filter((f) => {
|
|
112
|
+
const ext = f.split(".").pop()?.toLowerCase() ?? "";
|
|
113
|
+
return TS_EXTENSIONS.has(ext);
|
|
114
|
+
});
|
|
115
|
+
for (const filePath of tsFiles) {
|
|
116
|
+
try {
|
|
117
|
+
project.addSourceFileAtPath(filePath);
|
|
118
|
+
} catch {
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return project;
|
|
122
|
+
}
|
|
123
|
+
function buildProjectGraph(projectPath, files) {
|
|
124
|
+
const absPath = resolve(projectPath);
|
|
125
|
+
const tsFiles = files.filter((f) => TS_EXTENSIONS.has(f.extension)).map((f) => f.path);
|
|
126
|
+
if (tsFiles.length === 0) {
|
|
127
|
+
return emptyGraph(files);
|
|
128
|
+
}
|
|
129
|
+
let project;
|
|
130
|
+
try {
|
|
131
|
+
project = createProject(projectPath, tsFiles);
|
|
132
|
+
} catch {
|
|
133
|
+
return emptyGraph(files);
|
|
134
|
+
}
|
|
135
|
+
const edges = [];
|
|
136
|
+
const nodeSet = /* @__PURE__ */ new Set();
|
|
137
|
+
for (const sourceFile of project.getSourceFiles()) {
|
|
138
|
+
const fromRel = relative(absPath, sourceFile.getFilePath());
|
|
139
|
+
if (fromRel.startsWith("..") || fromRel.includes("node_modules")) continue;
|
|
140
|
+
nodeSet.add(fromRel);
|
|
141
|
+
for (const imp of sourceFile.getImportDeclarations()) {
|
|
142
|
+
const moduleSpecifier = imp.getModuleSpecifierValue();
|
|
143
|
+
const resolved = resolveImport(sourceFile, moduleSpecifier, absPath);
|
|
144
|
+
if (resolved) {
|
|
145
|
+
nodeSet.add(resolved);
|
|
146
|
+
edges.push({ from: fromRel, to: resolved, type: "import" });
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
for (const exp of sourceFile.getExportDeclarations()) {
|
|
150
|
+
const moduleSpecifier = exp.getModuleSpecifierValue();
|
|
151
|
+
if (moduleSpecifier) {
|
|
152
|
+
const resolved = resolveImport(sourceFile, moduleSpecifier, absPath);
|
|
153
|
+
if (resolved) {
|
|
154
|
+
nodeSet.add(resolved);
|
|
155
|
+
edges.push({ from: fromRel, to: resolved, type: "re-export" });
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
const nodes = Array.from(nodeSet);
|
|
161
|
+
const importedByCount = /* @__PURE__ */ new Map();
|
|
162
|
+
const importCount = /* @__PURE__ */ new Map();
|
|
163
|
+
for (const edge of edges) {
|
|
164
|
+
importedByCount.set(edge.to, (importedByCount.get(edge.to) ?? 0) + 1);
|
|
165
|
+
importCount.set(edge.from, (importCount.get(edge.from) ?? 0) + 1);
|
|
166
|
+
}
|
|
167
|
+
const N = Math.max(nodes.length, 1);
|
|
168
|
+
const hubs = nodes.map((node) => {
|
|
169
|
+
const inDeg = importedByCount.get(node) ?? 0;
|
|
170
|
+
const outDeg = importCount.get(node) ?? 0;
|
|
171
|
+
const centrality = N > 1 ? inDeg / (N - 1) * 100 : 0;
|
|
172
|
+
const score = Math.round(centrality + outDeg * (100 / (2 * N)));
|
|
173
|
+
return {
|
|
174
|
+
relativePath: node,
|
|
175
|
+
dependents: inDeg,
|
|
176
|
+
dependencies: outDeg,
|
|
177
|
+
score: Math.min(100, score)
|
|
178
|
+
};
|
|
179
|
+
}).filter((h) => h.dependents >= 3 || h.score >= 15).sort((a, b) => b.score - a.score);
|
|
180
|
+
const leaves = nodes.filter(
|
|
181
|
+
(node) => (importedByCount.get(node) ?? 0) === 0 && (importCount.get(node) ?? 0) > 0
|
|
182
|
+
);
|
|
183
|
+
const connectedNodes = /* @__PURE__ */ new Set();
|
|
184
|
+
for (const edge of edges) {
|
|
185
|
+
connectedNodes.add(edge.from);
|
|
186
|
+
connectedNodes.add(edge.to);
|
|
187
|
+
}
|
|
188
|
+
const allFileNodes = new Set(files.map((f) => f.relativePath));
|
|
189
|
+
const orphans = Array.from(allFileNodes).filter((n) => !connectedNodes.has(n));
|
|
190
|
+
const clusters = detectClusters(nodes, edges, files);
|
|
191
|
+
enrichComplexity(project, absPath, files);
|
|
192
|
+
return { nodes, edges, hubs, leaves, orphans, clusters };
|
|
193
|
+
}
|
|
194
|
+
var UnionFind = class {
|
|
195
|
+
parent;
|
|
196
|
+
rank;
|
|
197
|
+
constructor(nodes) {
|
|
198
|
+
this.parent = /* @__PURE__ */ new Map();
|
|
199
|
+
this.rank = /* @__PURE__ */ new Map();
|
|
200
|
+
for (const n of nodes) {
|
|
201
|
+
this.parent.set(n, n);
|
|
202
|
+
this.rank.set(n, 0);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
find(x) {
|
|
206
|
+
const p = this.parent.get(x);
|
|
207
|
+
if (p === void 0) return x;
|
|
208
|
+
if (p !== x) {
|
|
209
|
+
this.parent.set(x, this.find(p));
|
|
210
|
+
}
|
|
211
|
+
return this.parent.get(x);
|
|
212
|
+
}
|
|
213
|
+
union(a, b) {
|
|
214
|
+
const ra = this.find(a);
|
|
215
|
+
const rb = this.find(b);
|
|
216
|
+
if (ra === rb) return;
|
|
217
|
+
const rankA = this.rank.get(ra) ?? 0;
|
|
218
|
+
const rankB = this.rank.get(rb) ?? 0;
|
|
219
|
+
if (rankA < rankB) {
|
|
220
|
+
this.parent.set(ra, rb);
|
|
221
|
+
} else if (rankA > rankB) {
|
|
222
|
+
this.parent.set(rb, ra);
|
|
223
|
+
} else {
|
|
224
|
+
this.parent.set(rb, ra);
|
|
225
|
+
this.rank.set(ra, rankA + 1);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
};
|
|
229
|
+
function detectClusters(nodes, edges, files) {
|
|
230
|
+
const uf = new UnionFind(nodes);
|
|
231
|
+
for (const edge of edges) {
|
|
232
|
+
uf.union(edge.from, edge.to);
|
|
233
|
+
}
|
|
234
|
+
const components = /* @__PURE__ */ new Map();
|
|
235
|
+
for (const node of nodes) {
|
|
236
|
+
const root = uf.find(node);
|
|
237
|
+
if (!components.has(root)) components.set(root, []);
|
|
238
|
+
components.get(root).push(node);
|
|
239
|
+
}
|
|
240
|
+
const tokenMap = new Map(files.map((f) => [f.relativePath, f.tokens]));
|
|
241
|
+
const clusters = [];
|
|
242
|
+
for (const [, groupFiles] of components) {
|
|
243
|
+
if (groupFiles.length < 2) continue;
|
|
244
|
+
const name = commonPrefix(groupFiles);
|
|
245
|
+
const fileSet = new Set(groupFiles);
|
|
246
|
+
let internalEdges = 0;
|
|
247
|
+
let externalEdges = 0;
|
|
248
|
+
for (const edge of edges) {
|
|
249
|
+
const fromIn = fileSet.has(edge.from);
|
|
250
|
+
const toIn = fileSet.has(edge.to);
|
|
251
|
+
if (fromIn && toIn) internalEdges++;
|
|
252
|
+
else if (fromIn || toIn) externalEdges++;
|
|
253
|
+
}
|
|
254
|
+
const totalEdges = internalEdges + externalEdges;
|
|
255
|
+
const cohesion = totalEdges > 0 ? internalEdges / totalEdges : 0;
|
|
256
|
+
const totalTokens = groupFiles.reduce((s, f) => s + (tokenMap.get(f) ?? 0), 0);
|
|
257
|
+
clusters.push({
|
|
258
|
+
id: name.replace(/[^a-zA-Z0-9]/g, "-") || `cluster-${clusters.length}`,
|
|
259
|
+
name: name || `cluster-${clusters.length}`,
|
|
260
|
+
files: groupFiles,
|
|
261
|
+
totalTokens,
|
|
262
|
+
internalEdges,
|
|
263
|
+
externalEdges,
|
|
264
|
+
cohesion: Math.round(cohesion * 100) / 100
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
return clusters.sort((a, b) => b.files.length - a.files.length);
|
|
268
|
+
}
|
|
269
|
+
function commonPrefix(paths) {
|
|
270
|
+
if (paths.length === 0) return "";
|
|
271
|
+
const parts = paths.map((p) => p.split("/"));
|
|
272
|
+
const prefix = [];
|
|
273
|
+
for (let i = 0; i < parts[0].length - 1; i++) {
|
|
274
|
+
const segment = parts[0][i];
|
|
275
|
+
if (parts.every((p) => p[i] === segment)) {
|
|
276
|
+
prefix.push(segment);
|
|
277
|
+
} else break;
|
|
278
|
+
}
|
|
279
|
+
return prefix.join("/") || parts[0][0];
|
|
280
|
+
}
|
|
281
|
+
function enrichComplexity(project, absPath, files) {
|
|
282
|
+
const fileMap = new Map(files.map((f) => [f.relativePath, f]));
|
|
283
|
+
for (const sourceFile of project.getSourceFiles()) {
|
|
284
|
+
const relPath = relative(absPath, sourceFile.getFilePath());
|
|
285
|
+
if (relPath.startsWith("..") || relPath.includes("node_modules")) continue;
|
|
286
|
+
const file = fileMap.get(relPath);
|
|
287
|
+
if (!file) continue;
|
|
288
|
+
let totalComplexity = 0;
|
|
289
|
+
for (const func of sourceFile.getFunctions()) {
|
|
290
|
+
totalComplexity += calculateCyclomaticComplexity(func);
|
|
291
|
+
}
|
|
292
|
+
for (const cls of sourceFile.getClasses()) {
|
|
293
|
+
for (const method of cls.getMethods()) {
|
|
294
|
+
totalComplexity += calculateCyclomaticComplexity(method);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
for (const varDecl of sourceFile.getVariableDeclarations()) {
|
|
298
|
+
const init = varDecl.getInitializer();
|
|
299
|
+
if (init && (init.getKind() === SyntaxKind.ArrowFunction || init.getKind() === SyntaxKind.FunctionExpression)) {
|
|
300
|
+
totalComplexity += calculateCyclomaticComplexity(init);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
file.complexity = Math.max(1, totalComplexity);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
function calculateCyclomaticComplexity(node) {
|
|
307
|
+
let complexity = 1;
|
|
308
|
+
node.forEachDescendant((descendant) => {
|
|
309
|
+
switch (descendant.getKind()) {
|
|
310
|
+
case SyntaxKind.IfStatement:
|
|
311
|
+
case SyntaxKind.ConditionalExpression:
|
|
312
|
+
case SyntaxKind.ForStatement:
|
|
313
|
+
case SyntaxKind.ForInStatement:
|
|
314
|
+
case SyntaxKind.ForOfStatement:
|
|
315
|
+
case SyntaxKind.WhileStatement:
|
|
316
|
+
case SyntaxKind.DoStatement:
|
|
317
|
+
case SyntaxKind.CaseClause:
|
|
318
|
+
case SyntaxKind.CatchClause:
|
|
319
|
+
complexity++;
|
|
320
|
+
break;
|
|
321
|
+
case SyntaxKind.BinaryExpression: {
|
|
322
|
+
const opToken = descendant.getOperatorToken?.();
|
|
323
|
+
if (opToken) {
|
|
324
|
+
const kind = opToken.getKind();
|
|
325
|
+
if (kind === SyntaxKind.AmpersandAmpersandToken || kind === SyntaxKind.BarBarToken || kind === SyntaxKind.QuestionQuestionToken) {
|
|
326
|
+
complexity++;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
break;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
});
|
|
333
|
+
return complexity;
|
|
334
|
+
}
|
|
335
|
+
function resolveImport(sourceFile, moduleSpecifier, projectRoot) {
|
|
336
|
+
if (!moduleSpecifier.startsWith(".")) return null;
|
|
337
|
+
const sourceDir = dirname(sourceFile.getFilePath());
|
|
338
|
+
const basePath = resolve(sourceDir, moduleSpecifier);
|
|
339
|
+
const extensions = [".ts", ".tsx", ".js", ".jsx", "/index.ts", "/index.tsx", "/index.js", "/index.jsx"];
|
|
340
|
+
for (const ext of extensions) {
|
|
341
|
+
const candidate = basePath.endsWith(ext) ? basePath : basePath + ext;
|
|
342
|
+
if (existsSync(candidate)) {
|
|
343
|
+
const rel = relative(projectRoot, candidate);
|
|
344
|
+
if (!rel.startsWith("..")) return rel;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
if (moduleSpecifier.endsWith(".js")) {
|
|
348
|
+
const tsPath = basePath.replace(/\.js$/, ".ts");
|
|
349
|
+
if (existsSync(tsPath)) {
|
|
350
|
+
const rel = relative(projectRoot, tsPath);
|
|
351
|
+
if (!rel.startsWith("..")) return rel;
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
return null;
|
|
355
|
+
}
|
|
356
|
+
function emptyGraph(files) {
|
|
357
|
+
return {
|
|
358
|
+
nodes: files.map((f) => f.relativePath),
|
|
359
|
+
edges: [],
|
|
360
|
+
hubs: [],
|
|
361
|
+
leaves: [],
|
|
362
|
+
orphans: files.map((f) => f.relativePath),
|
|
363
|
+
clusters: []
|
|
364
|
+
};
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// src/engine/risk.ts
|
|
368
|
+
function scoreAllFiles(files, graph, weights = DEFAULT_RISK_WEIGHTS) {
|
|
369
|
+
const typeProviderUsage = computeTypeProviderUsage(files, graph);
|
|
370
|
+
for (const file of files) {
|
|
371
|
+
const factors = computeRiskFactors(file, graph, typeProviderUsage, weights);
|
|
372
|
+
file.riskFactors = factors;
|
|
373
|
+
file.riskScore = computeWeightedScore(factors);
|
|
374
|
+
file.exclusionImpact = scoreToImpact(file.riskScore);
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
function computeRiskFactors(file, graph, typeProviderUsage, weights) {
|
|
378
|
+
const factors = [];
|
|
379
|
+
factors.push(computeHubFactor(file, weights.hub));
|
|
380
|
+
factors.push(computeTypeProviderFactor(file, typeProviderUsage, weights.typeProvider));
|
|
381
|
+
factors.push(computeComplexityFactor(file, weights.complexity));
|
|
382
|
+
factors.push(computeRecencyFactor(file, weights.recency));
|
|
383
|
+
factors.push(computeConfigFactor(file, weights.config));
|
|
384
|
+
factors.push(computeChurnFactor(file, weights.churn));
|
|
385
|
+
return factors;
|
|
386
|
+
}
|
|
387
|
+
function computeHubFactor(file, weight) {
|
|
388
|
+
const dependents = file.importedBy.length;
|
|
389
|
+
const K = 12;
|
|
390
|
+
const score = dependents === 0 ? 0 : Math.min(100, Math.round(100 * Math.log2(1 + dependents) / Math.log2(1 + K)));
|
|
391
|
+
const detail = dependents === 0 ? "No dependents" : `Hub: ${dependents} file(s) depend on this (score ${score}/100)`;
|
|
392
|
+
return { type: "hub", score, weight, detail };
|
|
393
|
+
}
|
|
394
|
+
function computeTypeProviderFactor(file, usage, weight) {
|
|
395
|
+
const isTypeFile = file.kind === "type";
|
|
396
|
+
const consumers = usage.get(file.relativePath) ?? 0;
|
|
397
|
+
let score;
|
|
398
|
+
let detail;
|
|
399
|
+
if (isTypeFile && consumers >= 4) {
|
|
400
|
+
score = 100;
|
|
401
|
+
detail = `Type provider: used by ${consumers} files (critical type source)`;
|
|
402
|
+
} else if (isTypeFile && consumers >= 1) {
|
|
403
|
+
score = 50;
|
|
404
|
+
detail = `Type provider: used by ${consumers} files`;
|
|
405
|
+
} else if (isTypeFile) {
|
|
406
|
+
score = 30;
|
|
407
|
+
detail = "Type file (no detected consumers)";
|
|
408
|
+
} else {
|
|
409
|
+
score = 0;
|
|
410
|
+
detail = "Not a type provider";
|
|
411
|
+
}
|
|
412
|
+
return { type: "type-provider", score, weight, detail };
|
|
413
|
+
}
|
|
414
|
+
function computeComplexityFactor(file, weight) {
|
|
415
|
+
const c = file.complexity;
|
|
416
|
+
const K = 30;
|
|
417
|
+
const score = Math.min(100, Math.round(100 * Math.log(1 + c) / Math.log(1 + K)));
|
|
418
|
+
const detail = c >= 30 ? `Very high complexity: ${c} (AI needs full context)` : c >= 10 ? `High complexity: ${c}` : `Complexity: ${c}`;
|
|
419
|
+
return { type: "complexity", score, weight, detail };
|
|
420
|
+
}
|
|
421
|
+
function computeRecencyFactor(file, weight) {
|
|
422
|
+
const now = Date.now();
|
|
423
|
+
const modified = new Date(file.lastModified).getTime();
|
|
424
|
+
const daysAgo = (now - modified) / (1e3 * 60 * 60 * 24);
|
|
425
|
+
const HALF_LIFE = 7;
|
|
426
|
+
const score = Math.round(100 * Math.pow(2, -daysAgo / HALF_LIFE));
|
|
427
|
+
const detail = daysAgo <= 1 ? "Modified today" : `Modified ${Math.round(daysAgo)} days ago (decay score ${score})`;
|
|
428
|
+
return { type: "recency", score, weight, detail };
|
|
429
|
+
}
|
|
430
|
+
function computeConfigFactor(file, weight) {
|
|
431
|
+
let score;
|
|
432
|
+
let detail;
|
|
433
|
+
if (file.kind === "entry") {
|
|
434
|
+
score = 90;
|
|
435
|
+
detail = "Entry point \u2014 critical for understanding app structure";
|
|
436
|
+
} else if (file.kind === "config") {
|
|
437
|
+
score = 80;
|
|
438
|
+
detail = "Configuration file \u2014 affects runtime behavior";
|
|
439
|
+
} else {
|
|
440
|
+
score = 0;
|
|
441
|
+
detail = "Regular source file";
|
|
442
|
+
}
|
|
443
|
+
return { type: "config", score, weight, detail };
|
|
444
|
+
}
|
|
445
|
+
function computeChurnFactor(file, weight) {
|
|
446
|
+
const complexitySignal = Math.min(file.complexity / 20, 1);
|
|
447
|
+
const now = Date.now();
|
|
448
|
+
const daysAgo = (now - new Date(file.lastModified).getTime()) / (1e3 * 60 * 60 * 24);
|
|
449
|
+
const recencySignal = Math.pow(2, -daysAgo / 7);
|
|
450
|
+
const score = Math.round(Math.sqrt(complexitySignal * recencySignal) * 100);
|
|
451
|
+
const detail = score >= 50 ? "Likely under active development (complex + recent)" : score >= 20 ? "Some recent activity" : "Stable \u2014 low churn (proxy estimate)";
|
|
452
|
+
return { type: "churn", score, weight, detail };
|
|
453
|
+
}
|
|
454
|
+
function computeWeightedScore(factors) {
|
|
455
|
+
let totalWeightedScore = 0;
|
|
456
|
+
let totalWeight = 0;
|
|
457
|
+
for (const factor of factors) {
|
|
458
|
+
totalWeightedScore += factor.score * factor.weight;
|
|
459
|
+
totalWeight += factor.weight;
|
|
460
|
+
}
|
|
461
|
+
if (totalWeight === 0) return 0;
|
|
462
|
+
return Math.round(totalWeightedScore / totalWeight);
|
|
463
|
+
}
|
|
464
|
+
function scoreToImpact(score) {
|
|
465
|
+
if (score >= 80) return "critical";
|
|
466
|
+
if (score >= 60) return "high";
|
|
467
|
+
if (score >= 30) return "medium";
|
|
468
|
+
if (score > 0) return "low";
|
|
469
|
+
return "none";
|
|
470
|
+
}
|
|
471
|
+
function computeTypeProviderUsage(files, graph) {
|
|
472
|
+
const usage = /* @__PURE__ */ new Map();
|
|
473
|
+
const typeFiles = new Set(
|
|
474
|
+
files.filter((f) => f.kind === "type").map((f) => f.relativePath)
|
|
475
|
+
);
|
|
476
|
+
for (const edge of graph.edges) {
|
|
477
|
+
if (typeFiles.has(edge.to)) {
|
|
478
|
+
usage.set(edge.to, (usage.get(edge.to) ?? 0) + 1);
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
return usage;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
// src/engine/analyzer.ts
|
|
485
|
+
function matchesPattern(filename, patterns) {
|
|
486
|
+
for (const pattern of patterns) {
|
|
487
|
+
if (pattern.startsWith("*.")) {
|
|
488
|
+
const ext = pattern.slice(1);
|
|
489
|
+
if (filename.endsWith(ext)) return true;
|
|
490
|
+
} else if (filename === pattern) {
|
|
491
|
+
return true;
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
return false;
|
|
495
|
+
}
|
|
496
|
+
async function walkProject(rootPath, options) {
|
|
497
|
+
const results = [];
|
|
498
|
+
const { ignoreDirs, ignorePatterns, extensions, maxDepth = 20 } = options;
|
|
499
|
+
const ignoreDirSet = new Set(ignoreDirs);
|
|
500
|
+
async function walk(dir, depth) {
|
|
501
|
+
if (depth > maxDepth) return;
|
|
502
|
+
let entries;
|
|
503
|
+
try {
|
|
504
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
505
|
+
} catch {
|
|
506
|
+
return;
|
|
507
|
+
}
|
|
508
|
+
const promises = [];
|
|
509
|
+
for (const entry of entries) {
|
|
510
|
+
const fullPath = join2(dir, entry.name);
|
|
511
|
+
if (entry.isDirectory()) {
|
|
512
|
+
if (!ignoreDirSet.has(entry.name) && !entry.name.startsWith(".")) {
|
|
513
|
+
promises.push(walk(fullPath, depth + 1));
|
|
514
|
+
}
|
|
515
|
+
} else if (entry.isFile()) {
|
|
516
|
+
const ext = extname(entry.name).slice(1).toLowerCase();
|
|
517
|
+
if (ext && extensions.includes(ext) && !matchesPattern(entry.name, ignorePatterns)) {
|
|
518
|
+
promises.push(
|
|
519
|
+
(async () => {
|
|
520
|
+
const fileStat = await stat2(fullPath).catch(() => null);
|
|
521
|
+
if (!fileStat) return;
|
|
522
|
+
let lines = 0;
|
|
523
|
+
try {
|
|
524
|
+
const content = await readFile2(fullPath, "utf-8");
|
|
525
|
+
lines = content.split("\n").length;
|
|
526
|
+
} catch {
|
|
527
|
+
lines = 0;
|
|
528
|
+
}
|
|
529
|
+
results.push({
|
|
530
|
+
path: fullPath,
|
|
531
|
+
relativePath: relative2(rootPath, fullPath),
|
|
532
|
+
extension: ext,
|
|
533
|
+
size: fileStat.size,
|
|
534
|
+
lastModified: fileStat.mtime,
|
|
535
|
+
lines
|
|
536
|
+
});
|
|
537
|
+
})()
|
|
538
|
+
);
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
await Promise.all(promises);
|
|
543
|
+
}
|
|
544
|
+
await walk(rootPath, 0);
|
|
545
|
+
return results;
|
|
546
|
+
}
|
|
547
|
+
var TYPE_PATTERNS = [/types?\//i, /\.d\.ts$/, /interfaces?\//i];
|
|
548
|
+
var TEST_PATTERNS = [/\.test\.[jt]sx?$/, /\.spec\.[jt]sx?$/, /\/__tests__\//, /\/tests?\//];
|
|
549
|
+
var CONFIG_PATTERNS = [/\.config\.[jt]s$/, /rc\.[jt]s$/, /\.env/, /tsconfig/, /package\.json$/, /\.yml$/, /\.yaml$/, /\.toml$/];
|
|
550
|
+
var ENTRY_PATTERNS = [/^index\.[jt]sx?$/, /^main\.[jt]sx?$/, /^app\.[jt]sx?$/, /^server\.[jt]sx?$/];
|
|
551
|
+
function classifyFileKind(relativePath) {
|
|
552
|
+
const filename = basename2(relativePath);
|
|
553
|
+
if (TYPE_PATTERNS.some((p) => p.test(relativePath))) return "type";
|
|
554
|
+
if (TEST_PATTERNS.some((p) => p.test(relativePath))) return "test";
|
|
555
|
+
if (CONFIG_PATTERNS.some((p) => p.test(relativePath) || p.test(filename))) return "config";
|
|
556
|
+
if (ENTRY_PATTERNS.some((p) => p.test(filename))) return "entry";
|
|
557
|
+
return "source";
|
|
558
|
+
}
|
|
559
|
+
function detectStack(files) {
|
|
560
|
+
const stack = [];
|
|
561
|
+
const extensions = new Set(files.map((f) => f.extension));
|
|
562
|
+
const paths = files.map((f) => f.relativePath.toLowerCase());
|
|
563
|
+
if (extensions.has("ts") || extensions.has("tsx")) stack.push("TypeScript");
|
|
564
|
+
else if (extensions.has("js") || extensions.has("jsx")) stack.push("JavaScript");
|
|
565
|
+
if (extensions.has("py")) stack.push("Python");
|
|
566
|
+
if (extensions.has("go")) stack.push("Go");
|
|
567
|
+
if (extensions.has("rs")) stack.push("Rust");
|
|
568
|
+
if (extensions.has("java")) stack.push("Java");
|
|
569
|
+
if (extensions.has("kt")) stack.push("Kotlin");
|
|
570
|
+
if (extensions.has("rb")) stack.push("Ruby");
|
|
571
|
+
if (extensions.has("php")) stack.push("PHP");
|
|
572
|
+
if (extensions.has("cs")) stack.push("C#");
|
|
573
|
+
if (extensions.has("c") || extensions.has("cpp")) stack.push("C/C++");
|
|
574
|
+
if (paths.some((p) => p.includes("next.config"))) stack.push("Next.js");
|
|
575
|
+
if (paths.some((p) => p.includes("nuxt.config"))) stack.push("Nuxt");
|
|
576
|
+
if (paths.some((p) => p.includes("angular.json"))) stack.push("Angular");
|
|
577
|
+
return stack;
|
|
578
|
+
}
|
|
579
|
+
async function analyzeProject(projectPath, config) {
|
|
580
|
+
const absPath = resolve2(projectPath);
|
|
581
|
+
const projectName = basename2(absPath);
|
|
582
|
+
const mergedConfig = mergeConfig(DEFAULT_CONFIG, config);
|
|
583
|
+
const allExtensions = [
|
|
584
|
+
...mergedConfig.analysis.extensions.code,
|
|
585
|
+
...mergedConfig.analysis.extensions.config,
|
|
586
|
+
...mergedConfig.analysis.extensions.docs
|
|
587
|
+
];
|
|
588
|
+
const walkEntries = await walkProject(absPath, {
|
|
589
|
+
ignoreDirs: mergedConfig.analysis.ignore.dirs,
|
|
590
|
+
ignorePatterns: mergedConfig.analysis.ignore.patterns,
|
|
591
|
+
extensions: allExtensions,
|
|
592
|
+
maxDepth: mergedConfig.analysis.maxDepth
|
|
593
|
+
});
|
|
594
|
+
const tokenMethod = mergedConfig.tokens.method;
|
|
595
|
+
const files = [];
|
|
596
|
+
for (const entry of walkEntries) {
|
|
597
|
+
let tokens;
|
|
598
|
+
if (tokenMethod === "tiktoken") {
|
|
599
|
+
try {
|
|
600
|
+
const content = await readFile2(entry.path, "utf-8");
|
|
601
|
+
tokens = estimateTokens(content, entry.size, "tiktoken");
|
|
602
|
+
} catch {
|
|
603
|
+
tokens = countTokensChars4(entry.size);
|
|
604
|
+
}
|
|
605
|
+
} else {
|
|
606
|
+
tokens = countTokensChars4(entry.size);
|
|
607
|
+
}
|
|
608
|
+
files.push({
|
|
609
|
+
path: entry.path,
|
|
610
|
+
relativePath: entry.relativePath,
|
|
611
|
+
extension: entry.extension,
|
|
612
|
+
size: entry.size,
|
|
613
|
+
tokens,
|
|
614
|
+
lines: entry.lines,
|
|
615
|
+
lastModified: entry.lastModified,
|
|
616
|
+
kind: classifyFileKind(entry.relativePath),
|
|
617
|
+
// Graph data — populated by graph analysis
|
|
618
|
+
imports: [],
|
|
619
|
+
importedBy: [],
|
|
620
|
+
isHub: false,
|
|
621
|
+
complexity: 0,
|
|
622
|
+
// Risk data — populated by risk analysis
|
|
623
|
+
riskScore: 0,
|
|
624
|
+
riskFactors: [],
|
|
625
|
+
exclusionImpact: "none"
|
|
626
|
+
});
|
|
627
|
+
}
|
|
628
|
+
const graph = buildProjectGraph(absPath, files);
|
|
629
|
+
for (const file of files) {
|
|
630
|
+
const nodeImports = [];
|
|
631
|
+
const nodeImportedBy = [];
|
|
632
|
+
for (const edge of graph.edges) {
|
|
633
|
+
if (edge.from === file.relativePath) nodeImports.push(edge.to);
|
|
634
|
+
if (edge.to === file.relativePath) nodeImportedBy.push(edge.from);
|
|
635
|
+
}
|
|
636
|
+
file.imports = nodeImports;
|
|
637
|
+
file.importedBy = nodeImportedBy;
|
|
638
|
+
file.isHub = graph.hubs.some((h) => h.relativePath === file.relativePath);
|
|
639
|
+
}
|
|
640
|
+
const riskWeights = mergedConfig.risk.weights;
|
|
641
|
+
scoreAllFiles(files, graph, riskWeights);
|
|
642
|
+
const riskProfile = {
|
|
643
|
+
distribution: {
|
|
644
|
+
critical: files.filter((f) => f.riskScore >= 80).length,
|
|
645
|
+
high: files.filter((f) => f.riskScore >= 60 && f.riskScore < 80).length,
|
|
646
|
+
medium: files.filter((f) => f.riskScore >= 30 && f.riskScore < 60).length,
|
|
647
|
+
low: files.filter((f) => f.riskScore < 30).length
|
|
648
|
+
},
|
|
649
|
+
topRiskFiles: [...files].sort((a, b) => b.riskScore - a.riskScore).slice(0, 10),
|
|
650
|
+
overallComplexity: files.length > 0 ? files.reduce((s, f) => s + f.complexity, 0) / files.length : 0
|
|
651
|
+
};
|
|
652
|
+
const totalTokens = files.reduce((s, f) => s + f.tokens, 0);
|
|
653
|
+
const hashInput = files.map((f) => `${f.relativePath}:${f.tokens}:${f.riskScore}`).sort().join("|");
|
|
654
|
+
const hash = createHash("sha256").update(hashInput).digest("hex").substring(0, 16);
|
|
655
|
+
const stack = detectStack(walkEntries);
|
|
656
|
+
return {
|
|
657
|
+
projectPath: absPath,
|
|
658
|
+
projectName,
|
|
659
|
+
analyzedAt: /* @__PURE__ */ new Date(),
|
|
660
|
+
hash,
|
|
661
|
+
files,
|
|
662
|
+
totalFiles: files.length,
|
|
663
|
+
totalTokens,
|
|
664
|
+
graph,
|
|
665
|
+
riskProfile,
|
|
666
|
+
stack,
|
|
667
|
+
tokenMethod
|
|
668
|
+
};
|
|
669
|
+
}
|
|
670
|
+
function mergeConfig(base, overrides) {
|
|
671
|
+
if (!overrides) return base;
|
|
672
|
+
return {
|
|
673
|
+
...base,
|
|
674
|
+
...overrides,
|
|
675
|
+
analysis: {
|
|
676
|
+
...base.analysis,
|
|
677
|
+
...overrides.analysis,
|
|
678
|
+
extensions: {
|
|
679
|
+
...base.analysis.extensions,
|
|
680
|
+
...overrides.analysis?.extensions
|
|
681
|
+
},
|
|
682
|
+
ignore: {
|
|
683
|
+
...base.analysis.ignore,
|
|
684
|
+
...overrides.analysis?.ignore
|
|
685
|
+
}
|
|
686
|
+
},
|
|
687
|
+
risk: {
|
|
688
|
+
...base.risk,
|
|
689
|
+
...overrides.risk,
|
|
690
|
+
weights: {
|
|
691
|
+
...base.risk.weights,
|
|
692
|
+
...overrides.risk?.weights
|
|
693
|
+
}
|
|
694
|
+
},
|
|
695
|
+
interaction: {
|
|
696
|
+
...base.interaction,
|
|
697
|
+
...overrides.interaction
|
|
698
|
+
},
|
|
699
|
+
tokens: {
|
|
700
|
+
...base.tokens,
|
|
701
|
+
...overrides.tokens
|
|
702
|
+
},
|
|
703
|
+
governance: {
|
|
704
|
+
...base.governance,
|
|
705
|
+
...overrides.governance
|
|
706
|
+
}
|
|
707
|
+
};
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
// src/engine/cache.ts
|
|
711
|
+
import { createHash as createHash2 } from "crypto";
|
|
712
|
+
import { readdir as readdir2, stat as stat3 } from "fs/promises";
|
|
713
|
+
import { join as join3, extname as extname2, relative as relative3, resolve as resolve3 } from "path";
|
|
714
|
+
var DEFAULT_CACHE_OPTIONS = {
|
|
715
|
+
maxAgeMs: 5 * 60 * 1e3,
|
|
716
|
+
// 5 minutes
|
|
717
|
+
maxEntries: 10,
|
|
718
|
+
enabled: true
|
|
719
|
+
};
|
|
720
|
+
var cache = /* @__PURE__ */ new Map();
|
|
721
|
+
var cacheOptions = { ...DEFAULT_CACHE_OPTIONS };
|
|
722
|
+
async function computeFingerprint(rootPath, config = DEFAULT_CONFIG) {
|
|
723
|
+
const entries = [];
|
|
724
|
+
const allExtensions = /* @__PURE__ */ new Set([
|
|
725
|
+
...config.analysis.extensions.code,
|
|
726
|
+
...config.analysis.extensions.config,
|
|
727
|
+
...config.analysis.extensions.docs
|
|
728
|
+
]);
|
|
729
|
+
const ignoreDirSet = new Set(config.analysis.ignore.dirs);
|
|
730
|
+
async function walk(dir, depth) {
|
|
731
|
+
if (depth > config.analysis.maxDepth) return;
|
|
732
|
+
let dirEntries;
|
|
733
|
+
try {
|
|
734
|
+
dirEntries = await readdir2(dir, { withFileTypes: true });
|
|
735
|
+
} catch {
|
|
736
|
+
return;
|
|
737
|
+
}
|
|
738
|
+
const promises = [];
|
|
739
|
+
for (const entry of dirEntries) {
|
|
740
|
+
const fullPath = join3(dir, entry.name);
|
|
741
|
+
if (entry.isDirectory()) {
|
|
742
|
+
if (!ignoreDirSet.has(entry.name) && !entry.name.startsWith(".")) {
|
|
743
|
+
promises.push(walk(fullPath, depth + 1));
|
|
744
|
+
}
|
|
745
|
+
} else if (entry.isFile()) {
|
|
746
|
+
const ext = extname2(entry.name).slice(1).toLowerCase();
|
|
747
|
+
if (ext && allExtensions.has(ext)) {
|
|
748
|
+
promises.push(
|
|
749
|
+
(async () => {
|
|
750
|
+
try {
|
|
751
|
+
const s = await stat3(fullPath);
|
|
752
|
+
const rel = relative3(rootPath, fullPath);
|
|
753
|
+
entries.push(`${rel}:${s.mtimeMs.toFixed(0)}:${s.size}`);
|
|
754
|
+
} catch {
|
|
755
|
+
}
|
|
756
|
+
})()
|
|
757
|
+
);
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
await Promise.all(promises);
|
|
762
|
+
}
|
|
763
|
+
await walk(rootPath, 0);
|
|
764
|
+
entries.sort();
|
|
765
|
+
return createHash2("sha256").update(entries.join("|")).digest("hex").substring(0, 16);
|
|
766
|
+
}
|
|
767
|
+
async function getCachedAnalysis(projectPath, config) {
|
|
768
|
+
const absPath = resolve3(projectPath);
|
|
769
|
+
if (!cacheOptions.enabled) {
|
|
770
|
+
return analyzeProject(absPath, config);
|
|
771
|
+
}
|
|
772
|
+
const existing = cache.get(absPath);
|
|
773
|
+
if (existing) {
|
|
774
|
+
const age = Date.now() - existing.createdAt;
|
|
775
|
+
if (age > cacheOptions.maxAgeMs) {
|
|
776
|
+
cache.delete(absPath);
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
const mergedConfig = config ? { ...DEFAULT_CONFIG, ...config } : DEFAULT_CONFIG;
|
|
780
|
+
const fingerprint = await computeFingerprint(absPath, mergedConfig);
|
|
781
|
+
const cached = cache.get(absPath);
|
|
782
|
+
if (cached && cached.fingerprint === fingerprint) {
|
|
783
|
+
cached.hits++;
|
|
784
|
+
return cached.analysis;
|
|
785
|
+
}
|
|
786
|
+
const analysis = await analyzeProject(absPath, config);
|
|
787
|
+
if (cache.size >= cacheOptions.maxEntries) {
|
|
788
|
+
const oldest = [...cache.entries()].sort(
|
|
789
|
+
(a, b) => a[1].createdAt - b[1].createdAt
|
|
790
|
+
)[0];
|
|
791
|
+
if (oldest) cache.delete(oldest[0]);
|
|
792
|
+
}
|
|
793
|
+
cache.set(absPath, {
|
|
794
|
+
analysis,
|
|
795
|
+
fingerprint,
|
|
796
|
+
createdAt: Date.now(),
|
|
797
|
+
hits: 0
|
|
798
|
+
});
|
|
799
|
+
return analysis;
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
// src/engine/selector.ts
|
|
803
|
+
import { createHash as createHash3 } from "crypto";
|
|
804
|
+
|
|
805
|
+
// src/govern/secrets.ts
|
|
806
|
+
import { readFile as readFile3 } from "fs/promises";
|
|
807
|
+
import { resolve as resolve4, relative as relative4 } from "path";
|
|
808
|
+
var BUILTIN_PATTERNS = [
|
|
809
|
+
// API Keys
|
|
810
|
+
{ type: "api-key", source: `(?:api[_-]?key|apikey)\\s*[:=]\\s*['"]?([a-zA-Z0-9_\\-]{20,})['"]?`, flags: "gi", severity: "critical", description: "API Key" },
|
|
811
|
+
{ type: "api-key", source: "sk-[a-zA-Z0-9]{20,}", flags: "g", severity: "critical", description: "OpenAI/Anthropic API Key" },
|
|
812
|
+
{ type: "api-key", source: "sk-ant-[a-zA-Z0-9\\-]{20,}", flags: "g", severity: "critical", description: "Anthropic API Key" },
|
|
813
|
+
// AWS
|
|
814
|
+
{ type: "aws-key", source: "AKIA[0-9A-Z]{16}", flags: "g", severity: "critical", description: "AWS Access Key ID" },
|
|
815
|
+
{ type: "aws-key", source: `(?:aws_secret_access_key|aws_secret)\\s*[:=]\\s*['"]?([a-zA-Z0-9/+=]{40})['"]?`, flags: "gi", severity: "critical", description: "AWS Secret Key" },
|
|
816
|
+
// Private Keys
|
|
817
|
+
{ type: "private-key", source: "-----BEGIN (?:RSA |EC |DSA )?PRIVATE KEY-----", flags: "g", severity: "critical", description: "Private Key" },
|
|
818
|
+
{ type: "private-key", source: "-----BEGIN OPENSSH PRIVATE KEY-----", flags: "g", severity: "critical", description: "SSH Private Key" },
|
|
819
|
+
// Passwords
|
|
820
|
+
{ type: "password", source: `(?:password|passwd|pwd)\\s*[:=]\\s*['"]([^'"]{8,})['"](?!\\s*\\{)`, flags: "gi", severity: "high", description: "Hardcoded Password" },
|
|
821
|
+
{ type: "password", source: `(?:DB_PASSWORD|DATABASE_PASSWORD|MYSQL_PASSWORD|POSTGRES_PASSWORD)\\s*[:=]\\s*['"]?([^'"{}\\s]{4,})['"]?`, flags: "gi", severity: "high", description: "Database Password" },
|
|
822
|
+
// Tokens
|
|
823
|
+
{ type: "token", source: `(?:bearer|token|auth_token|access_token|refresh_token)\\s*[:=]\\s*['"]([a-zA-Z0-9_\\-.]{20,})['"](?!\\s*\\{)`, flags: "gi", severity: "high", description: "Auth Token" },
|
|
824
|
+
{ type: "token", source: "ghp_[a-zA-Z0-9]{36}", flags: "g", severity: "critical", description: "GitHub Personal Access Token" },
|
|
825
|
+
{ type: "token", source: "gho_[a-zA-Z0-9]{36}", flags: "g", severity: "critical", description: "GitHub OAuth Token" },
|
|
826
|
+
{ type: "token", source: "glpat-[a-zA-Z0-9\\-]{20,}", flags: "g", severity: "critical", description: "GitLab Personal Access Token" },
|
|
827
|
+
{ type: "token", source: "npm_[a-zA-Z0-9]{36}", flags: "g", severity: "high", description: "npm Token" },
|
|
828
|
+
// Connection strings
|
|
829
|
+
{ type: "connection-string", source: `(?:mongodb(?:\\+srv)?|postgres(?:ql)?|mysql|redis|amqp):\\/\\/[^\\s'"]+:[^\\s'"]+@[^\\s'"]+`, flags: "gi", severity: "critical", description: "Database Connection String" },
|
|
830
|
+
{ type: "connection-string", source: `(?:DATABASE_URL|REDIS_URL|MONGODB_URI)\\s*[:=]\\s*['"]?([^\\s'"]{10,})['"]?`, flags: "gi", severity: "high", description: "Database URL" },
|
|
831
|
+
// Environment variables with secrets
|
|
832
|
+
{ type: "env-variable", source: `(?:SECRET|PRIVATE|ENCRYPTION)[_-]?(?:KEY|TOKEN|PASS)\\s*[:=]\\s*['"]?([^\\s'"]{8,})['"]?`, flags: "gi", severity: "high", description: "Secret Environment Variable" }
|
|
833
|
+
];
|
|
834
|
+
function buildPatterns(customPatterns = []) {
|
|
835
|
+
const patterns = BUILTIN_PATTERNS.map((def) => ({
|
|
836
|
+
type: def.type,
|
|
837
|
+
pattern: new RegExp(def.source, def.flags),
|
|
838
|
+
severity: def.severity,
|
|
839
|
+
description: def.description
|
|
840
|
+
}));
|
|
841
|
+
for (const custom of customPatterns) {
|
|
842
|
+
try {
|
|
843
|
+
patterns.push({
|
|
844
|
+
type: "custom",
|
|
845
|
+
pattern: new RegExp(custom, "gi"),
|
|
846
|
+
severity: "medium",
|
|
847
|
+
description: `Custom pattern: ${custom}`
|
|
848
|
+
});
|
|
849
|
+
} catch {
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
return patterns;
|
|
853
|
+
}
|
|
854
|
+
function scanContentForSecrets(content, filePath, customPatterns = []) {
|
|
855
|
+
const findings = [];
|
|
856
|
+
const lines = content.split("\n");
|
|
857
|
+
const allPatterns = buildPatterns(customPatterns);
|
|
858
|
+
for (const secretPattern of allPatterns) {
|
|
859
|
+
for (let i = 0; i < lines.length; i++) {
|
|
860
|
+
const line = lines[i];
|
|
861
|
+
secretPattern.pattern.lastIndex = 0;
|
|
862
|
+
let match;
|
|
863
|
+
while ((match = secretPattern.pattern.exec(line)) !== null) {
|
|
864
|
+
const matchText = match[0];
|
|
865
|
+
if (isTemplateOrPlaceholder(matchText)) continue;
|
|
866
|
+
findings.push({
|
|
867
|
+
type: secretPattern.type,
|
|
868
|
+
file: filePath,
|
|
869
|
+
line: i + 1,
|
|
870
|
+
match: matchText,
|
|
871
|
+
redacted: redactSecret(matchText),
|
|
872
|
+
severity: secretPattern.severity
|
|
873
|
+
});
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
return deduplicateFindings(findings);
|
|
878
|
+
}
|
|
879
|
+
async function scanFileForSecrets(filePath, projectPath, customPatterns = []) {
|
|
880
|
+
try {
|
|
881
|
+
const content = await readFile3(filePath, "utf-8");
|
|
882
|
+
const relPath = relative4(resolve4(projectPath), resolve4(filePath));
|
|
883
|
+
return scanContentForSecrets(content, relPath, customPatterns);
|
|
884
|
+
} catch {
|
|
885
|
+
return [];
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
function redactSecret(value) {
|
|
889
|
+
if (value.length <= 8) return "***REDACTED***";
|
|
890
|
+
const prefix = value.substring(0, 4);
|
|
891
|
+
const suffix = value.substring(value.length - 2);
|
|
892
|
+
return `${prefix}${"*".repeat(Math.min(value.length - 6, 20))}${suffix}`;
|
|
893
|
+
}
|
|
894
|
+
function isTemplateOrPlaceholder(value) {
|
|
895
|
+
const placeholders = [
|
|
896
|
+
/\$\{.*\}/,
|
|
897
|
+
/\{\{.*\}\}/,
|
|
898
|
+
/%[sd]/,
|
|
899
|
+
/<[A-Z_]+>/,
|
|
900
|
+
/YOUR_.*_HERE/i,
|
|
901
|
+
/\bCHANGE_ME\b/i,
|
|
902
|
+
/\bPLACEHOLDER\b/i,
|
|
903
|
+
/\bexample\b/i,
|
|
904
|
+
/\bTODO\b/i,
|
|
905
|
+
/xxx+/i,
|
|
906
|
+
/\breplace.?me\b/i,
|
|
907
|
+
/\bdummy\b/i,
|
|
908
|
+
/\btest_?key\b/i,
|
|
909
|
+
/\bsample\b/i
|
|
910
|
+
];
|
|
911
|
+
return placeholders.some((p) => p.test(value));
|
|
912
|
+
}
|
|
913
|
+
function deduplicateFindings(findings) {
|
|
914
|
+
const seen = /* @__PURE__ */ new Set();
|
|
915
|
+
return findings.filter((f) => {
|
|
916
|
+
const key = `${f.file}:${f.line}:${f.type}:${f.match}`;
|
|
917
|
+
if (seen.has(key)) return false;
|
|
918
|
+
seen.add(key);
|
|
919
|
+
return true;
|
|
920
|
+
});
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
// src/engine/pruner.ts
|
|
924
|
+
import { Project as Project2, SyntaxKind as SyntaxKind2 } from "ts-morph";
|
|
925
|
+
import { readFile as readFile4 } from "fs/promises";
|
|
926
|
+
import { existsSync as existsSync2 } from "fs";
|
|
927
|
+
import { join as join4 } from "path";
|
|
928
|
+
var TS_EXTENSIONS2 = /* @__PURE__ */ new Set(["ts", "tsx", "js", "jsx", "mts", "mjs"]);
|
|
929
|
+
async function pruneFile(file, level) {
|
|
930
|
+
if (level === "excluded") {
|
|
931
|
+
return emptyResult(file, "excluded");
|
|
932
|
+
}
|
|
933
|
+
if (level === "full") {
|
|
934
|
+
return fullContent(file);
|
|
935
|
+
}
|
|
936
|
+
const ext = file.extension.toLowerCase();
|
|
937
|
+
const isTS = TS_EXTENSIONS2.has(ext);
|
|
938
|
+
if (isTS) {
|
|
939
|
+
return pruneTypeScript(file, level);
|
|
940
|
+
}
|
|
941
|
+
return pruneGeneric(file, level);
|
|
942
|
+
}
|
|
943
|
+
async function pruneTypeScript(file, level) {
|
|
944
|
+
let content;
|
|
945
|
+
try {
|
|
946
|
+
content = await readFile4(file.path, "utf-8");
|
|
947
|
+
} catch {
|
|
948
|
+
return emptyResult(file, level);
|
|
949
|
+
}
|
|
950
|
+
let project;
|
|
951
|
+
try {
|
|
952
|
+
const tsConfigPath = findTsConfig(file.path);
|
|
953
|
+
project = new Project2({
|
|
954
|
+
tsConfigFilePath: tsConfigPath,
|
|
955
|
+
skipAddingFilesFromTsConfig: true,
|
|
956
|
+
compilerOptions: tsConfigPath ? void 0 : { allowJs: true, esModuleInterop: true }
|
|
957
|
+
});
|
|
958
|
+
project.createSourceFile(file.path, content, { overwrite: true });
|
|
959
|
+
} catch {
|
|
960
|
+
return pruneGenericFromContent(file, content, level);
|
|
961
|
+
}
|
|
962
|
+
const sourceFile = project.getSourceFiles()[0];
|
|
963
|
+
if (!sourceFile) {
|
|
964
|
+
return pruneGenericFromContent(file, content, level);
|
|
965
|
+
}
|
|
966
|
+
const prunedContent = level === "signatures" ? extractSignaturesAST(sourceFile) : extractSkeletonAST(sourceFile);
|
|
967
|
+
const prunedTokens = countTokensChars4(Buffer.byteLength(prunedContent, "utf-8"));
|
|
968
|
+
const savingsPercent = file.tokens > 0 ? (file.tokens - prunedTokens) / file.tokens * 100 : 0;
|
|
969
|
+
return {
|
|
970
|
+
relativePath: file.relativePath,
|
|
971
|
+
originalTokens: file.tokens,
|
|
972
|
+
prunedTokens,
|
|
973
|
+
pruneLevel: level,
|
|
974
|
+
content: prunedContent,
|
|
975
|
+
savingsPercent: Math.max(0, savingsPercent)
|
|
976
|
+
};
|
|
977
|
+
}
|
|
978
|
+
function extractSignaturesAST(sf) {
|
|
979
|
+
const parts = [];
|
|
980
|
+
for (const imp of sf.getImportDeclarations()) {
|
|
981
|
+
parts.push(imp.getText());
|
|
982
|
+
}
|
|
983
|
+
if (parts.length > 0) parts.push("");
|
|
984
|
+
for (const ta of sf.getTypeAliases()) {
|
|
985
|
+
addJSDoc(ta, parts);
|
|
986
|
+
parts.push(ta.getText());
|
|
987
|
+
}
|
|
988
|
+
for (const iface of sf.getInterfaces()) {
|
|
989
|
+
addJSDoc(iface, parts);
|
|
990
|
+
parts.push(iface.getText());
|
|
991
|
+
}
|
|
992
|
+
for (const en of sf.getEnums()) {
|
|
993
|
+
addJSDoc(en, parts);
|
|
994
|
+
parts.push(en.getText());
|
|
995
|
+
}
|
|
996
|
+
for (const fn of sf.getFunctions()) {
|
|
997
|
+
addJSDoc(fn, parts);
|
|
998
|
+
const isExported = fn.isExported();
|
|
999
|
+
const isAsync = fn.isAsync();
|
|
1000
|
+
const name = fn.getName() ?? "<anonymous>";
|
|
1001
|
+
const params = fn.getParameters().map((p) => p.getText()).join(", ");
|
|
1002
|
+
const returnType = fn.getReturnTypeNode()?.getText();
|
|
1003
|
+
const returnStr = returnType ? `: ${returnType}` : "";
|
|
1004
|
+
const prefix = isExported ? "export " : "";
|
|
1005
|
+
const asyncStr = isAsync ? "async " : "";
|
|
1006
|
+
parts.push(`${prefix}${asyncStr}function ${name}(${params})${returnStr} { /* ... */ }`);
|
|
1007
|
+
}
|
|
1008
|
+
for (const stmt of sf.getVariableStatements()) {
|
|
1009
|
+
for (const decl of stmt.getDeclarations()) {
|
|
1010
|
+
const init = decl.getInitializer();
|
|
1011
|
+
if (init && (init.getKind() === SyntaxKind2.ArrowFunction || init.getKind() === SyntaxKind2.FunctionExpression)) {
|
|
1012
|
+
addJSDoc(stmt, parts);
|
|
1013
|
+
const isExported = stmt.isExported();
|
|
1014
|
+
const prefix = isExported ? "export " : "";
|
|
1015
|
+
const kind = stmt.getDeclarationKind();
|
|
1016
|
+
const name = decl.getName();
|
|
1017
|
+
const typeNode = decl.getTypeNode()?.getText();
|
|
1018
|
+
const typeStr = typeNode ? `: ${typeNode}` : "";
|
|
1019
|
+
parts.push(`${prefix}${kind} ${name}${typeStr} = /* ... */;`);
|
|
1020
|
+
} else {
|
|
1021
|
+
addJSDoc(stmt, parts);
|
|
1022
|
+
parts.push(stmt.getText());
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
for (const cls of sf.getClasses()) {
|
|
1027
|
+
addJSDoc(cls, parts);
|
|
1028
|
+
const isExported = cls.isExported();
|
|
1029
|
+
const prefix = isExported ? "export " : "";
|
|
1030
|
+
const name = cls.getName() ?? "<anonymous>";
|
|
1031
|
+
const ext = cls.getExtends()?.getText();
|
|
1032
|
+
const impl = cls.getImplements().map((i) => i.getText()).join(", ");
|
|
1033
|
+
let header = `${prefix}class ${name}`;
|
|
1034
|
+
if (ext) header += ` extends ${ext}`;
|
|
1035
|
+
if (impl) header += ` implements ${impl}`;
|
|
1036
|
+
header += " {";
|
|
1037
|
+
parts.push(header);
|
|
1038
|
+
for (const prop of cls.getProperties()) {
|
|
1039
|
+
parts.push(` ${prop.getText()}`);
|
|
1040
|
+
}
|
|
1041
|
+
const ctor = cls.getConstructors()[0];
|
|
1042
|
+
if (ctor) {
|
|
1043
|
+
const ctorParams = ctor.getParameters().map((p) => p.getText()).join(", ");
|
|
1044
|
+
parts.push(` constructor(${ctorParams}) { /* ... */ }`);
|
|
1045
|
+
}
|
|
1046
|
+
for (const method of cls.getMethods()) {
|
|
1047
|
+
const isStatic = method.isStatic();
|
|
1048
|
+
const isAsync = method.isAsync();
|
|
1049
|
+
const methodName = method.getName();
|
|
1050
|
+
const methodParams = method.getParameters().map((p) => p.getText()).join(", ");
|
|
1051
|
+
const returnType = method.getReturnTypeNode()?.getText();
|
|
1052
|
+
const returnStr = returnType ? `: ${returnType}` : "";
|
|
1053
|
+
const staticStr = isStatic ? "static " : "";
|
|
1054
|
+
const asyncStr = isAsync ? "async " : "";
|
|
1055
|
+
parts.push(` ${staticStr}${asyncStr}${methodName}(${methodParams})${returnStr} { /* ... */ }`);
|
|
1056
|
+
}
|
|
1057
|
+
parts.push("}");
|
|
1058
|
+
}
|
|
1059
|
+
for (const exp of sf.getExportDeclarations()) {
|
|
1060
|
+
parts.push(exp.getText());
|
|
1061
|
+
}
|
|
1062
|
+
for (const exp of sf.getExportAssignments()) {
|
|
1063
|
+
parts.push(exp.getText());
|
|
1064
|
+
}
|
|
1065
|
+
return parts.join("\n");
|
|
1066
|
+
}
|
|
1067
|
+
function extractSkeletonAST(sf) {
|
|
1068
|
+
const parts = [];
|
|
1069
|
+
for (const imp of sf.getImportDeclarations()) {
|
|
1070
|
+
parts.push(imp.getText());
|
|
1071
|
+
}
|
|
1072
|
+
if (parts.length > 0) parts.push("");
|
|
1073
|
+
for (const ta of sf.getTypeAliases()) {
|
|
1074
|
+
if (ta.isExported()) parts.push(ta.getText());
|
|
1075
|
+
}
|
|
1076
|
+
for (const iface of sf.getInterfaces()) {
|
|
1077
|
+
if (!iface.isExported()) continue;
|
|
1078
|
+
const ext = iface.getExtends().map((e) => e.getText());
|
|
1079
|
+
const extStr = ext.length > 0 ? ` extends ${ext.join(", ")}` : "";
|
|
1080
|
+
parts.push(`export interface ${iface.getName()}${extStr} { /* ${iface.getProperties().length} props */ }`);
|
|
1081
|
+
}
|
|
1082
|
+
for (const en of sf.getEnums()) {
|
|
1083
|
+
if (!en.isExported()) continue;
|
|
1084
|
+
const members = en.getMembers().map((m) => m.getName());
|
|
1085
|
+
parts.push(`export enum ${en.getName()} { ${members.join(", ")} }`);
|
|
1086
|
+
}
|
|
1087
|
+
for (const fn of sf.getFunctions()) {
|
|
1088
|
+
if (!fn.isExported()) continue;
|
|
1089
|
+
const name = fn.getName() ?? "<anonymous>";
|
|
1090
|
+
const params = fn.getParameters().map((p) => p.getText()).join(", ");
|
|
1091
|
+
parts.push(`export function ${name}(${params});`);
|
|
1092
|
+
}
|
|
1093
|
+
for (const cls of sf.getClasses()) {
|
|
1094
|
+
if (!cls.isExported()) continue;
|
|
1095
|
+
const methods = cls.getMethods().map((m) => m.getName());
|
|
1096
|
+
parts.push(`export class ${cls.getName()} { /* methods: ${methods.join(", ")} */ }`);
|
|
1097
|
+
}
|
|
1098
|
+
for (const exp of sf.getExportDeclarations()) {
|
|
1099
|
+
parts.push(exp.getText());
|
|
1100
|
+
}
|
|
1101
|
+
return parts.join("\n");
|
|
1102
|
+
}
|
|
1103
|
+
async function pruneGeneric(file, level) {
|
|
1104
|
+
let content;
|
|
1105
|
+
try {
|
|
1106
|
+
content = await readFile4(file.path, "utf-8");
|
|
1107
|
+
} catch {
|
|
1108
|
+
return emptyResult(file, level);
|
|
1109
|
+
}
|
|
1110
|
+
return pruneGenericFromContent(file, content, level);
|
|
1111
|
+
}
|
|
1112
|
+
function pruneGenericFromContent(file, content, level) {
|
|
1113
|
+
const lines = content.split("\n");
|
|
1114
|
+
let result;
|
|
1115
|
+
if (level === "signatures") {
|
|
1116
|
+
result = lines.filter((line) => {
|
|
1117
|
+
const t = line.trim();
|
|
1118
|
+
return t === "" || t.startsWith("#") || t.startsWith("//") || t.startsWith("import ") || t.startsWith("from ") || t.startsWith("export ") || t.startsWith("def ") || t.startsWith("async def ") || t.startsWith("class ") || t.startsWith("function ") || t.startsWith("const ") || t.startsWith("let ") || t.startsWith("var ") || /^(pub |fn |struct |enum |impl |mod |use )/.test(t);
|
|
1119
|
+
});
|
|
1120
|
+
} else {
|
|
1121
|
+
result = lines.filter((line) => {
|
|
1122
|
+
const t = line.trim();
|
|
1123
|
+
return t.startsWith("import ") || t.startsWith("from ") || t.startsWith("export ") || t.startsWith("def ") || t.startsWith("class ") || t.startsWith("function ") || /^(pub |fn |struct |enum |mod |use )/.test(t);
|
|
1124
|
+
});
|
|
1125
|
+
}
|
|
1126
|
+
const prunedContent = result.join("\n");
|
|
1127
|
+
const prunedTokens = countTokensChars4(Buffer.byteLength(prunedContent, "utf-8"));
|
|
1128
|
+
const savingsPercent = file.tokens > 0 ? (file.tokens - prunedTokens) / file.tokens * 100 : 0;
|
|
1129
|
+
return {
|
|
1130
|
+
relativePath: file.relativePath,
|
|
1131
|
+
originalTokens: file.tokens,
|
|
1132
|
+
prunedTokens,
|
|
1133
|
+
pruneLevel: level,
|
|
1134
|
+
content: prunedContent,
|
|
1135
|
+
savingsPercent: Math.max(0, savingsPercent)
|
|
1136
|
+
};
|
|
1137
|
+
}
|
|
1138
|
+
async function fullContent(file) {
|
|
1139
|
+
let content = "";
|
|
1140
|
+
try {
|
|
1141
|
+
content = await readFile4(file.path, "utf-8");
|
|
1142
|
+
} catch {
|
|
1143
|
+
}
|
|
1144
|
+
return {
|
|
1145
|
+
relativePath: file.relativePath,
|
|
1146
|
+
originalTokens: file.tokens,
|
|
1147
|
+
prunedTokens: file.tokens,
|
|
1148
|
+
pruneLevel: "full",
|
|
1149
|
+
content,
|
|
1150
|
+
savingsPercent: 0
|
|
1151
|
+
};
|
|
1152
|
+
}
|
|
1153
|
+
function emptyResult(file, level) {
|
|
1154
|
+
return {
|
|
1155
|
+
relativePath: file.relativePath,
|
|
1156
|
+
originalTokens: file.tokens,
|
|
1157
|
+
prunedTokens: 0,
|
|
1158
|
+
pruneLevel: level,
|
|
1159
|
+
content: "",
|
|
1160
|
+
savingsPercent: 100
|
|
1161
|
+
};
|
|
1162
|
+
}
|
|
1163
|
+
function addJSDoc(node, parts) {
|
|
1164
|
+
if (!node.getJsDocs) return;
|
|
1165
|
+
const docs = node.getJsDocs();
|
|
1166
|
+
if (docs.length > 0) {
|
|
1167
|
+
parts.push(docs[0].getText());
|
|
1168
|
+
}
|
|
1169
|
+
}
|
|
1170
|
+
function findTsConfig(filePath) {
|
|
1171
|
+
let dir = filePath;
|
|
1172
|
+
for (let i = 0; i < 10; i++) {
|
|
1173
|
+
dir = join4(dir, "..");
|
|
1174
|
+
const candidate = join4(dir, "tsconfig.json");
|
|
1175
|
+
if (existsSync2(candidate)) return candidate;
|
|
1176
|
+
}
|
|
1177
|
+
return void 0;
|
|
1178
|
+
}
|
|
1179
|
+
|
|
1180
|
+
// src/engine/graph-utils.ts
|
|
1181
|
+
function buildAdjacencyList(edges) {
|
|
1182
|
+
const forward = /* @__PURE__ */ new Map();
|
|
1183
|
+
const reverse = /* @__PURE__ */ new Map();
|
|
1184
|
+
for (const edge of edges) {
|
|
1185
|
+
if (!forward.has(edge.from)) forward.set(edge.from, []);
|
|
1186
|
+
forward.get(edge.from).push(edge.to);
|
|
1187
|
+
if (!reverse.has(edge.to)) reverse.set(edge.to, []);
|
|
1188
|
+
reverse.get(edge.to).push(edge.from);
|
|
1189
|
+
}
|
|
1190
|
+
return { forward, reverse };
|
|
1191
|
+
}
|
|
1192
|
+
function bfsBidirectional(seeds, adj, depth) {
|
|
1193
|
+
const result = new Set(seeds);
|
|
1194
|
+
let frontier = [...seeds];
|
|
1195
|
+
const visited = /* @__PURE__ */ new Set();
|
|
1196
|
+
for (let d = 0; d < depth; d++) {
|
|
1197
|
+
const nextFrontier = [];
|
|
1198
|
+
for (const node of frontier) {
|
|
1199
|
+
if (visited.has(node)) continue;
|
|
1200
|
+
visited.add(node);
|
|
1201
|
+
const fwd = adj.forward.get(node);
|
|
1202
|
+
if (fwd) {
|
|
1203
|
+
for (const neighbor of fwd) {
|
|
1204
|
+
if (!visited.has(neighbor)) {
|
|
1205
|
+
result.add(neighbor);
|
|
1206
|
+
nextFrontier.push(neighbor);
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
const rev = adj.reverse.get(node);
|
|
1211
|
+
if (rev) {
|
|
1212
|
+
for (const neighbor of rev) {
|
|
1213
|
+
if (!visited.has(neighbor)) {
|
|
1214
|
+
result.add(neighbor);
|
|
1215
|
+
nextFrontier.push(neighbor);
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
}
|
|
1219
|
+
}
|
|
1220
|
+
frontier = nextFrontier;
|
|
1221
|
+
}
|
|
1222
|
+
return result;
|
|
1223
|
+
}
|
|
1224
|
+
function matchGlob(path, pattern) {
|
|
1225
|
+
const regexStr = pattern.replace(/\./g, "\\.").replace(/\*\*/g, "\xA7\xA7").replace(/\*/g, "[^/]*").replace(/§§/g, ".*").replace(/\?/g, ".");
|
|
1226
|
+
try {
|
|
1227
|
+
return new RegExp(`^${regexStr}$`).test(path);
|
|
1228
|
+
} catch {
|
|
1229
|
+
return false;
|
|
1230
|
+
}
|
|
1231
|
+
}
|
|
1232
|
+
|
|
1233
|
+
// src/engine/coverage.ts
|
|
1234
|
+
function calculateCoverage(targetPaths, includedPaths, allFiles, graph, depth = 2) {
|
|
1235
|
+
const adj = buildAdjacencyList(graph.edges);
|
|
1236
|
+
const relevantSet = targetPaths.length > 0 ? bfsBidirectional(targetPaths, adj, depth) : /* @__PURE__ */ new Set();
|
|
1237
|
+
const includedSet = new Set(includedPaths);
|
|
1238
|
+
const tempFileMap = new Map(allFiles.map((f) => [f.relativePath, f]));
|
|
1239
|
+
for (const path of includedPaths) {
|
|
1240
|
+
const file = tempFileMap.get(path);
|
|
1241
|
+
if (!file) continue;
|
|
1242
|
+
for (const imp of file.imports) {
|
|
1243
|
+
const impFile = tempFileMap.get(imp);
|
|
1244
|
+
if (impFile && impFile.kind === "type") {
|
|
1245
|
+
relevantSet.add(imp);
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
const relevantFiles = Array.from(relevantSet);
|
|
1250
|
+
const includedRelevant = relevantFiles.filter((f) => includedSet.has(f));
|
|
1251
|
+
const missingRelevant = relevantFiles.filter((f) => !includedSet.has(f));
|
|
1252
|
+
const missingCritical = missingRelevant.filter((f) => {
|
|
1253
|
+
const file = tempFileMap.get(f);
|
|
1254
|
+
return file && (file.exclusionImpact === "critical" || file.exclusionImpact === "high");
|
|
1255
|
+
});
|
|
1256
|
+
const fileMap = new Map(allFiles.map((f) => [f.relativePath, f]));
|
|
1257
|
+
let totalRelevantRisk = 0;
|
|
1258
|
+
let includedRelevantRisk = 0;
|
|
1259
|
+
for (const f of relevantFiles) {
|
|
1260
|
+
const risk = fileMap.get(f)?.riskScore ?? 1;
|
|
1261
|
+
totalRelevantRisk += risk;
|
|
1262
|
+
if (includedSet.has(f)) {
|
|
1263
|
+
includedRelevantRisk += risk;
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
const score = totalRelevantRisk > 0 ? Math.round(includedRelevantRisk / totalRelevantRisk * 100) : relevantFiles.length > 0 ? Math.round(includedRelevant.length / relevantFiles.length * 100) : 100;
|
|
1267
|
+
let explanation;
|
|
1268
|
+
if (score >= 90) {
|
|
1269
|
+
explanation = `Excellent coverage (${score}%): AI has nearly all relevant context.`;
|
|
1270
|
+
} else if (score >= 70) {
|
|
1271
|
+
explanation = `Good coverage (${score}%): Most relevant files included.`;
|
|
1272
|
+
if (missingCritical.length > 0) {
|
|
1273
|
+
explanation += ` Warning: ${missingCritical.length} critical file(s) missing.`;
|
|
1274
|
+
}
|
|
1275
|
+
} else if (score >= 50) {
|
|
1276
|
+
explanation = `Partial coverage (${score}%): Significant context is missing.`;
|
|
1277
|
+
if (missingCritical.length > 0) {
|
|
1278
|
+
explanation += ` ${missingCritical.length} critical file(s) not included \u2014 AI quality will degrade.`;
|
|
1279
|
+
}
|
|
1280
|
+
} else {
|
|
1281
|
+
explanation = `Low coverage (${score}%): Most relevant files are excluded. AI response quality will be poor.`;
|
|
1282
|
+
}
|
|
1283
|
+
return {
|
|
1284
|
+
score,
|
|
1285
|
+
relevantFiles,
|
|
1286
|
+
includedRelevant,
|
|
1287
|
+
missingRelevant,
|
|
1288
|
+
missingCritical,
|
|
1289
|
+
explanation
|
|
1290
|
+
};
|
|
1291
|
+
}
|
|
1292
|
+
|
|
1293
|
+
// src/engine/budget.ts
|
|
1294
|
+
function getPruneLevelForRisk(riskScore) {
|
|
1295
|
+
if (riskScore >= 80) return "full";
|
|
1296
|
+
if (riskScore >= 60) return "full";
|
|
1297
|
+
if (riskScore >= 30) return "signatures";
|
|
1298
|
+
return "skeleton";
|
|
1299
|
+
}
|
|
1300
|
+
|
|
1301
|
+
// src/engine/selector.ts
|
|
1302
|
+
async function selectContext(input) {
|
|
1303
|
+
const { task, analysis, budget, policies, depth = 2 } = input;
|
|
1304
|
+
const decisions = [];
|
|
1305
|
+
const targetPaths = identifyTargetFiles(task, analysis.files);
|
|
1306
|
+
if (targetPaths.length > 0) {
|
|
1307
|
+
decisions.push({
|
|
1308
|
+
file: targetPaths.join(", "),
|
|
1309
|
+
action: "include-full",
|
|
1310
|
+
reason: `Target file(s) identified from task description`
|
|
1311
|
+
});
|
|
1312
|
+
}
|
|
1313
|
+
const adj = buildAdjacencyList(analysis.graph.edges);
|
|
1314
|
+
const expandedPaths = targetPaths.length > 0 ? Array.from(bfsBidirectional(targetPaths, adj, depth)) : [];
|
|
1315
|
+
const expansionCount = expandedPaths.length - targetPaths.length;
|
|
1316
|
+
if (expansionCount > 0) {
|
|
1317
|
+
decisions.push({
|
|
1318
|
+
file: `${expansionCount} dependencies`,
|
|
1319
|
+
action: "include-full",
|
|
1320
|
+
reason: `Expanded ${targetPaths.length} target(s) to ${expandedPaths.length} files via dependency graph (depth ${depth})`
|
|
1321
|
+
});
|
|
1322
|
+
}
|
|
1323
|
+
const allFileMap = new Map(analysis.files.map((f) => [f.relativePath, f]));
|
|
1324
|
+
if (targetPaths.length > 0) {
|
|
1325
|
+
for (const path of expandedPaths) {
|
|
1326
|
+
const file = allFileMap.get(path);
|
|
1327
|
+
if (!file) continue;
|
|
1328
|
+
for (const imp of file.imports) {
|
|
1329
|
+
const impFile = allFileMap.get(imp);
|
|
1330
|
+
if (impFile && impFile.kind === "type") {
|
|
1331
|
+
expandedPaths.push(imp);
|
|
1332
|
+
}
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
}
|
|
1336
|
+
const { mustInclude, mustExclude } = applyPolicies(analysis.files, policies);
|
|
1337
|
+
const candidateSet = /* @__PURE__ */ new Set([...expandedPaths, ...mustInclude]);
|
|
1338
|
+
if (targetPaths.length === 0) {
|
|
1339
|
+
for (const f of analysis.files) {
|
|
1340
|
+
candidateSet.add(f.relativePath);
|
|
1341
|
+
}
|
|
1342
|
+
}
|
|
1343
|
+
for (const ex of mustExclude) {
|
|
1344
|
+
candidateSet.delete(ex);
|
|
1345
|
+
decisions.push({
|
|
1346
|
+
file: ex,
|
|
1347
|
+
action: "exclude",
|
|
1348
|
+
reason: "Excluded by policy"
|
|
1349
|
+
});
|
|
1350
|
+
}
|
|
1351
|
+
const hasSecretBlock = policies?.rules.some(
|
|
1352
|
+
(r) => r.type === "secret-block" && r.enabled
|
|
1353
|
+
);
|
|
1354
|
+
if (hasSecretBlock) {
|
|
1355
|
+
for (const path of Array.from(candidateSet)) {
|
|
1356
|
+
const file = allFileMap.get(path);
|
|
1357
|
+
if (!file) continue;
|
|
1358
|
+
const findings = await scanFileForSecrets(
|
|
1359
|
+
file.path,
|
|
1360
|
+
analysis.projectPath
|
|
1361
|
+
);
|
|
1362
|
+
if (findings.length > 0) {
|
|
1363
|
+
candidateSet.delete(path);
|
|
1364
|
+
decisions.push({
|
|
1365
|
+
file: path,
|
|
1366
|
+
action: "exclude",
|
|
1367
|
+
reason: `Blocked: ${findings.length} secret(s) detected (${findings.map((f) => f.type).join(", ")})`
|
|
1368
|
+
});
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1372
|
+
const candidates = Array.from(candidateSet).map((p) => allFileMap.get(p)).filter((f) => f !== void 0).sort((a, b) => {
|
|
1373
|
+
const aIsTarget = targetPaths.includes(a.relativePath) ? 0 : 1;
|
|
1374
|
+
const bIsTarget = targetPaths.includes(b.relativePath) ? 0 : 1;
|
|
1375
|
+
if (aIsTarget !== bIsTarget) return aIsTarget - bIsTarget;
|
|
1376
|
+
const aIsMust = mustInclude.has(a.relativePath) ? 0 : 1;
|
|
1377
|
+
const bIsMust = mustInclude.has(b.relativePath) ? 0 : 1;
|
|
1378
|
+
if (aIsMust !== bIsMust) return aIsMust - bIsMust;
|
|
1379
|
+
return b.riskScore - a.riskScore;
|
|
1380
|
+
});
|
|
1381
|
+
const selectedFiles = [];
|
|
1382
|
+
let usedTokens = 0;
|
|
1383
|
+
for (const file of candidates) {
|
|
1384
|
+
const isTarget = targetPaths.includes(file.relativePath);
|
|
1385
|
+
const isMustInclude = mustInclude.has(file.relativePath);
|
|
1386
|
+
const defaultLevel = isTarget ? "full" : getPruneLevelForRisk(file.riskScore);
|
|
1387
|
+
const levels = getCascadeLevels(defaultLevel);
|
|
1388
|
+
let included = false;
|
|
1389
|
+
for (const level of levels) {
|
|
1390
|
+
if (level === "excluded") break;
|
|
1391
|
+
let tokens;
|
|
1392
|
+
if (level === "full") {
|
|
1393
|
+
tokens = file.tokens;
|
|
1394
|
+
} else {
|
|
1395
|
+
const pruned = await pruneFile(file, level);
|
|
1396
|
+
tokens = pruned.prunedTokens;
|
|
1397
|
+
}
|
|
1398
|
+
if (usedTokens + tokens <= budget) {
|
|
1399
|
+
usedTokens += tokens;
|
|
1400
|
+
selectedFiles.push({
|
|
1401
|
+
relativePath: file.relativePath,
|
|
1402
|
+
tokens,
|
|
1403
|
+
originalTokens: file.tokens,
|
|
1404
|
+
pruneLevel: level,
|
|
1405
|
+
riskScore: file.riskScore,
|
|
1406
|
+
reason: buildReason(file, level, isTarget, isMustInclude)
|
|
1407
|
+
});
|
|
1408
|
+
if (level !== defaultLevel) {
|
|
1409
|
+
decisions.push({
|
|
1410
|
+
file: file.relativePath,
|
|
1411
|
+
action: `include-${level}`,
|
|
1412
|
+
reason: `Downgraded from ${defaultLevel} to ${level} due to budget constraint`,
|
|
1413
|
+
alternatives: `Would need ${file.tokens - tokens} more tokens for ${defaultLevel}`
|
|
1414
|
+
});
|
|
1415
|
+
}
|
|
1416
|
+
included = true;
|
|
1417
|
+
break;
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1420
|
+
if (!included) {
|
|
1421
|
+
decisions.push({
|
|
1422
|
+
file: file.relativePath,
|
|
1423
|
+
action: "exclude",
|
|
1424
|
+
reason: `Budget exhausted (risk: ${file.riskScore}, needs ${file.tokens} tokens)`
|
|
1425
|
+
});
|
|
1426
|
+
}
|
|
1427
|
+
}
|
|
1428
|
+
const includedPaths = selectedFiles.map((f) => f.relativePath);
|
|
1429
|
+
const coverage = calculateCoverage(
|
|
1430
|
+
targetPaths,
|
|
1431
|
+
includedPaths,
|
|
1432
|
+
analysis.files,
|
|
1433
|
+
analysis.graph,
|
|
1434
|
+
depth
|
|
1435
|
+
);
|
|
1436
|
+
const includedSet = new Set(includedPaths);
|
|
1437
|
+
const excludedFiles = analysis.files.filter(
|
|
1438
|
+
(f) => !includedSet.has(f.relativePath)
|
|
1439
|
+
);
|
|
1440
|
+
const excludedRisk = excludedFiles.length > 0 ? Math.round(excludedFiles.reduce((s, f) => s + f.riskScore, 0) / excludedFiles.length) : 0;
|
|
1441
|
+
const hashInput = selectedFiles.map((f) => `${f.relativePath}:${f.pruneLevel}`).sort().join("|") + `|budget:${budget}`;
|
|
1442
|
+
const hash = createHash3("sha256").update(hashInput).digest("hex").substring(0, 16);
|
|
1443
|
+
return {
|
|
1444
|
+
files: selectedFiles,
|
|
1445
|
+
totalTokens: usedTokens,
|
|
1446
|
+
budget,
|
|
1447
|
+
usedPercent: budget > 0 ? Math.round(usedTokens / budget * 100 * 10) / 10 : 0,
|
|
1448
|
+
coverage,
|
|
1449
|
+
riskScore: excludedRisk,
|
|
1450
|
+
deterministic: true,
|
|
1451
|
+
hash,
|
|
1452
|
+
decisions
|
|
1453
|
+
};
|
|
1454
|
+
}
|
|
1455
|
+
function identifyTargetFiles(task, files) {
|
|
1456
|
+
const targets = [];
|
|
1457
|
+
const pathPattern = /(?:^|\s|["'`])([.\w/-]+\.[a-zA-Z]{1,4})(?:\s|$|["'`]|,|:)/g;
|
|
1458
|
+
let match;
|
|
1459
|
+
while ((match = pathPattern.exec(task)) !== null) {
|
|
1460
|
+
const candidate = match[1];
|
|
1461
|
+
const found = files.find(
|
|
1462
|
+
(f) => f.relativePath === candidate || f.relativePath.endsWith(candidate)
|
|
1463
|
+
);
|
|
1464
|
+
if (found && !targets.includes(found.relativePath)) {
|
|
1465
|
+
targets.push(found.relativePath);
|
|
1466
|
+
}
|
|
1467
|
+
}
|
|
1468
|
+
return targets;
|
|
1469
|
+
}
|
|
1470
|
+
function applyPolicies(files, policies) {
|
|
1471
|
+
const mustInclude = /* @__PURE__ */ new Set();
|
|
1472
|
+
const mustExclude = /* @__PURE__ */ new Set();
|
|
1473
|
+
if (!policies) return { mustInclude, mustExclude };
|
|
1474
|
+
for (const rule of policies.rules) {
|
|
1475
|
+
if (!rule.enabled) continue;
|
|
1476
|
+
if (rule.type === "include-always" && rule.pattern) {
|
|
1477
|
+
for (const file of files) {
|
|
1478
|
+
if (matchGlob(file.relativePath, rule.pattern)) {
|
|
1479
|
+
mustInclude.add(file.relativePath);
|
|
1480
|
+
}
|
|
1481
|
+
}
|
|
1482
|
+
}
|
|
1483
|
+
if (rule.type === "exclude-always" && rule.pattern) {
|
|
1484
|
+
for (const file of files) {
|
|
1485
|
+
if (matchGlob(file.relativePath, rule.pattern)) {
|
|
1486
|
+
mustExclude.add(file.relativePath);
|
|
1487
|
+
}
|
|
1488
|
+
}
|
|
1489
|
+
}
|
|
1490
|
+
}
|
|
1491
|
+
return { mustInclude, mustExclude };
|
|
1492
|
+
}
|
|
1493
|
+
function getCascadeLevels(startLevel) {
|
|
1494
|
+
const all = ["full", "signatures", "skeleton", "excluded"];
|
|
1495
|
+
const startIdx = all.indexOf(startLevel);
|
|
1496
|
+
return all.slice(startIdx);
|
|
1497
|
+
}
|
|
1498
|
+
function buildReason(file, level, isTarget, isMustInclude) {
|
|
1499
|
+
if (isTarget) return "Target file";
|
|
1500
|
+
if (isMustInclude) return "Required by policy";
|
|
1501
|
+
const impact = file.exclusionImpact;
|
|
1502
|
+
const levelStr = level === "full" ? "full content" : level;
|
|
1503
|
+
if (impact === "critical") return `Critical dependency (risk ${file.riskScore}) \u2014 ${levelStr}`;
|
|
1504
|
+
if (impact === "high") return `High-risk dependency (risk ${file.riskScore}) \u2014 ${levelStr}`;
|
|
1505
|
+
if (impact === "medium") return `Medium relevance (risk ${file.riskScore}) \u2014 ${levelStr}`;
|
|
1506
|
+
return `Low relevance (risk ${file.riskScore}) \u2014 ${levelStr}`;
|
|
1507
|
+
}
|
|
1508
|
+
|
|
1509
|
+
// src/engine/score.ts
|
|
1510
|
+
async function computeContextScore(analysis, task = "general code review and refactoring", budget = 5e4) {
|
|
1511
|
+
const selection = await selectContext({ task, analysis, budget });
|
|
1512
|
+
const insights = [];
|
|
1513
|
+
const efficiency = scoreEfficiency(analysis, selection, insights);
|
|
1514
|
+
const coverage = scoreCoverage(analysis, selection, insights);
|
|
1515
|
+
const riskControl = scoreRiskControl(analysis, selection, insights);
|
|
1516
|
+
const structure = scoreStructure(analysis, insights);
|
|
1517
|
+
const governance = scoreGovernance(analysis, insights);
|
|
1518
|
+
const overall = Math.round(
|
|
1519
|
+
efficiency.weighted + coverage.weighted + riskControl.weighted + structure.weighted + governance.weighted
|
|
1520
|
+
);
|
|
1521
|
+
const grade = scoreToGrade(overall);
|
|
1522
|
+
const naiveTokens = analysis.totalTokens;
|
|
1523
|
+
const optimizedTokens = selection.totalTokens;
|
|
1524
|
+
const savedTokens = naiveTokens - optimizedTokens;
|
|
1525
|
+
const savedPercent = naiveTokens > 0 ? Math.round(savedTokens / naiveTokens * 100) : 0;
|
|
1526
|
+
const interactionsPerMonth = 40 * 20;
|
|
1527
|
+
const costPerMToken = 3;
|
|
1528
|
+
const naiveMonthlyCost = naiveTokens / 1e6 * costPerMToken * interactionsPerMonth;
|
|
1529
|
+
const optimizedMonthlyCost = optimizedTokens / 1e6 * costPerMToken * interactionsPerMonth;
|
|
1530
|
+
const monthlySavingsUSD = Math.round((naiveMonthlyCost - optimizedMonthlyCost) * 100) / 100;
|
|
1531
|
+
return {
|
|
1532
|
+
overall,
|
|
1533
|
+
grade,
|
|
1534
|
+
dimensions: {
|
|
1535
|
+
efficiency,
|
|
1536
|
+
coverage,
|
|
1537
|
+
riskControl,
|
|
1538
|
+
structure,
|
|
1539
|
+
governance
|
|
1540
|
+
},
|
|
1541
|
+
insights: insights.sort((a, b) => {
|
|
1542
|
+
const order = { high: 0, medium: 1, low: 2 };
|
|
1543
|
+
return order[a.impact] - order[b.impact];
|
|
1544
|
+
}),
|
|
1545
|
+
comparison: {
|
|
1546
|
+
naiveTokens,
|
|
1547
|
+
optimizedTokens,
|
|
1548
|
+
savedTokens,
|
|
1549
|
+
savedPercent,
|
|
1550
|
+
monthlySavingsUSD
|
|
1551
|
+
},
|
|
1552
|
+
meta: {
|
|
1553
|
+
projectName: analysis.projectName,
|
|
1554
|
+
totalFiles: analysis.totalFiles,
|
|
1555
|
+
totalTokens: analysis.totalTokens,
|
|
1556
|
+
analyzedAt: analysis.analyzedAt
|
|
1557
|
+
}
|
|
1558
|
+
};
|
|
1559
|
+
}
|
|
1560
|
+
function scoreEfficiency(analysis, selection, insights) {
|
|
1561
|
+
const weight = 30;
|
|
1562
|
+
const ratio = analysis.totalTokens > 0 ? 1 - selection.totalTokens / analysis.totalTokens : 0;
|
|
1563
|
+
const selectivity = analysis.totalFiles > 0 ? 1 - selection.files.length / analysis.totalFiles : 0;
|
|
1564
|
+
const prunedFiles = selection.files.filter(
|
|
1565
|
+
(f) => f.pruneLevel === "signatures" || f.pruneLevel === "skeleton"
|
|
1566
|
+
).length;
|
|
1567
|
+
const pruneRatio = selection.files.length > 0 ? prunedFiles / selection.files.length : 0;
|
|
1568
|
+
const raw = (ratio * 0.5 + selectivity * 0.3 + pruneRatio * 0.2) * 100;
|
|
1569
|
+
const score = Math.min(100, Math.max(0, Math.round(raw)));
|
|
1570
|
+
const weighted = score / 100 * weight;
|
|
1571
|
+
if (ratio > 0.7) {
|
|
1572
|
+
insights.push({
|
|
1573
|
+
type: "strength",
|
|
1574
|
+
title: "Excellent compression",
|
|
1575
|
+
detail: `${Math.round(ratio * 100)}% token reduction while maintaining context quality`,
|
|
1576
|
+
impact: "high"
|
|
1577
|
+
});
|
|
1578
|
+
}
|
|
1579
|
+
if (ratio < 0.3 && analysis.totalTokens > 2e4) {
|
|
1580
|
+
insights.push({
|
|
1581
|
+
type: "weakness",
|
|
1582
|
+
title: "Low compression opportunity",
|
|
1583
|
+
detail: "Most files are needed. Consider splitting the project into smaller modules.",
|
|
1584
|
+
impact: "medium"
|
|
1585
|
+
});
|
|
1586
|
+
}
|
|
1587
|
+
return {
|
|
1588
|
+
score,
|
|
1589
|
+
weight,
|
|
1590
|
+
weighted,
|
|
1591
|
+
detail: `${Math.round(ratio * 100)}% compression, ${prunedFiles}/${selection.files.length} files pruned`
|
|
1592
|
+
};
|
|
1593
|
+
}
|
|
1594
|
+
function scoreCoverage(analysis, selection, insights) {
|
|
1595
|
+
const weight = 25;
|
|
1596
|
+
const coverageScore = selection.coverage.score;
|
|
1597
|
+
const missingCritical = selection.coverage.missingCritical.length;
|
|
1598
|
+
let penalty = 0;
|
|
1599
|
+
if (missingCritical > 0) {
|
|
1600
|
+
penalty = Math.min(30, missingCritical * 10);
|
|
1601
|
+
insights.push({
|
|
1602
|
+
type: "weakness",
|
|
1603
|
+
title: `${missingCritical} critical file(s) missing from context`,
|
|
1604
|
+
detail: `Missing: ${selection.coverage.missingCritical.slice(0, 3).join(", ")}${missingCritical > 3 ? ` +${missingCritical - 3} more` : ""}`,
|
|
1605
|
+
impact: "high"
|
|
1606
|
+
});
|
|
1607
|
+
}
|
|
1608
|
+
const score = Math.min(100, Math.max(0, Math.round(coverageScore - penalty)));
|
|
1609
|
+
const weighted = score / 100 * weight;
|
|
1610
|
+
if (coverageScore >= 90 && missingCritical === 0) {
|
|
1611
|
+
insights.push({
|
|
1612
|
+
type: "strength",
|
|
1613
|
+
title: "Excellent context coverage",
|
|
1614
|
+
detail: `${coverageScore}% of the relevant universe captured with zero critical gaps`,
|
|
1615
|
+
impact: "high"
|
|
1616
|
+
});
|
|
1617
|
+
}
|
|
1618
|
+
return {
|
|
1619
|
+
score,
|
|
1620
|
+
weight,
|
|
1621
|
+
weighted,
|
|
1622
|
+
detail: `${coverageScore}% coverage, ${missingCritical} critical gaps`
|
|
1623
|
+
};
|
|
1624
|
+
}
|
|
1625
|
+
function scoreRiskControl(analysis, selection, insights) {
|
|
1626
|
+
const weight = 20;
|
|
1627
|
+
const dist = analysis.riskProfile.distribution;
|
|
1628
|
+
const totalFiles = analysis.totalFiles;
|
|
1629
|
+
const criticalFiles = analysis.files.filter((f) => f.riskScore >= 80);
|
|
1630
|
+
const highFiles = analysis.files.filter((f) => f.riskScore >= 60 && f.riskScore < 80);
|
|
1631
|
+
const selectedPaths = new Set(selection.files.map((f) => f.relativePath));
|
|
1632
|
+
const criticalIncluded = criticalFiles.filter((f) => selectedPaths.has(f.relativePath)).length;
|
|
1633
|
+
const highIncluded = highFiles.filter((f) => selectedPaths.has(f.relativePath)).length;
|
|
1634
|
+
const criticalCoverage = criticalFiles.length > 0 ? criticalIncluded / criticalFiles.length : 1;
|
|
1635
|
+
const highCoverage = highFiles.length > 0 ? highIncluded / highFiles.length : 1;
|
|
1636
|
+
const criticalRatio = totalFiles > 0 ? dist.critical / totalFiles : 0;
|
|
1637
|
+
const healthScore = Math.max(0, 1 - criticalRatio * 5);
|
|
1638
|
+
const raw = (criticalCoverage * 0.5 + highCoverage * 0.3 + healthScore * 0.2) * 100;
|
|
1639
|
+
const score = Math.min(100, Math.max(0, Math.round(raw)));
|
|
1640
|
+
const weighted = score / 100 * weight;
|
|
1641
|
+
if (criticalCoverage === 1 && criticalFiles.length > 0) {
|
|
1642
|
+
insights.push({
|
|
1643
|
+
type: "strength",
|
|
1644
|
+
title: "All critical files included",
|
|
1645
|
+
detail: `${criticalFiles.length} critical-risk files are captured in context`,
|
|
1646
|
+
impact: "high"
|
|
1647
|
+
});
|
|
1648
|
+
}
|
|
1649
|
+
if (criticalRatio > 0.2) {
|
|
1650
|
+
insights.push({
|
|
1651
|
+
type: "opportunity",
|
|
1652
|
+
title: "High concentration of critical files",
|
|
1653
|
+
detail: `${dist.critical} files (${Math.round(criticalRatio * 100)}%) are critical risk. Consider refactoring complex modules.`,
|
|
1654
|
+
impact: "medium"
|
|
1655
|
+
});
|
|
1656
|
+
}
|
|
1657
|
+
return {
|
|
1658
|
+
score,
|
|
1659
|
+
weight,
|
|
1660
|
+
weighted,
|
|
1661
|
+
detail: `${criticalIncluded}/${criticalFiles.length} critical + ${highIncluded}/${highFiles.length} high-risk files included`
|
|
1662
|
+
};
|
|
1663
|
+
}
|
|
1664
|
+
function scoreStructure(analysis, insights) {
|
|
1665
|
+
const weight = 15;
|
|
1666
|
+
const graph = analysis.graph;
|
|
1667
|
+
const totalFiles = analysis.totalFiles;
|
|
1668
|
+
const avgCohesion = graph.clusters.length > 0 ? graph.clusters.reduce((s, c) => s + c.cohesion, 0) / graph.clusters.length : 0;
|
|
1669
|
+
const orphanRatio = totalFiles > 0 ? graph.orphans.length / totalFiles : 0;
|
|
1670
|
+
const hubRatio = totalFiles > 0 ? graph.hubs.length / totalFiles : 0;
|
|
1671
|
+
const hubHealth = hubRatio > 0.02 && hubRatio < 0.15 ? 1 : Math.max(0, 1 - Math.abs(hubRatio - 0.08) * 10);
|
|
1672
|
+
const typeFiles = analysis.files.filter((f) => f.kind === "type").length;
|
|
1673
|
+
const typeRatio = totalFiles > 0 ? typeFiles / totalFiles : 0;
|
|
1674
|
+
const typeScore = Math.min(1, typeRatio * 10);
|
|
1675
|
+
const raw = (avgCohesion * 0.3 + (1 - orphanRatio) * 0.3 + hubHealth * 0.2 + typeScore * 0.2) * 100;
|
|
1676
|
+
const score = Math.min(100, Math.max(0, Math.round(raw)));
|
|
1677
|
+
const weighted = score / 100 * weight;
|
|
1678
|
+
if (orphanRatio > 0.5) {
|
|
1679
|
+
insights.push({
|
|
1680
|
+
type: "weakness",
|
|
1681
|
+
title: "Many orphan files",
|
|
1682
|
+
detail: `${graph.orphans.length} files (${Math.round(orphanRatio * 100)}%) have no imports/exports. AI gets less context from the dependency graph.`,
|
|
1683
|
+
impact: "medium"
|
|
1684
|
+
});
|
|
1685
|
+
}
|
|
1686
|
+
if (graph.clusters.length > 0 && avgCohesion > 0.7) {
|
|
1687
|
+
insights.push({
|
|
1688
|
+
type: "strength",
|
|
1689
|
+
title: "Well-organized module structure",
|
|
1690
|
+
detail: `${graph.clusters.length} cohesive clusters (avg cohesion: ${(avgCohesion * 100).toFixed(0)}%). CTO can efficiently select relevant modules.`,
|
|
1691
|
+
impact: "medium"
|
|
1692
|
+
});
|
|
1693
|
+
}
|
|
1694
|
+
return {
|
|
1695
|
+
score,
|
|
1696
|
+
weight,
|
|
1697
|
+
weighted,
|
|
1698
|
+
detail: `${graph.clusters.length} clusters, ${graph.orphans.length} orphans, ${graph.hubs.length} hubs`
|
|
1699
|
+
};
|
|
1700
|
+
}
|
|
1701
|
+
function scoreGovernance(analysis, insights) {
|
|
1702
|
+
const weight = 10;
|
|
1703
|
+
const hasTypes = analysis.files.some((f) => f.kind === "type");
|
|
1704
|
+
const hasConfig = analysis.files.some((f) => f.kind === "config");
|
|
1705
|
+
const hasTests = analysis.files.some((f) => f.kind === "test");
|
|
1706
|
+
let score = 50;
|
|
1707
|
+
if (hasTypes) {
|
|
1708
|
+
score += 15;
|
|
1709
|
+
}
|
|
1710
|
+
if (hasConfig) {
|
|
1711
|
+
score += 10;
|
|
1712
|
+
}
|
|
1713
|
+
if (hasTests) {
|
|
1714
|
+
score += 15;
|
|
1715
|
+
}
|
|
1716
|
+
if (analysis.stack.length > 0) {
|
|
1717
|
+
score += 10;
|
|
1718
|
+
}
|
|
1719
|
+
score = Math.min(100, score);
|
|
1720
|
+
const weighted = score / 100 * weight;
|
|
1721
|
+
if (!hasTests) {
|
|
1722
|
+
insights.push({
|
|
1723
|
+
type: "opportunity",
|
|
1724
|
+
title: "No test files detected",
|
|
1725
|
+
detail: "Adding tests helps CTO understand code intent and provides better context boundaries.",
|
|
1726
|
+
impact: "low"
|
|
1727
|
+
});
|
|
1728
|
+
}
|
|
1729
|
+
if (!hasTypes) {
|
|
1730
|
+
insights.push({
|
|
1731
|
+
type: "opportunity",
|
|
1732
|
+
title: "No type definition files",
|
|
1733
|
+
detail: "Type files dramatically improve AI code generation accuracy. Consider adding interfaces/types.",
|
|
1734
|
+
impact: "medium"
|
|
1735
|
+
});
|
|
1736
|
+
}
|
|
1737
|
+
return {
|
|
1738
|
+
score,
|
|
1739
|
+
weight,
|
|
1740
|
+
weighted,
|
|
1741
|
+
detail: `types:${hasTypes ? "\u2713" : "\u2717"} tests:${hasTests ? "\u2713" : "\u2717"} config:${hasConfig ? "\u2713" : "\u2717"} stack:${analysis.stack.join(",") || "unknown"}`
|
|
1742
|
+
};
|
|
1743
|
+
}
|
|
1744
|
+
function scoreToGrade(score) {
|
|
1745
|
+
if (score >= 95) return "A+";
|
|
1746
|
+
if (score >= 90) return "A";
|
|
1747
|
+
if (score >= 85) return "A-";
|
|
1748
|
+
if (score >= 80) return "B+";
|
|
1749
|
+
if (score >= 75) return "B";
|
|
1750
|
+
if (score >= 70) return "B-";
|
|
1751
|
+
if (score >= 65) return "C+";
|
|
1752
|
+
if (score >= 60) return "C";
|
|
1753
|
+
if (score >= 55) return "C-";
|
|
1754
|
+
if (score >= 40) return "D";
|
|
1755
|
+
return "F";
|
|
1756
|
+
}
|
|
1757
|
+
|
|
1758
|
+
// src/engine/benchmark.ts
|
|
1759
|
+
async function runBenchmark(analysis, task = "general code review and refactoring", budget = 5e4) {
|
|
1760
|
+
const criticalFiles = analysis.files.filter((f) => f.riskScore >= 80);
|
|
1761
|
+
const highRiskFiles = analysis.files.filter((f) => f.riskScore >= 60 && f.riskScore < 80);
|
|
1762
|
+
const ctoStart = performance.now();
|
|
1763
|
+
const ctoSelection = await selectContext({ task, analysis, budget });
|
|
1764
|
+
const ctoTime = performance.now() - ctoStart;
|
|
1765
|
+
const ctoSelectedPaths = new Set(ctoSelection.files.map((f) => f.relativePath));
|
|
1766
|
+
const ctoCritical = criticalFiles.filter((f) => ctoSelectedPaths.has(f.relativePath)).length;
|
|
1767
|
+
const ctoHigh = highRiskFiles.filter((f) => ctoSelectedPaths.has(f.relativePath)).length;
|
|
1768
|
+
const cto = {
|
|
1769
|
+
filesSelected: ctoSelection.files.length,
|
|
1770
|
+
tokensUsed: ctoSelection.totalTokens,
|
|
1771
|
+
coverageScore: ctoSelection.coverage.score,
|
|
1772
|
+
criticalFilesCovered: ctoCritical,
|
|
1773
|
+
criticalFilesTotal: criticalFiles.length,
|
|
1774
|
+
highRiskCovered: ctoHigh,
|
|
1775
|
+
highRiskTotal: highRiskFiles.length,
|
|
1776
|
+
costPerInteractionUSD: ctoSelection.totalTokens / 1e6 * 3,
|
|
1777
|
+
// Sonnet pricing
|
|
1778
|
+
timeMs: Math.round(ctoTime)
|
|
1779
|
+
};
|
|
1780
|
+
const naiveStart = performance.now();
|
|
1781
|
+
const naiveFiles = [...analysis.files].sort((a, b) => a.relativePath.localeCompare(b.relativePath));
|
|
1782
|
+
let naiveTokens = 0;
|
|
1783
|
+
let naiveCount = 0;
|
|
1784
|
+
const naiveSelectedPaths = /* @__PURE__ */ new Set();
|
|
1785
|
+
for (const f of naiveFiles) {
|
|
1786
|
+
if (naiveTokens + f.tokens <= budget) {
|
|
1787
|
+
naiveTokens += f.tokens;
|
|
1788
|
+
naiveCount++;
|
|
1789
|
+
naiveSelectedPaths.add(f.relativePath);
|
|
1790
|
+
}
|
|
1791
|
+
}
|
|
1792
|
+
if (naiveTokens === 0 && analysis.totalTokens <= budget) {
|
|
1793
|
+
naiveTokens = analysis.totalTokens;
|
|
1794
|
+
naiveCount = analysis.totalFiles;
|
|
1795
|
+
for (const f of analysis.files) naiveSelectedPaths.add(f.relativePath);
|
|
1796
|
+
}
|
|
1797
|
+
const naiveTime = performance.now() - naiveStart;
|
|
1798
|
+
const naiveCritical = criticalFiles.filter((f) => naiveSelectedPaths.has(f.relativePath)).length;
|
|
1799
|
+
const naiveHigh = highRiskFiles.filter((f) => naiveSelectedPaths.has(f.relativePath)).length;
|
|
1800
|
+
const naiveCoverage = analysis.totalFiles > 0 ? Math.round(naiveCount / analysis.totalFiles * 100) : 0;
|
|
1801
|
+
const naive = {
|
|
1802
|
+
filesSelected: naiveCount,
|
|
1803
|
+
tokensUsed: naiveTokens > 0 ? naiveTokens : analysis.totalTokens,
|
|
1804
|
+
coverageScore: naiveTokens > 0 ? naiveCoverage : 100,
|
|
1805
|
+
criticalFilesCovered: naiveCritical,
|
|
1806
|
+
criticalFilesTotal: criticalFiles.length,
|
|
1807
|
+
highRiskCovered: naiveHigh,
|
|
1808
|
+
highRiskTotal: highRiskFiles.length,
|
|
1809
|
+
costPerInteractionUSD: (naiveTokens > 0 ? naiveTokens : analysis.totalTokens) / 1e6 * 3,
|
|
1810
|
+
timeMs: Math.round(naiveTime)
|
|
1811
|
+
};
|
|
1812
|
+
const randomStart = performance.now();
|
|
1813
|
+
const shuffled = [...analysis.files].sort(() => Math.random() - 0.5);
|
|
1814
|
+
let randomTokens = 0;
|
|
1815
|
+
let randomCount = 0;
|
|
1816
|
+
const randomSelectedPaths = /* @__PURE__ */ new Set();
|
|
1817
|
+
for (const f of shuffled) {
|
|
1818
|
+
if (randomTokens + f.tokens <= budget) {
|
|
1819
|
+
randomTokens += f.tokens;
|
|
1820
|
+
randomCount++;
|
|
1821
|
+
randomSelectedPaths.add(f.relativePath);
|
|
1822
|
+
}
|
|
1823
|
+
}
|
|
1824
|
+
const randomTime = performance.now() - randomStart;
|
|
1825
|
+
const randomCritical = criticalFiles.filter((f) => randomSelectedPaths.has(f.relativePath)).length;
|
|
1826
|
+
const randomHigh = highRiskFiles.filter((f) => randomSelectedPaths.has(f.relativePath)).length;
|
|
1827
|
+
const randomCoverage = analysis.totalFiles > 0 ? Math.round(randomCount / analysis.totalFiles * 100) : 0;
|
|
1828
|
+
const random = {
|
|
1829
|
+
filesSelected: randomCount,
|
|
1830
|
+
tokensUsed: randomTokens,
|
|
1831
|
+
coverageScore: randomCoverage,
|
|
1832
|
+
criticalFilesCovered: randomCritical,
|
|
1833
|
+
criticalFilesTotal: criticalFiles.length,
|
|
1834
|
+
highRiskCovered: randomHigh,
|
|
1835
|
+
highRiskTotal: highRiskFiles.length,
|
|
1836
|
+
costPerInteractionUSD: randomTokens / 1e6 * 3,
|
|
1837
|
+
timeMs: Math.round(randomTime)
|
|
1838
|
+
};
|
|
1839
|
+
const ctoScore = computeStrategyScore(cto, budget);
|
|
1840
|
+
const naiveScore = computeStrategyScore(naive, budget);
|
|
1841
|
+
const randomScore = computeStrategyScore(random, budget);
|
|
1842
|
+
const winner = ctoScore >= naiveScore && ctoScore >= randomScore ? "cto" : naiveScore >= randomScore ? "naive" : "random";
|
|
1843
|
+
const interactionsPerMonth = 800;
|
|
1844
|
+
const vsNaiveCostSaved = (naive.costPerInteractionUSD - cto.costPerInteractionUSD) * interactionsPerMonth;
|
|
1845
|
+
return {
|
|
1846
|
+
project: analysis.projectName,
|
|
1847
|
+
totalFiles: analysis.totalFiles,
|
|
1848
|
+
totalTokens: analysis.totalTokens,
|
|
1849
|
+
budget,
|
|
1850
|
+
task,
|
|
1851
|
+
strategies: { cto, naive, random },
|
|
1852
|
+
winner,
|
|
1853
|
+
ctoAdvantage: {
|
|
1854
|
+
vsNaiveTokensSaved: naive.tokensUsed - cto.tokensUsed,
|
|
1855
|
+
vsNaiveTokensSavedPercent: naive.tokensUsed > 0 ? Math.round((naive.tokensUsed - cto.tokensUsed) / naive.tokensUsed * 100) : 0,
|
|
1856
|
+
vsRandomCoverageGain: cto.coverageScore - random.coverageScore,
|
|
1857
|
+
vsNaiveCostSavedMonthlyUSD: Math.round(vsNaiveCostSaved * 100) / 100
|
|
1858
|
+
}
|
|
1859
|
+
};
|
|
1860
|
+
}
|
|
1861
|
+
function computeStrategyScore(strategy, budget) {
|
|
1862
|
+
const coverageWeight = strategy.coverageScore / 100;
|
|
1863
|
+
const criticalWeight = strategy.criticalFilesTotal > 0 ? strategy.criticalFilesCovered / strategy.criticalFilesTotal : 1;
|
|
1864
|
+
const efficiency = budget > 0 ? 1 - strategy.tokensUsed / budget : 0;
|
|
1865
|
+
return coverageWeight * 0.5 + criticalWeight * 0.3 + Math.max(0, efficiency) * 0.2;
|
|
1866
|
+
}
|
|
1867
|
+
|
|
1868
|
+
// src/api/dashboard.ts
|
|
1869
|
+
async function loadHistory(ctoDir) {
|
|
1870
|
+
try {
|
|
1871
|
+
const raw = await readFile5(join5(ctoDir, "history.json"), "utf-8");
|
|
1872
|
+
return JSON.parse(raw);
|
|
1873
|
+
} catch {
|
|
1874
|
+
return [];
|
|
1875
|
+
}
|
|
1876
|
+
}
|
|
1877
|
+
async function saveHistory(ctoDir, history) {
|
|
1878
|
+
await mkdir(ctoDir, { recursive: true });
|
|
1879
|
+
await writeFile(join5(ctoDir, "history.json"), JSON.stringify(history, null, 2));
|
|
1880
|
+
}
|
|
1881
|
+
async function generateDashboard(projectPath, task = "general code review and refactoring", budget = 5e4) {
|
|
1882
|
+
const absPath = resolve5(projectPath);
|
|
1883
|
+
const ctoDir = join5(absPath, ".cto");
|
|
1884
|
+
const analysis = await getCachedAnalysis(absPath);
|
|
1885
|
+
const score = await computeContextScore(analysis, task, budget);
|
|
1886
|
+
const benchmark = await runBenchmark(analysis, task, budget);
|
|
1887
|
+
const history = await loadHistory(ctoDir);
|
|
1888
|
+
const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
1889
|
+
const existingIdx = history.findIndex((h) => h.date === today);
|
|
1890
|
+
const entry = {
|
|
1891
|
+
date: today,
|
|
1892
|
+
overall: score.overall,
|
|
1893
|
+
grade: score.grade,
|
|
1894
|
+
files: score.meta.totalFiles,
|
|
1895
|
+
tokens: score.meta.totalTokens,
|
|
1896
|
+
savedPercent: score.comparison.savedPercent
|
|
1897
|
+
};
|
|
1898
|
+
if (existingIdx >= 0) {
|
|
1899
|
+
history[existingIdx] = entry;
|
|
1900
|
+
} else {
|
|
1901
|
+
history.push(entry);
|
|
1902
|
+
}
|
|
1903
|
+
const cutoff = history.length > 90 ? history.length - 90 : 0;
|
|
1904
|
+
const trimmedHistory = history.slice(cutoff);
|
|
1905
|
+
await saveHistory(ctoDir, trimmedHistory);
|
|
1906
|
+
const data = {
|
|
1907
|
+
score,
|
|
1908
|
+
benchmark,
|
|
1909
|
+
history: trimmedHistory,
|
|
1910
|
+
generatedAt: /* @__PURE__ */ new Date()
|
|
1911
|
+
};
|
|
1912
|
+
const html = renderDashboardHTML(data);
|
|
1913
|
+
const htmlPath = join5(ctoDir, "dashboard.html");
|
|
1914
|
+
await mkdir(ctoDir, { recursive: true });
|
|
1915
|
+
await writeFile(htmlPath, html, "utf-8");
|
|
1916
|
+
return { htmlPath, data };
|
|
1917
|
+
}
|
|
1918
|
+
function generateBadgeURL(score) {
|
|
1919
|
+
const color = score.grade.startsWith("A") ? "brightgreen" : score.grade.startsWith("B") ? "blue" : score.grade.startsWith("C") ? "yellow" : "red";
|
|
1920
|
+
return `https://img.shields.io/badge/CTO_Score-${score.overall}%2F100_${encodeURIComponent(score.grade)}-${color}`;
|
|
1921
|
+
}
|
|
1922
|
+
function generateBadgeMarkdown(score) {
|
|
1923
|
+
const url = generateBadgeURL(score);
|
|
1924
|
+
return `[](https://github.com/cto-ai/cto-ai-cli)`;
|
|
1925
|
+
}
|
|
1926
|
+
function renderDashboardHTML(data) {
|
|
1927
|
+
const { score, benchmark, history } = data;
|
|
1928
|
+
const s = score;
|
|
1929
|
+
const b = benchmark;
|
|
1930
|
+
const gradeColor = s.grade.startsWith("A") ? "#22c55e" : s.grade.startsWith("B") ? "#3b82f6" : s.grade.startsWith("C") ? "#eab308" : "#ef4444";
|
|
1931
|
+
const dims = [
|
|
1932
|
+
{ name: "Efficiency", score: s.dimensions.efficiency.score, detail: s.dimensions.efficiency.detail },
|
|
1933
|
+
{ name: "Coverage", score: s.dimensions.coverage.score, detail: s.dimensions.coverage.detail },
|
|
1934
|
+
{ name: "Risk Control", score: s.dimensions.riskControl.score, detail: s.dimensions.riskControl.detail },
|
|
1935
|
+
{ name: "Structure", score: s.dimensions.structure.score, detail: s.dimensions.structure.detail },
|
|
1936
|
+
{ name: "Governance", score: s.dimensions.governance.score, detail: s.dimensions.governance.detail }
|
|
1937
|
+
];
|
|
1938
|
+
const historyPoints = history.map((h) => `{date:'${h.date}',score:${h.overall}}`).join(",");
|
|
1939
|
+
return `<!DOCTYPE html>
|
|
1940
|
+
<html lang="en">
|
|
1941
|
+
<head>
|
|
1942
|
+
<meta charset="utf-8">
|
|
1943
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
1944
|
+
<title>CTO Dashboard \u2014 ${s.meta.projectName}</title>
|
|
1945
|
+
<style>
|
|
1946
|
+
*{margin:0;padding:0;box-sizing:border-box}
|
|
1947
|
+
body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;background:#0f172a;color:#e2e8f0;min-height:100vh}
|
|
1948
|
+
.container{max-width:1200px;margin:0 auto;padding:24px}
|
|
1949
|
+
h1{font-size:28px;font-weight:700;margin-bottom:4px}
|
|
1950
|
+
h2{font-size:20px;font-weight:600;margin-bottom:16px;color:#94a3b8}
|
|
1951
|
+
h3{font-size:16px;font-weight:600;margin-bottom:12px;color:#cbd5e1}
|
|
1952
|
+
.subtitle{color:#64748b;font-size:14px;margin-bottom:32px}
|
|
1953
|
+
.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(350px,1fr));gap:24px;margin-bottom:24px}
|
|
1954
|
+
.card{background:#1e293b;border-radius:12px;padding:24px;border:1px solid #334155}
|
|
1955
|
+
.score-hero{text-align:center;padding:40px 24px}
|
|
1956
|
+
.score-number{font-size:72px;font-weight:800;color:${gradeColor}}
|
|
1957
|
+
.score-grade{font-size:36px;font-weight:700;color:${gradeColor};margin-left:8px}
|
|
1958
|
+
.score-label{font-size:14px;color:#64748b;margin-top:4px}
|
|
1959
|
+
.dim-bar{display:flex;align-items:center;margin-bottom:12px}
|
|
1960
|
+
.dim-label{width:120px;font-size:13px;color:#94a3b8}
|
|
1961
|
+
.dim-track{flex:1;height:8px;background:#334155;border-radius:4px;overflow:hidden}
|
|
1962
|
+
.dim-fill{height:100%;border-radius:4px;transition:width .5s}
|
|
1963
|
+
.dim-value{width:50px;text-align:right;font-size:13px;font-weight:600}
|
|
1964
|
+
.table{width:100%;border-collapse:collapse;font-size:13px}
|
|
1965
|
+
.table th{text-align:left;padding:8px 12px;border-bottom:2px solid #334155;color:#64748b;font-weight:600}
|
|
1966
|
+
.table td{padding:8px 12px;border-bottom:1px solid #1e293b}
|
|
1967
|
+
.table tr:hover td{background:#1e293b}
|
|
1968
|
+
.badge{display:inline-block;padding:4px 10px;border-radius:12px;font-size:12px;font-weight:600}
|
|
1969
|
+
.badge-cto{background:#3b82f620;color:#60a5fa}
|
|
1970
|
+
.badge-naive{background:#64748b20;color:#94a3b8}
|
|
1971
|
+
.badge-random{background:#64748b20;color:#94a3b8}
|
|
1972
|
+
.insight{display:flex;gap:8px;margin-bottom:8px;font-size:13px}
|
|
1973
|
+
.insight-icon{width:20px;text-align:center}
|
|
1974
|
+
.stat{text-align:center}
|
|
1975
|
+
.stat-value{font-size:28px;font-weight:700}
|
|
1976
|
+
.stat-label{font-size:12px;color:#64748b;margin-top:2px}
|
|
1977
|
+
.stats-row{display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:24px}
|
|
1978
|
+
.history-chart{width:100%;height:120px;display:flex;align-items:flex-end;gap:2px;padding:8px 0}
|
|
1979
|
+
.history-bar{flex:1;background:#3b82f6;border-radius:2px 2px 0 0;min-width:3px;transition:height .3s}
|
|
1980
|
+
.history-bar:hover{background:#60a5fa}
|
|
1981
|
+
.badge-embed{background:#0f172a;border:1px solid #334155;border-radius:8px;padding:12px;font-family:monospace;font-size:12px;color:#94a3b8;word-break:break-all;cursor:pointer}
|
|
1982
|
+
.badge-embed:hover{border-color:#60a5fa}
|
|
1983
|
+
footer{text-align:center;padding:24px;color:#475569;font-size:12px}
|
|
1984
|
+
</style>
|
|
1985
|
+
</head>
|
|
1986
|
+
<body>
|
|
1987
|
+
<div class="container">
|
|
1988
|
+
<h1>\u26A1 CTO Dashboard</h1>
|
|
1989
|
+
<p class="subtitle">${s.meta.projectName} \xB7 ${s.meta.totalFiles} files \xB7 ${Math.round(s.meta.totalTokens / 1e3)}K tokens \xB7 Generated ${data.generatedAt.toISOString().split("T")[0]}</p>
|
|
1990
|
+
|
|
1991
|
+
<div class="stats-row">
|
|
1992
|
+
<div class="card stat"><div class="stat-value" style="color:${gradeColor}">${s.overall}</div><div class="stat-label">Context Score\u2122</div></div>
|
|
1993
|
+
<div class="card stat"><div class="stat-value" style="color:${gradeColor}">${s.grade}</div><div class="stat-label">Grade</div></div>
|
|
1994
|
+
<div class="card stat"><div class="stat-value">${s.comparison.savedPercent}%</div><div class="stat-label">Tokens Saved</div></div>
|
|
1995
|
+
<div class="card stat"><div class="stat-value">$${s.comparison.monthlySavingsUSD.toFixed(0)}</div><div class="stat-label">Monthly Savings</div></div>
|
|
1996
|
+
</div>
|
|
1997
|
+
|
|
1998
|
+
<div class="grid">
|
|
1999
|
+
|
|
2000
|
+
<div class="card">
|
|
2001
|
+
<h3>Dimensions</h3>
|
|
2002
|
+
${dims.map((d) => `
|
|
2003
|
+
<div class="dim-bar">
|
|
2004
|
+
<span class="dim-label">${d.name}</span>
|
|
2005
|
+
<div class="dim-track"><div class="dim-fill" style="width:${d.score}%;background:${d.score >= 80 ? "#22c55e" : d.score >= 60 ? "#3b82f6" : d.score >= 40 ? "#eab308" : "#ef4444"}"></div></div>
|
|
2006
|
+
<span class="dim-value">${d.score}%</span>
|
|
2007
|
+
</div>`).join("")}
|
|
2008
|
+
<div style="margin-top:16px;font-size:11px;color:#475569">
|
|
2009
|
+
${dims.map((d) => `${d.name}: ${d.detail}`).join("<br>")}
|
|
2010
|
+
</div>
|
|
2011
|
+
</div>
|
|
2012
|
+
|
|
2013
|
+
<div class="card">
|
|
2014
|
+
<h3>\u26A1 Benchmark: CTO vs Naive vs Random</h3>
|
|
2015
|
+
<table class="table">
|
|
2016
|
+
<tr><th>Metric</th><th><span class="badge badge-cto">CTO</span></th><th><span class="badge badge-naive">Naive</span></th><th><span class="badge badge-random">Random</span></th></tr>
|
|
2017
|
+
<tr><td>Files</td><td>${b.strategies.cto.filesSelected}</td><td>${b.strategies.naive.filesSelected}</td><td>${b.strategies.random.filesSelected}</td></tr>
|
|
2018
|
+
<tr><td>Tokens</td><td>${fmt(b.strategies.cto.tokensUsed)}</td><td>${fmt(b.strategies.naive.tokensUsed)}</td><td>${fmt(b.strategies.random.tokensUsed)}</td></tr>
|
|
2019
|
+
<tr><td>Coverage</td><td><b>${b.strategies.cto.coverageScore}%</b></td><td>${b.strategies.naive.coverageScore}%</td><td>${b.strategies.random.coverageScore}%</td></tr>
|
|
2020
|
+
<tr><td>High-Risk</td><td><b>${b.strategies.cto.highRiskCovered}/${b.strategies.cto.highRiskTotal}</b></td><td>${b.strategies.naive.highRiskCovered}/${b.strategies.naive.highRiskTotal}</td><td>${b.strategies.random.highRiskCovered}/${b.strategies.random.highRiskTotal}</td></tr>
|
|
2021
|
+
<tr><td>Cost/call</td><td>$${b.strategies.cto.costPerInteractionUSD.toFixed(4)}</td><td>$${b.strategies.naive.costPerInteractionUSD.toFixed(4)}</td><td>$${b.strategies.random.costPerInteractionUSD.toFixed(4)}</td></tr>
|
|
2022
|
+
</table>
|
|
2023
|
+
</div>
|
|
2024
|
+
|
|
2025
|
+
<div class="card">
|
|
2026
|
+
<h3>\u{1F4A1} Insights</h3>
|
|
2027
|
+
${s.insights.slice(0, 8).map((i) => {
|
|
2028
|
+
const icon = i.type === "strength" ? "\u2705" : i.type === "weakness" ? "\u26A0\uFE0F" : "\u{1F4A1}";
|
|
2029
|
+
return `<div class="insight"><span class="insight-icon">${icon}</span><span><b>${i.title}</b> \u2014 ${i.detail}</span></div>`;
|
|
2030
|
+
}).join("")}
|
|
2031
|
+
</div>
|
|
2032
|
+
|
|
2033
|
+
<div class="card">
|
|
2034
|
+
<h3>\u{1F4C8} Score History</h3>
|
|
2035
|
+
${history.length > 1 ? `
|
|
2036
|
+
<div class="history-chart">
|
|
2037
|
+
${history.map((h) => `<div class="history-bar" style="height:${h.overall}%" title="${h.date}: ${h.overall}/100 (${h.grade})"></div>`).join("")}
|
|
2038
|
+
</div>
|
|
2039
|
+
<div style="display:flex;justify-content:space-between;font-size:11px;color:#475569">
|
|
2040
|
+
<span>${history[0]?.date}</span>
|
|
2041
|
+
<span>${history[history.length - 1]?.date}</span>
|
|
2042
|
+
</div>
|
|
2043
|
+
` : '<p style="color:#64748b;font-size:13px">Run <code>cto2 dashboard</code> daily to build score history.</p>'}
|
|
2044
|
+
</div>
|
|
2045
|
+
|
|
2046
|
+
</div>
|
|
2047
|
+
|
|
2048
|
+
<div class="card" style="margin-bottom:24px">
|
|
2049
|
+
<h3>\u{1F3F7}\uFE0F Badge</h3>
|
|
2050
|
+
<p style="margin-bottom:12px"><img src="${generateBadgeURL(s)}" alt="CTO Score"></p>
|
|
2051
|
+
<p style="font-size:12px;color:#64748b;margin-bottom:8px">Add this to your README:</p>
|
|
2052
|
+
<div class="badge-embed" onclick="navigator.clipboard.writeText(this.textContent)">${generateBadgeMarkdown(s)}</div>
|
|
2053
|
+
</div>
|
|
2054
|
+
|
|
2055
|
+
<footer>
|
|
2056
|
+
CTO Context Score\u2122 \xB7 Generated by <a href="https://github.com/cto-ai/cto-ai-cli" style="color:#60a5fa">cto-ai-cli</a>
|
|
2057
|
+
</footer>
|
|
2058
|
+
|
|
2059
|
+
</div>
|
|
2060
|
+
</body>
|
|
2061
|
+
</html>`;
|
|
2062
|
+
}
|
|
2063
|
+
function fmt(n) {
|
|
2064
|
+
if (n >= 1e6) return `${(n / 1e6).toFixed(1)}M`;
|
|
2065
|
+
if (n >= 1e3) return `${(n / 1e3).toFixed(1)}K`;
|
|
2066
|
+
return n.toString();
|
|
2067
|
+
}
|
|
2068
|
+
export {
|
|
2069
|
+
generateBadgeMarkdown,
|
|
2070
|
+
generateBadgeURL,
|
|
2071
|
+
generateDashboard
|
|
2072
|
+
};
|
|
2073
|
+
//# sourceMappingURL=dashboard.js.map
|