@floydous/pi-agent-kernel 0.6.1 → 0.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/README.md +75 -65
- package/config.example.toml +7 -4
- package/package.json +7 -3
- package/src/config/agent_kernel_command.ts +13 -0
- package/src/editing/patch.ts +14 -9
- package/src/editing/post_edit_verification.ts +2 -1
- package/src/editing/smart_anchor.ts +2 -2
- package/src/editing/syntax-verify.ts +11 -10
- package/src/index.ts +12 -7
- package/src/retrieval/search_chunker.ts +5 -65
- package/src/retrieval/search_embedder.ts +52 -22
- package/src/retrieval/search_index.ts +105 -27
- package/src/retrieval/search_modal.ts +16 -0
- package/src/retrieval/tag_extractor.ts +6 -2
- package/src/retrieval/tree_sitter_engine.ts +67 -11
- package/src/safety/epistemic_guard.ts +299 -89
- package/src/tools/code_search_output.ts +49 -9
- package/src/tools/code_search_tool.ts +31 -28
- package/src/tools/edit_tool.ts +7 -5
- package/src/tools/read_tool.ts +20 -0
- package/src/ui/footer.ts +4 -3
|
@@ -3,7 +3,6 @@ import * as path from "node:path";
|
|
|
3
3
|
import * as crypto from "node:crypto";
|
|
4
4
|
import { walkWorkspaceFiles, DEFAULT_IGNORED_DIRS, type WorkspaceWalkCache } from "./workspace_walker";
|
|
5
5
|
import { extractFileTags, isTestPath, SymbolDef } from "./tag_extractor";
|
|
6
|
-
import { TreeSitterEngine } from "./tree_sitter_engine";
|
|
7
6
|
import { chunkHtmlFile } from "./html_chunker";
|
|
8
7
|
|
|
9
8
|
export interface CodeChunk {
|
|
@@ -93,72 +92,13 @@ export function chunkFile(rootDir: string, filePath: string, content?: string):
|
|
|
93
92
|
|
|
94
93
|
const chunks: CodeChunk[] = [];
|
|
95
94
|
|
|
96
|
-
// 1. Extract AST symbols
|
|
97
|
-
const tags = extractFileTags(absPath, fileContent
|
|
95
|
+
// 1. Extract AST symbols (and top-level JS/TS test blocks for test files) in a single parse.
|
|
96
|
+
const tags = extractFileTags(absPath, fileContent, {
|
|
97
|
+
includeJsTestBlocks: isTestPath(relPath),
|
|
98
|
+
collectReferences: false,
|
|
99
|
+
});
|
|
98
100
|
const defs = [...tags.definitions];
|
|
99
101
|
|
|
100
|
-
// For test files (.test., .spec., /test/, /tests/), also extract top-level test blocks (describe/it/test/suite)
|
|
101
|
-
// so test cases and assertions are indexed by code_search.
|
|
102
|
-
if (isTestPath(relPath) && (ext === ".ts" || ext === ".tsx" || ext === ".js" || ext === ".jsx")) {
|
|
103
|
-
const tsEngine = TreeSitterEngine.getInstance();
|
|
104
|
-
const parser = tsEngine.getParser(ext);
|
|
105
|
-
if (parser) {
|
|
106
|
-
try {
|
|
107
|
-
const tree = parser.parse(fileContent);
|
|
108
|
-
const root = tree.rootNode;
|
|
109
|
-
for (let i = 0; i < root.childCount; i++) {
|
|
110
|
-
const child = root.child(i);
|
|
111
|
-
if (child.type === "expression_statement") {
|
|
112
|
-
let expr = child.firstNamedChild;
|
|
113
|
-
let callee: any = null;
|
|
114
|
-
let argsNode: any = null;
|
|
115
|
-
while (expr && expr.type === "call_expression") {
|
|
116
|
-
const fn = expr.childForFieldName("function");
|
|
117
|
-
const args = expr.childForFieldName("arguments");
|
|
118
|
-
if (args && !argsNode) argsNode = args;
|
|
119
|
-
if (fn) {
|
|
120
|
-
callee = fn;
|
|
121
|
-
if (fn.type === "call_expression") {
|
|
122
|
-
expr = fn;
|
|
123
|
-
} else {
|
|
124
|
-
break;
|
|
125
|
-
}
|
|
126
|
-
} else {
|
|
127
|
-
break;
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
if (callee) {
|
|
131
|
-
const calleeText = callee.text;
|
|
132
|
-
const match = calleeText.match(/^(?:(?:suite|describe|context|it|test)(?:\.(?:only|skip|each|todo|concurrent|serial))?)/);
|
|
133
|
-
if (match) {
|
|
134
|
-
let title = "";
|
|
135
|
-
if (argsNode) {
|
|
136
|
-
for (const arg of argsNode.namedChildren) {
|
|
137
|
-
if (arg.type === "string" || arg.type === "template_string") {
|
|
138
|
-
title = arg.text.replace(/^['"`]|['"`]$/g, "");
|
|
139
|
-
break;
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
const testName = title ? `${match[0]}('${title}')` : match[0];
|
|
144
|
-
const firstLine = fileContent.slice(child.startIndex, fileContent.indexOf("\n", child.startIndex)).trim();
|
|
145
|
-
defs.push({
|
|
146
|
-
name: testName,
|
|
147
|
-
kind: "test",
|
|
148
|
-
signature: firstLine.length < 120 ? firstLine : testName,
|
|
149
|
-
line: child.startPosition.row + 1,
|
|
150
|
-
endLine: child.endPosition.row + 1,
|
|
151
|
-
});
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
} catch {
|
|
157
|
-
// Tree-sitter parsing is best-effort fallback
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
|
|
162
102
|
defs.sort((a, b) => a.line - b.line);
|
|
163
103
|
|
|
164
104
|
// If file has no AST definitions or is small (< 40 lines), chunk as single whole file
|
|
@@ -14,18 +14,35 @@ export class LocalEmbedder {
|
|
|
14
14
|
private config: SearchConfig;
|
|
15
15
|
private isInitializing = false;
|
|
16
16
|
private initPromise: Promise<void> | null = null;
|
|
17
|
+
private lastInitFailureAt = 0;
|
|
18
|
+
private retryCooldownMs: number;
|
|
19
|
+
private pipelineLoader?: (config: SearchConfig, onProgress?: (msg: string) => void) => Promise<any>;
|
|
17
20
|
private queryLruCache = new Map<string, Float32Array>();
|
|
18
21
|
private static readonly MAX_QUERY_CACHE_ENTRIES = 128;
|
|
22
|
+
private static readonly DEFAULT_INIT_RETRY_COOLDOWN_MS = 60_000;
|
|
19
23
|
|
|
20
|
-
constructor(
|
|
24
|
+
constructor(
|
|
25
|
+
config?: SearchConfig,
|
|
26
|
+
options?: {
|
|
27
|
+
retryCooldownMs?: number;
|
|
28
|
+
pipelineLoader?: (config: SearchConfig, onProgress?: (msg: string) => void) => Promise<any>;
|
|
29
|
+
},
|
|
30
|
+
) {
|
|
21
31
|
this.config = config || getSearchConfig();
|
|
32
|
+
this.retryCooldownMs = options?.retryCooldownMs ?? LocalEmbedder.DEFAULT_INIT_RETRY_COOLDOWN_MS;
|
|
33
|
+
this.pipelineLoader = options?.pipelineLoader;
|
|
22
34
|
}
|
|
23
35
|
|
|
24
36
|
public updateConfig(config: SearchConfig): void {
|
|
25
37
|
this.config = config;
|
|
38
|
+
this.lastInitFailureAt = 0;
|
|
26
39
|
this.queryLruCache.clear();
|
|
27
40
|
}
|
|
28
41
|
|
|
42
|
+
public resetFailureBackoff(): void {
|
|
43
|
+
this.lastInitFailureAt = 0;
|
|
44
|
+
}
|
|
45
|
+
|
|
29
46
|
public isLoaded(): boolean {
|
|
30
47
|
return this.extractor !== null;
|
|
31
48
|
}
|
|
@@ -138,6 +155,9 @@ export class LocalEmbedder {
|
|
|
138
155
|
await this.initPromise;
|
|
139
156
|
return this.extractor !== null;
|
|
140
157
|
}
|
|
158
|
+
if (this.lastInitFailureAt > 0 && Date.now() - this.lastInitFailureAt < this.retryCooldownMs) {
|
|
159
|
+
return false;
|
|
160
|
+
}
|
|
141
161
|
|
|
142
162
|
this.isInitializing = true;
|
|
143
163
|
this.initPromise = (async () => {
|
|
@@ -149,42 +169,51 @@ export class LocalEmbedder {
|
|
|
149
169
|
onProgress?.("Downloading embedding weights: 0% (~147 MB)...");
|
|
150
170
|
}
|
|
151
171
|
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
172
|
+
if (this.pipelineLoader) {
|
|
173
|
+
this.extractor = await this.pipelineLoader(this.config, onProgress);
|
|
174
|
+
} else {
|
|
175
|
+
// Enforce single-thread CPU constraints to avoid starving system processes
|
|
176
|
+
process.env.OMP_NUM_THREADS = String(this.config.numThreads || 1);
|
|
177
|
+
process.env.ORT_INTRA_OP_NUM_THREADS = String(this.config.numThreads || 1);
|
|
178
|
+
process.env.ORT_INTER_OP_NUM_THREADS = String(this.config.numThreads || 1);
|
|
179
|
+
|
|
180
|
+
const { env, pipeline } = await import(
|
|
181
|
+
"@huggingface/transformers"
|
|
182
|
+
);
|
|
183
|
+
if (env && env.backends && env.backends.onnx) {
|
|
184
|
+
env.backends.onnx.numThreads = this.config.numThreads || 1;
|
|
185
|
+
env.backends.onnx.logLevel = "warning";
|
|
186
|
+
}
|
|
156
187
|
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
188
|
+
this.extractor = await pipeline("feature-extraction", this.config.modelId, {
|
|
189
|
+
revision: this.config.modelRevision,
|
|
190
|
+
dtype: this.config.dtype,
|
|
191
|
+
progress_callback: (p: any) => {
|
|
192
|
+
if (p.status === "progress" && p.total && p.loaded) {
|
|
193
|
+
const pct = Math.round((p.loaded / p.total) * 100);
|
|
194
|
+
onProgress?.(`Downloading embedding weights: ${pct}%`);
|
|
195
|
+
}
|
|
196
|
+
},
|
|
197
|
+
});
|
|
163
198
|
}
|
|
164
199
|
|
|
165
|
-
this.extractor = await pipeline("feature-extraction", this.config.modelId, {
|
|
166
|
-
revision: this.config.modelRevision,
|
|
167
|
-
dtype: this.config.dtype,
|
|
168
|
-
progress_callback: (p: any) => {
|
|
169
|
-
if (p.status === "progress" && p.total && p.loaded) {
|
|
170
|
-
const pct = Math.round((p.loaded / p.total) * 100);
|
|
171
|
-
onProgress?.(`Downloading embedding weights: ${pct}%`);
|
|
172
|
-
}
|
|
173
|
-
},
|
|
174
|
-
});
|
|
175
|
-
|
|
176
200
|
// Clamp the sequence length to bound ONNX activation RAM. Texts are cut to 1,800 chars first; with this
|
|
177
201
|
// model those take ≤ 980 tokens in all but 3 of 23,000 measured chunks, so 1,024 rarely truncates.
|
|
178
202
|
if (this.extractor?.tokenizer?.config) {
|
|
179
203
|
this.extractor.tokenizer.config.model_max_length = 1024;
|
|
180
204
|
}
|
|
181
205
|
|
|
206
|
+
this.lastInitFailureAt = 0;
|
|
182
207
|
onProgress?.("Embedding model loaded.");
|
|
183
208
|
} catch (err: any) {
|
|
184
209
|
console.error("[Search Embedder] Error loading pipeline:", err);
|
|
185
210
|
this.extractor = null;
|
|
211
|
+
this.lastInitFailureAt = Date.now();
|
|
186
212
|
} finally {
|
|
187
213
|
this.isInitializing = false;
|
|
214
|
+
if (!this.extractor) {
|
|
215
|
+
this.initPromise = null;
|
|
216
|
+
}
|
|
188
217
|
}
|
|
189
218
|
})();
|
|
190
219
|
|
|
@@ -323,6 +352,7 @@ export class LocalEmbedder {
|
|
|
323
352
|
|
|
324
353
|
this.extractor = null;
|
|
325
354
|
this.initPromise = null;
|
|
355
|
+
this.lastInitFailureAt = 0;
|
|
326
356
|
this.queryLruCache.clear();
|
|
327
357
|
|
|
328
358
|
try {
|
|
@@ -60,6 +60,8 @@ interface PersistedIndexSnapshot {
|
|
|
60
60
|
chunkFiles: Map<string, string>;
|
|
61
61
|
ignoreConfigHashes: Map<string, string>;
|
|
62
62
|
staleFiles: Set<string>;
|
|
63
|
+
freshnessSnapshots: Map<string, FreshnessSnapshot>;
|
|
64
|
+
fileBytes: Map<string, number>;
|
|
63
65
|
}
|
|
64
66
|
|
|
65
67
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
@@ -228,6 +230,8 @@ export function validatePersistedIndex(
|
|
|
228
230
|
|
|
229
231
|
const validatedChunks: CodeChunk[] = [];
|
|
230
232
|
const staleFiles = new Set<string>();
|
|
233
|
+
const freshnessSnapshots = new Map<string, FreshnessSnapshot>();
|
|
234
|
+
const fileBytes = new Map<string, number>();
|
|
231
235
|
let validatedWorkspaceBytes = 0;
|
|
232
236
|
for (const [filePath, expectedHash] of fileHashes) {
|
|
233
237
|
const fileChunks = chunksByFile.get(filePath) || [];
|
|
@@ -298,7 +302,8 @@ export function validatePersistedIndex(
|
|
|
298
302
|
if (descriptor !== undefined) fs.closeSync(descriptor);
|
|
299
303
|
}
|
|
300
304
|
|
|
301
|
-
|
|
305
|
+
const sourceBytes = Buffer.byteLength(source, "utf8");
|
|
306
|
+
validatedWorkspaceBytes += sourceBytes;
|
|
302
307
|
if (validatedWorkspaceBytes > MAX_INDEX_WORKSPACE_BYTES) {
|
|
303
308
|
throw new Error("Persisted workspace exceeds index size limit");
|
|
304
309
|
}
|
|
@@ -322,6 +327,8 @@ export function validatePersistedIndex(
|
|
|
322
327
|
chunk.absolutePath = absolutePath;
|
|
323
328
|
validatedChunks.push(chunk);
|
|
324
329
|
}
|
|
330
|
+
freshnessSnapshots.set(filePath, freshnessSnapshot(sourceStat, expectedHash, sourceBytes));
|
|
331
|
+
fileBytes.set(filePath, sourceBytes);
|
|
325
332
|
}
|
|
326
333
|
|
|
327
334
|
const ignoreConfigHashes = new Map<string, string>();
|
|
@@ -341,7 +348,16 @@ export function validatePersistedIndex(
|
|
|
341
348
|
}
|
|
342
349
|
}
|
|
343
350
|
|
|
344
|
-
return {
|
|
351
|
+
return {
|
|
352
|
+
chunks: validatedChunks,
|
|
353
|
+
fileHashes,
|
|
354
|
+
chunkHashes,
|
|
355
|
+
chunkFiles,
|
|
356
|
+
ignoreConfigHashes,
|
|
357
|
+
staleFiles,
|
|
358
|
+
freshnessSnapshots,
|
|
359
|
+
fileBytes,
|
|
360
|
+
};
|
|
345
361
|
}
|
|
346
362
|
|
|
347
363
|
export interface SearchHit {
|
|
@@ -431,6 +447,7 @@ export class HybridSearchIndex {
|
|
|
431
447
|
/** relPath -> hash of content skipped by MAX_INDEX_CHUNKS; freshness checks cannot count chunks, so they match this. */
|
|
432
448
|
private chunkCapSkips = new Map<string, string>();
|
|
433
449
|
private freshnessSnapshots = new Map<string, FreshnessSnapshot>();
|
|
450
|
+
private fileBytes = new Map<string, number>();
|
|
434
451
|
private walkCache = new WorkspaceWalkCache();
|
|
435
452
|
/** Every indexable file of the last walk, in priority order (up to MAX_WALK_FILES), for coverage reporting. */
|
|
436
453
|
private walkedFiles: readonly RankedFile[] = [];
|
|
@@ -724,6 +741,8 @@ export class HybridSearchIndex {
|
|
|
724
741
|
this.ignoreConfigHashes.clear();
|
|
725
742
|
this.vectors.clear();
|
|
726
743
|
this.persistedVectorCaches = [];
|
|
744
|
+
this.freshnessSnapshots.clear();
|
|
745
|
+
this.fileBytes.clear();
|
|
727
746
|
|
|
728
747
|
for (const chunk of validated.chunks) {
|
|
729
748
|
if (this.isPathExcluded(chunk.filePath)) continue;
|
|
@@ -735,6 +754,14 @@ export class HybridSearchIndex {
|
|
|
735
754
|
if (this.isPathExcluded(file)) continue;
|
|
736
755
|
this.fileHashes.set(file, hash);
|
|
737
756
|
}
|
|
757
|
+
for (const [file, snapshot] of validated.freshnessSnapshots) {
|
|
758
|
+
if (this.isPathExcluded(file)) continue;
|
|
759
|
+
this.freshnessSnapshots.set(file, snapshot);
|
|
760
|
+
}
|
|
761
|
+
for (const [file, bytes] of validated.fileBytes) {
|
|
762
|
+
if (this.isPathExcluded(file)) continue;
|
|
763
|
+
this.fileBytes.set(file, bytes);
|
|
764
|
+
}
|
|
738
765
|
for (const [file, hash] of validated.ignoreConfigHashes) {
|
|
739
766
|
this.ignoreConfigHashes.set(file, hash);
|
|
740
767
|
}
|
|
@@ -847,7 +874,7 @@ export class HybridSearchIndex {
|
|
|
847
874
|
|
|
848
875
|
writeFileSyncAtomic(
|
|
849
876
|
this.getIndexFilePath(),
|
|
850
|
-
JSON.stringify(indexData
|
|
877
|
+
JSON.stringify(indexData),
|
|
851
878
|
);
|
|
852
879
|
} catch (err) {
|
|
853
880
|
console.error("[Search Index] Failed saving cache:", err);
|
|
@@ -1130,6 +1157,9 @@ export class HybridSearchIndex {
|
|
|
1130
1157
|
if (this.config.effectiveProfile === "off") {
|
|
1131
1158
|
return { chunkCount: 0, fileCount: 0, indexedCount: 0 };
|
|
1132
1159
|
}
|
|
1160
|
+
if (forceReindex) {
|
|
1161
|
+
this.embedder.resetFailureBackoff();
|
|
1162
|
+
}
|
|
1133
1163
|
if (signal?.aborted || this.generation !== syncGeneration) {
|
|
1134
1164
|
return { chunkCount: this.chunks.size, fileCount: this.fileHashes.size, indexedCount: 0 };
|
|
1135
1165
|
}
|
|
@@ -1171,6 +1201,36 @@ export class HybridSearchIndex {
|
|
|
1171
1201
|
continue;
|
|
1172
1202
|
}
|
|
1173
1203
|
try {
|
|
1204
|
+
// Fast path: reuse verified chunks/hash from loadFromDisk() or a prior sync
|
|
1205
|
+
// when the file's non-racy stat snapshot is unchanged.
|
|
1206
|
+
if (!forceReindex) {
|
|
1207
|
+
const known = this.freshnessSnapshots.get(relPath);
|
|
1208
|
+
if (known && !known.racy) {
|
|
1209
|
+
const currentStat = fs.lstatSync(absPath);
|
|
1210
|
+
if (currentStat.isFile() && sameFileSnapshot(known.stats, currentStat)) {
|
|
1211
|
+
if (currentStat.size > MAX_INDEX_FILE_BYTES || workspaceBytes + known.bytes > MAX_INDEX_WORKSPACE_BYTES) {
|
|
1212
|
+
this.skippedOversizedFiles.add(relPath);
|
|
1213
|
+
continue;
|
|
1214
|
+
}
|
|
1215
|
+
const cachedIds = this.fileHashes.get(relPath) === known.hash
|
|
1216
|
+
? this.chunks.idsForFile(relPath)
|
|
1217
|
+
: [];
|
|
1218
|
+
if (cachedIds.length > 0) {
|
|
1219
|
+
const chunks = cachedIds.map((id) => this.chunks.get(id)!);
|
|
1220
|
+
if (workspaceChunks + chunks.length > MAX_INDEX_CHUNKS) {
|
|
1221
|
+
this.skippedOversizedFiles.add(relPath);
|
|
1222
|
+
this.chunkCapSkips.set(relPath, known.hash);
|
|
1223
|
+
continue;
|
|
1224
|
+
}
|
|
1225
|
+
workspaceBytes += known.bytes;
|
|
1226
|
+
workspaceChunks += chunks.length;
|
|
1227
|
+
selectedFiles.set(relPath, { absPath, hash: known.hash, chunks });
|
|
1228
|
+
this.fileBytes.set(relPath, known.bytes);
|
|
1229
|
+
continue;
|
|
1230
|
+
}
|
|
1231
|
+
}
|
|
1232
|
+
}
|
|
1233
|
+
}
|
|
1174
1234
|
const stat = fs.statSync(absPath);
|
|
1175
1235
|
if (!stat.isFile() || stat.size > MAX_INDEX_FILE_BYTES) {
|
|
1176
1236
|
this.skippedOversizedFiles.add(relPath);
|
|
@@ -1222,6 +1282,7 @@ export class HybridSearchIndex {
|
|
|
1222
1282
|
workspaceBytes += actualBytes;
|
|
1223
1283
|
workspaceChunks += chunks.length;
|
|
1224
1284
|
selectedFiles.set(relPath, { absPath, hash, chunks });
|
|
1285
|
+
this.fileBytes.set(relPath, actualBytes);
|
|
1225
1286
|
this.freshnessSnapshots.set(relPath, freshnessSnapshot(opened, hash, actualBytes));
|
|
1226
1287
|
} catch (error) {
|
|
1227
1288
|
kernelDebug(error);
|
|
@@ -1257,6 +1318,8 @@ export class HybridSearchIndex {
|
|
|
1257
1318
|
for (const delPath of filesToDelete) {
|
|
1258
1319
|
this.bm25.removeFile(delPath);
|
|
1259
1320
|
this.fileHashes.delete(delPath);
|
|
1321
|
+
this.fileBytes.delete(delPath);
|
|
1322
|
+
this.freshnessSnapshots.delete(delPath);
|
|
1260
1323
|
this.deleteFileChunks(delPath);
|
|
1261
1324
|
}
|
|
1262
1325
|
if (filesToDelete.length > 0) {
|
|
@@ -1383,6 +1446,8 @@ export class HybridSearchIndex {
|
|
|
1383
1446
|
private removeIndexedFile(relPath: string): void {
|
|
1384
1447
|
this.bm25.removeFile(relPath);
|
|
1385
1448
|
this.fileHashes.delete(relPath);
|
|
1449
|
+
this.fileBytes.delete(relPath);
|
|
1450
|
+
this.freshnessSnapshots.delete(relPath);
|
|
1386
1451
|
this.deleteFileChunks(relPath);
|
|
1387
1452
|
}
|
|
1388
1453
|
|
|
@@ -1443,9 +1508,7 @@ export class HybridSearchIndex {
|
|
|
1443
1508
|
// Check if file was deleted
|
|
1444
1509
|
if (!fs.existsSync(resolvedPath)) {
|
|
1445
1510
|
if (this.fileGenerations.get(relPath) !== currentGen) return;
|
|
1446
|
-
this.
|
|
1447
|
-
this.fileHashes.delete(relPath);
|
|
1448
|
-
this.deleteFileChunks(relPath);
|
|
1511
|
+
this.removeIndexedFile(relPath);
|
|
1449
1512
|
this.dirtyFiles.delete(relPath);
|
|
1450
1513
|
this.bm25.recalculateStats();
|
|
1451
1514
|
this.scheduleDebouncedSave();
|
|
@@ -1454,6 +1517,8 @@ export class HybridSearchIndex {
|
|
|
1454
1517
|
|
|
1455
1518
|
// Read file content with bounded allocation and TOCTOU protection
|
|
1456
1519
|
let content: string;
|
|
1520
|
+
let opened: fs.Stats;
|
|
1521
|
+
let actualBytes: number;
|
|
1457
1522
|
try {
|
|
1458
1523
|
const stat = fs.statSync(resolvedPath);
|
|
1459
1524
|
if (!stat.isFile() || stat.size > MAX_INDEX_FILE_BYTES) {
|
|
@@ -1466,9 +1531,17 @@ export class HybridSearchIndex {
|
|
|
1466
1531
|
let workspaceBytes = 0;
|
|
1467
1532
|
for (const indexedPath of this.fileHashes.keys()) {
|
|
1468
1533
|
if (indexedPath === relPath) continue;
|
|
1534
|
+
const tracked = this.fileBytes.get(indexedPath);
|
|
1535
|
+
if (tracked !== undefined) {
|
|
1536
|
+
workspaceBytes += tracked;
|
|
1537
|
+
continue;
|
|
1538
|
+
}
|
|
1469
1539
|
try {
|
|
1470
1540
|
const indexedStat = fs.statSync(path.join(this.cwd, indexedPath));
|
|
1471
|
-
if (indexedStat.isFile())
|
|
1541
|
+
if (indexedStat.isFile()) {
|
|
1542
|
+
this.fileBytes.set(indexedPath, indexedStat.size);
|
|
1543
|
+
workspaceBytes += indexedStat.size;
|
|
1544
|
+
}
|
|
1472
1545
|
} catch {}
|
|
1473
1546
|
}
|
|
1474
1547
|
if (workspaceBytes + stat.size > MAX_INDEX_WORKSPACE_BYTES) {
|
|
@@ -1479,7 +1552,6 @@ export class HybridSearchIndex {
|
|
|
1479
1552
|
return;
|
|
1480
1553
|
}
|
|
1481
1554
|
const descriptor = fs.openSync(resolvedPath, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
|
|
1482
|
-
let opened: fs.Stats;
|
|
1483
1555
|
try {
|
|
1484
1556
|
opened = fs.fstatSync(descriptor);
|
|
1485
1557
|
if (!opened.isFile() || opened.size > MAX_INDEX_FILE_BYTES) throw new Error(`Invalid workspace file: ${relPath}`);
|
|
@@ -1491,7 +1563,8 @@ export class HybridSearchIndex {
|
|
|
1491
1563
|
if (!sameFileSnapshot(opened, afterRead)) {
|
|
1492
1564
|
throw new Error(`Workspace file changed while reading: ${relPath}`);
|
|
1493
1565
|
}
|
|
1494
|
-
|
|
1566
|
+
actualBytes = Buffer.byteLength(content, "utf8");
|
|
1567
|
+
if (actualBytes > MAX_INDEX_FILE_BYTES || workspaceBytes + actualBytes > MAX_INDEX_WORKSPACE_BYTES) {
|
|
1495
1568
|
this.skippedOversizedFiles.add(relPath);
|
|
1496
1569
|
this.removeIndexedFile(relPath);
|
|
1497
1570
|
this.dirtyFiles.delete(relPath);
|
|
@@ -1502,9 +1575,7 @@ export class HybridSearchIndex {
|
|
|
1502
1575
|
if (err?.code === "ENOENT") {
|
|
1503
1576
|
// File was removed concurrently between existsSync and readFileSync
|
|
1504
1577
|
if (this.fileGenerations.get(relPath) !== currentGen) return;
|
|
1505
|
-
this.
|
|
1506
|
-
this.fileHashes.delete(relPath);
|
|
1507
|
-
this.deleteFileChunks(relPath);
|
|
1578
|
+
this.removeIndexedFile(relPath);
|
|
1508
1579
|
this.dirtyFiles.delete(relPath);
|
|
1509
1580
|
this.bm25.recalculateStats();
|
|
1510
1581
|
this.scheduleDebouncedSave();
|
|
@@ -1522,6 +1593,8 @@ export class HybridSearchIndex {
|
|
|
1522
1593
|
return Boolean(vector && vector.length === this.config.matryoshkaDim);
|
|
1523
1594
|
});
|
|
1524
1595
|
if (this.fileHashes.get(relPath) === fileHash && !this.dirtyFiles.has(relPath) && fileVectorsReady) {
|
|
1596
|
+
this.fileBytes.set(relPath, actualBytes);
|
|
1597
|
+
this.freshnessSnapshots.set(relPath, freshnessSnapshot(opened, fileHash, actualBytes));
|
|
1525
1598
|
return;
|
|
1526
1599
|
}
|
|
1527
1600
|
|
|
@@ -1547,24 +1620,25 @@ export class HybridSearchIndex {
|
|
|
1547
1620
|
}
|
|
1548
1621
|
this.skippedOversizedFiles.delete(relPath);
|
|
1549
1622
|
this.chunkCapSkips.delete(relPath);
|
|
1550
|
-
// Map content hash -> vector from existing chunks
|
|
1551
|
-
const hashToVector = new Map<string, Float32Array>();
|
|
1552
|
-
for (const chunk of this.chunks.values()) {
|
|
1553
|
-
const vec = this.vectors.get(chunk.id);
|
|
1554
|
-
if (vec && vec.length === this.config.matryoshkaDim) {
|
|
1555
|
-
hashToVector.set(chunk.hash, vec);
|
|
1556
|
-
}
|
|
1557
|
-
}
|
|
1558
1623
|
|
|
1559
1624
|
const newVectors = new Map<string, Float32Array>();
|
|
1560
1625
|
const missingChunks: CodeChunk[] = [];
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
const
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1626
|
+
if (wantsVectors) {
|
|
1627
|
+
// Map content hash -> vector from existing chunks
|
|
1628
|
+
const hashToVector = new Map<string, Float32Array>();
|
|
1629
|
+
for (const chunk of this.chunks.values()) {
|
|
1630
|
+
const vec = this.vectors.get(chunk.id);
|
|
1631
|
+
if (vec && vec.length === this.config.matryoshkaDim) {
|
|
1632
|
+
hashToVector.set(chunk.hash, vec);
|
|
1633
|
+
}
|
|
1634
|
+
}
|
|
1635
|
+
for (const chunk of newChunks) {
|
|
1636
|
+
const reused = hashToVector.get(chunk.hash);
|
|
1637
|
+
if (reused) {
|
|
1638
|
+
newVectors.set(chunk.id, reused);
|
|
1639
|
+
} else {
|
|
1640
|
+
missingChunks.push(chunk);
|
|
1641
|
+
}
|
|
1568
1642
|
}
|
|
1569
1643
|
}
|
|
1570
1644
|
|
|
@@ -1597,6 +1671,8 @@ export class HybridSearchIndex {
|
|
|
1597
1671
|
this.deleteFileChunks(relPath);
|
|
1598
1672
|
|
|
1599
1673
|
this.fileHashes.set(relPath, fileHash);
|
|
1674
|
+
this.fileBytes.set(relPath, actualBytes);
|
|
1675
|
+
this.freshnessSnapshots.set(relPath, freshnessSnapshot(opened, fileHash, actualBytes));
|
|
1600
1676
|
for (const chunk of newChunks) {
|
|
1601
1677
|
this.chunks.set(chunk.id, chunk);
|
|
1602
1678
|
this.bm25.addChunk(chunk);
|
|
@@ -1640,6 +1716,8 @@ export class HybridSearchIndex {
|
|
|
1640
1716
|
) return;
|
|
1641
1717
|
this.bm25.removeFile(relPath);
|
|
1642
1718
|
this.fileHashes.delete(relPath);
|
|
1719
|
+
this.fileBytes.delete(relPath);
|
|
1720
|
+
this.freshnessSnapshots.delete(relPath);
|
|
1643
1721
|
this.deleteFileChunks(relPath);
|
|
1644
1722
|
this.bm25.recalculateStats();
|
|
1645
1723
|
this.generation++;
|
|
@@ -244,6 +244,7 @@ export class UnifiedControlModal implements Focusable {
|
|
|
244
244
|
if (id === "editing") return !isOverriddenByProject("editing", "mode") && globalRaw.editing?.mode !== undefined;
|
|
245
245
|
if (id === "read_mode") return !isOverriddenByProject("editing", "read_mode") && globalRaw.editing?.read_mode !== undefined;
|
|
246
246
|
if (id === "normalize_dots") return !isOverriddenByProject("editing", "normalize_fullwidth_dots") && globalRaw.editing?.normalize_fullwidth_dots !== undefined;
|
|
247
|
+
if (id === "syntax_gate") return !isOverriddenByProject("editing", "syntax_gate") && globalRaw.editing?.syntax_gate !== undefined;
|
|
247
248
|
if (id === "guidance") return !isOverriddenByProject("instructions", "enabled") && globalRaw.instructions?.enabled !== undefined;
|
|
248
249
|
if (id === "host_environment") return !isOverriddenByProject("instructions", "host_environment") && globalRaw.instructions?.host_environment !== undefined;
|
|
249
250
|
if (id === "pi_docs") return !isOverriddenByProject("instructions", "pi_docs") && globalRaw.instructions?.pi_docs !== undefined;
|
|
@@ -339,6 +340,18 @@ export class UnifiedControlModal implements Focusable {
|
|
|
339
340
|
disabled: "Fullwidth dot normalization disabled: Preserves Unicode fullwidth full stop verbatim.",
|
|
340
341
|
},
|
|
341
342
|
},
|
|
343
|
+
{
|
|
344
|
+
category: "Editing Engine",
|
|
345
|
+
id: "syntax_gate",
|
|
346
|
+
label: "Post-Edit Syntax Gate",
|
|
347
|
+
currentValue: currentConfig.editing.syntax_gate ?? "warn",
|
|
348
|
+
values: ["warn", "block"],
|
|
349
|
+
isGlobal: checkIsGlobal("syntax_gate"),
|
|
350
|
+
descriptions: {
|
|
351
|
+
warn: "Warn mode (default): Applies edits and reports syntax errors immediately in tool output.",
|
|
352
|
+
block: "Block mode: Rejects edits that fail candidate syntax validation before writing to disk.",
|
|
353
|
+
},
|
|
354
|
+
},
|
|
342
355
|
{
|
|
343
356
|
category: "System Guidance & UI",
|
|
344
357
|
id: "guidance",
|
|
@@ -475,6 +488,8 @@ export class UnifiedControlModal implements Focusable {
|
|
|
475
488
|
patch.editing = { read_mode: value as "auto" | "plain" | "anchored" };
|
|
476
489
|
} else if (id === "normalize_dots") {
|
|
477
490
|
patch.editing = { normalize_fullwidth_dots: value === "enabled" };
|
|
491
|
+
} else if (id === "syntax_gate") {
|
|
492
|
+
patch.editing = { syntax_gate: value as "warn" | "block" };
|
|
478
493
|
} else if (id === "guidance") {
|
|
479
494
|
patch.instructions = { enabled: value === "enabled" };
|
|
480
495
|
} else if (id === "host_environment") {
|
|
@@ -500,6 +515,7 @@ export class UnifiedControlModal implements Focusable {
|
|
|
500
515
|
case "editing": return { section: "editing", key: "mode" };
|
|
501
516
|
case "read_mode": return { section: "editing", key: "read_mode" };
|
|
502
517
|
case "normalize_dots": return { section: "editing", key: "normalize_fullwidth_dots" };
|
|
518
|
+
case "syntax_gate": return { section: "editing", key: "syntax_gate" };
|
|
503
519
|
case "guidance": return { section: "instructions", key: "enabled" };
|
|
504
520
|
case "host_environment": return { section: "instructions", key: "host_environment" };
|
|
505
521
|
case "pi_docs": return { section: "instructions", key: "pi_docs" };
|
|
@@ -165,10 +165,14 @@ function extractBalancedSig(
|
|
|
165
165
|
}
|
|
166
166
|
|
|
167
167
|
// Fast AST & Signature tag extractor with multi-line support
|
|
168
|
-
export function extractFileTags(
|
|
168
|
+
export function extractFileTags(
|
|
169
|
+
filePath: string,
|
|
170
|
+
content: string,
|
|
171
|
+
options?: { includeJsTestBlocks?: boolean; collectReferences?: boolean },
|
|
172
|
+
): FileTags {
|
|
169
173
|
const tsEngine = TreeSitterEngine.getInstance();
|
|
170
174
|
if (tsEngine.isSupported(filePath)) {
|
|
171
|
-
const treeTags = tsEngine.extractTags(filePath, content);
|
|
175
|
+
const treeTags = tsEngine.extractTags(filePath, content, options);
|
|
172
176
|
if (treeTags) {
|
|
173
177
|
return treeTags;
|
|
174
178
|
}
|
|
@@ -280,7 +280,11 @@ export class TreeSitterEngine {
|
|
|
280
280
|
}
|
|
281
281
|
}
|
|
282
282
|
|
|
283
|
-
public extractTags(
|
|
283
|
+
public extractTags(
|
|
284
|
+
filePath: string,
|
|
285
|
+
content: string,
|
|
286
|
+
options: { includeJsTestBlocks?: boolean; collectReferences?: boolean } = {},
|
|
287
|
+
): FileTags | null {
|
|
284
288
|
const ext = path.extname(filePath).toLowerCase();
|
|
285
289
|
let parser = this.getParser(ext);
|
|
286
290
|
if (!parser) {
|
|
@@ -896,20 +900,72 @@ export class TreeSitterEngine {
|
|
|
896
900
|
|
|
897
901
|
visit(root, false);
|
|
898
902
|
|
|
899
|
-
//
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
const
|
|
904
|
-
if (
|
|
905
|
-
|
|
903
|
+
// For JS/TS test files, extract top-level describe/it/test/suite blocks from the same AST
|
|
904
|
+
// instead of re-parsing the file in search_chunker.
|
|
905
|
+
if (options.includeJsTestBlocks && (ext === ".ts" || ext === ".tsx" || ext === ".js" || ext === ".jsx")) {
|
|
906
|
+
for (let i = 0; i < root.childCount; i++) {
|
|
907
|
+
const child = root.child(i);
|
|
908
|
+
if (child.type !== "expression_statement") continue;
|
|
909
|
+
let expr = child.firstNamedChild;
|
|
910
|
+
let callee: any = null;
|
|
911
|
+
let argsNode: any = null;
|
|
912
|
+
while (expr && expr.type === "call_expression") {
|
|
913
|
+
const fn = expr.childForFieldName("function");
|
|
914
|
+
const args = expr.childForFieldName("arguments");
|
|
915
|
+
if (args && !argsNode) argsNode = args;
|
|
916
|
+
if (fn) {
|
|
917
|
+
callee = fn;
|
|
918
|
+
if (fn.type === "call_expression") {
|
|
919
|
+
expr = fn;
|
|
920
|
+
} else {
|
|
921
|
+
break;
|
|
922
|
+
}
|
|
923
|
+
} else {
|
|
924
|
+
break;
|
|
925
|
+
}
|
|
906
926
|
}
|
|
927
|
+
if (!callee) continue;
|
|
928
|
+
const calleeText = callee.text;
|
|
929
|
+
const match = calleeText.match(/^(?:(?:suite|describe|context|it|test)(?:\.(?:only|skip|each|todo|concurrent|serial))?)/);
|
|
930
|
+
if (!match) continue;
|
|
931
|
+
let title = "";
|
|
932
|
+
if (argsNode) {
|
|
933
|
+
for (const arg of argsNode.namedChildren) {
|
|
934
|
+
if (arg.type === "string" || arg.type === "template_string") {
|
|
935
|
+
title = arg.text.replace(/^['"`]|['"`]$/g, "");
|
|
936
|
+
break;
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
const testName = title ? `${match[0]}('${title}')` : match[0];
|
|
941
|
+
const newlineIdx = content.indexOf("\n", child.startIndex);
|
|
942
|
+
const firstLine = (newlineIdx === -1 ? content.slice(child.startIndex) : content.slice(child.startIndex, newlineIdx)).trim();
|
|
943
|
+
definitions.push({
|
|
944
|
+
name: testName,
|
|
945
|
+
kind: "test",
|
|
946
|
+
signature: firstLine.length < 120 ? firstLine : testName,
|
|
947
|
+
line: child.startPosition.row + 1,
|
|
948
|
+
endLine: child.endPosition.row + 1,
|
|
949
|
+
});
|
|
907
950
|
}
|
|
908
|
-
|
|
909
|
-
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
// Extract clean AST identifiers for PageRank graph (skips comments, docstrings, and strings)
|
|
954
|
+
if (options.collectReferences !== false) {
|
|
955
|
+
function collectAstReferences(n: any) {
|
|
956
|
+
const t = n.type;
|
|
957
|
+
if (t === "identifier" || t === "property_identifier" || t === "type_identifier" || t === "field_identifier" || t === "word") {
|
|
958
|
+
const text = n.text;
|
|
959
|
+
if (text && text.length >= 3 && /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(text)) {
|
|
960
|
+
references.add(text);
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
for (const child of n.namedChildren) {
|
|
964
|
+
collectAstReferences(child);
|
|
965
|
+
}
|
|
910
966
|
}
|
|
967
|
+
collectAstReferences(root);
|
|
911
968
|
}
|
|
912
|
-
collectAstReferences(root);
|
|
913
969
|
if (ext === ".rs") markRustTests(root, definitions);
|
|
914
970
|
|
|
915
971
|
return {
|