@floydous/pi-agent-kernel 0.4.3 → 0.6.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.
Files changed (65) hide show
  1. package/AGENT_KERNEL_SYS_PROMPT.md +15 -12
  2. package/CHANGELOG.md +87 -0
  3. package/README.md +6 -54
  4. package/config.example.toml +1 -8
  5. package/docs/README.md +1 -2
  6. package/docs/architecture.md +2 -3
  7. package/docs/configuration.md +11 -10
  8. package/docs/editing-and-verification.md +21 -8
  9. package/docs/podman-linux-checks.md +24 -0
  10. package/docs/release-discipline.md +10 -0
  11. package/docs/retrieval.md +21 -23
  12. package/docs/testing.md +3 -3
  13. package/grammars/tree-sitter-html.wasm +0 -0
  14. package/package.json +5 -3
  15. package/src/config/agent_kernel_command.ts +60 -625
  16. package/src/config/kernel_config.ts +53 -69
  17. package/src/config/toml.ts +6 -1
  18. package/src/editing/auto_heal.ts +1 -1
  19. package/src/editing/patch.ts +75 -37
  20. package/src/editing/post_edit_verification.ts +20 -14
  21. package/src/editing/smart_anchor.ts +9 -6
  22. package/src/editing/syntax-verify.ts +79 -222
  23. package/src/index.ts +36 -453
  24. package/src/retrieval/html_chunker.ts +526 -0
  25. package/src/retrieval/search_bm25.ts +39 -28
  26. package/src/retrieval/search_chunker.ts +69 -7
  27. package/src/retrieval/search_config.ts +21 -40
  28. package/src/retrieval/search_embedder.ts +14 -31
  29. package/src/retrieval/search_index.ts +338 -129
  30. package/src/retrieval/search_modal.ts +1208 -222
  31. package/src/retrieval/{repomap.ts → tag_extractor.ts} +6 -293
  32. package/src/retrieval/tree_sitter_engine.ts +171 -36
  33. package/src/retrieval/workspace_walker.ts +78 -2
  34. package/src/safety/atomic_write.ts +1 -1
  35. package/src/safety/epistemic_guard.ts +105 -31
  36. package/src/safety/host_environment.ts +180 -0
  37. package/src/safety/output_clamper.ts +97 -27
  38. package/src/tools/code_search_output.ts +11 -2
  39. package/src/tools/code_search_tool.ts +25 -13
  40. package/src/tools/context.ts +11 -10
  41. package/src/tools/edit_tool.ts +243 -154
  42. package/src/tools/read_tool.ts +285 -214
  43. package/src/tools/stream_reader.ts +206 -0
  44. package/src/ui/footer.ts +7 -7
  45. package/docs/lsp.md +0 -31
  46. package/src/lsp/adapters/base.ts +0 -42
  47. package/src/lsp/adapters/index.ts +0 -21
  48. package/src/lsp/adapters/python.ts +0 -37
  49. package/src/lsp/adapters/rust.ts +0 -35
  50. package/src/lsp/adapters/typescript.ts +0 -40
  51. package/src/lsp/index.ts +0 -13
  52. package/src/lsp/lsp_client.ts +0 -765
  53. package/src/lsp/lsp_detector.ts +0 -52
  54. package/src/lsp/lsp_formatter.ts +0 -323
  55. package/src/lsp/lsp_installer.ts +0 -320
  56. package/src/lsp/lsp_manager.ts +0 -202
  57. package/src/lsp/lsp_modal.ts +0 -675
  58. package/src/lsp/lsp_registry.ts +0 -600
  59. package/src/lsp/lsp_types.ts +0 -143
  60. package/src/retrieval/ast_search.ts +0 -999
  61. package/src/retrieval/symbol_reader.ts +0 -228
  62. package/src/tools/ast_search_formatter.ts +0 -161
  63. package/src/tools/ast_search_tool.ts +0 -146
  64. package/src/tools/lsp_tool.ts +0 -794
  65. package/src/tools/repo_map_tool.ts +0 -56
@@ -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";
5
- import { extractFileTags, isTestPath, SymbolDef } from "./repomap";
4
+ import { walkWorkspaceFiles, DEFAULT_IGNORED_DIRS, type WorkspaceWalkCache } from "./workspace_walker";
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
  /**
@@ -3,11 +3,9 @@ import * as fs from "node:fs";
3
3
  import * as path from "node:path";
4
4
  import {
5
5
  getPiHomeDir,
6
- loadKernelConfig,
7
6
  saveProjectKernelConfig,
8
7
  saveGlobalKernelConfig,
9
8
  getProjectConfigPath,
10
- getGlobalConfigPath,
11
9
  getGlobalRawConfig,
12
10
  } from "../config";
13
11
  import { kernelDebug } from "../safety/kernel_debug";
@@ -16,12 +14,18 @@ import { parseToml } from "../config/toml";
16
14
 
17
15
  export type SearchProfile = "lean" | "hybrid" | "full" | "off" | "auto";
18
16
 
19
- export const EMBEDDING_MODEL_ID = "nomic-ai/nomic-embed-text-v1.5";
20
- 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;
21
24
 
22
25
  export interface SearchConfig {
23
26
  profile: SearchProfile;
24
- 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";
25
29
  matryoshkaDim: number;
26
30
  /** Minimum cosine similarity required before vector results enter RRF. */
27
31
  vectorSimilarityThreshold: number;
@@ -45,11 +49,8 @@ const SETTINGS_FILE = path.join(
45
49
  * Auto-detect the best profile based on current hardware.
46
50
  * Strictly defaults to "lean" (AST-aware BM25) for ultra-fast, zero-overhead lexical search.
47
51
  */
48
- export function detectBestProfile(): "lean" | "hybrid" | "full" {
49
- const cpuCount = os.cpus().length;
50
- if (cpuCount >= 8) return "full";
51
- if (cpuCount >= 4) return "hybrid";
52
- return "lean";
52
+ export function detectBestProfile(): "lean" | "full" {
53
+ return os.cpus().length >= 4 ? "full" : "lean";
53
54
  }
54
55
 
55
56
  /**
@@ -66,8 +67,8 @@ export function loadPersistedProfile(
66
67
  const raw = parseToml(fs.readFileSync(projectPath, "utf-8"));
67
68
  const retrieval = raw.retrieval;
68
69
  if (retrieval && typeof retrieval === "object" && !Array.isArray(retrieval)) {
69
- const p = (retrieval as any).default_profile;
70
- if (p && ["lean", "hybrid", "full", "off", "auto"].includes(p)) {
70
+ const p = (retrieval as Record<string, unknown>).default_profile;
71
+ if (typeof p === "string" && ["lean", "hybrid", "full", "off", "auto"].includes(p)) {
71
72
  return p as SearchProfile;
72
73
  }
73
74
  }
@@ -111,10 +112,10 @@ export function savePersistedProfile(profile: SearchProfile, cwd?: string): void
111
112
  try {
112
113
  if (cwd) {
113
114
  // Workspace-local profile update: writes only to project-local config.toml
114
- saveProjectKernelConfig(cwd, { retrieval: { default_profile: profile as any } });
115
+ saveProjectKernelConfig(cwd, { retrieval: { default_profile: profile } });
115
116
  } else {
116
117
  // Global profile update: writes to global ~/.pi/agent/config.toml and legacy search_settings.json
117
- saveGlobalKernelConfig({ retrieval: { default_profile: profile as any } });
118
+ saveGlobalKernelConfig({ retrieval: { default_profile: profile } });
118
119
  const dir = path.dirname(SETTINGS_FILE);
119
120
  if (!fs.existsSync(dir)) {
120
121
  fs.mkdirSync(dir, { recursive: true });
@@ -139,8 +140,8 @@ export function getSearchConfig(
139
140
  projectTrusted = false,
140
141
  ): SearchConfig {
141
142
  const profile = requestedProfile || loadPersistedProfile(cwd, projectTrusted);
142
- const effectiveProfile: "lean" | "hybrid" | "full" | "off" =
143
- profile === "auto" ? detectBestProfile() : profile || "lean";
143
+ const effectiveProfile: "lean" | "full" | "off" =
144
+ profile === "auto" ? detectBestProfile() : profile === "hybrid" ? "full" : profile || "lean";
144
145
 
145
146
  const globalCacheDir = path.join(os.homedir(), ".pi", "cache", "search");
146
147
 
@@ -179,38 +180,18 @@ export function getSearchConfig(
179
180
  };
180
181
  }
181
182
 
182
- // Hybrid Profile: Gentle 1-thread Nomic 256-dim embeddings with throttle sleeps.
183
- if (effectiveProfile === "hybrid") {
184
- return {
185
- profile,
186
- effectiveProfile: "hybrid",
187
- matryoshkaDim: 256,
188
- // Empirically calibrated: 0.55 admits natural-language cross-domain queries
189
- // while cleanly blocking off-topic noise (unrelated queries score ~0.48-0.52).
190
- vectorSimilarityThreshold: 0.55,
191
- numThreads: 1,
192
- modelId: EMBEDDING_MODEL_ID,
193
- modelRevision: EMBEDDING_MODEL_REVISION,
194
- dtype: "q8",
195
- batchSize: 1,
196
- sleepBetweenBatchesMs: 80, // 80ms sleep between chunk batches to prevent CPU starvation
197
- cacheDir: globalCacheDir,
198
- lazyLoad: true,
199
- };
200
- }
201
-
202
- // Full Profile: Controlled multi-core workstation setting.
183
+ // Full Profile: BM25 + 768-dim code embeddings, controlled multi-core setting.
203
184
  return {
204
185
  profile,
205
186
  effectiveProfile: "full",
206
187
  matryoshkaDim: 768,
207
- // Empirically calibrated floor for 768-dim embeddings.
208
- vectorSimilarityThreshold: 0.55,
188
+ vectorSimilarityThreshold: DENSE_SIMILARITY_FLOOR,
209
189
  numThreads: Math.min(2, Math.max(1, Math.floor(os.cpus().length / 2))),
210
190
  modelId: EMBEDDING_MODEL_ID,
211
191
  modelRevision: EMBEDDING_MODEL_REVISION,
212
192
  dtype: "q8",
213
- batchSize: 2,
193
+ // One text per call: with q8 weights, batched texts change each other's vectors.
194
+ batchSize: 1,
214
195
  sleepBetweenBatchesMs: 50,
215
196
  cacheDir: globalCacheDir,
216
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,13 +322,13 @@ 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
 
346
328
  try {
347
- if (typeof (global as any).gc === "function") {
348
- (global as any).gc();
329
+ const globalWithGc = globalThis as typeof globalThis & { gc?: () => void };
330
+ if (typeof globalWithGc.gc === "function") {
331
+ globalWithGc.gc();
349
332
  }
350
333
  } catch (e) {
351
334
  kernelDebug(e);