|
| 1 | +# pi-agenticoding |
| 2 | + |
| 3 | +[](LICENSE) |
| 4 | + |
| 5 | + |
| 6 | + |
| 7 | +**Context management for the pi coding agent.** Three primitives — spawn, ledger, handoff — that keep your agent focused, prevent context rot, and make complex multi-step tasks actually finish. |
| 8 | + |
| 9 | +--- |
| 10 | + |
| 11 | +## Stop treating context like infinite RAM. |
| 12 | + |
| 13 | +Every coding agent degrades as the conversation grows. The model "forgets" the beginning, hallucinates stale assumptions, and burns tokens re-deriving context it already knew. By the time you hit the token limit, performance has been degrading for a while — long before the error. |
| 14 | + |
| 15 | +*pi-agenticoding* is the antidote. It gives your agent three concrete primitives for managing context deliberately, so it stays sharp across long sessions, survives session restarts, and can pivot between tasks without carrying dead weight. |
| 16 | + |
| 17 | +> **What if your agent could hand off knowledge between sessions, isolate messy exploration to child contexts, and restart fresh without losing what it learned?** |
| 18 | +
|
| 19 | +That's what this does. |
| 20 | + |
| 21 | +*This README was written by an agent, using the same primitives this extension teaches: spawn research subtasks, cache findings in a ledger, handoff to the next phase.* |
| 22 | + |
| 23 | +--- |
| 24 | + |
| 25 | +https://github.com/user-attachments/assets/f3a181f8-52b9-4e18-a659-d753aa25b9b4 |
| 26 | + |
| 27 | +--- |
| 28 | + |
| 29 | +## Table of Contents |
| 30 | + |
| 31 | +- [Quick Start](#quick-start) |
| 32 | +- [The Three Primitives](#the-three-primitives) |
| 33 | + - [Spawn — isolate noise](#spawn--isolate-noise) |
| 34 | + - [Ledger — continuity across cuts](#ledger--continuity-across-cuts) |
| 35 | + - [Handoff — deliberate compaction](#handoff--deliberate-compaction) |
| 36 | +- [What You Get](#what-you-get) |
| 37 | +- [Under the Hood](#under-the-hood) |
| 38 | +- [Why This Exists](#why-this-exists) |
| 39 | +- [Contributing](#contributing) |
| 40 | +- [License](#license) |
| 41 | + |
| 42 | +--- |
| 43 | + |
| 44 | +## Quick Start |
| 45 | + |
| 46 | +**1. Install** |
| 47 | + |
| 48 | +```bash |
| 49 | +npm install pi-agenticoding |
| 50 | +``` |
| 51 | + |
| 52 | +**2. Enable in your pi configuration** |
| 53 | + |
| 54 | +Add the extension to your `pi` config and restart: |
| 55 | + |
| 56 | +```json |
| 57 | +{ |
| 58 | + "extensions": ["pi-agenticoding"] |
| 59 | +} |
| 60 | +``` |
| 61 | + |
| 62 | +**3. You're done.** |
| 63 | + |
| 64 | +Your agent now has access to `spawn`, `ledger_add`, `ledger_get`, `ledger_list`, and `handoff` tools. The status bar will show context usage and ledger entry count. |
| 65 | + |
| 66 | +**Try it in 30 seconds:** |
| 67 | + |
| 68 | +```bash |
| 69 | +# Tell your agent: |
| 70 | +# "Use spawn to research what the current primacy-zone heuristic says |
| 71 | +# about context degradation, then ledger_add a summary." |
| 72 | +``` |
| 73 | + |
| 74 | +The agent spawns a child with its own clean context, researches, and caches the result. You can now reference that knowledge across turns without re-deriving it. |
| 75 | + |
| 76 | +--- |
| 77 | + |
| 78 | +## The Three Primitives |
| 79 | + |
| 80 | +### Spawn — isolate noise |
| 81 | + |
| 82 | +Delegate messy, exploratory work to an isolated child agent. The child has its own clean context, inherits your model and tools, and reports back condensed results. The parent stays focused. |
| 83 | + |
| 84 | +```typescript |
| 85 | +// The agent calls spawn — you never see the child's messy exploration |
| 86 | +spawn({ |
| 87 | + prompt: "Research best error-handling patterns for async TypeScript. |
| 88 | + Summarize top 3 with code snippets.", |
| 89 | +}) |
| 90 | +// Returns: a concise summary. All intermediate noise stays in the child. |
| 91 | +``` |
| 92 | + |
| 93 | +- Max depth: 2 (parent → child → grandchild) |
| 94 | +- Real-time TUI rendering of the child session |
| 95 | +- Token cost and usage stats reported back |
| 96 | +- Ledger writes from children are visible to parent (same shared state) |
| 97 | + |
| 98 | +### Ledger — continuity across cuts |
| 99 | + |
| 100 | +A sparse key-value cache that survives context resets, handoffs, and session restarts. The agent saves compact reusable knowledge — facts, decisions, constraints, discoveries — and fetches it on demand. |
| 101 | + |
| 102 | +```typescript |
| 103 | +// Save |
| 104 | +ledger_add({ |
| 105 | + name: "architecture-decision", |
| 106 | + content: "- We chose SQLite for local-first sync\n- Reason: offline-first requirement\n- Constraint: max 5 concurrent writers", |
| 107 | +}) |
| 108 | + |
| 109 | +// Retrieve |
| 110 | +ledger_get({ name: "architecture-decision" }) |
| 111 | +// → restores full body |
| 112 | + |
| 113 | +// List |
| 114 | +ledger_list() |
| 115 | +// → architecture-decision: We chose SQLite for local-first sync |
| 116 | +``` |
| 117 | + |
| 118 | +- Entries persist in the session file — survive restarts |
| 119 | +- Newest write wins on rehydration |
| 120 | +- Children share the same ledger (one truth across contexts) |
| 121 | +- Capped at 50KB / 2000 lines per entry |
| 122 | + |
| 123 | +### Handoff — deliberate compaction |
| 124 | + |
| 125 | +When context gets noisy or the job changes, handoff replaces the active context with a clean restart brief. The agent captures what matters, inlines referenced ledger entries, and starts fresh. |
| 126 | + |
| 127 | +```bash |
| 128 | +# User triggers a handoff: |
| 129 | +/handoff Implement auth module |
| 130 | + |
| 131 | +# The agent: |
| 132 | +# 1. Saves reusable state to the ledger |
| 133 | +# 2. Drafts a concise brief that completes the picture |
| 134 | +# 3. Calls handoff() — context compacts, brief becomes the new top |
| 135 | +# 4. Continues in a clean context with all knowledge preserved |
| 136 | +``` |
| 137 | + |
| 138 | +- `/handoff <direction>` command for user-triggered pivots |
| 139 | +- `handoff()` tool for agent-initiated compaction |
| 140 | +- Inlines referenced ledger entries (up to 3, 4000 chars) into the brief |
| 141 | +- Full history preserved in session file — nothing lost |
| 142 | + |
| 143 | +--- |
| 144 | + |
| 145 | +## What You Get |
| 146 | + |
| 147 | +| Feature | What it looks like | |
| 148 | +|---------|-------------------| |
| 149 | +| **Context usage %** | `ctx 65%` in status bar — green < 30%, yellow < 50%, orange < 70%, red ≥ 70% | |
| 150 | +| **Ledger count** | 📒 `3` when entries exist, hidden when empty | |
| 151 | +| **`/handoff` command** | Instant pivot — agent drafts brief, compacts context, resumes | |
| 152 | +| **`/ledger` command** | Overlay showing all entries with previews | |
| 153 | +| **Auto-rehydration** | Ledger entries survive session restarts — determined by epoch | |
| 154 | +| **Spawn transparency** | Watch child agents work in real time in the TUI | |
| 155 | +| **Token cost visibility** | Each spawn reports input/output tokens, cache hits, and cost | |
| 156 | +| **No polling** | writes are serialized via a process-local lock — no race conditions | |
| 157 | + |
| 158 | +--- |
| 159 | + |
| 160 | +## Under the Hood |
| 161 | + |
| 162 | +<details> |
| 163 | +<summary><strong>Architecture overview</strong> — how the three primitives wire together</summary> |
| 164 | + |
| 165 | +The extension hooks into pi's lifecycle at key points: |
| 166 | + |
| 167 | +| Hook | What it does | |
| 168 | +|------|-------------| |
| 169 | +| `before_agent_start` | Injects context management primer + live ledger listing into system prompt | |
| 170 | +| `context` | Injects advisory watchdog reminders when context > 30% | |
| 171 | +| `session_start` | Rehydrates ledger from persisted entries; resets on `/new` | |
| 172 | +| `turn_end` | Updates TUI indicators (context %, ledger count) | |
| 173 | +| `agent_end` | Records last context usage percent | |
| 174 | +| `session_before_compact` | Consumes pending handoff task and sets it as compaction summary | |
| 175 | + |
| 176 | +All state lives in a single `AgenticodingState` instance: |
| 177 | + |
| 178 | +```typescript |
| 179 | +interface AgenticodingState { |
| 180 | + ledger: Map<string, string> // keyed by kebab-case name |
| 181 | + epoch: number // set on first ledger_add, for rehydration |
| 182 | + lastContextPercent: number | null // last reading from getContextUsage() |
| 183 | + pendingHandoff: { task, source } | null |
| 184 | + pendingRequestedHandoff: { direction, ... } | null |
| 185 | +} |
| 186 | +``` |
| 187 | + |
| 188 | +</details> |
| 189 | + |
| 190 | +<details> |
| 191 | +<summary><strong>The primacy-zone heuristic</strong> — why 30% matters</summary> |
| 192 | + |
| 193 | +LLMs use context unevenly. Performance degrades as context grows — even far from the token limit. The **first ~30%** is a practical heuristic for keeping the current job in active focus. Past that, the agent is nudged to consider handoff. |
| 194 | + |
| 195 | +The watchdog never force-disengages — it's advisory only. Three tiers: |
| 196 | + |
| 197 | +- **30–50%**: "Consider handoff if the phase is done or context is noisy" |
| 198 | +- **50–70%**: "Well past the heuristic — consider a deliberate handoff" |
| 199 | +- **≥70%**: "Deep in the degraded zone. Save state, draft a brief, call handoff" |
| 200 | + |
| 201 | +</details> |
| 202 | + |
| 203 | +<details> |
| 204 | +<summary><strong>Architecture deep dive</strong> → <code>ARCHITECTURE.md</code></summary> |
| 205 | + |
| 206 | +See [ARCHITECTURE.md](ARCHITECTURE.md) for: |
| 207 | +- Full module breakdown (handoff/, ledger/, spawn/, state.ts, system-prompt.ts, watchdog.ts) |
| 208 | +- Tool definitions and parameter schemas |
| 209 | +- Lifecycle hook wiring details |
| 210 | +- Spawn depth tracking and child session lifecycle |
| 211 | +- Ledger rehydration algorithm and epoch mechanics |
| 212 | + |
| 213 | +</details> |
| 214 | + |
| 215 | +--- |
| 216 | + |
| 217 | +## Why This Exists |
| 218 | + |
| 219 | +LLM context management is underspecified. Most developers discover it the hard way — their agent starts forgetting, hallucinating, or grinding to a halt mid-task. There's no built-in vocabulary for "save this discovery" or "start fresh with what I've learned." |
| 220 | + |
| 221 | +pi-agenticoding provides that vocabulary, embedded directly into the agent's toolset. The agent learns to manage its own context because the system teaches it how. |
| 222 | + |
| 223 | +The three primitives aren't arbitrary — they correspond to the three fundamental operations in any context management system: |
| 224 | + |
| 225 | +| Operation | Primitive | What it prevents | |
| 226 | +|-----------|-----------|-----------------| |
| 227 | +| Isolate | **Spawn** | Context pollution from noisy subtasks | |
| 228 | +| Persist | **Ledger** | Knowledge loss across resets and pivots | |
| 229 | +| Compact | **Handoff** | Degradation from overstuffed context | |
| 230 | + |
| 231 | +--- |
| 232 | + |
| 233 | +## Contributing |
| 234 | + |
| 235 | +Contributions are welcome. Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines. |
| 236 | + |
| 237 | +--- |
| 238 | + |
| 239 | +## License |
| 240 | + |
| 241 | +MIT — see [LICENSE](LICENSE). |
0 commit comments