pi-context-steward 0.0.0-stage → 1.0.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 ADDED
@@ -0,0 +1,15 @@
1
+ # Changelog
2
+
3
+ ## [1.0.0] - 2026-12-04
4
+
5
+ First public release.
6
+
7
+ - Persistent context meter on every tool result (handle, size, context vs. budget), cache-stable by design.
8
+ - Batched consolidation through Pi `context_edit` entries: stale results, large tool-call inputs, old listings, outputs and reads are replaced by stubs; originals are saved to disk.
9
+ - Pin-preserving compaction: pinned facts are appended verbatim; stub notes are kept by the summarizer.
10
+ - Modes `off`, `meter`, `net`, `full`, and an automatic default (`net` from a 32k budget, `meter` below).
11
+ - Budget follows Pi's compaction threshold when `reserveTokens` is configured.
12
+ - Cost model that accounts for Anthropic's ~20-block cache lookback.
13
+ - JSON configuration with global, project and per-model layers; a default file is created on first start.
14
+ - Model-switch handling: warning when the context exceeds the new budget, larger previous model writes the summary.
15
+ - JSONL metrics and `scripts/analyze.mjs` for A/B comparisons.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Deemkeen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,264 @@
1
- # Temporary Holding Version
1
+ # pi-context-steward
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/pi-context-steward)](https://www.npmjs.com/package/pi-context-steward)
4
+ [![CI](https://github.com/deemkeen/pi-context-steward/actions/workflows/ci.yml/badge.svg)](https://github.com/deemkeen/pi-context-steward/actions/workflows/ci.yml)
5
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
6
+
7
+ **Context awareness and cache-aware context management for the [Pi coding agent](https://pi.dev).**
8
+
9
+ The extension shows the model how full its context is. When the context approaches the budget, it removes stale and bulky tool output in a few large batches. That way the work goes on without compaction, and the prompt cache survives between those batches.
10
+
11
+ ![Results at a 128k budget](https://raw.githubusercontent.com/deemkeen/pi-context-steward/main/docs/results.png)
12
+
13
+ In 11 runs of the same task with Claude Opus 5.5 at a 128k budget, the recommended setting was the cheapest and fastest variant. It needed **no compaction**, while plain Pi needed three:
14
+
15
+ | Variant | Runs | Cost per run | Model time | Compactions | File reads |
16
+ |---|---|---|---|---|---|
17
+ | **`net`, soft 0.85 → target 0.35 (default)** | 1 | **$3.84** | **10.5 min** | **0** | **16** |
18
+ | `meter` | 2 | $4.08 | 11.3 min | 1 | 26.5 |
19
+ | `full`, soft 0.6 → 0.4 | 4 | $4.82 | 13.7 min | 0 | 16.8 |
20
+ | `net`, soft 0.6 → 0.4 | 2 | $5.08 | 12.6 min | 0 | 20 |
21
+ | `off` (Pi default) | 2 | $6.24 | 16.2 min | 3 | 33.5 |
22
+
23
+ Compared with plain Pi, the default setting cost **38% less**, finished **35% faster** and read **half as many files**. Every run reached the task goal. Run counts are small. The full study, including what it does *not* show, is in [docs/RESULTS.md](https://github.com/deemkeen/pi-context-steward/blob/main/docs/RESULTS.md).
24
+
25
+ ---
26
+
27
+ ## Contents
28
+
29
+ - [Install](#install)
30
+ - [Quick start: Opus via GitHub Copilot](#quick-start-opus-via-github-copilot)
31
+ - [How it works](#how-it-works)
32
+ - [Modes](#modes)
33
+ - [Configuration](#configuration)
34
+ - [Switching models](#switching-models)
35
+ - [Measuring your own runs](#measuring-your-own-runs)
36
+ - [Limitations](#limitations)
37
+ - [Development](#development)
38
+
39
+ ## Install
40
+
41
+ ```bash
42
+ # from npm (recommended)
43
+ pi install npm:pi-context-steward
44
+
45
+ # or straight from GitHub
46
+ pi install git:github.com/deemkeen/pi-context-steward
47
+
48
+ # or try it for one session without installing
49
+ pi -e npm:pi-context-steward
50
+ ```
51
+
52
+ Developed and tested with `@earendil-works/pi-coding-agent` 1.8.0. The extension needs no runtime dependencies besides what Pi supplies.
53
+
54
+ On first start it creates `~/.pi/agent/context-steward.json` with the recommended defaults. Run `/steward` to see what it decided for the current model.
55
+
56
+ ## Quick start: Opus via GitHub Copilot
57
+
58
+ 1. In Pi, run `/login` and choose **GitHub Copilot**.
59
+ 2. Make Opus the default model and set the compaction threshold, here 300k, in `~/.pi/agent/settings.json`:
60
+
61
+ ```json
62
+ {
63
+ "defaultProvider": "github-copilot",
64
+ "defaultModel": "claude-opus-5.5",
65
+ "compaction": {
66
+ "modelOverrides": {
67
+ "github-copilot/claude-opus-5.5": { "reserveTokens": 700000, "keepRecentTokens": 40000 }
68
+ }
69
+ }
70
+ }
71
+ ```
72
+
73
+ `reserveTokens` = context window − threshold = 1,000,000 − 300,000.
74
+ 3. Start Pi. The extension's budget follows that threshold, and the mode is chosen automatically (`net`). `/steward` should show:
75
+
76
+ ```
77
+ mode net · auto (budget 300k: harness consolidation, no compactions in measured runs)
78
+ context 4k / budget 300k · consolidation at 255k · Pi compaction at 300k
79
+ ```
80
+
81
+ No extension configuration is needed. Everything else is optional.
82
+
83
+ ## How it works
84
+
85
+ The extension has three layers.
86
+
87
+ ### 1. Meter
88
+
89
+ Every tool result gets a short meter, written into the stored result itself:
90
+
91
+ ```
92
+ ⟦r12 · 3.1k · ctx 46k/128k 36%⟧
93
+ ```
94
+
95
+ That is the result's handle (`r12`), its size, and the context against the budget. A short section in the system prompt explains it.
96
+
97
+ The meter is part of the result **when the result is created**, not added on each request. Pi places the cache breakpoint on the last block of a request. A meter that changed from one request to the next would make every cached prefix unreachable. A meter stored with the result is byte-identical in every later request.
98
+
99
+ The meter alone already changes behavior. With Opus 5.5 the model plans around it, for example:
100
+
101
+ > *"Compaction will likely happen, so I'll write my findings progressively into ARCHITECTURE.md"*
102
+
103
+ The model writes notes to disk early instead of losing them to a summary later.
104
+
105
+ ### 2. Consolidation (the safety net)
106
+
107
+ When the context reaches `softRatio` × budget (default 85%), the harness replaces tool results with stubs until the context is down to `targetRatio` × budget (default 35%). It works in this order:
108
+
109
+ 1. Results the model asked to prune (`full` mode only).
110
+ 2. Stale results: a file read and later edited, written or read again; a command that ran again.
111
+ 3. Large inputs of successful tool calls, such as file contents passed to `write`/`edit` or long heredoc scripts. They are cut to their first and last lines. Files on disk are unaffected. Thinking blocks and their signatures are never touched.
112
+ 4. Old listings and searches (`ls`, `find`, `grep`, `rg`, `git status`, …).
113
+ 5. Old command output. The stub keeps the last lines, which usually hold the verdict.
114
+ 6. Old file reads.
115
+
116
+ A stub looks like this:
117
+
118
+ ```
119
+ ⟦r31 pruned · bash `mvn … test` · was 4.8k⟧
120
+ Old output. Ended with: [INFO] Tests run: 1360, Failures: 0 | [INFO] BUILD SUCCESS
121
+ Original: ~/.pi/agent/sessions/…/context-steward/<session>/r31.txt
122
+ ```
123
+
124
+ The original is written to disk and can be read back. The session file keeps it as well, because Pi `context_edit` entries change the model's view, not the history.
125
+
126
+ **Never touched:** the newest 6 results, the newest 15% of the budget, your messages, the model's text and thinking, and error output unless it is stale.
127
+
128
+ **Why so late, and why so deep:** Anthropic looks for cached prefixes only about 20 content blocks back from the cache breakpoint. Editing anything older therefore makes the next request **re-write the entire conversation** to the cache. Every consolidation costs a full rewrite, however little it frees. So it should happen rarely and free a lot. Measured at 128k: consolidating late and deep (85% → 35%) cost **$3.84** per run with 2 consolidations, while consolidating early (60% → 40%) cost **$5.08** with 6. A consolidation that would free less than 12% of the budget is skipped.
129
+
130
+ A consolidation needs no model call. It took 0.02–0.4 s in the measured runs; a Pi compaction took 18–55 s.
131
+
132
+ ### 3. Pin-preserving compaction
133
+
134
+ If compaction still happens, the extension writes the summary with Pi's own summarizer and adds three things:
135
+ - an instruction to keep the notes from stubs,
136
+ - your pinned facts, appended **verbatim**,
137
+ - the lists of read and modified files.
138
+
139
+ If anything fails, Pi's default compaction runs instead.
140
+
141
+ ## Modes
142
+
143
+ | Mode | Meter | Consolidation + pin-preserving compaction | `context_prune` / `context_pin` tools |
144
+ |---|---|---|---|
145
+ | `off` | – | – | – |
146
+ | `meter` | ✓ | – | – |
147
+ | `net` | ✓ | ✓ | – |
148
+ | `full` | ✓ | ✓ | ✓ |
149
+
150
+ **Default: automatic.** Without an explicit `mode`, the extension chooses per model from the effective budget:
151
+ - **`net` from 32k up.** It was the best variant measured at 128k. At 300k a cost model calibrated on the runs estimates it as cheap as `meter`, about 10% faster, and without compactions.
152
+ - **`meter` below 32k.** The protected newest results then fill most of the room, and a consolidation rarely frees enough to pay for a cache rewrite.
153
+
154
+ `full` additionally gives the model two tools:
155
+ - `context_prune({ items: [{ id: "r12", note: "…" }], now? })`: the model removes results itself, and its note replaces the content.
156
+ - `context_pin({ add?, remove? })`: facts that survive every compaction word for word.
157
+
158
+ The model uses these sensibly, for example pruning once at a phase boundary. At 128k, though, the extra calls and cache rewrites cost more than they saved. That is why `full` is opt-in.
159
+
160
+ ## Configuration
161
+
162
+ Everyday settings live in JSON. Later layers win:
163
+
164
+ | Layer | Location |
165
+ |---|---|
166
+ | defaults | built in |
167
+ | global | `~/.pi/agent/context-steward.json`, created on first start (`PI_STEWARD_CONFIG` points elsewhere) |
168
+ | project | `<project>/.pi/context-steward.json`, read only in trusted projects (`/steward init` creates it) |
169
+ | per model | `"models": { "provider/id": { … } }` inside either file |
170
+ | environment | `PI_STEWARD_*` |
171
+ | flags | `--steward-mode`, `--steward-budget`, `--steward-label`, `--steward-summary-model` |
172
+
173
+ Example:
174
+
175
+ ```json
176
+ {
177
+ "softRatio": 0.85,
178
+ "targetRatio": 0.35,
179
+ "models": {
180
+ "github-copilot/claude-opus-5.5": { "budget": 300000 },
181
+ "github-copilot/claude-sonnet-5.5": { "mode": "meter" }
182
+ }
183
+ }
184
+ ```
185
+
186
+ | Key | Default | Meaning |
187
+ |---|---|---|
188
+ | `mode` | automatic | `auto`, `off`, `meter`, `net`, `full`. Leave it out for the automatic choice. |
189
+ | `budget` | follows Pi | Working budget in tokens. Without it, the budget follows Pi's compaction threshold when `reserveTokens` is set, else min(window, 128k). Capped at the model window. |
190
+ | `softRatio` | `0.85` | Consolidation starts at this share of the budget. |
191
+ | `targetRatio` | `0.35` | Consolidation goes down to this share. |
192
+ | `minFreeRatio` | `0.12` | A consolidation that frees less is skipped. |
193
+ | `elideInputs` | `true` | Shorten large inputs of successful tool calls. |
194
+ | `protectRecentResults` | `6` | Newest results the harness never prunes. |
195
+ | `protectTailRatio` | `0.15` | Newest share of the budget the harness never prunes. |
196
+ | `summaryModel` | current model | `provider/id` that writes compaction summaries. |
197
+ | `label` | – | Tags all metrics (top level only). |
198
+ | `metricsPath` | `~/.pi/agent/context-steward/metrics.jsonl` | Metrics file (top level only). |
199
+
200
+ Invalid values and unknown keys are reported at startup and in `/steward`. Valid keys still apply. The generated file references `context-steward.schema.json` for editor autocompletion. Run `/reload` after editing.
201
+
202
+ Environment variables: `PI_STEWARD_MODE`, `PI_STEWARD_BUDGET`, `PI_STEWARD_LABEL`, `PI_STEWARD_SUMMARY_MODEL`, `PI_STEWARD_SOFT`, `PI_STEWARD_TARGET`, `PI_STEWARD_MIN_FREE`, `PI_STEWARD_PROTECT_RESULTS`, `PI_STEWARD_PROTECT_TAIL`, `PI_STEWARD_ELIDE_INPUTS`, `PI_STEWARD_METRICS`, `PI_STEWARD_CONFIG`.
203
+
204
+ **Commands:**
205
+ - `/steward`: mode and why, context, budget, thresholds, counters, config files in use, and errors.
206
+ - `/steward init`: creates a project config.
207
+
208
+ ## Switching models
209
+
210
+ On a model switch the extension reloads the configuration for the new model, recomputes budget, thresholds and the automatic mode, and turns the tools on or off to match.
211
+
212
+ If the context is larger than the new model's budget, it warns: Pi will compact before the next request. In `net`/`full` it also picks a summarizer the history fits into, in this order:
213
+ 1. `summaryModel`, if set,
214
+ 2. the new model, if the history fits into 80% of its window,
215
+ 3. otherwise the previous, larger model.
216
+
217
+ To decide yourself what the summary keeps, run `/compact` before switching.
218
+
219
+ ## Measuring your own runs
220
+
221
+ Every mode, `off` included, writes one JSON line per event to `~/.pi/agent/context-steward/metrics.jsonl`: requests with token usage and cost, consolidations, compactions, prunes and pins. To compare variants:
222
+
223
+ ```bash
224
+ for mode in off meter net; do
225
+ pi --steward-mode $mode --steward-label "$mode-r1" -p "$(cat task.md)"
226
+ done
227
+ node scripts/analyze.mjs --by group --group '^(\w+)-' --outcomes outcomes.csv
228
+ ```
229
+
230
+ `outcomes.csv` holds `label,success` lines. The analysis prints cost, cache hit rate, cache writes, mean and peak prompt, consolidations, compactions and success rate per variant.
231
+
232
+ Use tasks that outgrow the budget; short tasks look the same in every mode. Expect large run-to-run variance from things like build environments: in our runs it was larger than some of the effects.
233
+
234
+ ## Limitations
235
+
236
+ - **Small number of runs.** The measurements cover 12 runs on one task with one model (Opus 5.5 via Copilot), mostly at a 128k budget. The 300k figures are estimates from a model calibrated on those runs. See [docs/RESULTS.md](https://github.com/deemkeen/pi-context-steward/blob/main/docs/RESULTS.md).
237
+ - **The task type favors compaction.** Everything lost could simply be re-read. Tasks whose state cannot be re-read, like long debugging sessions, should benefit more from avoiding compaction, but this is not measured.
238
+ - **Token positions are estimates** (chars/4, scaled to Pi's own count). Stale detection relies on the standard tool names (`read`, `edit`, `write`, `bash`, `ls`, `find`, `grep`) and a `path` argument.
239
+ - **Input elision is verified against the Anthropic API** (Opus 5.5 via Copilot). For Gemini, whose tool calls carry their own signatures, it is untested; set `"elideInputs": false` there.
240
+ - **Offloaded originals are not cleaned up** automatically. They live next to the session files.
241
+
242
+ ## Development
243
+
244
+ ```bash
245
+ npm install
246
+ npm run typecheck
247
+ npm test # unit tests + end-to-end tests on the real Pi runtime with a scripted model
248
+ ```
249
+
250
+ The end-to-end tests check the cache invariants directly: across a whole run, the message list sent to the model changes only at consolidations, and only from the first edited message on.
251
+
252
+ | File | Purpose |
253
+ |---|---|
254
+ | `src/index.ts` | wiring (events, tools, command) |
255
+ | `src/config.ts` | JSON layers, automatic mode |
256
+ | `src/planner.ts` | consolidation policy (pure) |
257
+ | `src/context-index.ts` | view of the projected context |
258
+ | `src/meter.ts`, `src/stubs.ts`, `src/elide.ts` | meter, stubs, input elision |
259
+ | `src/compaction.ts` | pin-preserving compaction |
260
+ | `src/metrics.ts`, `scripts/analyze.mjs` | measurements |
261
+
262
+ ## License
263
+
264
+ [MIT](LICENSE)
@@ -0,0 +1,123 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "urn:pi-context-steward:config",
4
+ "title": "context-steward configuration",
5
+ "type": "object",
6
+ "additionalProperties": false,
7
+ "properties": {
8
+ "$schema": {
9
+ "type": "string",
10
+ "description": "Path or URL of this schema (editor autocompletion)."
11
+ },
12
+ "mode": {
13
+ "$ref": "#/$defs/tunables/properties/mode"
14
+ },
15
+ "budget": {
16
+ "$ref": "#/$defs/tunables/properties/budget"
17
+ },
18
+ "softRatio": {
19
+ "$ref": "#/$defs/tunables/properties/softRatio"
20
+ },
21
+ "targetRatio": {
22
+ "$ref": "#/$defs/tunables/properties/targetRatio"
23
+ },
24
+ "minFreeRatio": {
25
+ "$ref": "#/$defs/tunables/properties/minFreeRatio"
26
+ },
27
+ "protectRecentResults": {
28
+ "$ref": "#/$defs/tunables/properties/protectRecentResults"
29
+ },
30
+ "protectTailRatio": {
31
+ "$ref": "#/$defs/tunables/properties/protectTailRatio"
32
+ },
33
+ "summaryModel": {
34
+ "$ref": "#/$defs/tunables/properties/summaryModel"
35
+ },
36
+ "elideInputs": {
37
+ "$ref": "#/$defs/tunables/properties/elideInputs"
38
+ },
39
+ "label": {
40
+ "type": "string",
41
+ "description": "Tags all metrics. Usually set per run with --steward-label instead."
42
+ },
43
+ "metricsPath": {
44
+ "type": "string",
45
+ "description": "Metrics file (JSONL). ~ is expanded."
46
+ },
47
+ "models": {
48
+ "type": "object",
49
+ "description": "Per-model overrides keyed by \"provider/id\".",
50
+ "additionalProperties": {
51
+ "$ref": "#/$defs/tunables"
52
+ }
53
+ }
54
+ },
55
+ "$defs": {
56
+ "tunables": {
57
+ "type": "object",
58
+ "additionalProperties": false,
59
+ "properties": {
60
+ "mode": {
61
+ "enum": [
62
+ "auto",
63
+ "off",
64
+ "meter",
65
+ "net",
66
+ "full"
67
+ ],
68
+ "default": "auto",
69
+ "description": "auto (default): net, or meter below a 32k budget; off: metrics only; meter: meter only; net: meter + harness consolidation + pin-preserving compaction; full: net + context_prune/context_pin tools"
70
+ },
71
+ "budget": {
72
+ "type": "integer",
73
+ "minimum": 0,
74
+ "description": "Working budget in tokens. 0 or absent: follow Pi's compaction threshold if configured, else min(window, 128000)."
75
+ },
76
+ "softRatio": {
77
+ "type": "number",
78
+ "minimum": 0,
79
+ "exclusiveMaximum": 1,
80
+ "default": 0.85,
81
+ "description": "Consolidation starts at this share of the budget."
82
+ },
83
+ "targetRatio": {
84
+ "type": "number",
85
+ "minimum": 0,
86
+ "exclusiveMaximum": 1,
87
+ "default": 0.35,
88
+ "description": "Consolidation tries to get down to this share of the budget."
89
+ },
90
+ "minFreeRatio": {
91
+ "type": "number",
92
+ "minimum": 0,
93
+ "exclusiveMaximum": 1,
94
+ "default": 0.12,
95
+ "description": "A soft-limit consolidation that frees less than this share of the budget is skipped."
96
+ },
97
+ "protectRecentResults": {
98
+ "type": "integer",
99
+ "minimum": 0,
100
+ "default": 6,
101
+ "description": "The newest N tool results are never pruned by the harness."
102
+ },
103
+ "protectTailRatio": {
104
+ "type": "number",
105
+ "minimum": 0,
106
+ "exclusiveMaximum": 1,
107
+ "default": 0.15,
108
+ "description": "Nothing in the newest share of the budget is pruned by the harness."
109
+ },
110
+ "summaryModel": {
111
+ "type": "string",
112
+ "pattern": "^[^/]+/.+$",
113
+ "description": "provider/id of the model that writes compaction summaries (default: current model)."
114
+ },
115
+ "elideInputs": {
116
+ "type": "boolean",
117
+ "default": true,
118
+ "description": "During consolidation, shorten large inputs (file contents passed to write/edit, long scripts) of successful tool calls to head + marker + tail. Files on disk are unaffected."
119
+ }
120
+ }
121
+ }
122
+ }
123
+ }
@@ -0,0 +1,9 @@
1
+ {
2
+ "softRatio": 0.85,
3
+ "targetRatio": 0.35,
4
+ "models": {
5
+ "github-copilot/claude-opus-5.5": {
6
+ "budget": 300000
7
+ }
8
+ }
9
+ }
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "pi-context-steward",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Context awareness and cache-aware context management for the Pi coding agent: a persistent context meter, batched consolidation instead of most compactions, and pin-preserving summaries.",
5
+ "keywords": [
6
+ "pi-package",
7
+ "pi",
8
+ "pi-extension",
9
+ "pi-coding-agent",
10
+ "context-window",
11
+ "context-management",
12
+ "prompt-caching",
13
+ "compaction",
14
+ "llm",
15
+ "agent"
16
+ ],
17
+ "license": "MIT",
18
+ "author": "Deemkeen",
19
+ "homepage": "https://github.com/deemkeen/pi-context-steward#readme",
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/deemkeen/pi-context-steward.git"
23
+ },
24
+ "bugs": {
25
+ "url": "https://github.com/deemkeen/pi-context-steward/issues"
26
+ },
27
+ "type": "module",
28
+ "files": [
29
+ "src",
30
+ "scripts",
31
+ "examples",
32
+ "context-steward.schema.json",
33
+ "README.md",
34
+ "CHANGELOG.md",
35
+ "LICENSE"
36
+ ],
37
+ "pi": {
38
+ "extensions": [
39
+ "./src/index.ts"
40
+ ],
41
+ "image": "https://raw.githubusercontent.com/deemkeen/pi-context-steward/main/docs/results.png"
42
+ },
43
+ "scripts": {
44
+ "typecheck": "tsc --noEmit",
45
+ "test": "node --experimental-strip-types --test test/*.test.ts",
46
+ "analyze": "node scripts/analyze.mjs"
47
+ },
48
+ "engines": {
49
+ "node": ">=22.6"
50
+ },
51
+ "peerDependencies": {
52
+ "@earendil-works/pi-coding-agent": "*",
53
+ "@earendil-works/pi-ai": "*",
54
+ "typebox": "*"
55
+ },
56
+ "devDependencies": {
57
+ "@earendil-works/pi-coding-agent": "1.8.0",
58
+ "@types/node": "^22.0.0",
59
+ "typescript": "^5.9.0"
60
+ }
61
+ }
@@ -0,0 +1,168 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Summarize context-steward metrics per run label (or per mode / session).
4
+ *
5
+ * Usage:
6
+ * node scripts/analyze.mjs [metrics.jsonl] [--by label|mode|session|group] [--group <regex>]
7
+ * [--match <regex>] [--outcomes outcomes.csv] [--csv]
8
+ *
9
+ * --by group --group '^(\w+)-' groups labels by the first capture, e.g. "full-2048-r1" -> "full"
10
+ * --outcomes file.csv lines "label,success" (1/0, pass/fail, yes/no) to add a success rate
11
+ *
12
+ * Default metrics path: ~/.pi/agent/context-steward/metrics.jsonl
13
+ */
14
+
15
+ import { readFileSync } from "node:fs";
16
+ import { homedir } from "node:os";
17
+ import { join } from "node:path";
18
+
19
+ const args = process.argv.slice(2);
20
+ const opt = (name) => {
21
+ const i = args.indexOf(`--${name}`);
22
+ return i >= 0 ? args[i + 1] : undefined;
23
+ };
24
+ const flag = (name) => args.includes(`--${name}`);
25
+ const valued = new Set(["--by", "--group", "--match", "--outcomes"]);
26
+ const positional = args.filter((a, i) => !a.startsWith("--") && !(i > 0 && valued.has(args[i - 1])));
27
+ const path = positional[0] ?? join(homedir(), ".pi", "agent", "context-steward", "metrics.jsonl");
28
+ const by = opt("by") ?? "label";
29
+ const groupRe = opt("group") ? new RegExp(opt("group")) : undefined;
30
+ const matchRe = opt("match") ? new RegExp(opt("match")) : undefined;
31
+
32
+ const lines = readFileSync(path, "utf8").split("\n").filter(Boolean);
33
+ const events = lines.map((l) => JSON.parse(l)).filter((e) => !matchRe || matchRe.test(e.label ?? ""));
34
+
35
+ const outcomes = new Map();
36
+ if (opt("outcomes")) {
37
+ for (const row of readFileSync(opt("outcomes"), "utf8").split("\n")) {
38
+ const [label, raw] = row.split(",").map((s) => s?.trim());
39
+ if (!label || raw === undefined || label === "label") continue;
40
+ outcomes.set(label, /^(1|pass|yes|true|ok)$/i.test(raw));
41
+ }
42
+ }
43
+
44
+ function keyOf(e) {
45
+ if (by === "mode") return e.mode || "?";
46
+ if (by === "session") return e.sessionId || "?";
47
+ if (by === "group") {
48
+ const m = groupRe?.exec(e.label ?? "");
49
+ return m?.[1] ?? e.label ?? "?";
50
+ }
51
+ return e.label || e.sessionId || "?";
52
+ }
53
+
54
+ const groups = new Map();
55
+ const get = (key) => {
56
+ if (!groups.has(key))
57
+ groups.set(key, {
58
+ key,
59
+ labels: new Set(),
60
+ sessions: new Set(),
61
+ modes: new Set(),
62
+ models: new Set(),
63
+ requests: 0,
64
+ input: 0,
65
+ output: 0,
66
+ cacheRead: 0,
67
+ cacheWrite: 0,
68
+ cost: 0,
69
+ peakPrompt: 0,
70
+ promptSum: 0,
71
+ consolidations: 0,
72
+ freed: 0,
73
+ elided: 0,
74
+ rewrite: 0,
75
+ compactions: 0,
76
+ compactionFailures: 0,
77
+ stewardSummaries: 0,
78
+ pruneRequests: 0,
79
+ prunedByModel: 0,
80
+ pins: 0,
81
+ });
82
+ return groups.get(key);
83
+ };
84
+
85
+ for (const e of events) {
86
+ const g = get(keyOf(e));
87
+ if (e.label) g.labels.add(e.label);
88
+ if (e.sessionId) g.sessions.add(e.sessionId);
89
+ if (e.mode) g.modes.add(e.mode);
90
+ if (e.model) g.models.add(e.model);
91
+ switch (e.event) {
92
+ case "request":
93
+ g.requests++;
94
+ g.input += e.input;
95
+ g.output += e.output;
96
+ g.cacheRead += e.cacheRead;
97
+ g.cacheWrite += e.cacheWrite;
98
+ g.cost += e.cost;
99
+ g.peakPrompt = Math.max(g.peakPrompt, e.prompt);
100
+ g.promptSum += e.prompt;
101
+ break;
102
+ case "consolidation":
103
+ g.consolidations++;
104
+ g.freed += e.freed;
105
+ g.rewrite += e.rewriteTokens;
106
+ g.prunedByModel += e.reasons?.requested ?? 0;
107
+ g.elided += e.elidedInputs ?? 0;
108
+ break;
109
+ case "compaction":
110
+ g.compactions++;
111
+ if (e.fromExtension) g.stewardSummaries++;
112
+ g.cost += e.summaryCost ?? 0;
113
+ break;
114
+ case "compaction_failed":
115
+ g.compactionFailures++;
116
+ break;
117
+ case "prune_request":
118
+ g.pruneRequests += e.handles?.length ?? 0;
119
+ break;
120
+ case "pin":
121
+ g.pins++;
122
+ break;
123
+ }
124
+ }
125
+
126
+ const k = (n) => (n >= 1e6 ? `${(n / 1e6).toFixed(2)}M` : n >= 1e3 ? `${(n / 1e3).toFixed(1)}k` : String(Math.round(n)));
127
+ const rows = [...groups.values()].map((g) => {
128
+ const promptTotal = g.input + g.cacheRead + g.cacheWrite;
129
+ const runs = g.sessions.size || 1;
130
+ const labelOutcomes = [...g.labels].filter((l) => outcomes.has(l));
131
+ const success = labelOutcomes.length > 0 ? labelOutcomes.filter((l) => outcomes.get(l)).length / labelOutcomes.length : undefined;
132
+ return {
133
+ group: g.key,
134
+ mode: [...g.modes].join("/"),
135
+ runs,
136
+ requests: g.requests,
137
+ "cost $": g.cost.toFixed(2),
138
+ "cost/run $": (g.cost / runs).toFixed(2),
139
+ "cache hit": promptTotal > 0 ? `${((g.cacheRead / promptTotal) * 100).toFixed(1)}%` : "-",
140
+ "cache write": k(g.cacheWrite),
141
+ "uncached in": k(g.input),
142
+ output: k(g.output),
143
+ "mean prompt": g.requests ? k(g.promptSum / g.requests) : "-",
144
+ "peak prompt": k(g.peakPrompt),
145
+ consolidations: g.consolidations,
146
+ freed: k(g.freed),
147
+ "inputs shortened": g.elided,
148
+ compactions: `${g.compactions}${g.compactionFailures ? ` (+${g.compactionFailures} failed)` : ""}`,
149
+ "model prunes": `${g.pruneRequests} req / ${g.prunedByModel} applied`,
150
+ pins: g.pins,
151
+ success: success === undefined ? "-" : `${(success * 100).toFixed(0)}% (${labelOutcomes.length})`,
152
+ };
153
+ });
154
+ rows.sort((a, b) => a.group.localeCompare(b.group));
155
+
156
+ if (rows.length === 0) {
157
+ console.log("No events.");
158
+ process.exit(0);
159
+ }
160
+ const cols = Object.keys(rows[0]);
161
+ if (flag("csv")) {
162
+ console.log(cols.join(","));
163
+ for (const r of rows) console.log(cols.map((c) => JSON.stringify(String(r[c]))).join(","));
164
+ } else {
165
+ console.log(`| ${cols.join(" | ")} |`);
166
+ console.log(`| ${cols.map(() => "---").join(" | ")} |`);
167
+ for (const r of rows) console.log(`| ${cols.map((c) => r[c]).join(" | ")} |`);
168
+ }