@floydous/pi-agent-kernel 0.5.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/AGENT_KERNEL_SYS_PROMPT.md +20 -6
  2. package/CHANGELOG.md +69 -0
  3. package/README.md +23 -20
  4. package/config.example.toml +1 -0
  5. package/docs/configuration.md +1 -1
  6. package/docs/editing-and-verification.md +20 -5
  7. package/docs/podman-linux-checks.md +24 -0
  8. package/docs/release-discipline.md +10 -0
  9. package/docs/retrieval.md +14 -11
  10. package/grammars/tree-sitter-html.wasm +0 -0
  11. package/package.json +2 -2
  12. package/src/config/agent_kernel_command.ts +60 -593
  13. package/src/config/kernel_config.ts +46 -2
  14. package/src/editing/patch.ts +48 -21
  15. package/src/editing/post_edit_verification.ts +8 -4
  16. package/src/editing/smart_anchor.ts +2 -1
  17. package/src/editing/syntax-verify.ts +73 -220
  18. package/src/index.ts +105 -203
  19. package/src/retrieval/html_chunker.ts +526 -0
  20. package/src/retrieval/search_bm25.ts +36 -27
  21. package/src/retrieval/search_chunker.ts +68 -6
  22. package/src/retrieval/search_config.ts +17 -34
  23. package/src/retrieval/search_embedder.ts +11 -29
  24. package/src/retrieval/search_index.ts +307 -145
  25. package/src/retrieval/search_modal.ts +1247 -222
  26. package/src/retrieval/tag_extractor.ts +1 -1
  27. package/src/retrieval/tree_sitter_engine.ts +103 -4
  28. package/src/retrieval/workspace_walker.ts +72 -0
  29. package/src/safety/host_environment.ts +190 -0
  30. package/src/safety/output_clamper.ts +83 -19
  31. package/src/tools/code_search_output.ts +9 -1
  32. package/src/tools/code_search_tool.ts +51 -14
  33. package/src/tools/context.ts +15 -0
  34. package/src/tools/edit_tool.ts +306 -79
  35. package/src/tools/read_tool.ts +248 -39
  36. package/src/tools/stream_reader.ts +206 -0
  37. package/src/ui/tui_utils.ts +70 -12
@@ -1,9 +1,10 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import * as crypto from "node:crypto";
4
- import { walkWorkspaceFiles, DEFAULT_IGNORED_DIRS } from "./workspace_walker";
4
+ import { walkWorkspaceFiles, DEFAULT_IGNORED_DIRS, type WorkspaceWalkCache } from "./workspace_walker";
5
5
  import { extractFileTags, isTestPath, SymbolDef } from "./tag_extractor";
6
6
  import { TreeSitterEngine } from "./tree_sitter_engine";
7
+ import { chunkHtmlFile } from "./html_chunker";
7
8
 
8
9
  export interface CodeChunk {
9
10
  id: string; // e.g. "src/auth.ts:45-90#verifyToken"
@@ -20,14 +21,37 @@ export interface CodeChunk {
20
21
  hash: string; // SHA-256 hash of content
21
22
  }
22
23
 
24
+ export const CODE_EXTENSIONS = new Set([
25
+ ".ts", ".tsx", ".js", ".jsx", ".py", ".rs", ".go", ".c", ".cpp", ".cc", ".cxx", ".h", ".hpp", ".hh", ".hxx", ".java", ".cs", ".rb", ".php", ".swift", ".sh", ".bash", ".sql"
26
+ ]);
27
+
28
+ export const HTML_EXTENSIONS = new Set([
29
+ ".html", ".htm"
30
+ ]);
31
+
23
32
  export const SUPPORTED_EXTENSIONS = new Set([
24
- ".ts", ".tsx", ".js", ".jsx", ".py", ".rs", ".go", ".c", ".cpp", ".h", ".hpp", ".java", ".cs", ".rb", ".php", ".swift", ".sh", ".bash", ".sql"
33
+ ...CODE_EXTENSIONS,
34
+ ...HTML_EXTENSIONS
25
35
  ]);
26
36
 
37
+ export function isHtmlPath(relPath: string): boolean {
38
+ const ext = path.extname(relPath).toLowerCase();
39
+ return HTML_EXTENSIONS.has(ext);
40
+ }
41
+
27
42
  export const IGNORED_DIRS = DEFAULT_IGNORED_DIRS;
28
43
  export const MAX_INDEX_FILE_BYTES = 2 * 1024 * 1024;
29
44
  export const MAX_INDEX_WORKSPACE_BYTES = 20 * 1024 * 1024;
30
45
  export const MAX_INDEX_CHUNKS = 10_000;
46
+ export const MAX_INDEX_FILES = 500;
47
+ /** Indexable files a walk collects for ranking; past this the walk stops in directory order. */
48
+ export const MAX_WALK_FILES = 20_000;
49
+ const VENDORED_PATH = /(^|\/)(deps|third_party|thirdparty|external|extern)\//;
50
+
51
+ /** Index priority when the caps cannot hold every file: 0 project source, 1 test, 2 vendored (a vendored test is vendored). */
52
+ export function fileTier(relPath: string): number {
53
+ return VENDORED_PATH.test(relPath) ? 2 : isTestPath(relPath) ? 1 : 0;
54
+ }
31
55
 
32
56
  /**
33
57
  * Compute SHA-256 hash of a string.
@@ -60,6 +84,10 @@ export function chunkFile(rootDir: string, filePath: string, content?: string):
60
84
  }
61
85
  if (Buffer.byteLength(fileContent, "utf8") > MAX_INDEX_FILE_BYTES) return [];
62
86
 
87
+ if (HTML_EXTENSIONS.has(ext)) {
88
+ return chunkHtmlFile(rootDir, absPath, fileContent);
89
+ }
90
+
63
91
  const lines = fileContent.split("\n");
64
92
  if (lines.length === 0) return [];
65
93
 
@@ -282,14 +310,48 @@ export function chunkFile(rootDir: string, filePath: string, content?: string):
282
310
  * Find supported source files in a workspace using the same traversal policy as
283
311
  * chunkWorkspace. The search index uses this to check live file freshness
284
312
  * without reparsing unchanged files.
313
+ *
314
+ * Returns the first `maxFiles` files in index priority order: fileTier, then
315
+ * workspace-relative path in code-unit order, independent of directory order.
285
316
  */
286
- export function findChunkableFiles(rootDir: string, maxFiles = 500): string[] {
287
- return walkWorkspaceFiles({
317
+ export function findChunkableFiles(rootDir: string, maxFiles = MAX_INDEX_FILES, cache?: WorkspaceWalkCache): string[] {
318
+ return rankChunkableFiles(rootDir, cache, Math.max(maxFiles, MAX_WALK_FILES)).slice(0, maxFiles).map((entry) => entry.file);
319
+ }
320
+
321
+ export interface RankedFile {
322
+ readonly file: string;
323
+ /** Workspace-relative path with forward slashes. */
324
+ readonly rel: string;
325
+ readonly tier: number;
326
+ }
327
+
328
+ /** A warm search repeats an unchanged walk; ranking 20,000 paths each time would cost more than the walk check. */
329
+ const rankingMemo = new WeakMap<WorkspaceWalkCache, { rootDir: string; walked: string[]; ranked: readonly RankedFile[] }>();
330
+
331
+ /** Every walked indexable file (up to `maxWalk`) in index priority order. The result is shared: do not mutate it. */
332
+ export function rankChunkableFiles(rootDir: string, cache?: WorkspaceWalkCache, maxWalk = MAX_WALK_FILES): readonly RankedFile[] {
333
+ const options = {
288
334
  rootDir,
289
- maxFiles,
335
+ maxFiles: maxWalk,
290
336
  extensions: SUPPORTED_EXTENSIONS,
291
337
  includeGithub: true,
292
- });
338
+ };
339
+ const walked = cache ? cache.walk(options) : walkWorkspaceFiles(options);
340
+ const memo = cache && rankingMemo.get(cache);
341
+ if (memo && memo.rootDir === rootDir && memo.walked.length === walked.length && memo.walked.every((file, i) => file === walked[i])) {
342
+ return memo.ranked;
343
+ }
344
+ // The walker builds every path from the resolved root, so slicing equals path.relative at a fraction of the cost.
345
+ const root = path.resolve(rootDir);
346
+ const prefix = root.endsWith(path.sep) ? root.length : root.length + 1;
347
+ const ranked = walked
348
+ .map((file) => {
349
+ const rel = file.slice(prefix).replace(/\\/g, "/");
350
+ return { file, rel, tier: fileTier(rel) };
351
+ })
352
+ .sort((a, b) => a.tier - b.tier || (isHtmlPath(a.rel) !== isHtmlPath(b.rel) ? (isHtmlPath(a.rel) ? 1 : -1) : 0) || (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));
353
+ if (cache) rankingMemo.set(cache, { rootDir, walked, ranked });
354
+ return ranked;
293
355
  }
294
356
 
295
357
  /**
@@ -14,12 +14,18 @@ import { parseToml } from "../config/toml";
14
14
 
15
15
  export type SearchProfile = "lean" | "hybrid" | "full" | "off" | "auto";
16
16
 
17
- export const EMBEDDING_MODEL_ID = "nomic-ai/nomic-embed-text-v1.5";
18
- export const EMBEDDING_MODEL_REVISION = "e9b6763023c676ca8431644204f50c2b100d9aab";
17
+ export const EMBEDDING_MODEL_ID = "Alibaba-NLP/gte-modernbert-base";
18
+ export const EMBEDDING_MODEL_REVISION = "e7f32e3c00f91d699e8c43b53106206bcc72bb22";
19
+ /**
20
+ * Minimum query–chunk cosine for a vector hit to enter fusion. Calibrated for gte-modernbert-base on 168 held-out
21
+ * queries: the highest floor that drops no top-5 hit (0.5 dropped 2 right files and 2 right chunks).
22
+ */
23
+ export const DENSE_SIMILARITY_FLOOR = 0.45;
19
24
 
20
25
  export interface SearchConfig {
21
26
  profile: SearchProfile;
22
- effectiveProfile: "lean" | "hybrid" | "full" | "off";
27
+ /** "hybrid" is accepted as a profile name but resolves to "full": both used the same model at the same cost. */
28
+ effectiveProfile: "lean" | "full" | "off";
23
29
  matryoshkaDim: number;
24
30
  /** Minimum cosine similarity required before vector results enter RRF. */
25
31
  vectorSimilarityThreshold: number;
@@ -43,11 +49,8 @@ const SETTINGS_FILE = path.join(
43
49
  * Auto-detect the best profile based on current hardware.
44
50
  * Strictly defaults to "lean" (AST-aware BM25) for ultra-fast, zero-overhead lexical search.
45
51
  */
46
- export function detectBestProfile(): "lean" | "hybrid" | "full" {
47
- const cpuCount = os.cpus().length;
48
- if (cpuCount >= 8) return "full";
49
- if (cpuCount >= 4) return "hybrid";
50
- return "lean";
52
+ export function detectBestProfile(): "lean" | "full" {
53
+ return os.cpus().length >= 4 ? "full" : "lean";
51
54
  }
52
55
 
53
56
  /**
@@ -137,8 +140,8 @@ export function getSearchConfig(
137
140
  projectTrusted = false,
138
141
  ): SearchConfig {
139
142
  const profile = requestedProfile || loadPersistedProfile(cwd, projectTrusted);
140
- const effectiveProfile: "lean" | "hybrid" | "full" | "off" =
141
- profile === "auto" ? detectBestProfile() : profile || "lean";
143
+ const effectiveProfile: "lean" | "full" | "off" =
144
+ profile === "auto" ? detectBestProfile() : profile === "hybrid" ? "full" : profile || "lean";
142
145
 
143
146
  const globalCacheDir = path.join(os.homedir(), ".pi", "cache", "search");
144
147
 
@@ -177,38 +180,18 @@ export function getSearchConfig(
177
180
  };
178
181
  }
179
182
 
180
- // Hybrid Profile: Gentle 1-thread Nomic 256-dim embeddings with throttle sleeps.
181
- if (effectiveProfile === "hybrid") {
182
- return {
183
- profile,
184
- effectiveProfile: "hybrid",
185
- matryoshkaDim: 256,
186
- // Empirically calibrated: 0.55 admits natural-language cross-domain queries
187
- // while cleanly blocking off-topic noise (unrelated queries score ~0.48-0.52).
188
- vectorSimilarityThreshold: 0.55,
189
- numThreads: 1,
190
- modelId: EMBEDDING_MODEL_ID,
191
- modelRevision: EMBEDDING_MODEL_REVISION,
192
- dtype: "q8",
193
- batchSize: 1,
194
- sleepBetweenBatchesMs: 80, // 80ms sleep between chunk batches to prevent CPU starvation
195
- cacheDir: globalCacheDir,
196
- lazyLoad: true,
197
- };
198
- }
199
-
200
- // Full Profile: Controlled multi-core workstation setting.
183
+ // Full Profile: BM25 + 768-dim code embeddings, controlled multi-core setting.
201
184
  return {
202
185
  profile,
203
186
  effectiveProfile: "full",
204
187
  matryoshkaDim: 768,
205
- // Empirically calibrated floor for 768-dim embeddings.
206
- vectorSimilarityThreshold: 0.55,
188
+ vectorSimilarityThreshold: DENSE_SIMILARITY_FLOOR,
207
189
  numThreads: Math.min(2, Math.max(1, Math.floor(os.cpus().length / 2))),
208
190
  modelId: EMBEDDING_MODEL_ID,
209
191
  modelRevision: EMBEDDING_MODEL_REVISION,
210
192
  dtype: "q8",
211
- batchSize: 2,
193
+ // One text per call: with q8 weights, batched texts change each other's vectors.
194
+ batchSize: 1,
212
195
  sleepBetweenBatchesMs: 50,
213
196
  cacheDir: globalCacheDir,
214
197
  lazyLoad: true,
@@ -11,7 +11,6 @@ export interface EmbeddingResult {
11
11
 
12
12
  export class LocalEmbedder {
13
13
  private extractor: any = null;
14
- private layerNormFn: any = null;
15
14
  private config: SearchConfig;
16
15
  private isInitializing = false;
17
16
  private initPromise: Promise<void> | null = null;
@@ -147,7 +146,7 @@ export class LocalEmbedder {
147
146
  if (cached) {
148
147
  onProgress?.("Loading embedding weights into RAM...");
149
148
  } else {
150
- onProgress?.("Downloading embedding weights: 0% (~135 MB)...");
149
+ onProgress?.("Downloading embedding weights: 0% (~147 MB)...");
151
150
  }
152
151
 
153
152
  // Enforce single-thread CPU constraints to avoid starving system processes
@@ -155,7 +154,7 @@ export class LocalEmbedder {
155
154
  process.env.ORT_INTRA_OP_NUM_THREADS = String(this.config.numThreads || 1);
156
155
  process.env.ORT_INTER_OP_NUM_THREADS = String(this.config.numThreads || 1);
157
156
 
158
- const { env, pipeline, layer_norm } = await import(
157
+ const { env, pipeline } = await import(
159
158
  "@huggingface/transformers"
160
159
  );
161
160
  if (env && env.backends && env.backends.onnx) {
@@ -163,8 +162,6 @@ export class LocalEmbedder {
163
162
  env.backends.onnx.logLevel = "warning";
164
163
  }
165
164
 
166
- this.layerNormFn = layer_norm;
167
-
168
165
  this.extractor = await pipeline("feature-extraction", this.config.modelId, {
169
166
  revision: this.config.modelRevision,
170
167
  dtype: this.config.dtype,
@@ -176,9 +173,10 @@ export class LocalEmbedder {
176
173
  },
177
174
  });
178
175
 
179
- // Strictly clamp tokenizer max sequence length to 512 tokens to prevent ONNX activation RAM explosions
176
+ // Clamp the sequence length to bound ONNX activation RAM. Texts are cut to 1,800 chars first; with this
177
+ // model those take ≤ 980 tokens in all but 3 of 23,000 measured chunks, so 1,024 rarely truncates.
180
178
  if (this.extractor?.tokenizer?.config) {
181
- this.extractor.tokenizer.config.model_max_length = 512;
179
+ this.extractor.tokenizer.config.model_max_length = 1024;
182
180
  }
183
181
 
184
182
  onProgress?.("Embedding model loaded.");
@@ -229,11 +227,12 @@ export class LocalEmbedder {
229
227
  }
230
228
 
231
229
  /**
232
- * Embed a batch of texts with Matryoshka dimension truncation and L2 normalization.
230
+ * Embed texts as L2-normalized CLS vectors (gte-modernbert-base: no task prefix). Callers pass one text per call:
231
+ * with q8 weights, texts batched together change each other's vectors.
233
232
  */
234
233
  public async embedBatch(
235
234
  texts: string[],
236
- isQuery = false,
235
+ _isQuery = false, // queries and documents are embedded alike (no task prefix)
237
236
  onProgress?: (msg: string) => void,
238
237
  ): Promise<Float32Array[]> {
239
238
  if (
@@ -250,28 +249,12 @@ export class LocalEmbedder {
250
249
 
251
250
  if (texts.length === 0) return [];
252
251
 
253
- // Apply mandatory Nomic task prefix and clamp character length to 1,800 chars (~400 tokens)
254
- const prefix = isQuery ? "search_query: " : "search_document: ";
255
- const prefixedTexts = texts.map((t) => `${prefix}${t.slice(0, 1800)}`);
256
-
257
252
  try {
258
- let tensorOutput = await this.extractor(prefixedTexts, {
259
- pooling: "mean",
260
- normalize: false,
253
+ const tensorOutput = await this.extractor(texts.map((t) => t.slice(0, 1800)), {
254
+ pooling: "cls",
255
+ normalize: true,
261
256
  });
262
257
 
263
- const targetDim =
264
- this.config.matryoshkaDim > 0 ? this.config.matryoshkaDim : 768;
265
-
266
- // Apply LayerNorm -> Slice to Matryoshka Dim -> L2 Normalize
267
- if (this.layerNormFn && targetDim < 768) {
268
- tensorOutput = this.layerNormFn(tensorOutput, [tensorOutput.dims[1]])
269
- .slice(null, [0, targetDim])
270
- .normalize(2, -1);
271
- } else {
272
- tensorOutput = tensorOutput.normalize(2, -1);
273
- }
274
-
275
258
  const data: Float32Array = tensorOutput.data;
276
259
  const batchCount = tensorOutput.dims[0];
277
260
  const actualDim = tensorOutput.dims[1];
@@ -339,7 +322,6 @@ export class LocalEmbedder {
339
322
  }
340
323
 
341
324
  this.extractor = null;
342
- this.layerNormFn = null;
343
325
  this.initPromise = null;
344
326
  this.queryLruCache.clear();
345
327