protect-context 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/LICENSE +21 -0
- package/README.md +613 -2
- package/extension/index.ts +1024 -0
- package/extension/lib/brief.ts +128 -0
- package/extension/lib/config.ts +67 -0
- package/extension/lib/contract.ts +160 -0
- package/extension/lib/contract_check.ts +62 -0
- package/extension/lib/defaults.ts +124 -0
- package/extension/lib/events.ts +69 -0
- package/extension/lib/fingerprint.ts +56 -0
- package/extension/lib/gitparse.ts +229 -0
- package/extension/lib/journal.ts +100 -0
- package/extension/lib/loops.ts +151 -0
- package/extension/lib/orientation.ts +209 -0
- package/extension/lib/status.ts +88 -0
- package/extension/lib/store.ts +500 -0
- package/extension/lib/text.ts +24 -0
- package/extension/lib/verify.ts +96 -0
- package/extension/lib/widget.ts +28 -0
- package/package.json +54 -4
- package/preview.png +0 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 XJTLUmedia
|
|
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,614 @@
|
|
|
1
|
-
#
|
|
1
|
+
# protect-context · Agent Guardrail Suite
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Durable context, real evidence, and a brake pedal for AI coding agents.**
|
|
4
|
+
|
|
5
|
+
`protect-context` keeps the rules, decisions, and proof-of-work an agent needs in
|
|
6
|
+
front of it — then makes scope creep, unverified claims, and repeated failures
|
|
7
|
+
visible *before* they cost you a session.
|
|
8
|
+
|
|
9
|
+
<p align="center">
|
|
10
|
+
<a href="./LICENSE"><img alt="license: MIT" src="https://img.shields.io/badge/license-MIT-green"></a>
|
|
11
|
+
<a href="https://pi.dev/packages"><img alt="pi-package" src="https://img.shields.io/badge/pi--package-gallery-8a2be2"></a>
|
|
12
|
+
<a href="pyproject.toml"><img alt="python 3.10+" src="https://img.shields.io/badge/python-3.10%2B-blue"></a>
|
|
13
|
+
<img alt="enforcement: advisory-first" src="https://img.shields.io/badge/enforcement-advisory--first-lightgrey">
|
|
14
|
+
<img alt="runtime dependencies: zero" src="https://img.shields.io/badge/npm%20runtime%20deps-0-success">
|
|
15
|
+
</p>
|
|
16
|
+
|
|
17
|
+

|
|
18
|
+
|
|
19
|
+
One project-local `.agent-guard/` store · three interfaces backed by the same
|
|
20
|
+
logic:
|
|
21
|
+
|
|
22
|
+
| Interface | Use it for | Runtime |
|
|
23
|
+
|---|---|---|
|
|
24
|
+
| **pi extension** | Automatic brief injection, status widget, loop blocking, diff warnings, risky-command confirmation | TypeScript, loaded by pi via jiti |
|
|
25
|
+
| **MCP server** | Portable model/host access to the same tools | Python 3.10+, `fastmcp` |
|
|
26
|
+
| **Python CLI** | People, scripts, CI, and hosts without MCP | Python 3.10+ |
|
|
27
|
+
|
|
28
|
+
The suite is **advisory-first**. It records evidence and makes unsafe or
|
|
29
|
+
repetitive behavior visible; it is not a sandbox and does not prove that a
|
|
30
|
+
change is correct. [`SPEC.md`](./SPEC.md) is the frozen v1.0 contract.
|
|
31
|
+
|
|
32
|
+
## Contents
|
|
33
|
+
|
|
34
|
+
- [Why this exists](#why-this-exists)
|
|
35
|
+
- [What it does](#what-it-does)
|
|
36
|
+
- [Quick start](#quick-start)
|
|
37
|
+
- [Install the pi extension](#install-the-pi-extension)
|
|
38
|
+
- [Install the MCP server](#install-the-mcp-server)
|
|
39
|
+
- [Install the Python CLI](#install-the-python-cli)
|
|
40
|
+
- [From source](#from-source)
|
|
41
|
+
- [A 30-second tour](#a-30-second-tour)
|
|
42
|
+
- [Interface comparison](#interface-comparison)
|
|
43
|
+
- [Reference](#reference)
|
|
44
|
+
- [pi commands and tools](#pi-commands-and-tools)
|
|
45
|
+
- [MCP tools](#mcp-tools)
|
|
46
|
+
- [CLI](#cli)
|
|
47
|
+
- [Configuration](#configuration)
|
|
48
|
+
- [Environment variables](#environment-variables)
|
|
49
|
+
- [Runtime store and concurrency](#runtime-store-and-concurrency)
|
|
50
|
+
- [The 12 failure modes and what ships](#the-12-failure-modes-and-what-ships)
|
|
51
|
+
- [How it works](#how-it-works)
|
|
52
|
+
- [Session lifecycle](#session-lifecycle)
|
|
53
|
+
- [The brief](#the-brief)
|
|
54
|
+
- [Evidence and loop detection](#evidence-and-loop-detection)
|
|
55
|
+
- [Scope audit](#scope-audit)
|
|
56
|
+
- [Trust and provenance](#trust-and-provenance)
|
|
57
|
+
- [Context budget](#context-budget)
|
|
58
|
+
- [Development and validation](#development-and-validation)
|
|
59
|
+
- [Troubleshooting](#troubleshooting)
|
|
60
|
+
- [Limitations and security boundary](#limitations-and-security-boundary)
|
|
61
|
+
- [Design sources](#design-sources)
|
|
62
|
+
- [Non-goals](#non-goals)
|
|
63
|
+
- [License](#license)
|
|
64
|
+
|
|
65
|
+
## Why this exists
|
|
66
|
+
|
|
67
|
+
Long agent sessions fail in boring, expensive ways:
|
|
68
|
+
|
|
69
|
+
- the constraints you stated at minute two are gone by minute forty;
|
|
70
|
+
- "done" is claimed with no command output behind it;
|
|
71
|
+
- a "quick fix" quietly rewrites six unrelated files;
|
|
72
|
+
- decisions get re-litigated because nothing recorded the reasoning;
|
|
73
|
+
- the same failing command is retried until the context window dies.
|
|
74
|
+
|
|
75
|
+
`protect-context` treats those as **state** problems, not intelligence problems.
|
|
76
|
+
A durable store plus three small habits — brief before work, evidence after
|
|
77
|
+
work, journal when something is decided — removes most of the failure surface
|
|
78
|
+
without turning the agent into a different agent.
|
|
79
|
+
|
|
80
|
+
## What it does
|
|
81
|
+
|
|
82
|
+
| Primitive | What it gives you | Where you meet it |
|
|
83
|
+
|---|---|---|
|
|
84
|
+
| **Brief** | Contract, recent trusted decisions and corrections, open loops, and the last evidence ID, injected before the agent starts a turn | Automatic in pi; `orientation`, `status`, `guard_journal` elsewhere |
|
|
85
|
+
| **Orientation** | Bounded repo digest: tree, languages, and conventions files (`CLAUDE.md`, `AGENTS.md`, `CONVENTIONS.md`, `README.md`, `README`) | Injected once per digest in pi; `orientation` in CLI/MCP |
|
|
86
|
+
| **Evidence ledger** | Every verification run recorded as `ev-NNNN` with exit code, duration, command, and a bounded output digest | `guard_verify`, `protect-context verify`, `guard_evidence` |
|
|
87
|
+
| **Loop brake** | Identical failing commands are fingerprinted; the Nth attempt is blocked instead of re-run | Hard block in pi and the CLI; reported through MCP |
|
|
88
|
+
| **Scope audit** | `git` diff stats over tracked, staged, and bounded untracked work, with `ok` / `warn` / `hard` verdicts | Widget and `status` in pi; `diff`, `guard_diff_audit` |
|
|
89
|
+
| **Journal** | Durable `decision` / `correction` / `risk` / `note` entries with tags and trust levels | `guard_note`, `protect-context note`, `guard_journal` |
|
|
90
|
+
| **Risky-command confirm** | Nine catastrophic shell patterns get one grouped confirmation instead of none | pi, when a UI is available |
|
|
91
|
+
| **Preflight** | Tool presence and versions plus Git worktree detection | `preflight`, `guard_preflight` |
|
|
92
|
+
| **Context budget** | Watermarks on context usage and hard caps on every injected block | Widget, `budget`, `guard_budget` |
|
|
93
|
+
|
|
94
|
+
## Quick start
|
|
95
|
+
|
|
96
|
+
Python 3.10+ is required for the CLI and MCP server. Node 22.19+ is required
|
|
97
|
+
only to validate the TypeScript extension from a checkout — pi supplies the
|
|
98
|
+
extension's runtime modules, and the extension has **zero npm runtime
|
|
99
|
+
dependencies**.
|
|
100
|
+
|
|
101
|
+
### Install the pi extension
|
|
102
|
+
|
|
103
|
+
Installed from npm. The package declares `"pi": { "extensions":
|
|
104
|
+
["./extension/index.ts"], "image": "./preview.png" }` and the `pi-package`
|
|
105
|
+
keyword required by the Pi package gallery:
|
|
106
|
+
|
|
107
|
+
```sh
|
|
108
|
+
pi install npm:protect-context
|
|
109
|
+
|
|
110
|
+
# Try it for one run without adding it to settings
|
|
111
|
+
pi -e npm:protect-context
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
Or copy/symlink the checkout into a trusted extension directory:
|
|
115
|
+
|
|
116
|
+
```sh
|
|
117
|
+
# Personal
|
|
118
|
+
mkdir -p ~/.pi/agent/extensions
|
|
119
|
+
cp -r extension ~/.pi/agent/extensions/protect-context
|
|
120
|
+
|
|
121
|
+
# Project-local (read after the project is trusted)
|
|
122
|
+
mkdir -p .pi/extensions
|
|
123
|
+
cp -r extension .pi/extensions/protect-context
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
Start a session and you get a single-line status widget, a brief before the
|
|
127
|
+
first turn, and five slash commands. No configuration file is needed: the
|
|
128
|
+
extension seeds `.agent-guard/config.json` with the frozen defaults on first
|
|
129
|
+
session start.
|
|
130
|
+
|
|
131
|
+
### Install the MCP server
|
|
132
|
+
|
|
133
|
+
For pi with `pi-mcp-adapter`, add `.mcp.json` at the project root:
|
|
134
|
+
|
|
135
|
+
```json
|
|
136
|
+
{
|
|
137
|
+
"mcpServers": {
|
|
138
|
+
"protect-context": {
|
|
139
|
+
"command": "/absolute/path/to/protect-context/.venv/bin/python",
|
|
140
|
+
"args": ["-m", "protect_context.mcp_server"]
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
The same stdio shape works in any generic MCP host. Set `PC_SESSION_ID` when
|
|
147
|
+
several host sessions need distinct evidence and loop views:
|
|
148
|
+
|
|
149
|
+
```json
|
|
150
|
+
{
|
|
151
|
+
"mcpServers": {
|
|
152
|
+
"protect-context": {
|
|
153
|
+
"command": "/absolute/path/to/protect-context/.venv/bin/python",
|
|
154
|
+
"args": ["-m", "protect_context.mcp_server"],
|
|
155
|
+
"env": { "PC_SESSION_ID": "my-session" }
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
The MCP surface exposes the nine frozen v1.0 tools plus two compatible read
|
|
162
|
+
surfaces added to close the original reachability gaps (`guard_journal` and
|
|
163
|
+
`guard_orientation`). Tools carry conservative MCP annotations; in particular
|
|
164
|
+
`guard_verify` is marked destructive and open-world because it can run any
|
|
165
|
+
shell command. Annotations are host hints, not enforcement — configure the host
|
|
166
|
+
to require human approval for that tool.
|
|
167
|
+
|
|
168
|
+
### Install the Python CLI
|
|
169
|
+
|
|
170
|
+
```sh
|
|
171
|
+
pip install protect-context # or: pipx install protect-context
|
|
172
|
+
protect-context init # seed .agent-guard/ in the current project
|
|
173
|
+
protect-context status
|
|
174
|
+
protect-context verify "pytest -q"
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
The CLI and MCP server are distributed through PyPI; the npm package ships only
|
|
178
|
+
the pi extension. Both read the same `.agent-guard/` directory, so a project can
|
|
179
|
+
use the extension in pi and scripted verification in CI at the same time.
|
|
180
|
+
|
|
181
|
+
### From source
|
|
182
|
+
|
|
183
|
+
```sh
|
|
184
|
+
# Python package, CLI, MCP server, and Python tests
|
|
185
|
+
python3 -m venv .venv
|
|
186
|
+
.venv/bin/python -m pip install -e ".[dev]"
|
|
187
|
+
|
|
188
|
+
# Reproducible extension development checks (dev dependencies only)
|
|
189
|
+
npm ci --ignore-scripts
|
|
190
|
+
npm run check
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
If the machine's default Node is older than 22.19, run the same checks with an
|
|
194
|
+
ephemeral Node 22 binary after `npm ci`:
|
|
195
|
+
|
|
196
|
+
```sh
|
|
197
|
+
npx -y node@22 node_modules/typescript/bin/tsc --noEmit -p extension/tsconfig.json
|
|
198
|
+
npx -y node@22 --experimental-strip-types --test extension/test/*.test.ts
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
## A 30-second tour
|
|
202
|
+
|
|
203
|
+
Excerpts from a real session in this repository.
|
|
204
|
+
|
|
205
|
+
Ask for the current state:
|
|
206
|
+
|
|
207
|
+
```console
|
|
208
|
+
$ protect-context status
|
|
209
|
+
PC status · session default · git 91fad4d
|
|
210
|
+
Δdiff +88/-8 · 6 files · verdict ok
|
|
211
|
+
loops: none
|
|
212
|
+
contract 12 constraints
|
|
213
|
+
conventions: README.md
|
|
214
|
+
Nudge: verify changes with guard_verify and cite the evidence id before claiming success.
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
Record proof instead of asserting it:
|
|
218
|
+
|
|
219
|
+
```console
|
|
220
|
+
$ protect-context verify "npm run check"
|
|
221
|
+
PC evidence ev-0005 · exit 0 · 1440ms
|
|
222
|
+
…output digest…
|
|
223
|
+
Nudge: cite evidence ids, not memory, when claiming success.
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
Re-run the same failing command a third time and the brake engages:
|
|
227
|
+
|
|
228
|
+
```console
|
|
229
|
+
$ protect-context verify "npm test"
|
|
230
|
+
PC verify blocked · npm test · 3 prior failures
|
|
231
|
+
Nudge: change approach or gather new information — do not re-run unchanged.
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
What pi injects before the agent starts working (sections elided):
|
|
235
|
+
|
|
236
|
+
```console
|
|
237
|
+
contract:
|
|
238
|
+
01-obey-instructions: Obey the owner's explicit instructions and stated constraints exactly; when instructions conflict, ask instead of guessing.
|
|
239
|
+
02-evidence-before-success: Never claim success without citing a fresh verification run (evidence id or pasted output) for the exact claim.
|
|
240
|
+
…
|
|
241
|
+
decisions:
|
|
242
|
+
- Use the atomic-mkdir lease, not fcntl alone; Python must interoperate with the extension. [locking,spec]
|
|
243
|
+
last verify: ev-0005 exit=0 'npm run check' 1.4s
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
And the always-on one-line widget:
|
|
247
|
+
|
|
248
|
+
```console
|
|
249
|
+
PC Δ+88L/6f 0loop ev5 ctx8%
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
## Interface comparison
|
|
253
|
+
|
|
254
|
+
| Capability | pi extension | MCP server | CLI |
|
|
255
|
+
|---|---|---|---|
|
|
256
|
+
| Brief injected automatically before a turn | yes (change-triggered) | — | — |
|
|
257
|
+
| Orientation digest (tree, languages, conventions) | injected once per digest | `guard_orientation` | `orientation` |
|
|
258
|
+
| Verification evidence (`ev-NNNN`) | `guard_verify`, `/guard-verify` | `guard_verify` | `verify` |
|
|
259
|
+
| Loop blocking | blocks the command | `guard_loop_check` reports and advises | `verify` refuses; `loops` exits 1 |
|
|
260
|
+
| Scope audit | session-start baseline + warnings | `guard_diff_audit` (explicit baseline) | `diff --baseline REF` |
|
|
261
|
+
| Journal write/read | `guard_note`, `/guard-note` | `guard_note`, `guard_journal` | `note`, `journal` |
|
|
262
|
+
| Trusted re-injection of decisions | yes, after change or compaction | read views only | read views only |
|
|
263
|
+
| Contract management | `/guard-contract` | `guard_contract` | `contract list\|add\|remove` |
|
|
264
|
+
| Risky-command confirmation | one grouped confirm | host approval policy | — |
|
|
265
|
+
| Status widget | yes | — | `status` |
|
|
266
|
+
|
|
267
|
+
## Reference
|
|
268
|
+
|
|
269
|
+
### pi commands and tools
|
|
270
|
+
|
|
271
|
+
Slash commands:
|
|
272
|
+
|
|
273
|
+
| Command | Action |
|
|
274
|
+
|---|---|
|
|
275
|
+
| `/guard-status` | Compact session status: diff verdict, loops, evidence, contract, context |
|
|
276
|
+
| `/guard-contract` | `list` · `add <text>` · `remove <id>` — edit the persistent contract |
|
|
277
|
+
| `/guard-verify` | Run a command through the evidence ledger |
|
|
278
|
+
| `/guard-note` | Journal a `decision` · `correction` · `risk` · `note` |
|
|
279
|
+
| `/guard-report` | Full session summary for handoff or review |
|
|
280
|
+
|
|
281
|
+
Model-callable tools:
|
|
282
|
+
|
|
283
|
+
| Tool | Arguments | Notes |
|
|
284
|
+
|---|---|---|
|
|
285
|
+
| `guard_verify` | `command`, `timeout_s` (default 180, clamped 1–900) | Records `ev-NNNN`; refusal on a blocked loop |
|
|
286
|
+
| `guard_note` | `type`, `text`, optional `tags` | Forced to the `agent` trust level |
|
|
287
|
+
| `guard_contract_check` | `summary` | Deterministic keyword coverage checklist, never a proof |
|
|
288
|
+
| `guard_status` | — | Same data that feeds the widget |
|
|
289
|
+
|
|
290
|
+
### MCP tools
|
|
291
|
+
|
|
292
|
+
| Tool | Annotation class | Purpose |
|
|
293
|
+
|---|---|---|
|
|
294
|
+
| `guard_status` | local, initializing read | Session status digest |
|
|
295
|
+
| `guard_verify` | **shell execution** (destructive, open-world) | Run a command, record evidence |
|
|
296
|
+
| `guard_evidence` | read-only | Recent verification entries |
|
|
297
|
+
| `guard_contract` | local mutation | `list` · `add` · `remove` |
|
|
298
|
+
| `guard_note` | local append | Journal an entry (tagged `agent`) |
|
|
299
|
+
| `guard_journal` | read-only | Recent journal entries, optionally filtered by type |
|
|
300
|
+
| `guard_loop_check` | local, initializing read | Failing-command streaks and advice |
|
|
301
|
+
| `guard_diff_audit` | local, initializing read | Diff stats and verdict vs thresholds |
|
|
302
|
+
| `guard_preflight` | local, initializing read | Tool/version and worktree check |
|
|
303
|
+
| `guard_budget` | read-only | Context-budget watermarks |
|
|
304
|
+
| `guard_orientation` | read-only | Repo digest and conventions files |
|
|
305
|
+
|
|
306
|
+
### CLI
|
|
307
|
+
|
|
308
|
+
Every command returns `0` for OK, `1` for a triggered warning or failed
|
|
309
|
+
verification, and `2` for an input/environment error.
|
|
310
|
+
|
|
311
|
+
```sh
|
|
312
|
+
protect-context init
|
|
313
|
+
protect-context status
|
|
314
|
+
protect-context verify "pytest -q" [--timeout 180]
|
|
315
|
+
protect-context evidence [--limit 5]
|
|
316
|
+
protect-context contract list
|
|
317
|
+
protect-context contract add "Keep the public API stable"
|
|
318
|
+
protect-context contract remove ID
|
|
319
|
+
protect-context note correction "use rg, not grep" --tags search
|
|
320
|
+
protect-context journal [--limit 5] [--type decision]
|
|
321
|
+
protect-context orientation
|
|
322
|
+
protect-context loops
|
|
323
|
+
protect-context diff [--baseline REF]
|
|
324
|
+
protect-context preflight
|
|
325
|
+
protect-context budget
|
|
326
|
+
```
|
|
327
|
+
|
|
328
|
+
### Configuration
|
|
329
|
+
|
|
330
|
+
The extension seeds `.agent-guard/config.json` on first session start; `init`
|
|
331
|
+
does the same for CLI/MCP-first use. Unknown, wrongly typed, fractional, or
|
|
332
|
+
out-of-range values fall back to the frozen default.
|
|
333
|
+
|
|
334
|
+
| Key | Default | Meaning |
|
|
335
|
+
|---|---:|---|
|
|
336
|
+
| `loop_block_after` | `3` | Block the Nth identical failing command attempt |
|
|
337
|
+
| `diff_warn_lines` | `400` | Changed-line warning threshold |
|
|
338
|
+
| `diff_hard_lines` | `800` | Changed-line hard-level threshold |
|
|
339
|
+
| `diff_warn_files` | `10` | Changed-file warning threshold |
|
|
340
|
+
| `ctx_warn_pct` | `70` | First context-usage warning watermark |
|
|
341
|
+
| `brief_mode` | `"changed"` | Inject only when the brief digest changes; `"always"` injects every turn |
|
|
342
|
+
| `risk_confirm` | `true` | Ask once before a matching risky pi bash command when UI is available |
|
|
343
|
+
| `preflight_tools` | `git`, `python3`, `pip`, `node`, `npm`, `rg`, `pytest` | Executables checked by preflight |
|
|
344
|
+
|
|
345
|
+
Numeric thresholds may be set to zero; the extension records an explicit first
|
|
346
|
+
notification so a zero watermark does not silently disable alerts. Preflight
|
|
347
|
+
checks at most 20 configured tool entries. If more are configured, it lists the
|
|
348
|
+
omitted count and returns a warning instead of claiming the environment is
|
|
349
|
+
fully checked. Version probes have a two-second per-tool timeout, share a
|
|
350
|
+
15-second overall deadline, and decode at most 4 KiB of output; a missing
|
|
351
|
+
version is reported as an incomplete preflight.
|
|
352
|
+
|
|
353
|
+
The nine catastrophic patterns that trigger the pi confirmation are frozen and
|
|
354
|
+
deliberately narrow, so benign lookalikes stay silent:
|
|
355
|
+
|
|
356
|
+
`rm -rf /` · `rm -rf ~` · `git push --force` (not `--force-with-lease`) ·
|
|
357
|
+
`git reset --hard` · `mkfs … /dev/…` · `dd … of=/dev/…` ·
|
|
358
|
+
`chmod -R 777 /` · `curl … | sh` · `sudo rm`
|
|
359
|
+
|
|
360
|
+
### Environment variables
|
|
361
|
+
|
|
362
|
+
| Variable | Effect |
|
|
363
|
+
|---|---|
|
|
364
|
+
| `PC_SESSION_ID` | Names the session used for evidence and loop views, so parallel hosts do not share a view |
|
|
365
|
+
|
|
366
|
+
### Runtime store and concurrency
|
|
367
|
+
|
|
368
|
+
Runtime files stay in the frozen `.agent-guard/` layout and are gitignored:
|
|
369
|
+
|
|
370
|
+
`config.json` · `contract.json` · `journal.jsonl` · `events.jsonl` ·
|
|
371
|
+
`verify_runs.jsonl` · `state.json`
|
|
372
|
+
|
|
373
|
+
Python and TypeScript use the same atomic-directory lease at
|
|
374
|
+
`.agent-guard/.lock.d`, with an owner token, PID/hostname checks, bounded
|
|
375
|
+
waiting, and conservative stale recovery. Python also takes its legacy local
|
|
376
|
+
`fcntl.flock` inside that lease. Evidence-ID allocation, JSONL appends, and
|
|
377
|
+
contract read-modify-write operations hold the shared lease, preventing
|
|
378
|
+
duplicate IDs and lost contract updates across runtimes. JSON file replacement
|
|
379
|
+
uses unique temporary files.
|
|
380
|
+
|
|
381
|
+
The lease follows the atomic `mkdir` design used by mature lock libraries while
|
|
382
|
+
remaining dependency-free and interoperable with Python. A crashed same-host
|
|
383
|
+
owner is reclaimable after the stale interval; a stale foreign-host owner fails
|
|
384
|
+
closed because process liveness cannot be proved safely without an external
|
|
385
|
+
coordinator. Recovery retains a small identity-bound `.lock.d.stale.*`
|
|
386
|
+
directory as a durable race guard; it does not block new writers and lives
|
|
387
|
+
inside the already-ignored runtime store. Contract mutations also fail closed
|
|
388
|
+
when owner rows are malformed, preserving the original file for repair.
|
|
389
|
+
|
|
390
|
+
## The 12 failure modes and what ships
|
|
391
|
+
|
|
392
|
+
| # | Failure mode | Shipped mitigation | Enforcement |
|
|
393
|
+
|---|---|---|---|
|
|
394
|
+
| 1 | Violating instructions | Persistent contract; provenance-aware, change-triggered brief injection; seed-removal refusal at the MCP boundary | Context/advisory |
|
|
395
|
+
| 2 | Claiming success without verification | Verification ledger, evidence IDs, status/evidence views, failure digests | Recorded evidence; not semantic proof |
|
|
396
|
+
| 3 | Editing too much / scope creep | Git diff audit over tracked, staged, and bounded non-ignored untracked work; safe explicit baselines | Warn/advisory |
|
|
397
|
+
| 4 | Misunderstanding the repo | Worktree-root-aware bounded orientation digest in pi, CLI, and MCP; conventions-file discovery | Automatic context + explicit read |
|
|
398
|
+
| 5 | Plausible but subtly wrong code | Deterministic contract checklist, verification gate, test-required seed | Heuristic/advisory |
|
|
399
|
+
| 6 | Losing earlier context | Persistent journal; recent trusted decisions re-injected after change and compaction; CLI/MCP read views | Automatic context + explicit read |
|
|
400
|
+
| 7 | Repeating corrected behavior | Bounded tagged corrections; trusted corrections re-injected; model-authored entries retained for owner review | Automatic context + trust boundary |
|
|
401
|
+
| 8 | Large diffs | Configurable line/file warning and hard-level notifications, status verdict, widget | Warn/advisory |
|
|
402
|
+
| 9 | Repetitive debugging loops | Shared bash/evidence streak reconstruction; third identical failing command blocked by default in pi, CLI, and MCP | Hard block at configured threshold |
|
|
403
|
+
| 10 | Environment/tool failures | Tool/version and Git-worktree preflight with warning exit outside a repository | Diagnostic |
|
|
404
|
+
| 11 | Permission interruptions | One grouped pi confirmation for the frozen risky-command patterns; environment preflight | Interactive confirmation where UI exists |
|
|
405
|
+
| 12 | Token/API cost and latency | Bounded brief sections, journal/contract text, evidence digests, untracked reads, output previews, and context watermarks | Automatic budgeting/advisory |
|
|
406
|
+
|
|
407
|
+
"Shipped" means the mitigation is reachable and tested. It does not turn an
|
|
408
|
+
advisory signal into a security or correctness guarantee.
|
|
409
|
+
|
|
410
|
+
## How it works
|
|
411
|
+
|
|
412
|
+
### Session lifecycle
|
|
413
|
+
|
|
414
|
+
The extension is a thin event layer over the shared store. Nothing leaves your
|
|
415
|
+
machine: there are no network calls and no LLM calls in the guardrail logic.
|
|
416
|
+
|
|
417
|
+
| Event | What happens |
|
|
418
|
+
|---|---|
|
|
419
|
+
| `session_start` | Seed config if missing, scan orientation, freeze the diff baseline, start the status widget |
|
|
420
|
+
| `before_agent_start` | Build the brief; inject orientation and/or brief as a hidden message when their digests changed |
|
|
421
|
+
| `tool_call` (bash) | Match the nine risky patterns → one grouped confirm; check the loop fingerprint → block at the threshold |
|
|
422
|
+
| `tool_execution_start` / `tool_execution_end` | Record bash outcomes and verify results into the shared loop state and evidence ledger |
|
|
423
|
+
| `turn_end` | Refresh the widget: diff stats, open loops, evidence count, context percentage |
|
|
424
|
+
| `session_compact` | Re-inject trusted context so compaction cannot silently erase it |
|
|
425
|
+
| `session_shutdown` | Flush state and clear the widget |
|
|
426
|
+
|
|
427
|
+
### The brief
|
|
428
|
+
|
|
429
|
+
The brief is deliberately tiny — a persistent prompt that grows without bound is
|
|
430
|
+
its own failure mode. Within the frozen 12-line constraint cap:
|
|
431
|
+
|
|
432
|
+
1. newest **owner** constraints are selected first,
|
|
433
|
+
2. then the frozen seed constraints,
|
|
434
|
+
3. then other entries.
|
|
435
|
+
|
|
436
|
+
An agent-authored constraint therefore cannot crowd out a seed. Below the
|
|
437
|
+
contract it carries up to 3 recent trusted decisions, up to 3 trusted
|
|
438
|
+
corrections, up to 2 open loops, and the last evidence ID with its exit code,
|
|
439
|
+
duration, and a truncated command. `brief_mode: "changed"` (default) injects
|
|
440
|
+
only when the rendered digest actually changed, so a quiet turn costs nothing.
|
|
441
|
+
|
|
442
|
+
### Evidence and loop detection
|
|
443
|
+
|
|
444
|
+
`guard_verify` runs your command with the caller's privileges, spools output to
|
|
445
|
+
temporary files to bound RAM, and records one append-only entry: ID, exit code,
|
|
446
|
+
duration, command, and a digest of the output. IDs are allocated inside the
|
|
447
|
+
shared lease, so parallel pi and CLI processes never collide.
|
|
448
|
+
|
|
449
|
+
Loop detection normalizes a command (whitespace collapsed, including inside
|
|
450
|
+
quoted strings) into a fingerprint, then counts consecutive failures of that
|
|
451
|
+
fingerprint across both bash and `guard_verify`. At `loop_block_after` the
|
|
452
|
+
attempt is refused, with the prior failure count and a change-strategy nudge —
|
|
453
|
+
the single cheapest intervention in the suite.
|
|
454
|
+
|
|
455
|
+
### Scope audit
|
|
456
|
+
|
|
457
|
+
Diffs are computed with `git` porcelain/numstat over tracked, staged, and
|
|
458
|
+
bounded non-ignored untracked files, then compared against the configured line
|
|
459
|
+
and file thresholds to produce `ok`, `warn`, or `hard`. The pi extension freezes
|
|
460
|
+
its baseline at session start, so committing mid-session does not reset the
|
|
461
|
+
scope; CLI and MCP default to `HEAD` and accept an explicit baseline.
|
|
462
|
+
|
|
463
|
+
Untracked content reads are capped at 1,000 files, 1 MB per file, and 8 MB
|
|
464
|
+
total, and stop once the hard line threshold is known. A truncated scan is
|
|
465
|
+
reported as a bounded scan, promoted to at least a warning (CLI exit `1`), and
|
|
466
|
+
its count treated as a lower bound — the widget renders it as `Δ≥`.
|
|
467
|
+
|
|
468
|
+
### Trust and provenance
|
|
469
|
+
|
|
470
|
+
Direct CLI and pi slash-command contract writes are treated as owner input.
|
|
471
|
+
MCP/model journal writes are forcibly tagged `agent`: they stay inspectable
|
|
472
|
+
through journal views but are not re-injected as trusted decisions or
|
|
473
|
+
corrections. CLI and pi slash-command journal entries are trusted. Untagged
|
|
474
|
+
legacy entries are treated as trusted for backward compatibility, because the
|
|
475
|
+
frozen journal schema has no dedicated author field.
|
|
476
|
+
|
|
477
|
+
This is a provenance convention, not authentication. A model that already has
|
|
478
|
+
shell access can invoke the CLI and appear on that trusted path; use host-level
|
|
479
|
+
tool permissions when the distinction must be a security boundary.
|
|
480
|
+
|
|
481
|
+
All newly stored contract, journal, and tag text is normalized to one bounded
|
|
482
|
+
line, and legacy values are normalized again when rendered. This prevents
|
|
483
|
+
terminal-line forging and unbounded persistent prompt growth; it does not make
|
|
484
|
+
untrusted prose safe to follow.
|
|
485
|
+
|
|
486
|
+
### Context budget
|
|
487
|
+
|
|
488
|
+
Every injected and printed block has a cap: brief sections, journal and contract
|
|
489
|
+
text, evidence digests, orientation output, and previews. Context-watermark
|
|
490
|
+
notifications fire at `ctx_warn_pct` and above, and the widget always shows the
|
|
491
|
+
current percentage. The result is a guardrail layer whose own cost stays
|
|
492
|
+
constant while a session grows.
|
|
493
|
+
|
|
494
|
+
## Development and validation
|
|
495
|
+
|
|
496
|
+
```sh
|
|
497
|
+
.venv/bin/pytest -q # Python suites
|
|
498
|
+
npm run typecheck # extension types (tsc --noEmit)
|
|
499
|
+
npm test # extension unit tests (node --test)
|
|
500
|
+
.venv/bin/python -m compileall -q src # byte-compile check
|
|
501
|
+
.venv/bin/python -m build --outdir /tmp/protect-context-dist
|
|
502
|
+
```
|
|
503
|
+
|
|
504
|
+
`npm run check` runs the typecheck and the extension tests together. The
|
|
505
|
+
definition-of-done checks are run twice consecutively before release. The dated
|
|
506
|
+
audit records the observed counts, integration probes, and package smoke test
|
|
507
|
+
instead of leaving stale numbers in this README.
|
|
508
|
+
|
|
509
|
+
| Path | Contents |
|
|
510
|
+
|---|---|
|
|
511
|
+
| `src/protect_context/` | Store, contract, journal, verify, loops, diff scope, orientation, preflight, budget, report, CLI, MCP server |
|
|
512
|
+
| `extension/` | pi entry point (`index.ts`) and pi-import-free `lib/` modules |
|
|
513
|
+
| `tests/` | pytest suites, including a fastmcp in-memory client smoke over every MCP tool |
|
|
514
|
+
| `extension/test/` | `node --test` suites for fingerprinting, risk patterns, loops, brief digest, widget, git parsing, config |
|
|
515
|
+
| `SPEC.md` | Frozen v1.0 contract — structure, defaults, and definition of done |
|
|
516
|
+
|
|
517
|
+
## Troubleshooting
|
|
518
|
+
|
|
519
|
+
| Symptom | Likely cause | Fix |
|
|
520
|
+
|---|---|---|
|
|
521
|
+
| No brief appears in pi | Digest unchanged (`brief_mode: "changed"`) and nothing new to say | Expected on quiet turns; set `brief_mode: "always"` to see it every turn |
|
|
522
|
+
| `Δ?` in the widget | Not a Git worktree, so no diff baseline | Run inside a repository, or use the CLI with an explicit `--baseline` |
|
|
523
|
+
| `Δ≥` in the widget | Bounded untracked scan hit a cap | Treat the count as a lower bound; narrow the scan or review scope manually |
|
|
524
|
+
| Loop never blocks | Commands differ (paths, flags) so fingerprints differ | Compare with `loops` / `guard_loop_check`; fingerprints intentionally ignore whitespace only |
|
|
525
|
+
| `PC_SESSION_ID` changes nothing in evidence | It scopes ledger *views*, not `state.json` | Expected: state is project-global by design |
|
|
526
|
+
| MCP tool missing in host | Server not started with the venv interpreter | Point `command` at `.venv/bin/python` and pass `-m protect_context.mcp_server` |
|
|
527
|
+
| Extension does not load | Node older than 22.19 or pi not restarted | Check `pi list`, then restart; use `pi -ne` to start without extensions |
|
|
528
|
+
| Contract edit rejected over MCP | Removing a frozen seed constraint | Seeds are protected; use the CLI or a pi slash command as the owner |
|
|
529
|
+
|
|
530
|
+
## Limitations and security boundary
|
|
531
|
+
|
|
532
|
+
#### Shell execution
|
|
533
|
+
|
|
534
|
+
- `guard_verify` deliberately invokes a shell with the caller's privileges. It
|
|
535
|
+
can modify files, access the network, or disclose data. The pi layer asks for
|
|
536
|
+
confirmation only when one of the frozen regex patterns matches; the MCP layer
|
|
537
|
+
relies on host approval. Neither is a shell parser or a sandbox.
|
|
538
|
+
- MCP annotations are untrusted hints. A client may ignore them. Do not expose
|
|
539
|
+
`guard_verify` to an untrusted model without a real host sandbox/approval
|
|
540
|
+
policy.
|
|
541
|
+
|
|
542
|
+
#### Evidence
|
|
543
|
+
|
|
544
|
+
- An evidence record proves only that one command returned one exit code. It is
|
|
545
|
+
not cryptographically bound to a commit/worktree, has no freshness policy, and
|
|
546
|
+
does not prove the claimed behavior.
|
|
547
|
+
|
|
548
|
+
#### Scope
|
|
549
|
+
|
|
550
|
+
- The pi extension freezes its diff baseline at session start, so committing
|
|
551
|
+
mid-session does not reset its scope. CLI/MCP audits default to current
|
|
552
|
+
`HEAD`; pass them an explicit baseline for cross-commit scope. Binary files
|
|
553
|
+
count as files but zero lines.
|
|
554
|
+
- Untracked-file content reads are capped at 1,000 files, 1 MB per file, and
|
|
555
|
+
8 MB total, and stop once the hard line threshold is known. Output explicitly
|
|
556
|
+
reports a bounded scan, promotes it to at least a warning/CLI exit 1, and
|
|
557
|
+
treats the truncated count as a lower bound.
|
|
558
|
+
|
|
559
|
+
#### Determinism
|
|
560
|
+
|
|
561
|
+
- The frozen brief carries at most 12 constraints. Overflow is visible, and
|
|
562
|
+
owner constraints are prioritized, but hidden constraints are not enforced by
|
|
563
|
+
context injection.
|
|
564
|
+
- Frozen fingerprint normalization collapses whitespace everywhere, including
|
|
565
|
+
inside quoted shell strings. Semantically different commands can therefore
|
|
566
|
+
share a loop fingerprint.
|
|
567
|
+
- The deterministic contract checker is keyword coverage, not program analysis.
|
|
568
|
+
Treat every `addressed` result as a review prompt, not proof.
|
|
569
|
+
|
|
570
|
+
#### Store
|
|
571
|
+
|
|
572
|
+
- `state.json` is project-global. Atomic replacement prevents torn JSON, but
|
|
573
|
+
simultaneous sessions can still overwrite notification/session state; use
|
|
574
|
+
`PC_SESSION_ID` to separate ledger views, not state files.
|
|
575
|
+
- Commands and the last 2,000 output characters are stored verbatim. There is
|
|
576
|
+
no automatic secret detector or redactor; never put credentials in commands or
|
|
577
|
+
verification output.
|
|
578
|
+
- JSONL ledgers have no automatic retention or rotation. Output views stay
|
|
579
|
+
bounded, but long-lived stores grow on disk and full session reconstruction
|
|
580
|
+
becomes progressively more expensive; archive runtime state deliberately.
|
|
581
|
+
- Python verification bounds RAM by spooling output to temporary files, but a
|
|
582
|
+
very noisy command can consume temporary disk until it exits. On Windows,
|
|
583
|
+
killing the direct process cannot guarantee that every descendant exits.
|
|
584
|
+
|
|
585
|
+
## Design sources
|
|
586
|
+
|
|
587
|
+
The implementation was checked against primary or professional sources:
|
|
588
|
+
|
|
589
|
+
- Git's stable porcelain/other-file interfaces for non-ignored untracked
|
|
590
|
+
enumeration: [git-status](https://git-scm.com/docs/git-status) and
|
|
591
|
+
[git-ls-files](https://git-scm.com/docs/git-ls-files).
|
|
592
|
+
- Pi's documented lifecycle, tool, context, and UI APIs:
|
|
593
|
+
[Pi extension documentation](https://pi.dev/docs/latest/extensions).
|
|
594
|
+
- The mature `proper-lockfile` design, which uses atomic `mkdir` rather than
|
|
595
|
+
`O_EXCL`: [moxystudio/node-proper-lockfile](https://github.com/moxystudio/node-proper-lockfile).
|
|
596
|
+
The package itself was not added because the frozen extension requirement is
|
|
597
|
+
zero runtime dependencies and the lock must interoperate with Python.
|
|
598
|
+
- Operational-safety evidence motivating explicit constraints, failure
|
|
599
|
+
transparency, and safe-halt behavior: [What Breaks When LLMs Code?](https://arxiv.org/abs/2605.30777)
|
|
600
|
+
(ASE 2026), plus evidence-conditioned execution results in
|
|
601
|
+
[Preventing Premature Commitment in Coding Agents](https://arxiv.org/abs/2607.28815).
|
|
602
|
+
- MCP's own warning that annotations are risk vocabulary rather than
|
|
603
|
+
enforcement: [Tool Annotations as Risk Vocabulary](https://blog.modelcontextprotocol.io/posts/2026-03-16-tool-annotations/).
|
|
604
|
+
|
|
605
|
+
## Non-goals
|
|
606
|
+
|
|
607
|
+
No network or LLM calls are made by the guardrail logic itself. It is not a
|
|
608
|
+
sandbox, policy engine, auto-fixer, secret manager, or replacement for pi/MCP
|
|
609
|
+
host permissions. It complements those controls with durable context, evidence,
|
|
610
|
+
telemetry, and narrowly scoped blocking.
|
|
611
|
+
|
|
612
|
+
## License
|
|
613
|
+
|
|
614
|
+
MIT — see [`LICENSE`](./LICENSE). Copyright (c) 2026 XJTLUmedia.
|