@floydous/pi-agent-kernel 0.4.3 → 0.5.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/AGENT_KERNEL_SYS_PROMPT.md +1 -7
- package/CHANGELOG.md +36 -0
- package/README.md +6 -53
- package/config.example.toml +0 -8
- package/docs/README.md +1 -2
- package/docs/architecture.md +2 -3
- package/docs/configuration.md +10 -9
- package/docs/editing-and-verification.md +1 -3
- package/docs/retrieval.md +6 -11
- package/docs/testing.md +3 -3
- package/package.json +4 -2
- package/src/config/agent_kernel_command.ts +8 -39
- package/src/config/kernel_config.ts +30 -68
- package/src/config/toml.ts +6 -1
- package/src/editing/auto_heal.ts +1 -1
- package/src/editing/patch.ts +27 -16
- package/src/editing/post_edit_verification.ts +12 -10
- package/src/editing/smart_anchor.ts +7 -5
- package/src/editing/syntax-verify.ts +9 -5
- package/src/index.ts +15 -257
- package/src/retrieval/search_bm25.ts +4 -2
- package/src/retrieval/search_chunker.ts +1 -1
- package/src/retrieval/search_config.ts +4 -6
- package/src/retrieval/search_embedder.ts +3 -2
- package/src/retrieval/search_index.ts +82 -35
- package/src/retrieval/search_modal.ts +7 -8
- package/src/retrieval/{repomap.ts → tag_extractor.ts} +5 -292
- package/src/retrieval/tree_sitter_engine.ts +70 -34
- package/src/retrieval/workspace_walker.ts +6 -2
- package/src/safety/atomic_write.ts +1 -1
- package/src/safety/epistemic_guard.ts +105 -31
- package/src/safety/output_clamper.ts +14 -8
- package/src/tools/code_search_output.ts +2 -1
- package/src/tools/code_search_tool.ts +2 -5
- package/src/tools/context.ts +0 -14
- package/src/tools/edit_tool.ts +82 -115
- package/src/tools/read_tool.ts +42 -178
- package/src/ui/footer.ts +7 -7
- package/docs/lsp.md +0 -31
- package/src/lsp/adapters/base.ts +0 -42
- package/src/lsp/adapters/index.ts +0 -21
- package/src/lsp/adapters/python.ts +0 -37
- package/src/lsp/adapters/rust.ts +0 -35
- package/src/lsp/adapters/typescript.ts +0 -40
- package/src/lsp/index.ts +0 -13
- package/src/lsp/lsp_client.ts +0 -765
- package/src/lsp/lsp_detector.ts +0 -52
- package/src/lsp/lsp_formatter.ts +0 -323
- package/src/lsp/lsp_installer.ts +0 -320
- package/src/lsp/lsp_manager.ts +0 -202
- package/src/lsp/lsp_modal.ts +0 -675
- package/src/lsp/lsp_registry.ts +0 -600
- package/src/lsp/lsp_types.ts +0 -143
- package/src/retrieval/ast_search.ts +0 -999
- package/src/retrieval/symbol_reader.ts +0 -228
- package/src/tools/ast_search_formatter.ts +0 -161
- package/src/tools/ast_search_tool.ts +0 -146
- package/src/tools/lsp_tool.ts +0 -794
- package/src/tools/repo_map_tool.ts +0 -56
|
@@ -49,7 +49,13 @@ interface PersistedIndexSnapshot {
|
|
|
49
49
|
}
|
|
50
50
|
|
|
51
51
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
52
|
-
return
|
|
52
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function compareStrings(a: string, b: string): number {
|
|
56
|
+
if (a < b) return -1;
|
|
57
|
+
if (a > b) return 1;
|
|
58
|
+
return 0;
|
|
53
59
|
}
|
|
54
60
|
|
|
55
61
|
function readDescriptorBounded(descriptor: number, maxBytes: number): Buffer {
|
|
@@ -150,6 +156,8 @@ export function validatePersistedIndex(
|
|
|
150
156
|
const chunkFiles = new Map<string, string>();
|
|
151
157
|
for (const value of data.chunks) {
|
|
152
158
|
if (!isRecord(value)) throw new Error("Persisted chunk must be an object");
|
|
159
|
+
// SAFETY: value is confirmed to be an object via isRecord, and each property of CodeChunk
|
|
160
|
+
// is individually runtime-validated below (id, filePath, lines, content, hash) before acceptance.
|
|
153
161
|
const chunk = value as unknown as CodeChunk;
|
|
154
162
|
if (
|
|
155
163
|
typeof chunk.id !== "string" ||
|
|
@@ -336,8 +344,6 @@ export class HybridSearchIndex {
|
|
|
336
344
|
private activeFileUpdates = new Map<string, Promise<void>>();
|
|
337
345
|
private debouncedSaveTimer: NodeJS.Timeout | null = null;
|
|
338
346
|
private debouncedSaveDeadline: number | null = null;
|
|
339
|
-
private isSaving = false;
|
|
340
|
-
private hasPendingSave = false;
|
|
341
347
|
private isShuttingDown = false;
|
|
342
348
|
private activeSavePromise: Promise<void> | null = null;
|
|
343
349
|
private activeSync: Promise<{ chunkCount: number; fileCount: number; indexedCount: number }> | null = null;
|
|
@@ -398,8 +404,9 @@ export class HybridSearchIndex {
|
|
|
398
404
|
) {
|
|
399
405
|
void this.embedder.dispose();
|
|
400
406
|
try {
|
|
401
|
-
|
|
402
|
-
|
|
407
|
+
const globalWithGc = globalThis as typeof globalThis & { gc?: () => void };
|
|
408
|
+
if (typeof globalWithGc.gc === "function") {
|
|
409
|
+
globalWithGc.gc();
|
|
403
410
|
}
|
|
404
411
|
} catch (e) {
|
|
405
412
|
kernelDebug(e);
|
|
@@ -417,7 +424,7 @@ export class HybridSearchIndex {
|
|
|
417
424
|
this.config.effectiveProfile === "hybrid" ||
|
|
418
425
|
this.config.effectiveProfile === "full"
|
|
419
426
|
) {
|
|
420
|
-
return
|
|
427
|
+
return this.embedder.initialize(onProgress);
|
|
421
428
|
}
|
|
422
429
|
return false;
|
|
423
430
|
}
|
|
@@ -648,8 +655,6 @@ export class HybridSearchIndex {
|
|
|
648
655
|
*/
|
|
649
656
|
public saveToDisk(): void {
|
|
650
657
|
try {
|
|
651
|
-
const cacheDir = this.getCacheDir();
|
|
652
|
-
|
|
653
658
|
const chunkList = Array.from(this.chunks.values());
|
|
654
659
|
const fileHashesObj: Record<string, string> = {};
|
|
655
660
|
for (const [f, h] of this.fileHashes.entries()) {
|
|
@@ -667,7 +672,14 @@ export class HybridSearchIndex {
|
|
|
667
672
|
Array.from(this.vectors.keys()).every((id) => this.chunks.has(id))
|
|
668
673
|
) {
|
|
669
674
|
const vectorChunkIds = Array.from(this.vectors.keys());
|
|
670
|
-
const vectorArrays =
|
|
675
|
+
const vectorArrays: Float32Array[] = [];
|
|
676
|
+
for (const id of vectorChunkIds) {
|
|
677
|
+
const vec = this.vectors.get(id);
|
|
678
|
+
if (vec) vectorArrays.push(vec);
|
|
679
|
+
}
|
|
680
|
+
if (vectorArrays.length !== vectorChunkIds.length || vectorArrays.length === 0) {
|
|
681
|
+
return;
|
|
682
|
+
}
|
|
671
683
|
const vectorDim = vectorArrays[0].length;
|
|
672
684
|
const vectorBuffer = Buffer.alloc(vectorArrays.length * vectorDim * 4);
|
|
673
685
|
for (let i = 0; i < vectorArrays.length; i++) {
|
|
@@ -870,7 +882,7 @@ export class HybridSearchIndex {
|
|
|
870
882
|
private getWorkspaceFileHashes(): Map<string, string> | null {
|
|
871
883
|
const hashes = new Map<string, string>();
|
|
872
884
|
let workspaceBytes = 0;
|
|
873
|
-
const files = findChunkableFiles(this.cwd).sort();
|
|
885
|
+
const files = findChunkableFiles(this.cwd).sort(compareStrings);
|
|
874
886
|
for (const filePath of files) {
|
|
875
887
|
const relPath = path.relative(this.cwd, filePath).replace(/\\/g, "/");
|
|
876
888
|
try {
|
|
@@ -984,7 +996,7 @@ export class HybridSearchIndex {
|
|
|
984
996
|
onProgress?.("Scanning workspace files...");
|
|
985
997
|
|
|
986
998
|
// Ensure Tree-sitter parsers are warm for languages present in this workspace
|
|
987
|
-
const chunkableFiles = findChunkableFiles(this.cwd).sort();
|
|
999
|
+
const chunkableFiles = findChunkableFiles(this.cwd).sort(compareStrings);
|
|
988
1000
|
this.skippedOversizedFiles.clear();
|
|
989
1001
|
const workspaceExts = new Set<string>();
|
|
990
1002
|
for (const f of chunkableFiles) {
|
|
@@ -1072,12 +1084,16 @@ export class HybridSearchIndex {
|
|
|
1072
1084
|
for (const delPath of filesToDelete) {
|
|
1073
1085
|
this.bm25.removeFile(delPath);
|
|
1074
1086
|
this.fileHashes.delete(delPath);
|
|
1075
|
-
|
|
1087
|
+
const toDelete: string[] = [];
|
|
1088
|
+
for (const chunkId of this.chunks.keys()) {
|
|
1076
1089
|
if (chunkId.startsWith(`${delPath}:`)) {
|
|
1077
|
-
|
|
1078
|
-
this.vectors.delete(chunkId);
|
|
1090
|
+
toDelete.push(chunkId);
|
|
1079
1091
|
}
|
|
1080
1092
|
}
|
|
1093
|
+
for (const chunkId of toDelete) {
|
|
1094
|
+
this.chunks.delete(chunkId);
|
|
1095
|
+
this.vectors.delete(chunkId);
|
|
1096
|
+
}
|
|
1081
1097
|
}
|
|
1082
1098
|
if (filesToDelete.length > 0) {
|
|
1083
1099
|
this.bm25.recalculateStats();
|
|
@@ -1091,12 +1107,16 @@ export class HybridSearchIndex {
|
|
|
1091
1107
|
for (const relPath of filesToReindex) {
|
|
1092
1108
|
// Clean old chunks for this file
|
|
1093
1109
|
this.bm25.removeFile(relPath);
|
|
1094
|
-
|
|
1110
|
+
const toDelete: string[] = [];
|
|
1111
|
+
for (const chunkId of this.chunks.keys()) {
|
|
1095
1112
|
if (chunkId.startsWith(`${relPath}:`)) {
|
|
1096
|
-
|
|
1097
|
-
this.vectors.delete(chunkId);
|
|
1113
|
+
toDelete.push(chunkId);
|
|
1098
1114
|
}
|
|
1099
1115
|
}
|
|
1116
|
+
for (const chunkId of toDelete) {
|
|
1117
|
+
this.chunks.delete(chunkId);
|
|
1118
|
+
this.vectors.delete(chunkId);
|
|
1119
|
+
}
|
|
1100
1120
|
|
|
1101
1121
|
const fileInfo = currentFiles.get(relPath);
|
|
1102
1122
|
if (fileInfo) {
|
|
@@ -1203,12 +1223,16 @@ export class HybridSearchIndex {
|
|
|
1203
1223
|
private removeIndexedFile(relPath: string): void {
|
|
1204
1224
|
this.bm25.removeFile(relPath);
|
|
1205
1225
|
this.fileHashes.delete(relPath);
|
|
1206
|
-
|
|
1226
|
+
const toDelete: string[] = [];
|
|
1227
|
+
for (const chunkId of this.chunks.keys()) {
|
|
1207
1228
|
if (chunkId.startsWith(`${relPath}:`)) {
|
|
1208
|
-
|
|
1209
|
-
this.vectors.delete(chunkId);
|
|
1229
|
+
toDelete.push(chunkId);
|
|
1210
1230
|
}
|
|
1211
1231
|
}
|
|
1232
|
+
for (const chunkId of toDelete) {
|
|
1233
|
+
this.chunks.delete(chunkId);
|
|
1234
|
+
this.vectors.delete(chunkId);
|
|
1235
|
+
}
|
|
1212
1236
|
}
|
|
1213
1237
|
|
|
1214
1238
|
/**
|
|
@@ -1255,12 +1279,16 @@ export class HybridSearchIndex {
|
|
|
1255
1279
|
if (this.fileGenerations.get(relPath) !== currentGen) return;
|
|
1256
1280
|
this.bm25.removeFile(relPath);
|
|
1257
1281
|
this.fileHashes.delete(relPath);
|
|
1258
|
-
|
|
1282
|
+
const toDelete: string[] = [];
|
|
1283
|
+
for (const chunkId of this.chunks.keys()) {
|
|
1259
1284
|
if (chunkId.startsWith(`${relPath}:`)) {
|
|
1260
|
-
|
|
1261
|
-
this.vectors.delete(chunkId);
|
|
1285
|
+
toDelete.push(chunkId);
|
|
1262
1286
|
}
|
|
1263
1287
|
}
|
|
1288
|
+
for (const chunkId of toDelete) {
|
|
1289
|
+
this.chunks.delete(chunkId);
|
|
1290
|
+
this.vectors.delete(chunkId);
|
|
1291
|
+
}
|
|
1264
1292
|
this.dirtyFiles.delete(relPath);
|
|
1265
1293
|
this.bm25.recalculateStats();
|
|
1266
1294
|
this.scheduleDebouncedSave();
|
|
@@ -1319,12 +1347,16 @@ export class HybridSearchIndex {
|
|
|
1319
1347
|
if (this.fileGenerations.get(relPath) !== currentGen) return;
|
|
1320
1348
|
this.bm25.removeFile(relPath);
|
|
1321
1349
|
this.fileHashes.delete(relPath);
|
|
1322
|
-
|
|
1350
|
+
const toDelete: string[] = [];
|
|
1351
|
+
for (const chunkId of this.chunks.keys()) {
|
|
1323
1352
|
if (chunkId.startsWith(`${relPath}:`)) {
|
|
1324
|
-
|
|
1325
|
-
this.vectors.delete(chunkId);
|
|
1353
|
+
toDelete.push(chunkId);
|
|
1326
1354
|
}
|
|
1327
1355
|
}
|
|
1356
|
+
for (const chunkId of toDelete) {
|
|
1357
|
+
this.chunks.delete(chunkId);
|
|
1358
|
+
this.vectors.delete(chunkId);
|
|
1359
|
+
}
|
|
1328
1360
|
this.dirtyFiles.delete(relPath);
|
|
1329
1361
|
this.bm25.recalculateStats();
|
|
1330
1362
|
this.scheduleDebouncedSave();
|
|
@@ -1341,7 +1373,7 @@ export class HybridSearchIndex {
|
|
|
1341
1373
|
const fileChunks = Array.from(this.chunks.values()).filter((chunk) => chunk.filePath === relPath);
|
|
1342
1374
|
const fileVectorsReady = !wantsVectors || fileChunks.every((chunk) => {
|
|
1343
1375
|
const vector = this.vectors.get(chunk.id);
|
|
1344
|
-
return
|
|
1376
|
+
return Boolean(vector && vector.length === this.config.matryoshkaDim);
|
|
1345
1377
|
});
|
|
1346
1378
|
if (this.fileHashes.get(relPath) === fileHash && !this.dirtyFiles.has(relPath) && fileVectorsReady) {
|
|
1347
1379
|
return;
|
|
@@ -1414,12 +1446,16 @@ export class HybridSearchIndex {
|
|
|
1414
1446
|
|
|
1415
1447
|
// Atomic in-memory swap:
|
|
1416
1448
|
this.bm25.removeFile(relPath);
|
|
1417
|
-
|
|
1449
|
+
const toDelete: string[] = [];
|
|
1450
|
+
for (const chunkId of this.chunks.keys()) {
|
|
1418
1451
|
if (chunkId.startsWith(`${relPath}:`)) {
|
|
1419
|
-
|
|
1420
|
-
this.vectors.delete(chunkId);
|
|
1452
|
+
toDelete.push(chunkId);
|
|
1421
1453
|
}
|
|
1422
1454
|
}
|
|
1455
|
+
for (const chunkId of toDelete) {
|
|
1456
|
+
this.chunks.delete(chunkId);
|
|
1457
|
+
this.vectors.delete(chunkId);
|
|
1458
|
+
}
|
|
1423
1459
|
|
|
1424
1460
|
this.fileHashes.set(relPath, fileHash);
|
|
1425
1461
|
for (const chunk of newChunks) {
|
|
@@ -1465,12 +1501,16 @@ export class HybridSearchIndex {
|
|
|
1465
1501
|
) return;
|
|
1466
1502
|
this.bm25.removeFile(relPath);
|
|
1467
1503
|
this.fileHashes.delete(relPath);
|
|
1468
|
-
|
|
1504
|
+
const toDelete: string[] = [];
|
|
1505
|
+
for (const chunkId of this.chunks.keys()) {
|
|
1469
1506
|
if (chunkId.startsWith(`${relPath}:`)) {
|
|
1470
|
-
|
|
1471
|
-
this.vectors.delete(chunkId);
|
|
1507
|
+
toDelete.push(chunkId);
|
|
1472
1508
|
}
|
|
1473
1509
|
}
|
|
1510
|
+
for (const chunkId of toDelete) {
|
|
1511
|
+
this.chunks.delete(chunkId);
|
|
1512
|
+
this.vectors.delete(chunkId);
|
|
1513
|
+
}
|
|
1474
1514
|
this.bm25.recalculateStats();
|
|
1475
1515
|
this.generation++;
|
|
1476
1516
|
this.dirtyFiles.add(relPath);
|
|
@@ -1528,7 +1568,7 @@ export class HybridSearchIndex {
|
|
|
1528
1568
|
// 1. BM25 Search (Instant AST-tokenized lexical retrieval)
|
|
1529
1569
|
const bm25Results = this.bm25.search(query, 100, (chunkId) => {
|
|
1530
1570
|
const chunk = this.chunks.get(chunkId);
|
|
1531
|
-
return
|
|
1571
|
+
return Boolean(chunk && matchesFilePattern(chunk));
|
|
1532
1572
|
});
|
|
1533
1573
|
const bm25RankMap = new Map<
|
|
1534
1574
|
string,
|
|
@@ -1603,12 +1643,19 @@ export class HybridSearchIndex {
|
|
|
1603
1643
|
const rrfVec = vecData ? 1 / (k + vecRank) : 0;
|
|
1604
1644
|
const rrfScore = rrfBm25 + rrfVec;
|
|
1605
1645
|
|
|
1646
|
+
let signal: "hybrid" | "semantic" | "lexical" = "lexical";
|
|
1647
|
+
if (bmData && vecData) {
|
|
1648
|
+
signal = "hybrid";
|
|
1649
|
+
} else if (vecData) {
|
|
1650
|
+
signal = "semantic";
|
|
1651
|
+
}
|
|
1652
|
+
|
|
1606
1653
|
hits.push({
|
|
1607
1654
|
chunk,
|
|
1608
1655
|
rrfScore,
|
|
1609
1656
|
bm25Score: bmData ? bmData.score : 0,
|
|
1610
1657
|
vectorScore: vecData ? vecData.score : 0,
|
|
1611
|
-
signal
|
|
1658
|
+
signal,
|
|
1612
1659
|
bm25Rank: bmData?.rank,
|
|
1613
1660
|
vectorRank: vecData?.rank,
|
|
1614
1661
|
matches: bmData?.matches || [],
|
|
@@ -243,11 +243,12 @@ export class SearchControlModal implements Focusable {
|
|
|
243
243
|
const cursor = isSelected ? `${fgTitle} > ` : " ";
|
|
244
244
|
const radio = isCurrentProfile ? `${fgSelected}[x]` : `${fgDim}[ ]`;
|
|
245
245
|
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
246
|
+
let labelText = `${fgMuted}${item.label}`;
|
|
247
|
+
if (isSelected) {
|
|
248
|
+
labelText = `${fgActive}${item.label}`;
|
|
249
|
+
} else if (isCurrentProfile) {
|
|
250
|
+
labelText = `${fgSelected}${item.label}`;
|
|
251
|
+
}
|
|
251
252
|
|
|
252
253
|
let descExtra = "";
|
|
253
254
|
if (item.profile === "hybrid" || item.profile === "full") {
|
|
@@ -296,9 +297,7 @@ export class SearchControlModal implements Focusable {
|
|
|
296
297
|
cardLines.push(bgCard + fgBorder + `╰${"─".repeat(innerW)}╯` + reset);
|
|
297
298
|
|
|
298
299
|
// Terminal height resolution for full-viewport coverage
|
|
299
|
-
const termHeight =
|
|
300
|
-
this.tui?.terminal?.rows ||
|
|
301
|
-
(process.stdout && process.stdout.rows ? process.stdout.rows : 24);
|
|
300
|
+
const termHeight = this.tui?.terminal?.rows || process.stdout?.rows || 24;
|
|
302
301
|
|
|
303
302
|
// Layout calculations for full-screen backdrop framing
|
|
304
303
|
const leftPad = Math.max(0, Math.floor((width - cardWidth) / 2));
|
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import * as fs from "node:fs";
|
|
2
1
|
import * as path from "node:path";
|
|
3
2
|
import { TreeSitterEngine } from "./tree_sitter_engine";
|
|
4
|
-
import { walkWorkspaceFiles
|
|
3
|
+
import { walkWorkspaceFiles } from "./workspace_walker";
|
|
5
4
|
|
|
6
5
|
export interface SymbolDef {
|
|
7
6
|
name: string;
|
|
@@ -32,8 +31,6 @@ export interface FileTags {
|
|
|
32
31
|
hasSyntaxError?: boolean;
|
|
33
32
|
}
|
|
34
33
|
|
|
35
|
-
const IGNORED_DIRS = DEFAULT_IGNORED_DIRS;
|
|
36
|
-
|
|
37
34
|
const SUPPORTED_EXTENSIONS = new Set([
|
|
38
35
|
".ts",
|
|
39
36
|
".tsx",
|
|
@@ -75,7 +72,6 @@ function extractBalancedSig(
|
|
|
75
72
|
let parenDepth = 0;
|
|
76
73
|
let braceDepth = 0;
|
|
77
74
|
let angleDepth = 0;
|
|
78
|
-
let seenOpenParen = false;
|
|
79
75
|
let seenArrow = false;
|
|
80
76
|
|
|
81
77
|
for (let j = startIdx; j < Math.min(lines.length, startIdx + 20); j++) {
|
|
@@ -97,7 +93,6 @@ function extractBalancedSig(
|
|
|
97
93
|
|
|
98
94
|
if (ch === "(") {
|
|
99
95
|
parenDepth++;
|
|
100
|
-
seenOpenParen = true;
|
|
101
96
|
} else if (ch === ")") {
|
|
102
97
|
if (parenDepth > 0) parenDepth--;
|
|
103
98
|
} else if (ch === "<") {
|
|
@@ -628,9 +623,12 @@ export function extractFileTags(filePath: string, content: string): FileTags {
|
|
|
628
623
|
/^(?:public|private|protected|internal|abstract|static|final|\s)*\s*(class|interface|enum)\s+([a-zA-Z0-9_]+)/,
|
|
629
624
|
);
|
|
630
625
|
if (jClass) {
|
|
626
|
+
let kind: "class" | "interface" | "enum" = "class";
|
|
627
|
+
if (jClass[1] === "interface") kind = "interface";
|
|
628
|
+
else if (jClass[1] === "enum") kind = "enum";
|
|
631
629
|
definitions.push({
|
|
632
630
|
name: jClass[2],
|
|
633
|
-
kind
|
|
631
|
+
kind,
|
|
634
632
|
signature: line.split("{")[0].trim(),
|
|
635
633
|
line: i + 1,
|
|
636
634
|
});
|
|
@@ -797,288 +795,3 @@ export function isTestPath(relPath: string): boolean {
|
|
|
797
795
|
p.includes(".spec.")
|
|
798
796
|
);
|
|
799
797
|
}
|
|
800
|
-
|
|
801
|
-
export interface CodebaseMetrics {
|
|
802
|
-
implFiles: number;
|
|
803
|
-
implBytes: number;
|
|
804
|
-
testFiles: number;
|
|
805
|
-
testBytes: number;
|
|
806
|
-
isLight: boolean;
|
|
807
|
-
}
|
|
808
|
-
|
|
809
|
-
// Evaluate codebase scale by separating non-test implementation code from test suites.
|
|
810
|
-
// A codebase is light only if both implementation file count and byte mass are small.
|
|
811
|
-
export function evaluateCodebaseMetrics(
|
|
812
|
-
rootDir: string,
|
|
813
|
-
minImplFiles = 10,
|
|
814
|
-
minImplBytes = 50 * 1024,
|
|
815
|
-
): CodebaseMetrics {
|
|
816
|
-
const allFiles = findSourceFiles(rootDir);
|
|
817
|
-
let implFiles = 0;
|
|
818
|
-
let implBytes = 0;
|
|
819
|
-
let testFiles = 0;
|
|
820
|
-
let testBytes = 0;
|
|
821
|
-
|
|
822
|
-
for (const file of allFiles) {
|
|
823
|
-
const rel = path.relative(rootDir, file);
|
|
824
|
-
let size = 0;
|
|
825
|
-
try {
|
|
826
|
-
size = fs.statSync(file).size;
|
|
827
|
-
} catch {
|
|
828
|
-
// skip unreadable
|
|
829
|
-
}
|
|
830
|
-
|
|
831
|
-
if (isTestPath(rel)) {
|
|
832
|
-
testFiles++;
|
|
833
|
-
testBytes += size;
|
|
834
|
-
} else {
|
|
835
|
-
implFiles++;
|
|
836
|
-
implBytes += size;
|
|
837
|
-
}
|
|
838
|
-
}
|
|
839
|
-
|
|
840
|
-
const isLight = implFiles <= minImplFiles && implBytes < minImplBytes;
|
|
841
|
-
return {
|
|
842
|
-
implFiles,
|
|
843
|
-
implBytes,
|
|
844
|
-
testFiles,
|
|
845
|
-
testBytes,
|
|
846
|
-
isLight,
|
|
847
|
-
};
|
|
848
|
-
}
|
|
849
|
-
|
|
850
|
-
// Classify a file path into a PageRank demotion factor. Test suites form
|
|
851
|
-
// dense mutual-reference clusters that otherwise dominate raw PageRank —
|
|
852
|
-
// mirrors the test-path penalties in ast_search.computeSymbolRankScore.
|
|
853
|
-
function getPathDemotion(relPath: string): number {
|
|
854
|
-
if (isTestPath(relPath)) return 0.25; // strong demotion
|
|
855
|
-
const p = relPath.replace(/\\/g, "/").toLowerCase();
|
|
856
|
-
const isBenchmarkOrExample =
|
|
857
|
-
p.includes("/benchmarks/") ||
|
|
858
|
-
p.includes("/benchmark/") ||
|
|
859
|
-
p.includes("/examples/") ||
|
|
860
|
-
p.includes("/example/") ||
|
|
861
|
-
p.includes("/samples/") ||
|
|
862
|
-
p.includes("/fixtures/") ||
|
|
863
|
-
p.startsWith("benchmarks/") ||
|
|
864
|
-
p.startsWith("examples/") ||
|
|
865
|
-
p.startsWith("samples/");
|
|
866
|
-
if (isBenchmarkOrExample) return 0.6; // moderate demotion
|
|
867
|
-
return 1;
|
|
868
|
-
}
|
|
869
|
-
|
|
870
|
-
function isTrivialDataDefinition(def: SymbolDef): boolean {
|
|
871
|
-
if (def.kind !== "constant" && def.kind !== "variable") return false;
|
|
872
|
-
const signature = def.signature.toLowerCase();
|
|
873
|
-
return (
|
|
874
|
-
signature.includes("color::rgb") ||
|
|
875
|
-
signature.includes("lazylock") ||
|
|
876
|
-
signature.includes("regex") ||
|
|
877
|
-
signature.includes("hashset") ||
|
|
878
|
-
signature.includes("mimetype") ||
|
|
879
|
-
signature.includes("mime") ||
|
|
880
|
-
signature.includes("once_lock") ||
|
|
881
|
-
signature.includes("mutex") ||
|
|
882
|
-
(signature.includes("static") && signature.includes("table"))
|
|
883
|
-
);
|
|
884
|
-
}
|
|
885
|
-
|
|
886
|
-
/**
|
|
887
|
-
* Return a stable orientation priority for common executable and routing
|
|
888
|
-
* anchors. PageRank is still used for the rest of the map, but declaration
|
|
889
|
-
* density must not hide the entry point behind UI palette constants.
|
|
890
|
-
*/
|
|
891
|
-
function entryPointPriority(relPath: string, def: SymbolDef): number | null {
|
|
892
|
-
const normalizedPath = relPath.replace(/\\/g, "/").toLowerCase();
|
|
893
|
-
const fileName = path.basename(normalizedPath, path.extname(normalizedPath));
|
|
894
|
-
const name = def.name.toLowerCase();
|
|
895
|
-
|
|
896
|
-
if (name === "main") return 0;
|
|
897
|
-
if (name === "router") return 1;
|
|
898
|
-
if (name === "startup" || name === "start") return 2;
|
|
899
|
-
if (fileName === "main" && (def.kind === "function" || def.kind === "method")) return 3;
|
|
900
|
-
if ((fileName === "index" || fileName === "mod") && name === "createapp") return 4;
|
|
901
|
-
if (name === "run" && (normalizedPath.includes("/bin/") || normalizedPath.includes("/cmd/"))) return 5;
|
|
902
|
-
return null;
|
|
903
|
-
}
|
|
904
|
-
|
|
905
|
-
// Compute Graph PageRank for files and their symbols
|
|
906
|
-
export function computeRepoMap(rootDir: string, tokenBudget = 1024): string {
|
|
907
|
-
const sourceFiles = findSourceFiles(rootDir);
|
|
908
|
-
if (sourceFiles.length === 0) {
|
|
909
|
-
return "(No supported source files found in repository)";
|
|
910
|
-
}
|
|
911
|
-
|
|
912
|
-
// Ensure languages present in sourceFiles are loaded in TreeSitterEngine
|
|
913
|
-
const detectedExts = new Set<string>();
|
|
914
|
-
for (const f of sourceFiles) {
|
|
915
|
-
const ext = path.extname(f).toLowerCase();
|
|
916
|
-
if (ext) detectedExts.add(ext);
|
|
917
|
-
}
|
|
918
|
-
// Note: loadLanguages is async, but if called from an async context it is pre-warmed.
|
|
919
|
-
// We also trigger loadLanguages asynchronously if not loaded.
|
|
920
|
-
void TreeSitterEngine.getInstance().loadLanguages(Array.from(detectedExts));
|
|
921
|
-
|
|
922
|
-
const fileTagsMap = new Map<string, FileTags>();
|
|
923
|
-
const fileLineCounts = new Map<string, number>();
|
|
924
|
-
const defToFile = new Map<string, Set<string>>();
|
|
925
|
-
|
|
926
|
-
for (const file of sourceFiles) {
|
|
927
|
-
try {
|
|
928
|
-
const content = fs.readFileSync(file, "utf8");
|
|
929
|
-
const tags = extractFileTags(file, content);
|
|
930
|
-
fileTagsMap.set(file, tags);
|
|
931
|
-
fileLineCounts.set(file, content.split("\n").length);
|
|
932
|
-
|
|
933
|
-
for (const def of tags.definitions) {
|
|
934
|
-
if (!defToFile.has(def.name)) {
|
|
935
|
-
defToFile.set(def.name, new Set());
|
|
936
|
-
}
|
|
937
|
-
defToFile.get(def.name)!.add(file);
|
|
938
|
-
}
|
|
939
|
-
} catch {
|
|
940
|
-
// Skip unreadable files
|
|
941
|
-
}
|
|
942
|
-
}
|
|
943
|
-
|
|
944
|
-
// Build adjacency graph between files
|
|
945
|
-
const files = Array.from(fileTagsMap.keys());
|
|
946
|
-
const N = files.length;
|
|
947
|
-
if (N === 0) return "(Empty repository)";
|
|
948
|
-
|
|
949
|
-
const fileIndex = new Map<string, number>();
|
|
950
|
-
files.forEach((f, idx) => fileIndex.set(f, idx));
|
|
951
|
-
|
|
952
|
-
const inEdges: number[][] = Array.from({ length: N }, () => []);
|
|
953
|
-
const outDegree = new Array(N).fill(0);
|
|
954
|
-
|
|
955
|
-
for (let i = 0; i < N; i++) {
|
|
956
|
-
const fileA = files[i];
|
|
957
|
-
const tagsA = fileTagsMap.get(fileA)!;
|
|
958
|
-
const referencedFiles = new Set<number>();
|
|
959
|
-
|
|
960
|
-
for (const ref of tagsA.references) {
|
|
961
|
-
const targetFiles = defToFile.get(ref);
|
|
962
|
-
if (targetFiles) {
|
|
963
|
-
for (const targetFile of targetFiles) {
|
|
964
|
-
const targetIdx = fileIndex.get(targetFile);
|
|
965
|
-
if (targetIdx !== undefined && targetIdx !== i) {
|
|
966
|
-
referencedFiles.add(targetIdx);
|
|
967
|
-
}
|
|
968
|
-
}
|
|
969
|
-
}
|
|
970
|
-
}
|
|
971
|
-
|
|
972
|
-
outDegree[i] = referencedFiles.size;
|
|
973
|
-
for (const targetIdx of referencedFiles) {
|
|
974
|
-
inEdges[targetIdx].push(i);
|
|
975
|
-
}
|
|
976
|
-
}
|
|
977
|
-
|
|
978
|
-
// PageRank iteration (d = 0.85)
|
|
979
|
-
const d = 0.85;
|
|
980
|
-
let rank = new Array(N).fill(1 / N);
|
|
981
|
-
|
|
982
|
-
for (let iter = 0; iter < 15; iter++) {
|
|
983
|
-
const nextRank = new Array(N).fill((1 - d) / N);
|
|
984
|
-
for (let i = 0; i < N; i++) {
|
|
985
|
-
let sum = 0;
|
|
986
|
-
for (const src of inEdges[i]) {
|
|
987
|
-
if (outDegree[src] > 0) {
|
|
988
|
-
sum += rank[src] / outDegree[src];
|
|
989
|
-
}
|
|
990
|
-
}
|
|
991
|
-
nextRank[i] += d * sum;
|
|
992
|
-
}
|
|
993
|
-
rank = nextRank;
|
|
994
|
-
}
|
|
995
|
-
|
|
996
|
-
// Sort files by anchor priority first, then effective PageRank. This keeps
|
|
997
|
-
// executable/router entry points visible on cold start while retaining the
|
|
998
|
-
// graph ranking for the rest of the repository.
|
|
999
|
-
const rankedFiles = files
|
|
1000
|
-
.map((f, idx) => {
|
|
1001
|
-
const relPath = path.relative(rootDir, f).replace(/\\/g, "/");
|
|
1002
|
-
const tags = fileTagsMap.get(f)!;
|
|
1003
|
-
const anchorPriorities = tags.definitions
|
|
1004
|
-
.map((def) => entryPointPriority(relPath, def))
|
|
1005
|
-
.filter((priority): priority is number => priority !== null);
|
|
1006
|
-
return {
|
|
1007
|
-
file: f,
|
|
1008
|
-
effectiveRank: rank[idx] * getPathDemotion(relPath),
|
|
1009
|
-
tags,
|
|
1010
|
-
anchorPriority: anchorPriorities.length > 0 ? Math.min(...anchorPriorities) : Number.POSITIVE_INFINITY,
|
|
1011
|
-
};
|
|
1012
|
-
})
|
|
1013
|
-
.sort((a, b) =>
|
|
1014
|
-
a.anchorPriority - b.anchorPriority || b.effectiveRank - a.effectiveRank,
|
|
1015
|
-
);
|
|
1016
|
-
|
|
1017
|
-
// Pack symbols into token budget (~4 chars per token).
|
|
1018
|
-
const charBudget = Math.max(80, tokenBudget * 4);
|
|
1019
|
-
let currentChars = 0;
|
|
1020
|
-
const lines: string[] = [];
|
|
1021
|
-
const addLine = (line: string): boolean => {
|
|
1022
|
-
const extra = lines.length > 0 ? 1 : 0;
|
|
1023
|
-
if (currentChars + extra + line.length > charBudget) return false;
|
|
1024
|
-
lines.push(line);
|
|
1025
|
-
currentChars += extra + line.length;
|
|
1026
|
-
return true;
|
|
1027
|
-
};
|
|
1028
|
-
|
|
1029
|
-
addLine("Repository Map (Tree-Sitter AST & PageRank Ranked):");
|
|
1030
|
-
|
|
1031
|
-
// A compact orientation strip gives a cold-start caller the files it is most
|
|
1032
|
-
// likely to need without requiring a separate `ls`/`wc` shell round trip.
|
|
1033
|
-
if (charBudget >= 512) {
|
|
1034
|
-
const anchors = rankedFiles
|
|
1035
|
-
.flatMap((item) => {
|
|
1036
|
-
const relPath = path.relative(rootDir, item.file).replace(/\\/g, "/");
|
|
1037
|
-
return item.tags.definitions
|
|
1038
|
-
.map((def) => ({ def, priority: entryPointPriority(relPath, def), relPath }))
|
|
1039
|
-
.filter((entry): entry is { def: SymbolDef; priority: number; relPath: string } => entry.priority !== null);
|
|
1040
|
-
})
|
|
1041
|
-
.sort((a, b) => a.priority - b.priority)
|
|
1042
|
-
.slice(0, 8)
|
|
1043
|
-
.map((entry) => `${entry.relPath}::${entry.def.name}`);
|
|
1044
|
-
if (anchors.length > 0) addLine(`Entry points: ${anchors.join(", ")}`);
|
|
1045
|
-
}
|
|
1046
|
-
|
|
1047
|
-
if (charBudget >= 1024) {
|
|
1048
|
-
const sizeList = files
|
|
1049
|
-
.slice()
|
|
1050
|
-
.sort((a, b) => (fileLineCounts.get(b) || 0) - (fileLineCounts.get(a) || 0))
|
|
1051
|
-
.slice(0, 12)
|
|
1052
|
-
.map((file) => `${path.relative(rootDir, file).replace(/\\/g, "/")}(${fileLineCounts.get(file) || 0})`);
|
|
1053
|
-
if (sizeList.length > 0) addLine(`Files by size: ${sizeList.join(", ")}`);
|
|
1054
|
-
}
|
|
1055
|
-
|
|
1056
|
-
for (const item of rankedFiles) {
|
|
1057
|
-
const relPath = path.relative(rootDir, item.file).replace(/\\/g, "/");
|
|
1058
|
-
const fileHeader = `${relPath}:`;
|
|
1059
|
-
if (currentChars + fileHeader.length + 1 > charBudget) break;
|
|
1060
|
-
|
|
1061
|
-
const nonAliasDefs = item.tags.definitions.filter((d) => d.kind !== "alias");
|
|
1062
|
-
const meaningfulDefs = nonAliasDefs.filter((d) => !isTrivialDataDefinition(d));
|
|
1063
|
-
const defs = meaningfulDefs.length > 0 ? meaningfulDefs : nonAliasDefs;
|
|
1064
|
-
if (defs.length === 0) continue;
|
|
1065
|
-
|
|
1066
|
-
if (!addLine(fileHeader)) break;
|
|
1067
|
-
for (const def of defs) {
|
|
1068
|
-
const cleanSig = def.signature.replace(/\s+/g, " ").trim();
|
|
1069
|
-
const sigLine = ` ${cleanSig}`;
|
|
1070
|
-
if (!addLine(sigLine)) break;
|
|
1071
|
-
}
|
|
1072
|
-
}
|
|
1073
|
-
|
|
1074
|
-
// A bare header with nothing under it gives the caller zero guidance —
|
|
1075
|
-
// say why the map is empty and how to get useful output.
|
|
1076
|
-
if (lines.length === 1) {
|
|
1077
|
-
lines.push("");
|
|
1078
|
-
lines.push(
|
|
1079
|
-
`[No symbols fit within budget_tokens=${tokenBudget} (~${charBudget} chars). Increase 'budget_tokens' (e.g. 1024+) to see the ranked symbol map.]`,
|
|
1080
|
-
);
|
|
1081
|
-
}
|
|
1082
|
-
|
|
1083
|
-
return lines.join("\n");
|
|
1084
|
-
}
|