@floydous/pi-agent-kernel 0.3.31 → 0.4.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 (40) hide show
  1. package/AGENT_KERNEL_SYS_PROMPT.md +6 -4
  2. package/CHANGELOG.md +35 -4
  3. package/README.md +39 -74
  4. package/config.example.toml +36 -0
  5. package/docs/configuration.md +11 -3
  6. package/docs/retrieval.md +17 -1
  7. package/docs/testing.md +5 -3
  8. package/package.json +9 -7
  9. package/src/config/agent_kernel_command.ts +91 -91
  10. package/src/config/kernel_config.ts +179 -43
  11. package/src/config/toml.ts +15 -4
  12. package/src/context/session_repair.ts +179 -80
  13. package/src/editing/patch.ts +28 -16
  14. package/src/editing/smart_anchor.ts +29 -36
  15. package/src/editing/syntax-verify.ts +52 -18
  16. package/src/index.ts +257 -219
  17. package/src/lsp/lsp_client.ts +138 -23
  18. package/src/lsp/lsp_formatter.ts +61 -24
  19. package/src/lsp/lsp_installer.ts +277 -561
  20. package/src/lsp/lsp_manager.ts +1 -1
  21. package/src/lsp/lsp_registry.ts +110 -73
  22. package/src/retrieval/ast_search.ts +136 -172
  23. package/src/retrieval/repomap.ts +8 -47
  24. package/src/retrieval/search_bm25.ts +5 -2
  25. package/src/retrieval/search_cache.ts +69 -0
  26. package/src/retrieval/search_chunker.ts +21 -43
  27. package/src/retrieval/search_config.ts +75 -18
  28. package/src/retrieval/search_embedder.ts +8 -16
  29. package/src/retrieval/search_index.ts +923 -123
  30. package/src/retrieval/workspace_walker.ts +262 -0
  31. package/src/safety/atomic_write.ts +59 -20
  32. package/src/safety/epistemic_guard.ts +163 -43
  33. package/src/safety/output_clamper.ts +316 -74
  34. package/src/tools/code_search_output.ts +59 -23
  35. package/src/tools/code_search_tool.ts +42 -46
  36. package/src/tools/context.ts +15 -1
  37. package/src/tools/edit_tool.ts +124 -43
  38. package/src/tools/lsp_tool.ts +17 -4
  39. package/src/tools/read_tool.ts +48 -7
  40. package/config.toml +0 -31
@@ -16,18 +16,20 @@ import {
16
16
  loadKernelConfig,
17
17
  saveGlobalKernelConfig,
18
18
  removeGlobalKernelConfigKey,
19
+ removeProjectKernelConfigKey,
19
20
  saveProjectKernelConfig,
21
+ mergeDeep,
20
22
  getGlobalConfigPath,
21
23
  getGlobalRawConfig,
22
24
  getProjectConfigPath,
23
25
  type KernelConfig,
24
26
  type KernelConfigOverrides,
25
- type CodebaseProfile,
26
27
  } from "./kernel_config";
28
+ import { kernelDebug } from "../safety/kernel_debug";
27
29
 
28
30
  export interface AgentKernelCommandDeps {
29
31
  getConfig: (cwd: string) => KernelConfig;
30
- invalidateConfig: (cwd: string) => void;
32
+ invalidateConfig: (cwd: string, ctx?: any) => void;
31
33
  clearCaches?: () => void;
32
34
  }
33
35
 
@@ -43,8 +45,7 @@ export function formatConfigDashboard(cwd: string, config: KernelConfig): string
43
45
  `Project Config: ${projectPath ?? "none"} [${projectExists ? "ACTIVE" : "NONE"}]`,
44
46
  ``,
45
47
  `[Retrieval & Tools]`,
46
- ` • Profile (Engine) : ${config.retrieval.default_profile} (lean | hybrid | full)`,
47
- ` • Codebase Scale : ${config.retrieval.codebase_profile} (auto | light | heavy)`,
48
+ ` • Profile (Engine) : ${config.retrieval.default_profile} (auto | lean | hybrid | full | off)`,
48
49
  ` • Passive Shield : ${config.retrieval.enable_tools ? "all (6 tools exposed)" : "gated (core 3 tools default)"}`,
49
50
  ` • Repo Map Budget : ${config.retrieval.repo_map_budget} tokens`,
50
51
  ` • Max Search Results : ${config.retrieval.max_search_results}`,
@@ -85,8 +86,7 @@ export function registerAgentKernelCommand(pi: ExtensionAPI, deps: AgentKernelCo
85
86
 
86
87
  const keys = [
87
88
  { value: "set tools", label: "set tools <gated|all> - Toggle Passive Shield tool gating" },
88
- { value: "set profile", label: "set profile <lean|hybrid|full> - Retrieval engine profile" },
89
- { value: "set codebase", label: "set codebase <auto|light|heavy> - Codebase scale profile" },
89
+ { value: "set profile", label: "set profile <auto|lean|hybrid|full|off> - Retrieval engine profile" },
90
90
  { value: "set epistemic", label: "set epistemic <on|off> - Toggle Epistemic Guard" },
91
91
  { value: "set editing", label: "set editing <smart_anchor|standard> - Editing engine mode" },
92
92
  { value: "set read_mode", label: "set read_mode <plain|anchored|auto> - Reading anchor mode" },
@@ -121,7 +121,11 @@ export function registerAgentKernelCommand(pi: ExtensionAPI, deps: AgentKernelCo
121
121
  if (fs.existsSync(globalPath)) {
122
122
  fs.unlinkSync(globalPath);
123
123
  }
124
- deps.invalidateConfig(currentCwd);
124
+ const legacySettings = path.join(path.dirname(globalPath), "search_settings.json");
125
+ if (fs.existsSync(legacySettings)) {
126
+ try { fs.unlinkSync(legacySettings); } catch {}
127
+ }
128
+ deps.invalidateConfig(currentCwd, ctx);
125
129
  deps.clearCaches?.();
126
130
  const msg = "Reset global Agent Kernel configuration to defaults.";
127
131
  ctx.ui?.notify?.(msg, "info");
@@ -145,27 +149,16 @@ export function registerAgentKernelCommand(pi: ExtensionAPI, deps: AgentKernelCo
145
149
  case "passive_shield": {
146
150
  const enable = val === "all" || val === "true" || val === "1";
147
151
  updates.retrieval = { enable_tools: enable };
148
- desc = `Passive Shield tools set to '${enable ? "all (6 tools)" : "gated (core 3 tools)"}'`;
152
+ desc = `Passive Shield tools set to '${enable ? "all (6 tools)" : "gated (core 3 tools)"}' (takes effect on reload)`;
149
153
  break;
150
154
  }
151
155
  case "profile":
152
156
  case "engine": {
153
- if (val === "lean" || val === "hybrid" || val === "full") {
157
+ if (val === "auto" || val === "lean" || val === "hybrid" || val === "full" || val === "off") {
154
158
  updates.retrieval = { default_profile: val };
155
159
  desc = `Retrieval profile set to '${val}'`;
156
160
  } else {
157
- ctx.ui?.notify?.("Invalid profile. Options: lean | hybrid | full", "error");
158
- return;
159
- }
160
- break;
161
- }
162
- case "codebase":
163
- case "codebase_profile": {
164
- if (val === "auto" || val === "light" || val === "heavy") {
165
- updates.retrieval = { codebase_profile: val };
166
- desc = `Codebase scale profile set to '${val}'`;
167
- } else {
168
- ctx.ui?.notify?.("Invalid codebase profile. Options: auto | light | heavy", "error");
161
+ ctx.ui?.notify?.("Invalid profile. Options: auto | lean | hybrid | full | off", "error");
169
162
  return;
170
163
  }
171
164
  break;
@@ -237,7 +230,7 @@ export function registerAgentKernelCommand(pi: ExtensionAPI, deps: AgentKernelCo
237
230
  }
238
231
 
239
232
  saveGlobalKernelConfig(updates);
240
- deps.invalidateConfig(currentCwd);
233
+ deps.invalidateConfig(currentCwd, ctx);
241
234
  deps.clearCaches?.();
242
235
  ctx.ui?.notify?.(`Saved to ~/.pi/agent/config.toml: ${desc}`, "info");
243
236
  console.log(`[agent-kernel] ${desc} (persisted globally)`);
@@ -276,7 +269,6 @@ export function registerAgentKernelCommand(pi: ExtensionAPI, deps: AgentKernelCo
276
269
  function checkIsGlobal(id: string): boolean {
277
270
  if (id === "tools") return globalRaw.retrieval?.enable_tools !== undefined;
278
271
  if (id === "profile") return globalRaw.retrieval?.default_profile !== undefined;
279
- if (id === "codebase") return globalRaw.retrieval?.codebase_profile !== undefined;
280
272
  if (id === "epistemic") return globalRaw.safety?.enable_epistemic_guard !== undefined;
281
273
  if (id === "max_lines") return globalRaw.safety?.max_lines !== undefined;
282
274
  if (id === "editing") return globalRaw.editing?.mode !== undefined;
@@ -297,9 +289,6 @@ export function registerAgentKernelCommand(pi: ExtensionAPI, deps: AgentKernelCo
297
289
  } else if (id === "profile") {
298
290
  patch.retrieval = { default_profile: value as any };
299
291
  desc = `Retrieval profile = ${value}`;
300
- } else if (id === "codebase") {
301
- patch.retrieval = { codebase_profile: value as any };
302
- desc = `Codebase scale profile = ${value}`;
303
292
  } else if (id === "epistemic") {
304
293
  const enable = value === "enabled";
305
294
  patch.safety = { enable_epistemic_guard: enable };
@@ -338,8 +327,6 @@ export function registerAgentKernelCommand(pi: ExtensionAPI, deps: AgentKernelCo
338
327
  return { section: "retrieval", key: "enable_tools" };
339
328
  case "profile":
340
329
  return { section: "retrieval", key: "default_profile" };
341
- case "codebase":
342
- return { section: "retrieval", key: "codebase_profile" };
343
330
  case "epistemic":
344
331
  return { section: "safety", key: "enable_epistemic_guard" };
345
332
  case "max_lines":
@@ -380,28 +367,15 @@ export function registerAgentKernelCommand(pi: ExtensionAPI, deps: AgentKernelCo
380
367
  id: "profile",
381
368
  label: "Retrieval Engine Profile",
382
369
  currentValue: currentConfig.retrieval.default_profile,
383
- values: ["lean", "hybrid", "full"],
370
+ values: ["auto", "lean", "hybrid", "full", "off"],
384
371
  isGlobal: checkIsGlobal("profile"),
385
372
  descriptions: {
373
+ auto: "Auto profile: Dynamically selects lean (VPS), hybrid (laptop), or full (desktop) based on system specs.",
386
374
  lean: "Lean profile: BM25 keyword index + AST code chunking. Zero RAM overhead, sub-millisecond retrieval, ideal for VPS and standard tasks.",
387
375
  hybrid:
388
376
  "Hybrid profile: BM25 keyword matching blended with Matryoshka sub-vector embeddings for balanced lexical and semantic retrieval.",
389
- full: "Full profile: Dense 768-dim embeddings with deep semantic chunking. Maximizes recall on complex multi-repository conceptual queries.",
390
- },
391
- },
392
- {
393
- category: "Retrieval & Exploration",
394
- id: "codebase",
395
- label: "Codebase Scale Profile",
396
- currentValue: currentConfig.retrieval.codebase_profile,
397
- values: ["auto", "light", "heavy"],
398
- isGlobal: checkIsGlobal("codebase"),
399
- descriptions: {
400
- auto: "Auto scale mode: Automatically analyzes repository file count and git metrics to dynamically size AST repo-mapping token budget.",
401
- light:
402
- "Light scale mode: Enforces minimal indexing and suppresses automatic repo-map injection for small repos and resource-tight environments.",
403
- heavy:
404
- "Heavy scale mode: Always injects full PageRank AST repository map for large multi-package enterprise codebases.",
377
+ full: "Full profile: Dense 768d embeddings + BM25 keyword index. Maximum semantic recall, ideal for large workstations.",
378
+ off: "Off profile: Retrieval subsystem disabled. Searches return empty results.",
405
379
  },
406
380
  },
407
381
 
@@ -447,9 +421,9 @@ export function registerAgentKernelCommand(pi: ExtensionAPI, deps: AgentKernelCo
447
421
  isGlobal: checkIsGlobal("editing"),
448
422
  descriptions: {
449
423
  smart_anchor:
450
- "Smart Anchors: Deterministic Tree-sitter WASM validation (<2ms), lexical delimiter balancing, and line-hint disambiguation.",
424
+ "Smart Anchors: syntax validation, lexical delimiter balancing, and line-hint disambiguation.",
451
425
  standard:
452
- "Standard editing: Standard exact string replacement without delimiter auto-healing or Tree-sitter syntax verification.",
426
+ "Standard editing: exact string replacement with delimiter auto-healing disabled; the common syntax safety gate remains enabled.",
453
427
  },
454
428
  },
455
429
  {
@@ -532,6 +506,7 @@ export function registerAgentKernelCommand(pi: ExtensionAPI, deps: AgentKernelCo
532
506
  onCancel: () => void;
533
507
  searchInput: Input;
534
508
  categoryOrder: string[];
509
+ private initialStates = new Map<string, { value: string; isGlobal: boolean }>();
535
510
 
536
511
  constructor(
537
512
  items: CategorizedSettingItem[],
@@ -545,6 +520,13 @@ export function registerAgentKernelCommand(pi: ExtensionAPI, deps: AgentKernelCo
545
520
  this.onCancel = onCancel;
546
521
  this.categoryOrder = categoryOrder;
547
522
  this.searchInput = new Input();
523
+
524
+ for (const item of items) {
525
+ this.initialStates.set(item.id, {
526
+ value: item.currentValue,
527
+ isGlobal: !!item.isGlobal,
528
+ });
529
+ }
548
530
  }
549
531
 
550
532
  applyFilter(query: string) {
@@ -581,56 +563,74 @@ export function registerAgentKernelCommand(pi: ExtensionAPI, deps: AgentKernelCo
581
563
  const curIdx = item.values.indexOf(item.currentValue);
582
564
  const nextIdx = (curIdx + 1) % item.values.length;
583
565
  item.currentValue = item.values[nextIdx];
584
-
585
- const { patch } = createPatchForSetting(item.id, item.currentValue);
586
- if (item.isGlobal) {
587
- saveGlobalKernelConfig(patch);
588
- ctx.ui?.notify?.(
589
- `Saved '${item.label}' = '${item.currentValue}' globally (~/.pi/agent/config.toml)`,
590
- "info",
591
- );
592
- } else {
593
- saveProjectKernelConfig(currentCwd, patch);
594
- ctx.ui?.notify?.(
595
- `Saved '${item.label}' = '${item.currentValue}' to project (.pi/config.toml)`,
596
- "info",
597
- );
598
- }
599
- deps.invalidateConfig(currentCwd);
600
- deps.clearCaches?.();
601
566
  }
602
567
 
603
568
  toggleGlobalSetting() {
604
569
  const item = this.filteredItems[this.selectedIndex];
605
570
  if (!item) return;
571
+ item.isGlobal = !item.isGlobal;
572
+ }
606
573
 
607
- const meta = getSettingSectionAndKey(item.id);
608
- if (!meta) return;
574
+ closeAndApply() {
575
+ let hasChanges = false;
576
+ const globalUpdates: KernelConfigOverrides = {};
577
+ const projectUpdates: KernelConfigOverrides = {};
578
+ const revertedGlobals: Array<{ section: string; key: string }> = [];
579
+ const revertedProjects: Array<{ section: string; key: string }> = [];
580
+
581
+ for (const item of this.items) {
582
+ const initial = this.initialStates.get(item.id);
583
+ if (!initial) continue;
584
+
585
+ const valueChanged = item.currentValue !== initial.value;
586
+ const scopeChanged = !!item.isGlobal !== initial.isGlobal;
587
+
588
+ if (valueChanged || scopeChanged) {
589
+ hasChanges = true;
590
+ const { patch } = createPatchForSetting(item.id, item.currentValue);
591
+
592
+ if (item.isGlobal) {
593
+ mergeDeep(globalUpdates, patch);
594
+ if (!initial.isGlobal) {
595
+ const meta = getSettingSectionAndKey(item.id);
596
+ if (meta) revertedProjects.push(meta);
597
+ }
598
+ } else {
599
+ if (initial.isGlobal) {
600
+ const meta = getSettingSectionAndKey(item.id);
601
+ if (meta) revertedGlobals.push(meta);
602
+ }
603
+ mergeDeep(projectUpdates, patch);
604
+ }
605
+ }
606
+ }
609
607
 
610
- if (item.isGlobal) {
611
- // Revert/remove single setting from global config
612
- removeGlobalKernelConfigKey(meta.section, meta.key);
613
- item.isGlobal = false;
614
- deps.invalidateConfig(currentCwd);
615
- deps.clearCaches?.();
608
+ if (hasChanges) {
609
+ try {
610
+ if (Object.keys(globalUpdates).length > 0) {
611
+ saveGlobalKernelConfig(globalUpdates);
612
+ }
613
+ if (Object.keys(projectUpdates).length > 0) {
614
+ saveProjectKernelConfig(currentCwd, projectUpdates);
615
+ }
616
+ for (const { section, key } of revertedGlobals) {
617
+ removeGlobalKernelConfigKey(section, key);
618
+ }
619
+ for (const { section, key } of revertedProjects) {
620
+ removeProjectKernelConfigKey(currentCwd, section, key);
621
+ }
616
622
 
617
- ctx.ui?.notify?.(
618
- `Reverted '${item.label}' from global (now using workspace/default)`,
619
- "info",
620
- );
621
- } else {
622
- // Apply single setting to global config
623
- const { patch } = createPatchForSetting(item.id, item.currentValue);
624
- saveGlobalKernelConfig(patch);
625
- item.isGlobal = true;
626
- deps.invalidateConfig(currentCwd);
627
- deps.clearCaches?.();
628
-
629
- ctx.ui?.notify?.(
630
- `Applied '${item.label}' = '${item.currentValue}' globally to ~/.pi/agent/config.toml`,
631
- "info",
632
- );
623
+ deps.invalidateConfig(currentCwd, ctx);
624
+ deps.clearCaches?.();
625
+ ctx.ui?.notify?.("Applied Agent Kernel configuration changes.", "info");
626
+ } catch (error) {
627
+ const message = error instanceof Error ? error.message : String(error);
628
+ ctx.ui?.notify?.(`Failed to apply Agent Kernel configuration: ${message}`, "error");
629
+ console.error(`[agent-kernel] Configuration apply failed: ${message}`);
630
+ }
633
631
  }
632
+
633
+ this.onCancel();
634
634
  }
635
635
 
636
636
  jumpCategory(forward = true) {
@@ -685,8 +685,8 @@ export function registerAgentKernelCommand(pi: ExtensionAPI, deps: AgentKernelCo
685
685
  (data === " " && this.searchInput.getValue().length === 0)
686
686
  ) {
687
687
  this.activateItem();
688
- } else if (kb.matches(data, "tui.select.cancel")) {
689
- this.onCancel();
688
+ } else if (kb.matches(data, "tui.select.cancel") || data === "q") {
689
+ this.closeAndApply();
690
690
  } else {
691
691
  this.searchInput.handleInput(data);
692
692
  this.applyFilter(this.searchInput.getValue());
@@ -764,7 +764,7 @@ export function registerAgentKernelCommand(pi: ExtensionAPI, deps: AgentKernelCo
764
764
  lines.push("");
765
765
  lines.push(
766
766
  this.theme.hint(
767
- " Type to search · Enter/Space change · G toggle global · Tab category · Esc cancel",
767
+ " Type to search · Enter/Space cycle · G toggle global · Tab category · Esc close & apply",
768
768
  ),
769
769
  );
770
770
  return lines;
@@ -5,11 +5,8 @@ import { parseToml, stringifyToml, type TomlValue } from "./toml";
5
5
  import { kernelDebug } from "../safety/kernel_debug";
6
6
  import { writeFileSyncAtomic } from "../safety/atomic_write";
7
7
 
8
- export type CodebaseProfile = "auto" | "light" | "heavy";
9
-
10
8
  export interface RetrievalConfig {
11
- default_profile: "lean" | "hybrid" | "full";
12
- codebase_profile: CodebaseProfile;
9
+ default_profile: "auto" | "lean" | "hybrid" | "full" | "off";
13
10
  repo_map_budget: number;
14
11
  repo_map_min_files: number;
15
12
  repo_map_min_bytes: number;
@@ -29,6 +26,7 @@ export interface EditingConfig {
29
26
  mode: "smart_anchor" | "standard";
30
27
  default_anchors: boolean;
31
28
  read_mode: "auto" | "plain" | "anchored";
29
+ syntax_gate?: "warn" | "block";
32
30
  }
33
31
 
34
32
  export interface KernelConfigOverrides {
@@ -69,7 +67,6 @@ export interface KernelConfig {
69
67
  const DEFAULT_CONFIG: KernelConfig = {
70
68
  retrieval: {
71
69
  default_profile: "lean",
72
- codebase_profile: "auto",
73
70
  repo_map_budget: 1024,
74
71
  repo_map_min_files: 10,
75
72
  repo_map_min_bytes: 50 * 1024,
@@ -79,7 +76,7 @@ const DEFAULT_CONFIG: KernelConfig = {
79
76
  safety: {
80
77
  enable_epistemic_guard: true,
81
78
  max_line_length: 300,
82
- max_lines: 40,
79
+ max_lines: 100,
83
80
  max_total_bytes: 20 * 1024,
84
81
  exec_timeout_ms: 5000,
85
82
  },
@@ -87,6 +84,7 @@ const DEFAULT_CONFIG: KernelConfig = {
87
84
  mode: "smart_anchor",
88
85
  default_anchors: false,
89
86
  read_mode: "plain",
87
+ syntax_gate: "warn",
90
88
  },
91
89
  lsp: {
92
90
  idle_timeout_ms: 5 * 60 * 1000, // 5 minutes
@@ -104,6 +102,138 @@ const DEFAULT_CONFIG: KernelConfig = {
104
102
  },
105
103
  };
106
104
 
105
+ export class KernelConfigError extends Error {}
106
+
107
+ const ALLOWED_CONFIG_KEYS: Record<keyof KernelConfig, ReadonlySet<string>> = {
108
+ retrieval: new Set([
109
+ "default_profile",
110
+ "repo_map_budget",
111
+ "repo_map_min_files",
112
+ "repo_map_min_bytes",
113
+ "max_search_results",
114
+ "enable_tools",
115
+ ]),
116
+ safety: new Set([
117
+ "enable_epistemic_guard",
118
+ "max_line_length",
119
+ "max_lines",
120
+ "max_total_bytes",
121
+ "exec_timeout_ms",
122
+ ]),
123
+ editing: new Set(["mode", "default_anchors", "read_mode", "syntax_gate"]),
124
+ lsp: new Set([
125
+ "idle_timeout_ms",
126
+ "diagnostic_timeout_ms",
127
+ "init_timeout_ms",
128
+ "spinner_interval_ms",
129
+ "disabled_servers",
130
+ ]),
131
+ ui: new Set(["enable_pastel_footer"]),
132
+ instructions: new Set(["enabled", "pi_docs"]),
133
+ };
134
+
135
+ function configPath(parts: string[]): string {
136
+ return parts.join(".");
137
+ }
138
+
139
+ function requireBoolean(value: unknown, path: string): void {
140
+ if (typeof value !== "boolean") throw new KernelConfigError(`${path} must be a boolean`);
141
+ }
142
+
143
+ function requireSafeInt(value: unknown, path: string, min: number, max: number): void {
144
+ if (!Number.isSafeInteger(value) || (value as number) < min || (value as number) > max) {
145
+ throw new KernelConfigError(`${path} must be a safe integer between ${min} and ${max}`);
146
+ }
147
+ }
148
+
149
+ function requireEnum<T extends string>(value: unknown, path: string, values: readonly T[]): void {
150
+ if (typeof value !== "string" || !values.includes(value as T)) {
151
+ throw new KernelConfigError(`${path} must be one of: ${values.join(", ")}`);
152
+ }
153
+ }
154
+
155
+ export function validateKernelConfig(config: KernelConfig): KernelConfig {
156
+ for (const section of Object.keys(config) as Array<keyof KernelConfig>) {
157
+ const value = (config as any)[section];
158
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
159
+ throw new KernelConfigError(`${section} must be a table`);
160
+ }
161
+ for (const key of Object.keys(value)) {
162
+ if (!ALLOWED_CONFIG_KEYS[section].has(key)) {
163
+ throw new KernelConfigError(`Unknown configuration key: ${configPath([section, key])}`);
164
+ }
165
+ }
166
+ }
167
+
168
+ const retrieval = config.retrieval;
169
+ requireEnum(retrieval.default_profile, "retrieval.default_profile", ["auto", "lean", "hybrid", "full", "off"]);
170
+ requireSafeInt(retrieval.repo_map_budget, "retrieval.repo_map_budget", 64, 32_768);
171
+ requireSafeInt(retrieval.repo_map_min_files, "retrieval.repo_map_min_files", 0, 10_000);
172
+ requireSafeInt(retrieval.repo_map_min_bytes, "retrieval.repo_map_min_bytes", 0, 1024 * 1024 * 1024);
173
+ requireSafeInt(retrieval.max_search_results, "retrieval.max_search_results", 1, 15);
174
+ requireBoolean(retrieval.enable_tools, "retrieval.enable_tools");
175
+
176
+ const safety = config.safety;
177
+ requireBoolean(safety.enable_epistemic_guard, "safety.enable_epistemic_guard");
178
+ requireSafeInt(safety.max_line_length, "safety.max_line_length", 20, 10_000);
179
+ requireSafeInt(safety.max_lines, "safety.max_lines", 1, 10_000);
180
+ requireSafeInt(safety.max_total_bytes, "safety.max_total_bytes", 64, 10 * 1024 * 1024);
181
+ requireSafeInt(safety.exec_timeout_ms, "safety.exec_timeout_ms", 100, 120_000);
182
+
183
+ requireEnum(config.editing.mode, "editing.mode", ["smart_anchor", "standard"]);
184
+ requireBoolean(config.editing.default_anchors, "editing.default_anchors");
185
+ requireEnum(config.editing.read_mode, "editing.read_mode", ["auto", "plain", "anchored"]);
186
+ if (config.editing.syntax_gate !== undefined) {
187
+ requireEnum(config.editing.syntax_gate, "editing.syntax_gate", ["warn", "block"]);
188
+ }
189
+
190
+ requireSafeInt(config.lsp.idle_timeout_ms, "lsp.idle_timeout_ms", 1_000, 60 * 60 * 1_000);
191
+ requireSafeInt(config.lsp.diagnostic_timeout_ms, "lsp.diagnostic_timeout_ms", 100, 120_000);
192
+ requireSafeInt(config.lsp.init_timeout_ms, "lsp.init_timeout_ms", 100, 5 * 60 * 1_000);
193
+ requireSafeInt(config.lsp.spinner_interval_ms, "lsp.spinner_interval_ms", 16, 1_000);
194
+ if (
195
+ !Array.isArray(config.lsp.disabled_servers) ||
196
+ config.lsp.disabled_servers.length > 64 ||
197
+ config.lsp.disabled_servers.some(
198
+ (server) => typeof server !== "string" || !/^[a-z0-9._-]{1,64}$/i.test(server),
199
+ )
200
+ ) {
201
+ throw new KernelConfigError("lsp.disabled_servers must be an array of up to 64 safe server keys");
202
+ }
203
+
204
+ requireBoolean(config.ui.enable_pastel_footer, "ui.enable_pastel_footer");
205
+ requireBoolean(config.instructions.enabled, "instructions.enabled");
206
+ requireBoolean(config.instructions.pi_docs, "instructions.pi_docs");
207
+ return config;
208
+ }
209
+
210
+ export function mergeKernelConfig(target: KernelConfig, source: unknown): KernelConfig {
211
+ const candidate = structuredClone(target);
212
+ if (!source || typeof source !== "object" || Array.isArray(source)) {
213
+ throw new KernelConfigError("Configuration root must be a table");
214
+ }
215
+ for (const [section, value] of Object.entries(source as Record<string, unknown>)) {
216
+ if (!ALLOWED_CONFIG_KEYS[section as keyof KernelConfig]) {
217
+ throw new KernelConfigError(`Unknown configuration section: ${section}`);
218
+ }
219
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
220
+ throw new KernelConfigError(`${section} must be a table`);
221
+ }
222
+ for (const key of Object.keys(value as Record<string, unknown>)) {
223
+ if (!ALLOWED_CONFIG_KEYS[section as keyof KernelConfig].has(key)) {
224
+ throw new KernelConfigError(`Unknown configuration key: ${configPath([section, key])}`);
225
+ }
226
+ }
227
+ }
228
+ mergeDeep(candidate, source);
229
+ validateKernelConfig(candidate);
230
+ for (const key of Object.keys(target) as Array<keyof KernelConfig>) {
231
+ delete (target as any)[key];
232
+ }
233
+ Object.assign(target, candidate);
234
+ return target;
235
+ }
236
+
107
237
  /**
108
238
  * Resolve ~/.pi root directory
109
239
  */
@@ -133,18 +263,15 @@ export function getGlobalConfigPath(): string {
133
263
  }
134
264
 
135
265
  /**
136
- * Resolve workspace project-local configuration path (.pi/config.toml, agent-kernel/config.toml, or config.toml)
266
+ * Resolve workspace project-local configuration path (.pi/config.toml only).
267
+ * Generic root config.toml and agent-kernel/config.toml are intentionally ignored.
137
268
  */
138
269
  export function getProjectConfigPath(cwd = process.cwd()): string | null {
139
270
  let current = path.resolve(cwd);
140
271
  const root = path.parse(current).root;
141
272
 
142
273
  while (current && current !== root) {
143
- const candidates = [
144
- path.join(current, "config.toml"),
145
- path.join(current, "agent-kernel", "config.toml"),
146
- path.join(current, ".pi", "config.toml"),
147
- ];
274
+ const candidates = [path.join(current, ".pi", "config.toml")];
148
275
  for (const candidate of candidates) {
149
276
  if (fs.existsSync(candidate)) {
150
277
  return candidate;
@@ -162,7 +289,10 @@ export function getProjectConfigPath(cwd = process.cwd()): string | null {
162
289
  * Load and merge hierarchical configuration:
163
290
  * Defaults -> Global (~/.pi/agent/config.toml) -> Project (.pi/config.toml) -> Environment Variables
164
291
  */
165
- export function loadKernelConfig(cwd = process.cwd()): KernelConfig {
292
+ export function loadKernelConfig(
293
+ cwd = process.cwd(),
294
+ options: { projectTrusted?: boolean } = {},
295
+ ): KernelConfig {
166
296
  // Deep clone defaults
167
297
  const config: KernelConfig = structuredClone(DEFAULT_CONFIG);
168
298
 
@@ -172,19 +302,21 @@ export function loadKernelConfig(cwd = process.cwd()): KernelConfig {
172
302
  try {
173
303
  const raw = fs.readFileSync(globalPath, "utf-8");
174
304
  const parsed = parseToml(raw);
175
- mergeDeep(config, parsed);
305
+ mergeKernelConfig(config, parsed);
176
306
  } catch (e) {
177
307
  kernelDebug(e);
178
308
  }
179
309
  }
180
310
 
181
311
  // 2. Merge Project-Local Config if present
182
- const projectPath = getProjectConfigPath(cwd);
312
+ const projectPath = options.projectTrusted === true
313
+ ? getProjectConfigPath(cwd)
314
+ : null;
183
315
  if (projectPath && fs.existsSync(projectPath)) {
184
316
  try {
185
317
  const raw = fs.readFileSync(projectPath, "utf-8");
186
318
  const parsed = parseToml(raw);
187
- mergeDeep(config, parsed);
319
+ mergeKernelConfig(config, parsed);
188
320
  } catch (e) {
189
321
  kernelDebug(e);
190
322
  }
@@ -203,14 +335,7 @@ export function loadKernelConfig(cwd = process.cwd()): KernelConfig {
203
335
  }
204
336
  }
205
337
 
206
- if (process.env.PI_CODEBASE_PROFILE) {
207
- const cp = process.env.PI_CODEBASE_PROFILE.toLowerCase();
208
- if (cp === "auto" || cp === "smart" || cp === "light" || cp === "heavy") {
209
- config.retrieval.codebase_profile = (cp === "smart" ? "auto" : cp) as CodebaseProfile;
210
- }
211
- }
212
-
213
- return config;
338
+ return validateKernelConfig(config);
214
339
  }
215
340
 
216
341
  /**
@@ -223,15 +348,11 @@ export function saveGlobalKernelConfig(updates: KernelConfigOverrides): void {
223
348
  fs.mkdirSync(parentDir, { recursive: true });
224
349
  }
225
350
 
226
- let existing: Record<string, TomlValue> = {};
227
- if (fs.existsSync(globalPath)) {
228
- try {
229
- existing = parseToml(fs.readFileSync(globalPath, "utf-8"));
230
- } catch (e) {
231
- kernelDebug(e);
232
- }
233
- }
234
-
351
+ const existing: Record<string, TomlValue> = fs.existsSync(globalPath)
352
+ ? parseToml(fs.readFileSync(globalPath, "utf-8"))
353
+ : {};
354
+ validateConfigDocument(existing);
355
+ validateConfigDocument({ ...existing, ...updates });
235
356
  mergeDeep(existing, updates);
236
357
  const tomlString = stringifyToml(existing);
237
358
  writeFileSyncAtomic(globalPath, tomlString);
@@ -251,6 +372,7 @@ export function removeGlobalKernelConfigKey(section: string, key: string): void
251
372
  if (Object.keys(existing[section]).length === 0) {
252
373
  delete existing[section];
253
374
  }
375
+ validateConfigDocument(existing);
254
376
  const tomlString = stringifyToml(existing);
255
377
  writeFileSyncAtomic(globalPath, tomlString);
256
378
  }
@@ -283,6 +405,18 @@ export function getTargetProjectConfigPath(cwd = process.cwd()): string {
283
405
  return path.join(path.resolve(cwd), ".pi", "config.toml");
284
406
  }
285
407
 
408
+ export function removeProjectKernelConfigKey(cwd: string, section: string, key: string): void {
409
+ const projectPath = getTargetProjectConfigPath(cwd);
410
+ if (!fs.existsSync(projectPath)) return;
411
+ const existing = parseToml(fs.readFileSync(projectPath, "utf-8"));
412
+ const table = existing[section];
413
+ if (!table || typeof table !== "object" || Array.isArray(table) || !(key in table)) return;
414
+ delete (table as Record<string, TomlValue>)[key];
415
+ if (Object.keys(table).length === 0) delete existing[section];
416
+ validateConfigDocument(existing);
417
+ writeFileSyncAtomic(projectPath, stringifyToml(existing));
418
+ }
419
+
286
420
  /**
287
421
  * Save user overrides to project-local configuration file (.pi/config.toml)
288
422
  */
@@ -293,24 +427,26 @@ export function saveProjectKernelConfig(cwd: string, updates: KernelConfigOverri
293
427
  fs.mkdirSync(parentDir, { recursive: true });
294
428
  }
295
429
 
296
- let existing: Record<string, TomlValue> = {};
297
- if (fs.existsSync(projectPath)) {
298
- try {
299
- existing = parseToml(fs.readFileSync(projectPath, "utf-8"));
300
- } catch (e) {
301
- kernelDebug(e);
302
- }
303
- }
304
-
430
+ const existing: Record<string, TomlValue> = fs.existsSync(projectPath)
431
+ ? parseToml(fs.readFileSync(projectPath, "utf-8"))
432
+ : {};
433
+ validateConfigDocument(existing);
434
+ validateConfigDocument({ ...existing, ...updates });
305
435
  mergeDeep(existing, updates);
306
436
  const tomlString = stringifyToml(existing);
307
437
  writeFileSyncAtomic(projectPath, tomlString);
308
438
  return projectPath;
309
439
  }
310
440
 
311
- function mergeDeep(target: any, source: any) {
441
+ export function validateConfigDocument(source: unknown): KernelConfig {
442
+ return mergeKernelConfig(structuredClone(DEFAULT_CONFIG), source);
443
+ }
444
+
445
+ export function mergeDeep(target: any, source: any) {
312
446
  if (!source || typeof source !== "object") return;
313
447
  for (const key of Object.keys(source)) {
448
+ if (key === "__proto__" || key === "prototype" || key === "constructor") continue;
449
+ if (!Object.prototype.hasOwnProperty.call(source, key)) continue;
314
450
  const sVal = source[key];
315
451
  if (sVal && typeof sVal === "object" && !Array.isArray(sVal)) {
316
452
  if (!target[key] || typeof target[key] !== "object") {