@floydous/pi-agent-kernel 0.3.31 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,44 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.4.0] - 2026-09-23
4
+
5
+ ### Added
6
+ - **.gitignore-Aware Workspace Traversal**: Added unified workspace walker (`src/retrieval/workspace_walker.ts`) shared across `search_chunker`, `repomap`, and `ast_search`. Evaluates hierarchical `.gitignore` files leaf-to-root with directory pruning (`dir/`), wildcard descent (`dir/*`), child negation overrides (`!keep.ts`), and additive `.piignore` support.
7
+ - **Transactional Incremental Vector Updates**: Added `updateFile()` to `HybridSearchIndex` to re-chunk only modified files on mutation and reuse cached 768d vectors by content hash across line shifts and untouched functions.
8
+ - **Generational Protection & Query-Time Freshness**: Protected in-flight file updates with generation counters to cancel superseded jobs, and made `search()` await active updates for strict snapshot freshness.
9
+ - **Debounced Disk Persistence**: Implemented `scheduleDebouncedSave()` and `flushPendingSave()` to coalesce rapid sequential mutations into debounced atomic writes and guarantee persistence on session shutdown.
10
+ - **Direct Ignore Dependency**: Added `"ignore": "^7.0.5"` as an explicit dependency for standards-compliant pattern matching.
11
+ - **Reference Configuration Template**: Added `config.example.toml` as a clean, documented template for project (`.pi/config.toml`) and global (`~/.pi/agent/config.toml`) settings.
12
+ - **Test Suites**: Added comprehensive regression suites for security hardening (`tests/security-hardening/`), Windows deep verification (`tests/windows-deep-verification.ts`), incremental updates (`tests/retrieval/incremental_update.test.ts`), and gitignore traversal parity (`tests/retrieval/gitignore_traversal.test.ts`).
13
+
14
+ ### Changed
15
+ - **Profile Scope Expansion**: Fully aligned configuration types, TUI selectors, and CLI subcommands to support `auto` (adaptive VPS/desktop profile) and `off` (completely disabled retrieval) alongside `lean`, `hybrid`, and `full`.
16
+ - **Decoupled Snapshot Invalidation**: Ignore configuration hashes (`.gitignore`, `.piignore`) are tracked in dedicated snapshot metadata (`ignoreConfigHashes`) rather than indexed code file tables, automatically purging newly-ignored files on the next search without reporting phantom files.
17
+ - **Live Retrieval Configuration Sync**: Unified `/engine`, `SearchControlModal`, and `/agent-kernel` commands to reconfigure running `HybridSearchIndex` instances and refresh statusline/footer badges immediately upon profile change without requiring session reloads.
18
+ - **Hierarchical Config Scoping**: Enforced strict configuration isolation where project-level changes write strictly to local `.pi/config.toml`, following the hierarchy: Project TOML > Global TOML > Legacy JSON > Lean defaults.
19
+ - **Index Mutation Purity**: Removed silent disk-write side effects from `HybridSearchIndex.setProfile()`.
20
+
21
+ ### Fixed
22
+ - **Retrieval Index Pollution**: Search chunking respects `.gitignore` rules and hard exclusions (`agent-kernel-benchmark/cache/`, `.git/`, `node_modules/`), preventing third-party benchmark fixtures from polluting workspace search indexes.
23
+ - **Symlink & Path Containment**: Traversal skips symbolic links and confirms canonical paths remain bounded inside the workspace root.
24
+ - **Windows Path & Line Ending Resilience**: Preserved CRLF line endings during smart anchor edits and syntax verification without introducing mixed newlines. Normalized relative display paths to POSIX forward slashes in `read`, `edit`, and LSP formatters.
25
+ - **NTFS Case-Insensitive Collisions**: Prevented duplicate target path collisions in multi-file edits on case-insensitive filesystems. Handled case-insensitive path comparisons in LSP references and AST symbol search.
26
+ - **PowerShell Clamping & Windows Executables**: Intercepted and clamped `powershell` tool output in `tool_result` hooks alongside `bash`, and recognized `.cmd`, `.bat`, and `.exe` extensions in epistemic guard inspection.
27
+ - **LSP Installer Discovery**: Required confirmed executable presence on disk before reporting successful LSP server installation.
28
+ - **Config Tracking Removal**: Untracked root `config.toml` from Git and removed it from package distribution. Default configurations run purely in-memory, while user overrides persist cleanly to `.pi/config.toml` (workspace, gitignored) or `~/.pi/agent/config.toml` (global).
29
+ - **Deferred Settings Application in `/agent-kernel` TUI**: Cycling through setting options (e.g. `lean` -> `hybrid` -> `full`) no longer writes intermediate states to disk or triggers intermediate re-indexing runs. Changes are buffered in-memory and applied in a single atomic batch only when the user closes the modal (`Esc` / `q`).
30
+ - **In-Flight Re-indexing Cancellation on Profile Switch**: Fixed a race condition where switching retrieval profiles while background indexing was active (e.g. `hybrid` -> `full`) continued running the superseded profile's embedding loop and overwrote the statusline with the old profile tag. In-flight sync jobs are now cleanly aborted via generation tokens and abort controllers, and the statusline immediately tracks the newly active profile.
31
+
32
+ ### Security
33
+ - **TOML Prototype Pollution Hardening**: Hardened `parseToml` and `mergeDeep` using null-prototype dictionaries and explicit rejection of dangerous keys (`__proto__`, `constructor`, `prototype`).
34
+ - **Safe Executable Discovery**: Replaced shell-spawning executable resolution with direct filesystem PATH/PATHEXT scanning and `execFileSync`.
35
+ - **LSP Stdio Framing Guard**: Enforced strict `Content-Length` boundary checks, exact decimal matching, and stream resynchronization recovery against malformed headers and buffer overflows.
36
+ - **Bounded Session Repair**: Added bounded session repair log scanning with atomic writes and filtered out symlinks during temporary spillover log cleanup in `/tmp`.
37
+
38
+ ### Removed
39
+ - **Legacy `/profile` Command & `codebase_profile`**: Completely removed the redundant `/profile` slash command (`auto`, `light`, `heavy`, `status`), `codebaseProfileBySession` tracking map, and unused repo-map scale injection code in `before_agent_start`.
40
+ - **Codebase Scale Settings**: Removed `codebase_profile` from `RetrievalConfig`, TOML defaults, environment variables (`PI_CODEBASE_PROFILE`), `/agent-kernel` CLI (`set codebase`), and the TUI settings modal. Code retrieval configuration is now unified exclusively under `/engine` and `/agent-kernel`.
41
+
3
42
  ## [0.3.31] - 2026-09-22
4
43
 
5
44
  ### Added
@@ -8,3 +47,54 @@
8
47
 
9
48
  ### Changed
10
49
  - Removed repository-level `AGENTS.md` from git tracking.
50
+
51
+ ## [0.3.3] - 2026-09-20
52
+
53
+ ### Added
54
+ - **Multi-File Atomic Edits**: Extended the `edit` tool with `files: { path, search, replace, line_hint, edits }[]` payload (with resilient per-item `path` normalization in `edits`). Implemented a 2-stage atomic commit with preflight validation, duplicate path detection, in-memory snapshot backups, and automatic rollback across all targets if any file fails patch application or syntax verification.
55
+ - **Batch Multi-File `read`**: Extended the `read` tool to accept `paths: string[]` (and resilient alias `path: string[]`), allowing the model to inspect multiple files in one turn while authorizing all targets in `EpistemicGuard`.
56
+ - **Automatic Turn 1 Reproduction Diff Grounding**: In `before_agent_start`, automatically detects unstaged/staged git diffs and injects a sanitized, clamped (max 25 lines, 2KB hard ceiling) reproduction status into initial context with session caching, eliminating redundant Turn 1 exploratory `git status` / `git diff` commands.
57
+
58
+ ### Changed
59
+ - **Read Tool Budgeting & Anchor Guardrails**: Bounded batch reading to 150 lines per file and a 24KB aggregate ceiling with explicit continuation markers (`[truncated: <file>, returned lines 1-150 of <N>. Continue with read(path, offset=151)]`). Added a 100-line cap on explicit `anchors: true` requests (`MAX_ANCHOR_LINES = 100`) to prevent models from generating expensive `#HASH│` line hashes on large files.
60
+ - **Targeted Reading Workflow Guidance**: Updated `AGENT_KERNEL_SYS_PROMPT.md` to emphasize targeted sequential reads (`read(path, offset, limit)`) centered on search coordinates as the primary inspection workflow, reserving batch `paths` for short files or known regions.
61
+ - **Search Specificity Guidance**: Directed agents toward exact identifiers, error symbols, and test phrases, preventing noisy broad single-word searches from polluting conversation context.
62
+
63
+ ### Validated
64
+ - Verified 38 test suites passing (`npm test`) with 0 regressions.
65
+ - Multi-harness benchmarks on `cx/gpt-5.6-luna:high` across all 8 standard tasks demonstrate:
66
+ - **100% Solve Rate (8 / 8 tasks solved)**.
67
+ - **Aggregate task time cut in half**: **600s (10.0m) vs 1,223s (20.4m)** (-50.9% time reduction, **2.04× faster**).
68
+ - **Uncached input tokens reduced by -18.4%**: **270k vs 331k** (-60.8k tokens saved across the suite).
69
+ - **Tool calls reduced**: **107 calls vs 112 calls**.
70
+ - Consistent speedup across all repositories: UFO (36s vs 119s), Fastify (47s vs 177s), p-limit (60s vs 176s), Ky (89s vs 253s), Zod (135s vs 212s), Hono (64s vs 96s), UUID (53s vs 64s), and Picomatch (116s vs 126s).
71
+
72
+ ## [0.3.2] - 2026-09-16
73
+
74
+ ### Added
75
+ - **Statusline Retrieval Indicator & Extension Row Integration**: Relocated the retrieval profile tag from Line 1 to Line 2 (extension statusline via `ctx.ui.setStatus("retrieval", ...)`) alongside external extensions (such as Ponytail), preserving individual extension ANSI colors.
76
+ - **Profile Semantic Glyphs**: Added distinct visual tier glyphs: `🌿 retrieval:bm25` (AST lexical), `◈ retrieval:hybrid-256d` (Matryoshka hybrid), and `🧠 retrieval:dense-768d` (Full semantic).
77
+ - **Live Embedding Throughput & Stream Arrow Status**: Added real-time chunk processing throughput (`chunk/s`) with a static Stream Arrow indicator during workspace indexing (`🧠 retrieval:dense-768d ⇢ 45% (22/48 • 14.2 chunk/s)`).
78
+ - **Automatic Kernel Guidance Injection**: Bundled `AGENT_KERNEL_SYS_PROMPT.md` is injected through Pi's `before_agent_start` lifecycle hook, enabled by default and configurable with `[instructions] enabled = false`.
79
+ - **Benchmark Comparison Chart**: Added the latest aggregate harness comparison graphic at `static/benchmark-comparison.png` for display in the project README.
80
+ - **Six-Harness Cross-Agent Benchmark**: Integrated comprehensive multi-harness comparison runner supporting Pi Kernel, Pi Vanilla, Claude Code, Codex CLI, OMP, and OpenCode across 8 real-world tasks.
81
+ - **Passive Shield Architecture**: Gated exploratory tools (`ast_search`, `get_repo_map`, `lsp`) behind `enable_tools: false` / `PI_ENABLE_ALL_RETRIEVAL_TOOLS=1`, keeping the active tool interface lean (`read`, `edit`, `write`, `bash`, and compact `code_search`) to eliminate per-turn schema overhead and tool distraction loops.
82
+ - **Deterministic Delimiter Auto-Healing**: Added patch-scoped lexical delimiter balancing and Tree-sitter AST repair (`MISSING` node detection) to automatically recover truncated closing braces/brackets (`})`, `};`, `]}`) pre-write.
83
+ - **Line-Hinted Range Disambiguation & Multi-Block Line Deltas**: Added optional `line_hint`, `start_line`, and `end_line` parameters (supporting both camelCase and snake_case) to `edit` with sequential delta tracking to disambiguate identical search blocks without line-hash bloat.
84
+ - **Capped Plain-Text Reads**: Enforced 50KB / 2,000-line caps on broad reads with continuation hints (`offset`) and oversized line detection, recording precise exposure ranges in `EpistemicGuard`.
85
+ - **Model Property Aliasing & Epistemic Confirmation**: Supported model convention drift across parameter names (`search`/`replace`, `old`/`new`, `old_text`/`new_text`) and emitted concise positive confirmation strings (`Successfully applied edit to <file>.`) to prevent paranoid agent verification loops.
86
+
87
+ ### Changed
88
+ - Included `AGENT_KERNEL_SYS_PROMPT.md` in the published package so automatic guidance works after installation.
89
+ - Added lifecycle coverage for guidance injection, duplicate prevention, and the disabled configuration path.
90
+ - **Tool Description Optimization**: Completely redesigned tool descriptions for `read` and `edit` to explicitly declare clean plain-text defaults and precision parameter expectations, dropping 10k+ prompt inflation tokens on real benchmarks.
91
+ - **Performance**: Cut 8-task benchmark token consumption from **1,214,112 tokens down to 465,139 tokens (-61.7%)**, outperforming stock Pi Vanilla (579,088 tokens, -19.7% overall) across 8 real-world repositories.
92
+ - **Persistent Vector Profiles**: Preserved dimension-specific binary caches (`vectors-256d.bin`, `vectors-768d.bin`) on disk across profile switches, preventing cache loss when toggling to BM25.
93
+ - **On-Demand Embedder Loading**: Removed premature model preloading on startup; weights load on-demand only when unindexed chunks are detected.
94
+
95
+ ### Fixed
96
+ - **Startup Background Indexing Visibility**: Fixed a bug where workspace indexing on `session_start` ran silently in the background without updating the UI statusline on cold or unindexed workspaces.
97
+ - **Companion Symbol Token Inflation**: Deduplicated companion symbols and clamped surrounding context lines during targeted symbol reads to eliminate token bloat.
98
+
99
+ ### Removed
100
+ - Removed the obsolete `AGENT_KERNEL_PROPMPTS.md` prompt document.
@@ -1,10 +1,15 @@
1
- # Agent Kernel Project Configuration
2
- # Location: agent-kernel/config.toml
1
+ # Agent Kernel - Configuration Example
2
+ # Copy to `.pi/config.toml` (workspace) or `~/.pi/agent/config.toml` (global).
3
+ # All fields are optional; defaults apply when omitted.
3
4
 
4
5
  [retrieval]
6
+ # "auto" (VPS=lean, laptop=hybrid, desktop=full), "lean" (BM25 only),
7
+ # "hybrid" (BM25 + 256d vectors), "full" (768d dense vectors), or "off"
5
8
  default_profile = "lean"
6
9
  repo_map_budget = 1024
7
10
  max_search_results = 5
11
+ # true exposes ast_search, get_repo_map, and lsp tools directly to the model
12
+ enable_tools = false
8
13
 
9
14
  [safety]
10
15
  enable_epistemic_guard = true
@@ -4,17 +4,25 @@ The configuration loader applies values in this order:
4
4
 
5
5
  1. Built-in defaults.
6
6
  2. Global configuration: `~/.pi/agent/config.toml` (or the configured Pi home).
7
- 3. Project configuration: the nearest `config.toml`, `agent-kernel/config.toml`,
8
- or `.pi/config.toml` while walking upward from the workspace.
7
+ 3. Project configuration: the nearest `.pi/config.toml`, `config.toml`,
8
+ or `agent-kernel/config.toml` while walking upward from the workspace.
9
9
  4. Environment-variable overrides supported by the loader.
10
10
 
11
11
  The repository-root `config.toml` is ignored so local settings are not committed.
12
+ See `config.example.toml` in the repository root for a documented configuration template.
13
+
14
+ ## Managing Settings
15
+
16
+ Settings can be managed via the `/agent-kernel` interactive modal or CLI subcommands:
17
+ - `/agent-kernel` opens an interactive TUI to view and toggle settings across project and global scopes.
18
+ - Modifications made in the modal are buffered in-memory while navigating and applied in a single atomic batch on modal close (`Esc` / `q`), preventing intermediate re-indexing runs.
19
+ - CLI subcommands: `/agent-kernel status`, `/agent-kernel set <key> <val> [--global]`, `/agent-kernel reset [--global]`.
12
20
 
13
21
  ## Main sections
14
22
 
15
23
  ### `[retrieval]`
16
24
 
17
- - `default_profile`: `lean`, `hybrid`, or `full`.
25
+ - `default_profile`: `auto`, `lean`, `hybrid`, `full`, or `off`.
18
26
  - `repo_map_budget`: token budget for the repository map.
19
27
  - `max_search_results`: result limit for code search.
20
28
 
package/docs/retrieval.md CHANGED
@@ -5,13 +5,14 @@ fast discovery does not require loading the local embedding model.
5
5
 
6
6
  ## Components
7
7
 
8
+ - `workspace_walker.ts` provides unified, `.gitignore`- and `.piignore`-aware filesystem traversal shared across indexing, repository maps, and AST search with directory pruning and child negation.
8
9
  - `repomap.ts` extracts AST symbols and produces a ranked repository map.
9
10
  - `ast_search.ts` provides structural symbol search and language-aware fallback
10
11
  operations such as document symbols, references, and local hover details.
11
12
  - `search_chunker.ts` creates syntax-aware chunks with breadcrumbs.
12
13
  - `search_bm25.ts` provides the fast lexical search path.
13
14
  - `search_embedder.ts` provides optional local embeddings.
14
- - `search_index.ts` coordinates indexing, profiles, and fallback behavior.
15
+ - `search_index.ts` coordinates indexing, incremental file updates, profiles, and fallback behavior.
15
16
  - `search_modal.ts` exposes profile controls in the Pi UI.
16
17
 
17
18
  ## Profiles
@@ -40,3 +41,16 @@ The default remains 60.
40
41
  Vector caches are accepted only when their metadata, chunk IDs, dimensions, byte
41
42
  length, and content hash agree; invalid vector data is ignored while the BM25
42
43
  index remains usable.
44
+
45
+ ## Workspace Traversal & Ignore Rules
46
+
47
+ Traversal walks workspace directories hierarchically using `workspace_walker.ts`:
48
+ - `.gitignore` and `.piignore` rules are evaluated with standard precedence, including directory pruning (`dir/`), wildcard descent (`dir/*`), and child negations (`!keep.ts`).
49
+ - Traversal strictly rejects symlinks and escapes outside workspace boundaries.
50
+ - Ignore configurations are tracked in dedicated snapshot metadata (`ignoreConfigHashes`). Modifying ignore files evicts newly ignored source chunks on the next query without counting phantom files.
51
+
52
+ ## Incremental Updates & Profile Switching
53
+
54
+ - **Incremental File Updates (`updateFile`)**: When a file is modified, only that file's AST chunks are re-parsed. Unchanged chunks reuse existing dense vectors by content hash across line shifts, avoiding full-repository re-embeddings.
55
+ - **In-Flight Cancellation**: Switching retrieval profiles (e.g. `hybrid` -> `full`) while background indexing is running immediately aborts in-flight embedding jobs via generation counters and `AbortController`. Stale vectors are rejected post-await, and the statusline switches directly to tracking the new profile.
56
+ - **Debounced Persistence**: Sequential mutations are coalesced into debounced atomic writes (`scheduleDebouncedSave`) and flushed cleanly on session shutdown (`flushPendingSave`).
package/docs/testing.md CHANGED
@@ -6,11 +6,13 @@ independently runnable and uses isolated temporary workspaces where needed.
6
6
  ## Commands
7
7
 
8
8
  ```sh
9
- # Full suite
10
- npm test
9
+ # Full verification
10
+ npm run typecheck && npm test
11
11
 
12
12
  # One focused section
13
- npx tsx tests/epistemic-guard/index.ts
13
+ npx tsx tests/retrieval/incremental_update.test.ts
14
+ npx tsx tests/retrieval/gitignore_traversal.test.ts
15
+ npx tsx tests/security-hardening/index.ts
14
16
  ```
15
17
 
16
18
  `npm test` runs the suite orchestrator under `tests/`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@floydous/pi-agent-kernel",
3
- "version": "0.3.31",
3
+ "version": "0.4.0",
4
4
  "description": "Focused code retrieval, editing, safety checks, and language-server support for Pi.",
5
5
  "keywords": [
6
6
  "pi-package"
@@ -18,6 +18,7 @@
18
18
  "dependencies": {
19
19
  "@huggingface/transformers": "^4.2.0",
20
20
  "diff": "^9.0.0",
21
+ "ignore": "^7.0.5",
21
22
  "typebox": "^1.3.16",
22
23
  "web-tree-sitter": "^0.26.12"
23
24
  },
@@ -45,7 +46,7 @@
45
46
  "README.md",
46
47
  "docs",
47
48
  "LICENSE",
48
- "config.toml",
49
+ "config.example.toml",
49
50
  "AGENT_KERNEL_SYS_PROMPT.md",
50
51
  "CHANGELOG.md"
51
52
  ],
@@ -17,17 +17,18 @@ import {
17
17
  saveGlobalKernelConfig,
18
18
  removeGlobalKernelConfigKey,
19
19
  saveProjectKernelConfig,
20
+ mergeDeep,
20
21
  getGlobalConfigPath,
21
22
  getGlobalRawConfig,
22
23
  getProjectConfigPath,
23
24
  type KernelConfig,
24
25
  type KernelConfigOverrides,
25
- type CodebaseProfile,
26
26
  } from "./kernel_config";
27
+ import { kernelDebug } from "../safety/kernel_debug";
27
28
 
28
29
  export interface AgentKernelCommandDeps {
29
30
  getConfig: (cwd: string) => KernelConfig;
30
- invalidateConfig: (cwd: string) => void;
31
+ invalidateConfig: (cwd: string, ctx?: any) => void;
31
32
  clearCaches?: () => void;
32
33
  }
33
34
 
@@ -43,8 +44,7 @@ export function formatConfigDashboard(cwd: string, config: KernelConfig): string
43
44
  `Project Config: ${projectPath ?? "none"} [${projectExists ? "ACTIVE" : "NONE"}]`,
44
45
  ``,
45
46
  `[Retrieval & Tools]`,
46
- ` • Profile (Engine) : ${config.retrieval.default_profile} (lean | hybrid | full)`,
47
- ` • Codebase Scale : ${config.retrieval.codebase_profile} (auto | light | heavy)`,
47
+ ` • Profile (Engine) : ${config.retrieval.default_profile} (auto | lean | hybrid | full | off)`,
48
48
  ` • Passive Shield : ${config.retrieval.enable_tools ? "all (6 tools exposed)" : "gated (core 3 tools default)"}`,
49
49
  ` • Repo Map Budget : ${config.retrieval.repo_map_budget} tokens`,
50
50
  ` • Max Search Results : ${config.retrieval.max_search_results}`,
@@ -85,8 +85,7 @@ export function registerAgentKernelCommand(pi: ExtensionAPI, deps: AgentKernelCo
85
85
 
86
86
  const keys = [
87
87
  { 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" },
88
+ { value: "set profile", label: "set profile <auto|lean|hybrid|full|off> - Retrieval engine profile" },
90
89
  { value: "set epistemic", label: "set epistemic <on|off> - Toggle Epistemic Guard" },
91
90
  { value: "set editing", label: "set editing <smart_anchor|standard> - Editing engine mode" },
92
91
  { value: "set read_mode", label: "set read_mode <plain|anchored|auto> - Reading anchor mode" },
@@ -121,7 +120,11 @@ export function registerAgentKernelCommand(pi: ExtensionAPI, deps: AgentKernelCo
121
120
  if (fs.existsSync(globalPath)) {
122
121
  fs.unlinkSync(globalPath);
123
122
  }
124
- deps.invalidateConfig(currentCwd);
123
+ const legacySettings = path.join(path.dirname(globalPath), "search_settings.json");
124
+ if (fs.existsSync(legacySettings)) {
125
+ try { fs.unlinkSync(legacySettings); } catch {}
126
+ }
127
+ deps.invalidateConfig(currentCwd, ctx);
125
128
  deps.clearCaches?.();
126
129
  const msg = "Reset global Agent Kernel configuration to defaults.";
127
130
  ctx.ui?.notify?.(msg, "info");
@@ -145,27 +148,16 @@ export function registerAgentKernelCommand(pi: ExtensionAPI, deps: AgentKernelCo
145
148
  case "passive_shield": {
146
149
  const enable = val === "all" || val === "true" || val === "1";
147
150
  updates.retrieval = { enable_tools: enable };
148
- desc = `Passive Shield tools set to '${enable ? "all (6 tools)" : "gated (core 3 tools)"}'`;
151
+ desc = `Passive Shield tools set to '${enable ? "all (6 tools)" : "gated (core 3 tools)"}' (takes effect on reload)`;
149
152
  break;
150
153
  }
151
154
  case "profile":
152
155
  case "engine": {
153
- if (val === "lean" || val === "hybrid" || val === "full") {
156
+ if (val === "auto" || val === "lean" || val === "hybrid" || val === "full" || val === "off") {
154
157
  updates.retrieval = { default_profile: val };
155
158
  desc = `Retrieval profile set to '${val}'`;
156
159
  } 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");
160
+ ctx.ui?.notify?.("Invalid profile. Options: auto | lean | hybrid | full | off", "error");
169
161
  return;
170
162
  }
171
163
  break;
@@ -237,7 +229,7 @@ export function registerAgentKernelCommand(pi: ExtensionAPI, deps: AgentKernelCo
237
229
  }
238
230
 
239
231
  saveGlobalKernelConfig(updates);
240
- deps.invalidateConfig(currentCwd);
232
+ deps.invalidateConfig(currentCwd, ctx);
241
233
  deps.clearCaches?.();
242
234
  ctx.ui?.notify?.(`Saved to ~/.pi/agent/config.toml: ${desc}`, "info");
243
235
  console.log(`[agent-kernel] ${desc} (persisted globally)`);
@@ -276,7 +268,6 @@ export function registerAgentKernelCommand(pi: ExtensionAPI, deps: AgentKernelCo
276
268
  function checkIsGlobal(id: string): boolean {
277
269
  if (id === "tools") return globalRaw.retrieval?.enable_tools !== undefined;
278
270
  if (id === "profile") return globalRaw.retrieval?.default_profile !== undefined;
279
- if (id === "codebase") return globalRaw.retrieval?.codebase_profile !== undefined;
280
271
  if (id === "epistemic") return globalRaw.safety?.enable_epistemic_guard !== undefined;
281
272
  if (id === "max_lines") return globalRaw.safety?.max_lines !== undefined;
282
273
  if (id === "editing") return globalRaw.editing?.mode !== undefined;
@@ -297,9 +288,6 @@ export function registerAgentKernelCommand(pi: ExtensionAPI, deps: AgentKernelCo
297
288
  } else if (id === "profile") {
298
289
  patch.retrieval = { default_profile: value as any };
299
290
  desc = `Retrieval profile = ${value}`;
300
- } else if (id === "codebase") {
301
- patch.retrieval = { codebase_profile: value as any };
302
- desc = `Codebase scale profile = ${value}`;
303
291
  } else if (id === "epistemic") {
304
292
  const enable = value === "enabled";
305
293
  patch.safety = { enable_epistemic_guard: enable };
@@ -338,8 +326,6 @@ export function registerAgentKernelCommand(pi: ExtensionAPI, deps: AgentKernelCo
338
326
  return { section: "retrieval", key: "enable_tools" };
339
327
  case "profile":
340
328
  return { section: "retrieval", key: "default_profile" };
341
- case "codebase":
342
- return { section: "retrieval", key: "codebase_profile" };
343
329
  case "epistemic":
344
330
  return { section: "safety", key: "enable_epistemic_guard" };
345
331
  case "max_lines":
@@ -380,28 +366,15 @@ export function registerAgentKernelCommand(pi: ExtensionAPI, deps: AgentKernelCo
380
366
  id: "profile",
381
367
  label: "Retrieval Engine Profile",
382
368
  currentValue: currentConfig.retrieval.default_profile,
383
- values: ["lean", "hybrid", "full"],
369
+ values: ["auto", "lean", "hybrid", "full", "off"],
384
370
  isGlobal: checkIsGlobal("profile"),
385
371
  descriptions: {
372
+ auto: "Auto profile: Dynamically selects lean (VPS), hybrid (laptop), or full (desktop) based on system specs.",
386
373
  lean: "Lean profile: BM25 keyword index + AST code chunking. Zero RAM overhead, sub-millisecond retrieval, ideal for VPS and standard tasks.",
387
374
  hybrid:
388
375
  "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.",
376
+ full: "Full profile: Dense 768d embeddings + BM25 keyword index. Maximum semantic recall, ideal for large workstations.",
377
+ off: "Off profile: Retrieval subsystem disabled. Searches return empty results.",
405
378
  },
406
379
  },
407
380
 
@@ -532,6 +505,7 @@ export function registerAgentKernelCommand(pi: ExtensionAPI, deps: AgentKernelCo
532
505
  onCancel: () => void;
533
506
  searchInput: Input;
534
507
  categoryOrder: string[];
508
+ private initialStates = new Map<string, { value: string; isGlobal: boolean }>();
535
509
 
536
510
  constructor(
537
511
  items: CategorizedSettingItem[],
@@ -545,6 +519,13 @@ export function registerAgentKernelCommand(pi: ExtensionAPI, deps: AgentKernelCo
545
519
  this.onCancel = onCancel;
546
520
  this.categoryOrder = categoryOrder;
547
521
  this.searchInput = new Input();
522
+
523
+ for (const item of items) {
524
+ this.initialStates.set(item.id, {
525
+ value: item.currentValue,
526
+ isGlobal: !!item.isGlobal,
527
+ });
528
+ }
548
529
  }
549
530
 
550
531
  applyFilter(query: string) {
@@ -581,56 +562,60 @@ export function registerAgentKernelCommand(pi: ExtensionAPI, deps: AgentKernelCo
581
562
  const curIdx = item.values.indexOf(item.currentValue);
582
563
  const nextIdx = (curIdx + 1) % item.values.length;
583
564
  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
565
  }
602
566
 
603
567
  toggleGlobalSetting() {
604
568
  const item = this.filteredItems[this.selectedIndex];
605
569
  if (!item) return;
570
+ item.isGlobal = !item.isGlobal;
571
+ }
606
572
 
607
- const meta = getSettingSectionAndKey(item.id);
608
- if (!meta) return;
573
+ closeAndApply() {
574
+ let hasChanges = false;
575
+ const globalUpdates: KernelConfigOverrides = {};
576
+ const projectUpdates: KernelConfigOverrides = {};
577
+ const revertedGlobals: Array<{ section: string; key: string }> = [];
578
+
579
+ for (const item of this.items) {
580
+ const initial = this.initialStates.get(item.id);
581
+ if (!initial) continue;
582
+
583
+ const valueChanged = item.currentValue !== initial.value;
584
+ const scopeChanged = !!item.isGlobal !== initial.isGlobal;
585
+
586
+ if (valueChanged || scopeChanged) {
587
+ hasChanges = true;
588
+ const { patch } = createPatchForSetting(item.id, item.currentValue);
589
+
590
+ if (item.isGlobal) {
591
+ mergeDeep(globalUpdates, patch);
592
+ } else {
593
+ if (initial.isGlobal) {
594
+ const meta = getSettingSectionAndKey(item.id);
595
+ if (meta) revertedGlobals.push(meta);
596
+ }
597
+ mergeDeep(projectUpdates, patch);
598
+ }
599
+ }
600
+ }
609
601
 
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?.();
602
+ if (hasChanges) {
603
+ for (const { section, key } of revertedGlobals) {
604
+ removeGlobalKernelConfigKey(section, key);
605
+ }
606
+ if (Object.keys(globalUpdates).length > 0) {
607
+ saveGlobalKernelConfig(globalUpdates);
608
+ }
609
+ if (Object.keys(projectUpdates).length > 0) {
610
+ saveProjectKernelConfig(currentCwd, projectUpdates);
611
+ }
616
612
 
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);
613
+ deps.invalidateConfig(currentCwd, ctx);
627
614
  deps.clearCaches?.();
628
-
629
- ctx.ui?.notify?.(
630
- `Applied '${item.label}' = '${item.currentValue}' globally to ~/.pi/agent/config.toml`,
631
- "info",
632
- );
615
+ ctx.ui?.notify?.("Applied Agent Kernel configuration changes.", "info");
633
616
  }
617
+
618
+ this.onCancel();
634
619
  }
635
620
 
636
621
  jumpCategory(forward = true) {
@@ -685,8 +670,8 @@ export function registerAgentKernelCommand(pi: ExtensionAPI, deps: AgentKernelCo
685
670
  (data === " " && this.searchInput.getValue().length === 0)
686
671
  ) {
687
672
  this.activateItem();
688
- } else if (kb.matches(data, "tui.select.cancel")) {
689
- this.onCancel();
673
+ } else if (kb.matches(data, "tui.select.cancel") || data === "q") {
674
+ this.closeAndApply();
690
675
  } else {
691
676
  this.searchInput.handleInput(data);
692
677
  this.applyFilter(this.searchInput.getValue());
@@ -764,7 +749,7 @@ export function registerAgentKernelCommand(pi: ExtensionAPI, deps: AgentKernelCo
764
749
  lines.push("");
765
750
  lines.push(
766
751
  this.theme.hint(
767
- " Type to search · Enter/Space change · G toggle global · Tab category · Esc cancel",
752
+ " Type to search · Enter/Space cycle · G toggle global · Tab category · Esc close & apply",
768
753
  ),
769
754
  );
770
755
  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;
@@ -69,7 +66,6 @@ export interface KernelConfig {
69
66
  const DEFAULT_CONFIG: KernelConfig = {
70
67
  retrieval: {
71
68
  default_profile: "lean",
72
- codebase_profile: "auto",
73
69
  repo_map_budget: 1024,
74
70
  repo_map_min_files: 10,
75
71
  repo_map_min_bytes: 50 * 1024,
@@ -141,9 +137,9 @@ export function getProjectConfigPath(cwd = process.cwd()): string | null {
141
137
 
142
138
  while (current && current !== root) {
143
139
  const candidates = [
140
+ path.join(current, ".pi", "config.toml"),
144
141
  path.join(current, "config.toml"),
145
142
  path.join(current, "agent-kernel", "config.toml"),
146
- path.join(current, ".pi", "config.toml"),
147
143
  ];
148
144
  for (const candidate of candidates) {
149
145
  if (fs.existsSync(candidate)) {
@@ -203,13 +199,6 @@ export function loadKernelConfig(cwd = process.cwd()): KernelConfig {
203
199
  }
204
200
  }
205
201
 
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
202
  return config;
214
203
  }
215
204
 
@@ -308,9 +297,11 @@ export function saveProjectKernelConfig(cwd: string, updates: KernelConfigOverri
308
297
  return projectPath;
309
298
  }
310
299
 
311
- function mergeDeep(target: any, source: any) {
300
+ export function mergeDeep(target: any, source: any) {
312
301
  if (!source || typeof source !== "object") return;
313
302
  for (const key of Object.keys(source)) {
303
+ if (key === "__proto__" || key === "prototype" || key === "constructor") continue;
304
+ if (!Object.prototype.hasOwnProperty.call(source, key)) continue;
314
305
  const sVal = source[key];
315
306
  if (sVal && typeof sVal === "object" && !Array.isArray(sVal)) {
316
307
  if (!target[key] || typeof target[key] !== "object") {
@@ -16,8 +16,12 @@ export type TomlValue =
16
16
  | TomlValue[]
17
17
  | { [key: string]: TomlValue };
18
18
 
19
+ function isDangerousKey(key: string): boolean {
20
+ return key === "__proto__" || key === "prototype" || key === "constructor";
21
+ }
22
+
19
23
  export function parseToml(tomlStr: string): Record<string, TomlValue> {
20
- const root: Record<string, TomlValue> = {};
24
+ const root: Record<string, TomlValue> = Object.create(null);
21
25
  let currentTable: Record<string, TomlValue> = root;
22
26
 
23
27
  const lines = tomlStr.split(/\r?\n/);
@@ -33,12 +37,15 @@ export function parseToml(tomlStr: string): Record<string, TomlValue> {
33
37
  // Table header: [table] or [table.sub]
34
38
  if (line.startsWith("[") && line.endsWith("]") && !line.startsWith("[[")) {
35
39
  const tableName = line.slice(1, -1).trim();
36
- const parts = tableName.split(".").map((p) => p.trim());
40
+ const parts = tableName.split(".").map((p) => p.trim().replace(/^["']|["']$/g, ""));
41
+ if (parts.some(isDangerousKey)) {
42
+ continue;
43
+ }
37
44
  let cursor = root;
38
45
  for (const part of parts) {
39
- const existing = cursor[part];
46
+ const existing = Object.prototype.hasOwnProperty.call(cursor, part) ? cursor[part] : undefined;
40
47
  if (!existing || typeof existing !== "object" || Array.isArray(existing)) {
41
- cursor[part] = {};
48
+ cursor[part] = Object.create(null);
42
49
  }
43
50
  cursor = cursor[part] as Record<string, TomlValue>;
44
51
  }
@@ -51,6 +58,10 @@ export function parseToml(tomlStr: string): Record<string, TomlValue> {
51
58
  if (eqIndex === -1) continue;
52
59
 
53
60
  const key = line.slice(0, eqIndex).trim();
61
+ const cleanKey = key.replace(/^["']|["']$/g, "").trim();
62
+ if (isDangerousKey(cleanKey) || cleanKey.split(".").some(isDangerousKey)) {
63
+ continue;
64
+ }
54
65
  let rawValue = line.slice(eqIndex + 1).trim();
55
66
 
56
67
  // Handle multi-line arrays if open bracket without close bracket