@floydous/pi-agent-kernel 0.1.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/LICENSE +15 -0
- package/README.md +108 -0
- package/config.toml +24 -0
- package/docs/README.md +22 -0
- package/docs/architecture.md +40 -0
- package/docs/configuration.md +43 -0
- package/docs/editing-and-verification.md +41 -0
- package/docs/lsp.md +31 -0
- package/docs/retrieval.md +42 -0
- package/docs/testing.md +32 -0
- package/package.json +48 -0
- package/src/config/index.ts +2 -0
- package/src/config/kernel_config.ts +218 -0
- package/src/config/toml.ts +237 -0
- package/src/context/session_repair.ts +99 -0
- package/src/dedup/content_store.ts +365 -0
- package/src/dedup/recall_tool.ts +157 -0
- package/src/editing/patch.ts +482 -0
- package/src/editing/post_edit_verification.ts +200 -0
- package/src/editing/syntax-verify.ts +353 -0
- package/src/index.ts +852 -0
- package/src/lsp/adapters/base.ts +42 -0
- package/src/lsp/adapters/index.ts +21 -0
- package/src/lsp/adapters/python.ts +37 -0
- package/src/lsp/adapters/rust.ts +35 -0
- package/src/lsp/adapters/typescript.ts +40 -0
- package/src/lsp/index.ts +13 -0
- package/src/lsp/lsp_client.ts +650 -0
- package/src/lsp/lsp_detector.ts +52 -0
- package/src/lsp/lsp_formatter.ts +284 -0
- package/src/lsp/lsp_installer.ts +604 -0
- package/src/lsp/lsp_manager.ts +202 -0
- package/src/lsp/lsp_modal.ts +675 -0
- package/src/lsp/lsp_registry.ts +539 -0
- package/src/lsp/lsp_types.ts +143 -0
- package/src/retrieval/ast_search.ts +926 -0
- package/src/retrieval/repomap.ts +779 -0
- package/src/retrieval/search_bm25.ts +190 -0
- package/src/retrieval/search_chunker.ts +251 -0
- package/src/retrieval/search_config.ts +162 -0
- package/src/retrieval/search_embedder.ts +362 -0
- package/src/retrieval/search_index.ts +753 -0
- package/src/retrieval/search_modal.ts +358 -0
- package/src/retrieval/symbol_reader.ts +200 -0
- package/src/safety/atomic_write.ts +26 -0
- package/src/safety/epistemic_guard.ts +733 -0
- package/src/safety/kernel_debug.ts +15 -0
- package/src/safety/output_clamper.ts +213 -0
- package/src/tools/ast_search_tool.ts +131 -0
- package/src/tools/code_search_tool.ts +147 -0
- package/src/tools/context.ts +20 -0
- package/src/tools/edit_tool.ts +288 -0
- package/src/tools/lsp_tool.ts +813 -0
- package/src/tools/read_tool.ts +348 -0
- package/src/tools/repo_map_tool.ts +57 -0
- package/src/ui/footer.ts +287 -0
- package/src/ui/tui_utils.ts +278 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
ISC License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026, floydous <https://github.com/floydous>
|
|
4
|
+
|
|
5
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
|
6
|
+
purpose with or without fee is hereby granted, provided that the above
|
|
7
|
+
copyright notice and this permission notice appear in all copies.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
|
10
|
+
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
|
11
|
+
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
|
12
|
+
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
|
13
|
+
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
|
14
|
+
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
|
15
|
+
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
# Pi agent kernel
|
|
2
|
+
|
|
3
|
+
A Pi extension for code retrieval, surgical editing, safety checks, and language-server support.
|
|
4
|
+
|
|
5
|
+
## Design priorities
|
|
6
|
+
|
|
7
|
+
The extension keeps agent interactions small while improving reliability. It uses focused retrieval, bounded output, deterministic checks, and grounded edits. It avoids loading unnecessary context, doing background work without a reason, or making speculative changes.
|
|
8
|
+
|
|
9
|
+
## Token and performance measurements
|
|
10
|
+
|
|
11
|
+
The table compares this extension with an unconstrained harness that dumps whole files, walks the entire repository, rewrites files for every edit, and streams unbounded terminal output.
|
|
12
|
+
|
|
13
|
+
| Capability / Interaction | Unconstrained Harness | `pi-agent-kernel` | Token / Overhead Delta | Latency |
|
|
14
|
+
|---|---|---|---|---|
|
|
15
|
+
| **Context Ingestion** (Workspace map) | Raw recursive tree / full dump (~92.8k tokens) | PageRank AST Repo Map (~1.0k tokens) | **-98.9%** context tokens | ~40 ms |
|
|
16
|
+
| **Code Inspection** (Targeted function read) | Whole file read (~1.4k tokens) | AST Symbol Extraction (`read(symbol=...)`) (~428 tokens) | **-68.5%** prompt tokens | <1 ms |
|
|
17
|
+
| **Code Mutation** (Surgical function patch) | Full file rewrite (~1.4k tokens in tool payload) | Surgical search/replace (`edit`) (~58 tokens) | **-95.7%** output tokens | <5 ms |
|
|
18
|
+
| **Command Execution** (Large test/build output) | Unbounded stream (~27.5k tokens) | Bounded Clamp + Disk Spillover (~1.1k tokens) | **-95.9%** flood tokens prevented | Instant |
|
|
19
|
+
| **Codebase Search** (Lexical / BM25 Query) | Linear `grep`/`find` disk scan | Inverted In-Memory BM25 Index | **0 MB** background RAM (Lean) | ~0.03 ms / query |
|
|
20
|
+
| **Pre-Commit Safety** (Broken syntax gate) | Allowed to commit broken code | Local Fast AST Delimiter Gate | **Deterministic** failure block | Instant |
|
|
21
|
+
|
|
22
|
+
*These measurements come from `tests/benchmark_metrics.ts`, using this codebase with 45 source files and about 92.8k raw tokens.*
|
|
23
|
+
|
|
24
|
+
## Architecture and directory layout
|
|
25
|
+
|
|
26
|
+
Runtime code lives under `src/`. Tests, documentation, and example configuration remain at the repository root.
|
|
27
|
+
|
|
28
|
+
```
|
|
29
|
+
pi-agent-kernel/
|
|
30
|
+
├── src/
|
|
31
|
+
│ ├── index.ts # Main extension entry point
|
|
32
|
+
│ ├── config/ # Hierarchical TOML configuration loader
|
|
33
|
+
│ ├── context/ # Context engineering and session repair
|
|
34
|
+
│ ├── editing/ # Surgical patching and verification
|
|
35
|
+
│ ├── lsp/ # Language Server Protocol integration
|
|
36
|
+
│ ├── retrieval/ # AST, BM25, and semantic code search
|
|
37
|
+
│ ├── safety/ # Epistemic guards and bounded execution
|
|
38
|
+
│ ├── tools/ # Pi tool registrations
|
|
39
|
+
│ └── ui/ # Terminal UI components
|
|
40
|
+
├── tests/ # Focused verification sections
|
|
41
|
+
├── docs/ # Project documentation and guides
|
|
42
|
+
├── config.toml # Live configuration
|
|
43
|
+
└── package.json # Extension manifest
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Tool suite
|
|
47
|
+
|
|
48
|
+
| Tool | Purpose | Output Strategy |
|
|
49
|
+
|---|---|---|
|
|
50
|
+
| `read` | Content and surgical AST symbol inspection | Bounded, zero bloat, line-targeted |
|
|
51
|
+
| `edit` | Exact and fuzzy surgical patching with a syntax gate | Empty on clean (`OK!`), diagnostic on `WARN/FAIL` |
|
|
52
|
+
| `write` | Complete new-file authoring | Direct write |
|
|
53
|
+
| `get_repo_map` | PageRank-ranked repository AST definitions | Pure code symbols without import noise (~1k tokens) |
|
|
54
|
+
| `ast_search` | AST structure search across definitions | Concise `file:line [kind] signature` |
|
|
55
|
+
| `code_search` | Hybrid BM25 and semantic AST chunk search | Compact `file:start-end (breadcrumb)` snippets |
|
|
56
|
+
| `lsp` | Realtime Language Server Protocol queries | Compact `def`, `ref`, and structural symbols |
|
|
57
|
+
| `recall` | Restore an exact deduplicated tool result by reference | Bare original output content |
|
|
58
|
+
| `search_tools` | Deferred tool discovery | On-demand tool capability matching |
|
|
59
|
+
|
|
60
|
+
## Safety and invariants
|
|
61
|
+
|
|
62
|
+
- **Epistemic Guard**: Requires inspection before editing an existing file. It rejects ungrounded edits with short, copyable instructions and preserves authorization across sequential mutations.
|
|
63
|
+
- **Output Clamping**: Limits stdout and stderr so they do not fill the context window, while saving complete output to disk.
|
|
64
|
+
- **Tool Result Deduplication**: Replaces byte-identical repeated output with a small `[=rN,sizeB,tool,paramsKey]` notice that can be recovered with `recall`.
|
|
65
|
+
- **Bounded Syntax Verification**: Runs a fast local check on mutations before committing changes to disk.
|
|
66
|
+
|
|
67
|
+
## Installation
|
|
68
|
+
|
|
69
|
+
Install the extension as a Pi package, either globally or in a project:
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
pi install npm:@floydous/pi-agent-kernel
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
For a project-local installation:
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
pi install -l npm:@floydous/pi-agent-kernel
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
The entry point is declared in `package.json` under `pi.extensions` (`./src/index.ts`). Pi loads it when a session starts.
|
|
82
|
+
|
|
83
|
+
## Slash commands
|
|
84
|
+
|
|
85
|
+
| Command | Args | Purpose |
|
|
86
|
+
|---|---|---|
|
|
87
|
+
| `/repomap` | `[budget]` | Render the AST and PageRank-ranked repository map. The default budget is 1024 tokens. |
|
|
88
|
+
| `/engine` | `auto\|lean\|hybrid\|full\|off\|status\|reindex` | Change the retrieval profile or inspect engine state. `lean` is the default and uses AST-aware BM25; `hybrid` adds local embeddings. |
|
|
89
|
+
| `/lsp` | `[install <lang>]` | Inspect active language servers or install one, for example `/lsp install python`. |
|
|
90
|
+
|
|
91
|
+
## Configuration
|
|
92
|
+
|
|
93
|
+
The loader resolves configuration per workspace. It looks for `agent-kernel/config.toml` or `config.toml` at the workspace root and then walks upward. The built-in defaults are in [`src/config/kernel_config.ts`](src/config/kernel_config.ts), and the example configuration is [`config.toml`](config.toml). See [`docs/configuration.md`](docs/configuration.md) for the full schema and override rules.
|
|
94
|
+
|
|
95
|
+
The top-level sections are `[retrieval]`, `[safety]`, `[lsp]`, and `[ui]`.
|
|
96
|
+
|
|
97
|
+
## Documentation
|
|
98
|
+
|
|
99
|
+
- [`docs/architecture.md`](docs/architecture.md): module map and request flow
|
|
100
|
+
- [`docs/retrieval.md`](docs/retrieval.md): search profile semantics
|
|
101
|
+
- [`docs/editing-and-verification.md`](docs/editing-and-verification.md): patch and verification pipeline
|
|
102
|
+
- [`docs/lsp.md`](docs/lsp.md): LSP integration and registry
|
|
103
|
+
- [`docs/configuration.md`](docs/configuration.md): TOML schema and precedence
|
|
104
|
+
- [`docs/testing.md`](docs/testing.md): section-based test layout
|
|
105
|
+
|
|
106
|
+
## License
|
|
107
|
+
|
|
108
|
+
ISC. See [`LICENSE`](LICENSE).
|
package/config.toml
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# Agent Kernel Project Configuration
|
|
2
|
+
# Location: agent-kernel/config.toml
|
|
3
|
+
|
|
4
|
+
[retrieval]
|
|
5
|
+
default_profile = "lean"
|
|
6
|
+
repo_map_budget = 1024
|
|
7
|
+
max_search_results = 5
|
|
8
|
+
|
|
9
|
+
[safety]
|
|
10
|
+
enable_epistemic_guard = true
|
|
11
|
+
max_line_length = 300
|
|
12
|
+
max_lines = 40
|
|
13
|
+
max_total_bytes = 20480
|
|
14
|
+
exec_timeout_ms = 5000
|
|
15
|
+
dedup_min_bytes = 80
|
|
16
|
+
dedup_max_entries_per_session = 1024
|
|
17
|
+
|
|
18
|
+
[lsp]
|
|
19
|
+
idle_timeout_ms = 300000
|
|
20
|
+
spinner_interval_ms = 80
|
|
21
|
+
disabled_servers = []
|
|
22
|
+
|
|
23
|
+
[ui]
|
|
24
|
+
enable_pastel_footer = true
|
package/docs/README.md
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# Agent Kernel Documentation
|
|
2
|
+
|
|
3
|
+
This directory contains focused documentation for the `agent-kernel` Pi package.
|
|
4
|
+
|
|
5
|
+
## Design priorities
|
|
6
|
+
|
|
7
|
+
The extension targets bare-minimum token usage while maximizing performance and
|
|
8
|
+
reliability across agent work. Its documentation and implementation favor
|
|
9
|
+
focused retrieval, bounded output, deterministic verification, and grounded
|
|
10
|
+
edits instead of unnecessary context or background processing.
|
|
11
|
+
|
|
12
|
+
## Guides
|
|
13
|
+
|
|
14
|
+
- [Architecture](architecture.md) — source layout, subsystem boundaries, and runtime flow.
|
|
15
|
+
- [LSP](lsp.md) — language-server discovery, lifecycle, and diagnostics.
|
|
16
|
+
- [Configuration](configuration.md) — global, project-local, and environment configuration.
|
|
17
|
+
- [Editing and verification](editing-and-verification.md) — surgical edits, safety checks, and post-edit verification.
|
|
18
|
+
- [Retrieval](retrieval.md) — repository maps, AST search, and hybrid code search.
|
|
19
|
+
- [Testing](testing.md) — focused tests, the full suite, and verification policy.
|
|
20
|
+
|
|
21
|
+
The implementation lives under `src/`. This directory documents the public
|
|
22
|
+
contracts and operating behavior without duplicating source comments.
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# Architecture
|
|
2
|
+
|
|
3
|
+
`agent-kernel` is a lightweight Pi extension. Its authored runtime code is
|
|
4
|
+
under `src/`, while tests and project documentation remain outside the runtime
|
|
5
|
+
package.
|
|
6
|
+
|
|
7
|
+
## Layout
|
|
8
|
+
|
|
9
|
+
```text
|
|
10
|
+
src/
|
|
11
|
+
├── index.ts Extension integration boundary
|
|
12
|
+
├── config/ Hierarchical TOML configuration
|
|
13
|
+
├── context/ Session repair
|
|
14
|
+
├── editing/ Surgical patching and verification
|
|
15
|
+
├── lsp/ Language Server Protocol support
|
|
16
|
+
├── retrieval/ AST, repository-map, and code-search logic
|
|
17
|
+
├── safety/ Read guards, output limits, and execution helpers
|
|
18
|
+
├── tools/ Pi tool registrations
|
|
19
|
+
└── ui/ Footer and terminal rendering helpers
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Boundaries
|
|
23
|
+
|
|
24
|
+
- `src/index.ts` wires the extension into Pi and registers commands, tools, and
|
|
25
|
+
lifecycle handlers.
|
|
26
|
+
- `src/tools/` adapts kernel capabilities to Pi tool contracts. Tool modules
|
|
27
|
+
receive explicit dependencies instead of creating hidden application state.
|
|
28
|
+
- `src/retrieval/`, `src/editing/`, `src/lsp/`, and `src/safety/` contain the
|
|
29
|
+
reusable implementation modules.
|
|
30
|
+
- `src/config/` owns configuration loading and merging.
|
|
31
|
+
- `src/context/` owns session repair.
|
|
32
|
+
- `src/ui/` contains presentation helpers and width-safe rendering utilities.
|
|
33
|
+
|
|
34
|
+
## Runtime flow
|
|
35
|
+
|
|
36
|
+
1. Pi loads `src/index.ts` from the package's `pi.extensions` declaration.
|
|
37
|
+
2. The extension loads configuration and registers its tools and commands.
|
|
38
|
+
3. Read and edit operations pass through the epistemic guard where enabled.
|
|
39
|
+
4. Retrieval operations use AST-aware indexing and bounded output contracts.
|
|
40
|
+
5. Edits are verified locally and return compact structured status text.
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# Configuration
|
|
2
|
+
|
|
3
|
+
The configuration loader applies values in this order:
|
|
4
|
+
|
|
5
|
+
1. Built-in defaults.
|
|
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.
|
|
9
|
+
4. Environment-variable overrides supported by the loader.
|
|
10
|
+
|
|
11
|
+
The repository-root `config.toml` is ignored so local settings are not committed.
|
|
12
|
+
|
|
13
|
+
## Main sections
|
|
14
|
+
|
|
15
|
+
### `[retrieval]`
|
|
16
|
+
|
|
17
|
+
- `default_profile`: `lean`, `hybrid`, or `full`.
|
|
18
|
+
- `repo_map_budget`: token budget for the repository map.
|
|
19
|
+
- `max_search_results`: result limit for code search.
|
|
20
|
+
|
|
21
|
+
### `[safety]`
|
|
22
|
+
|
|
23
|
+
- `enable_epistemic_guard`: require inspection before editing existing files.
|
|
24
|
+
- `max_line_length`, `max_lines`, and `max_total_bytes`: output-clamping limits.
|
|
25
|
+
- `exec_timeout_ms`: bounded subprocess timeout.
|
|
26
|
+
- `dedup_min_bytes`: minimum rendered byte size for tool output deduplication side storage.
|
|
27
|
+
- `dedup_max_entries_per_session`: maximum LRU capacity for deduplicated tool results per session.
|
|
28
|
+
|
|
29
|
+
### `[lsp]`
|
|
30
|
+
|
|
31
|
+
- `idle_timeout_ms`: idle language-server shutdown delay.
|
|
32
|
+
- `diagnostic_timeout_ms`: timeout for diagnostic publishing and pull requests.
|
|
33
|
+
- `init_timeout_ms`: cold-start LSP initialization timeout.
|
|
34
|
+
- `spinner_interval_ms`: LSP modal spinner interval.
|
|
35
|
+
- `disabled_servers`: language identifiers to disable.
|
|
36
|
+
|
|
37
|
+
### `[ui]`
|
|
38
|
+
|
|
39
|
+
- `enable_pastel_footer`: enable the TrueColor footer when supported.
|
|
40
|
+
|
|
41
|
+
Invalid or unreadable configuration is handled as a best-effort load failure;
|
|
42
|
+
the loader retains defaults rather than presenting an uncertain value as a
|
|
43
|
+
successful override.
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# Editing and Verification
|
|
2
|
+
|
|
3
|
+
The edit tool is registered by `src/tools/edit_tool.ts` and delegates patching
|
|
4
|
+
to `src/editing/patch.ts`.
|
|
5
|
+
|
|
6
|
+
## Edit flow
|
|
7
|
+
|
|
8
|
+
1. Resolve the target path.
|
|
9
|
+
2. Apply one search/replace block or multiple disjoint blocks.
|
|
10
|
+
3. Enforce the read-before-write guard for existing files when enabled. Successful edits update the epistemic ledger to maintain continuity across sequential edits without redundant reads.
|
|
11
|
+
4. Validate the complete candidate content with the bounded local syntax gate; the target is written only after validation succeeds.
|
|
12
|
+
5. Reuse an already-ready LSP client when one exists; verification does not
|
|
13
|
+
start a new language server or trigger broad analysis.
|
|
14
|
+
6. Return compact status text and structured verification details.
|
|
15
|
+
|
|
16
|
+
The patch engine tries exact and normalized matching strategies and refuses an
|
|
17
|
+
ambiguous or missing match rather than guessing.
|
|
18
|
+
|
|
19
|
+
## Verification states
|
|
20
|
+
|
|
21
|
+
The renderer keeps uncertainty explicit:
|
|
22
|
+
|
|
23
|
+
- `clean` — the check completed without findings.
|
|
24
|
+
- `failed` — the check completed and found a failure.
|
|
25
|
+
- `findings` — diagnostics were returned.
|
|
26
|
+
- `not run` — no check was requested or available.
|
|
27
|
+
- `unavailable`, `timeout`, and `inconclusive` — verification did not establish
|
|
28
|
+
a reliable result.
|
|
29
|
+
|
|
30
|
+
These states must not be collapsed into `clean`.
|
|
31
|
+
|
|
32
|
+
## Repository history
|
|
33
|
+
|
|
34
|
+
The extension does not automatically stage, commit, reset, or otherwise alter
|
|
35
|
+
a repository. Edits only modify the requested file after the
|
|
36
|
+
candidate passes the local syntax gate.
|
|
37
|
+
|
|
38
|
+
The edit result reports verification in `details`, while the visible message
|
|
39
|
+
remains compact. Failed candidate validation leaves the target unchanged and
|
|
40
|
+
reports the failure. Post-write diagnostic failures do not roll back an
|
|
41
|
+
already-valid edit; their uncertainty remains explicit.
|
package/docs/lsp.md
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# Language Server Protocol
|
|
2
|
+
|
|
3
|
+
LSP support lives under `src/lsp/`. It provides language-server discovery,
|
|
4
|
+
client lifecycle management, formatting, diagnostics, and interactive controls.
|
|
5
|
+
|
|
6
|
+
## Components
|
|
7
|
+
|
|
8
|
+
- `lsp_registry.ts` describes supported language servers.
|
|
9
|
+
- `lsp_detector.ts` detects a file language and workspace root.
|
|
10
|
+
- `lsp_client.ts` manages JSON-RPC communication with a server process.
|
|
11
|
+
- `lsp_manager.ts` owns client reuse, lifecycle, and status reporting.
|
|
12
|
+
- `lsp_formatter.ts` renders diagnostics and navigation results for agents.
|
|
13
|
+
- `lsp_installer.ts` handles optional server installation.
|
|
14
|
+
- `lsp_modal.ts` provides the interactive server-control UI.
|
|
15
|
+
|
|
16
|
+
## Edit verification
|
|
17
|
+
|
|
18
|
+
Post-edit verification only reuses a client that is already ready for the
|
|
19
|
+
edited file. It does not start a new server solely to verify an edit. If a
|
|
20
|
+
client is unavailable, the result remains explicitly `not run`, `unavailable`,
|
|
21
|
+
or otherwise uncertain; it is never presented as `clean`.
|
|
22
|
+
|
|
23
|
+
The LSP tool can request diagnostics, definitions, references, hover details,
|
|
24
|
+
and document symbols. AST-based fallback behavior is kept in
|
|
25
|
+
`src/retrieval/ast_search.ts` for cases where no ready language server can
|
|
26
|
+
answer the request.
|
|
27
|
+
|
|
28
|
+
## Output formatting
|
|
29
|
+
|
|
30
|
+
- Diagnostics render in token-minimal format (`- [line:col] [SEV] [code] message (source)`) with no redundant `<path>` preamble. Clean files return strictly `<path> clean`.
|
|
31
|
+
- References support `exclude_tests` and `exclude_declaration` filters with bounded code window snippets (`windowAround`).
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# Retrieval
|
|
2
|
+
|
|
3
|
+
Retrieval is implemented in `src/retrieval/` and is intentionally layered so
|
|
4
|
+
fast discovery does not require loading the local embedding model.
|
|
5
|
+
|
|
6
|
+
## Components
|
|
7
|
+
|
|
8
|
+
- `repomap.ts` extracts AST symbols and produces a ranked repository map.
|
|
9
|
+
- `ast_search.ts` provides structural symbol search and language-aware fallback
|
|
10
|
+
operations such as document symbols, references, and local hover details.
|
|
11
|
+
- `search_chunker.ts` creates syntax-aware chunks with breadcrumbs.
|
|
12
|
+
- `search_bm25.ts` provides the fast lexical search path.
|
|
13
|
+
- `search_embedder.ts` provides optional local embeddings.
|
|
14
|
+
- `search_index.ts` coordinates indexing, profiles, and fallback behavior.
|
|
15
|
+
- `search_modal.ts` exposes profile controls in the Pi UI.
|
|
16
|
+
|
|
17
|
+
## Profiles
|
|
18
|
+
|
|
19
|
+
- `lean`: AST-aware BM25 search with minimal startup cost.
|
|
20
|
+
- `hybrid`: BM25 combined with local embeddings when available.
|
|
21
|
+
- `full`: the highest-cost configured retrieval profile.
|
|
22
|
+
- `off`: disables retrieval indexing where supported.
|
|
23
|
+
- `auto`: lets the runtime select the configured/default profile.
|
|
24
|
+
|
|
25
|
+
During indexing, search can fall back to the lean path rather than blocking on
|
|
26
|
+
model initialization. Hybrid/full profiles require vector cosine similarity of at
|
|
27
|
+
least 0.6 before candidates enter reciprocal-rank fusion; lower-confidence vector
|
|
28
|
+
candidates are abstained from while BM25 results remain available. This floor is a
|
|
29
|
+
conservative initial boundary measured on the bounded feedback fixture and must be
|
|
30
|
+
recalibrated against a larger labeled corpus before changing it. Output limits
|
|
31
|
+
remain enforced so retrieval cannot flood agent context.
|
|
32
|
+
|
|
33
|
+
AST and code-search path filters match normalized relative path substrings
|
|
34
|
+
(including directory fragments, filenames, and extensions). `includeBody` returns
|
|
35
|
+
a bounded preview of up to 25 lines; when the preview is truncated, the AST
|
|
36
|
+
result marks it as truncated; use the targeted symbol reader for the complete
|
|
37
|
+
implementation. `code_search` reports whether each result is `lexical`, `semantic`,
|
|
38
|
+
or `hybrid`, and accepts an optional bounded RRF smoothing constant from 1 to 200.
|
|
39
|
+
The default remains 60.
|
|
40
|
+
Vector caches are accepted only when their metadata, chunk IDs, dimensions, byte
|
|
41
|
+
length, and content hash agree; invalid vector data is ignored while the BM25
|
|
42
|
+
index remains usable.
|
package/docs/testing.md
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# Testing
|
|
2
|
+
|
|
3
|
+
The suite is split into focused section files under `tests/`. Each section is
|
|
4
|
+
independently runnable and uses isolated temporary workspaces where needed.
|
|
5
|
+
|
|
6
|
+
## Commands
|
|
7
|
+
|
|
8
|
+
```sh
|
|
9
|
+
# Full suite
|
|
10
|
+
npm test
|
|
11
|
+
|
|
12
|
+
# Direct section orchestrator
|
|
13
|
+
npm run test:focused
|
|
14
|
+
|
|
15
|
+
# One focused section
|
|
16
|
+
npx tsx tests/section-13-epistemic-guard.ts
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
`npm test` runs the section orchestrator under `tests/`.
|
|
20
|
+
|
|
21
|
+
## Verification policy
|
|
22
|
+
|
|
23
|
+
Prefer the narrowest useful check first:
|
|
24
|
+
|
|
25
|
+
1. Run the focused section related to a change.
|
|
26
|
+
2. Run bounded TypeScript/LSP diagnostics for changed implementation files.
|
|
27
|
+
3. Run the full suite once the focused checks are understood.
|
|
28
|
+
4. Review `git diff --check` and the final working-tree status.
|
|
29
|
+
|
|
30
|
+
The suite covers AST extraction, repository maps, patching, syntax checks,
|
|
31
|
+
session repair, retrieval, output clamping, LSP support,
|
|
32
|
+
configuration, lifecycle integration, and post-edit verification.
|
package/package.json
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@floydous/pi-agent-kernel",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Focused code retrieval, editing, safety checks, and language-server support for Pi.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"pi-package"
|
|
7
|
+
],
|
|
8
|
+
"license": "ISC",
|
|
9
|
+
"author": "floydous https://github.com/floydous",
|
|
10
|
+
"scripts": {
|
|
11
|
+
"test": "npx tsx tests/run-all.ts",
|
|
12
|
+
"test:focused": "npx tsx tests/run-all.ts",
|
|
13
|
+
"typecheck": "tsc --noEmit"
|
|
14
|
+
},
|
|
15
|
+
"dependencies": {
|
|
16
|
+
"@huggingface/transformers": "^4.2.0",
|
|
17
|
+
"diff": "^9.0.0"
|
|
18
|
+
},
|
|
19
|
+
"peerDependencies": {
|
|
20
|
+
"typebox": "^1.3.16"
|
|
21
|
+
},
|
|
22
|
+
"devDependencies": {
|
|
23
|
+
"@earendil-works/pi-coding-agent": "0.84.3",
|
|
24
|
+
"tsx": "^4.23.13",
|
|
25
|
+
"typebox": "^1.3.16",
|
|
26
|
+
"typescript": "^7.0.2"
|
|
27
|
+
},
|
|
28
|
+
"overrides": {
|
|
29
|
+
"adm-zip": "^0.6.0",
|
|
30
|
+
"sharp": "^0.35.3"
|
|
31
|
+
},
|
|
32
|
+
"pi": {
|
|
33
|
+
"extensions": [
|
|
34
|
+
"./src/index.ts"
|
|
35
|
+
]
|
|
36
|
+
},
|
|
37
|
+
"repository": {
|
|
38
|
+
"type": "git",
|
|
39
|
+
"url": "git+https://github.com/floydous/pi-agent-kernel.git"
|
|
40
|
+
},
|
|
41
|
+
"files": [
|
|
42
|
+
"src",
|
|
43
|
+
"README.md",
|
|
44
|
+
"docs",
|
|
45
|
+
"LICENSE",
|
|
46
|
+
"config.toml"
|
|
47
|
+
]
|
|
48
|
+
}
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import * as os from "node:os";
|
|
4
|
+
import { parseToml, stringifyToml, type TomlValue } from "./toml";
|
|
5
|
+
import { kernelDebug } from "../safety/kernel_debug";
|
|
6
|
+
import { writeFileSyncAtomic } from "../safety/atomic_write";
|
|
7
|
+
|
|
8
|
+
export interface RetrievalConfig {
|
|
9
|
+
default_profile: "lean" | "hybrid" | "full";
|
|
10
|
+
repo_map_budget: number;
|
|
11
|
+
max_search_results: number;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface SafetyConfig {
|
|
15
|
+
enable_epistemic_guard: boolean;
|
|
16
|
+
max_line_length: number;
|
|
17
|
+
max_lines: number;
|
|
18
|
+
max_total_bytes: number;
|
|
19
|
+
exec_timeout_ms: number;
|
|
20
|
+
/** Don't dedup tool results whose rendered text is <= this many bytes. */
|
|
21
|
+
dedup_min_bytes: number;
|
|
22
|
+
/** LRU cap per session for the dedup side store. */
|
|
23
|
+
dedup_max_entries_per_session: number;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface KernelConfigOverrides {
|
|
27
|
+
retrieval?: Partial<RetrievalConfig>;
|
|
28
|
+
safety?: Partial<SafetyConfig>;
|
|
29
|
+
lsp?: Partial<LspConfig>;
|
|
30
|
+
ui?: Partial<UiConfig>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface LspConfig {
|
|
34
|
+
idle_timeout_ms: number;
|
|
35
|
+
diagnostic_timeout_ms: number;
|
|
36
|
+
init_timeout_ms: number;
|
|
37
|
+
spinner_interval_ms: number;
|
|
38
|
+
disabled_servers: string[];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface UiConfig {
|
|
42
|
+
enable_pastel_footer: boolean;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface KernelConfig {
|
|
46
|
+
retrieval: RetrievalConfig;
|
|
47
|
+
safety: SafetyConfig;
|
|
48
|
+
lsp: LspConfig;
|
|
49
|
+
ui: UiConfig;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const DEFAULT_CONFIG: KernelConfig = {
|
|
53
|
+
retrieval: {
|
|
54
|
+
default_profile: "lean",
|
|
55
|
+
repo_map_budget: 1024,
|
|
56
|
+
max_search_results: 5,
|
|
57
|
+
},
|
|
58
|
+
safety: {
|
|
59
|
+
enable_epistemic_guard: true,
|
|
60
|
+
max_line_length: 300,
|
|
61
|
+
max_lines: 40,
|
|
62
|
+
max_total_bytes: 20 * 1024,
|
|
63
|
+
exec_timeout_ms: 5000,
|
|
64
|
+
dedup_min_bytes: 80,
|
|
65
|
+
dedup_max_entries_per_session: 1024,
|
|
66
|
+
},
|
|
67
|
+
lsp: {
|
|
68
|
+
idle_timeout_ms: 5 * 60 * 1000, // 5 minutes
|
|
69
|
+
diagnostic_timeout_ms: 8000, // 8s for type-checking on large workspaces
|
|
70
|
+
init_timeout_ms: 25000, // 25s for heavy servers like rust-analyzer/vtsls/gopls
|
|
71
|
+
spinner_interval_ms: 80,
|
|
72
|
+
disabled_servers: [],
|
|
73
|
+
},
|
|
74
|
+
ui: {
|
|
75
|
+
enable_pastel_footer: true,
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Resolve ~/.pi root directory
|
|
81
|
+
*/
|
|
82
|
+
export function getPiHomeDir(): string {
|
|
83
|
+
if (process.env.PI_DIR) return process.env.PI_DIR;
|
|
84
|
+
if (process.env.PI_CODING_AGENT_DIR) return process.env.PI_CODING_AGENT_DIR;
|
|
85
|
+
return path.join(os.homedir(), ".pi");
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Resolve global configuration file path
|
|
90
|
+
*/
|
|
91
|
+
export function getGlobalConfigPath(): string {
|
|
92
|
+
const piDir = getPiHomeDir();
|
|
93
|
+
const agentPath = path.join(piDir, "agent", "config.toml");
|
|
94
|
+
if (fs.existsSync(agentPath)) return agentPath;
|
|
95
|
+
|
|
96
|
+
const rootPath = path.join(piDir, "config.toml");
|
|
97
|
+
if (fs.existsSync(rootPath)) return rootPath;
|
|
98
|
+
|
|
99
|
+
// If PI_CODING_AGENT_DIR was set directly to ~/.pi/agent, check for config.toml right in piDir
|
|
100
|
+
if (path.basename(piDir) === "agent") {
|
|
101
|
+
return rootPath;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return agentPath;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Resolve workspace project-local configuration path (.pi/config.toml, agent-kernel/config.toml, or config.toml)
|
|
109
|
+
*/
|
|
110
|
+
export function getProjectConfigPath(cwd = process.cwd()): string | null {
|
|
111
|
+
let current = path.resolve(cwd);
|
|
112
|
+
const root = path.parse(current).root;
|
|
113
|
+
|
|
114
|
+
while (current && current !== root) {
|
|
115
|
+
const candidates = [
|
|
116
|
+
path.join(current, "config.toml"),
|
|
117
|
+
path.join(current, "agent-kernel", "config.toml"),
|
|
118
|
+
path.join(current, ".pi", "config.toml"),
|
|
119
|
+
];
|
|
120
|
+
for (const candidate of candidates) {
|
|
121
|
+
if (fs.existsSync(candidate)) {
|
|
122
|
+
return candidate;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
const parent = path.dirname(current);
|
|
126
|
+
if (parent === current) break;
|
|
127
|
+
current = parent;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
return null;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Load and merge hierarchical configuration:
|
|
135
|
+
* Defaults -> Global (~/.pi/agent/config.toml) -> Project (.pi/config.toml) -> Environment Variables
|
|
136
|
+
*/
|
|
137
|
+
export function loadKernelConfig(cwd = process.cwd()): KernelConfig {
|
|
138
|
+
// Deep clone defaults
|
|
139
|
+
const config: KernelConfig = structuredClone(DEFAULT_CONFIG);
|
|
140
|
+
|
|
141
|
+
// 1. Merge Global Config if present
|
|
142
|
+
const globalPath = getGlobalConfigPath();
|
|
143
|
+
if (fs.existsSync(globalPath)) {
|
|
144
|
+
try {
|
|
145
|
+
const raw = fs.readFileSync(globalPath, "utf-8");
|
|
146
|
+
const parsed = parseToml(raw);
|
|
147
|
+
mergeDeep(config, parsed);
|
|
148
|
+
} catch (e) {
|
|
149
|
+
kernelDebug(e);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// 2. Merge Project-Local Config if present
|
|
154
|
+
const projectPath = getProjectConfigPath(cwd);
|
|
155
|
+
if (projectPath && fs.existsSync(projectPath)) {
|
|
156
|
+
try {
|
|
157
|
+
const raw = fs.readFileSync(projectPath, "utf-8");
|
|
158
|
+
const parsed = parseToml(raw);
|
|
159
|
+
mergeDeep(config, parsed);
|
|
160
|
+
} catch (e) {
|
|
161
|
+
kernelDebug(e);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// 3. Environment Variable Overrides
|
|
166
|
+
if (process.env.PI_REPO_MAP_BUDGET) {
|
|
167
|
+
const b = parseInt(process.env.PI_REPO_MAP_BUDGET, 10);
|
|
168
|
+
if (!isNaN(b)) config.retrieval.repo_map_budget = b;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
if (process.env.PI_RETRIEVAL_PROFILE) {
|
|
172
|
+
const p = process.env.PI_RETRIEVAL_PROFILE.toLowerCase();
|
|
173
|
+
if (p === "lean" || p === "hybrid" || p === "full") {
|
|
174
|
+
config.retrieval.default_profile = p as any;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
return config;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Save user overrides to global configuration file (~/.pi/agent/config.toml)
|
|
183
|
+
*/
|
|
184
|
+
export function saveGlobalKernelConfig(updates: KernelConfigOverrides): void {
|
|
185
|
+
const globalPath = getGlobalConfigPath();
|
|
186
|
+
const parentDir = path.dirname(globalPath);
|
|
187
|
+
if (!fs.existsSync(parentDir)) {
|
|
188
|
+
fs.mkdirSync(parentDir, { recursive: true });
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
let existing: Record<string, TomlValue> = {};
|
|
192
|
+
if (fs.existsSync(globalPath)) {
|
|
193
|
+
try {
|
|
194
|
+
existing = parseToml(fs.readFileSync(globalPath, "utf-8"));
|
|
195
|
+
} catch (e) {
|
|
196
|
+
kernelDebug(e);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
mergeDeep(existing, updates);
|
|
201
|
+
const tomlString = stringifyToml(existing);
|
|
202
|
+
writeFileSyncAtomic(globalPath, tomlString);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function mergeDeep(target: any, source: any) {
|
|
206
|
+
if (!source || typeof source !== "object") return;
|
|
207
|
+
for (const key of Object.keys(source)) {
|
|
208
|
+
const sVal = source[key];
|
|
209
|
+
if (sVal && typeof sVal === "object" && !Array.isArray(sVal)) {
|
|
210
|
+
if (!target[key] || typeof target[key] !== "object") {
|
|
211
|
+
target[key] = {};
|
|
212
|
+
}
|
|
213
|
+
mergeDeep(target[key], sVal);
|
|
214
|
+
} else if (sVal !== undefined) {
|
|
215
|
+
target[key] = sVal;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|