Architecture
Principles
-
Never patch upstream security code. The permission engine (
@gotgenes/pi-permission-system) is consumed unmodified through its public extension points. Upstream fixes arrive by bumping the pinned version, never by carrying local patches. -
Simple checks are simple code. Anything a pattern or a file read can decide is decided deterministically, in about a millisecond. A model is consulted only for the genuinely ambiguous — and only about danger.
-
Ship policy in the package, not on disk. Rules, guidance, and themes live inside
@gadhs/piand update with it. The only things written to a user’s machine are a tiny routing config (seeded once), the marker-managed agent definitions pi-agents seeds (pi cannot ship agents in a package), and files the user asks for. -
All model calls go through pi’s composed provider, so ADC/Vertex models work everywhere a model is needed — including the judge.
-
"Verified" means observed. Every enforcement claim in this repo is backed by a live run showing the mechanism firing, not by reading configuration.
What is in the box
@gadhs/pi (the one install)
├── @gotgenes/pi-permission-system vendored — deterministic permission engine
├── @gotgenes/pi-subagents vendored — helper agents
├── pi-web-access vendored — web search / fetch
├── @gadhs/pi-vertex ours — every publisher on Vertex AI
│ Claude · Gemini · MaaS — per-model regions · ADC auth · rotation pickup · turn-preserving retry
├── @gadhs/pi-modes ours — the policy layer
│ modes · rules · judge · subagent gate · traces · status
├── @gadhs/pi-workflow ours — delivery-workflow enforcement
│ commit guards · cold-reader review · SPDX · setup drift (every mode, on the session's workspace)
├── @gadhs/pi-ssh ours — pi over SSH
│ the remote's files, shell and searches · resilient link · /ssh
├── @gadhs/pi-shellcheck ours — the shell guard
│ two delete rules · pinned shellcheck · block / warn / ignore
├── @gadhs/pi-guidance ours — agency standards content
│ global digest · language profiles · composition seam · /gadhs-init
├── @gadhs/pi-agents ours — subagent definitions, seeded
│ Explore · Research · general-purpose · managed-file semantics
└── @gadhs/pi-remote ours — pivot's box side: /remote-control
relay link · Noise via @gadhs/pivot-wire · virtual RPC host · the ask broker's answerer
pi-modes and pi-workflow both read commands through @gadhs/pi-bash, a
library of ours with no extension of its own: one tree-sitter bash parser, the
structure and line views, and one wrapper table (#206).
The meta package ships each of its eleven extensions as two built files
(#801; tools/lib/bundle.mjs, from packages/pi/extensions.json), and the
four Orchard TUI themes itself. Order matters: pi-modes loads first so its
first-run seeding happens before the permission system reads its config.
A shim and a bundle
| File | What it is |
|---|---|
|
About twenty generated lines, and the file |
|
Every module the extension runs, ours and third-party, as one file that
Node imports as it is: no transpile, no cache entry. It exports one
function and imports nothing but two Node modules; pi’s modules arrive as
an argument. A bundle that named them would fail Node’s import and be
transpiled whole. The hash is of its content, so a |
|
The files a module reads beside itself ( |
Why: a start used to read about 1,500 files, every .ts source an
extension reached, its transpile-cache entry, and each dependency file.
On Windows, Defender scans a file on its first read after it is written
or after Defender’s configuration changes, about 10 ms a file and mostly
per file rather than per byte (the same 4.8 MB cost 0.25 s as one file and
7.3 s as 500), so such a start took 19 to 20 s. Bundled, a start reads
the eleven shims and eleven bundles.
Three packages are loaded as files rather than modules, so they cannot go
inside a bundle: web-tree-sitter and tree-sitter-bash (their wasm) and
@gadhs/pivot-wire. The build copies the few files of each that are used
to dist/node_modules/, where a require by name finds them from a shim,
from a bundle, and from a module’s place under dist/assets/ (#835). So
@gadhs/pi has no dependencies: an install is that one package, where it
was 246, and nothing is compiled or downloaded beside it.
Two consequences:
-
Upstream source is bundled as published, apart from that location rewrite; nothing in it is patched.
-
Third-party code inside a bundle is at the version
pnpm-lock.yamlheld when the release was built. Before, npm resolved each range on the day of the install; now a dependency’s fix reaches users with our next release.dist/THIRD-PARTY-NOTICES.txtnames each bundled package with its licence, and the build refuses a licence it does not list.
Inside pi-modes
packages/pi-modes/index.ts is a composition root, not the code. It
creates one mode controller and wires every module against it, in one
visible order: memory, subagents, plan tools, the entry renderers
(trace-renderers.ts), the session hooks (session-wiring.ts, which also
builds the bridge object), then the tools and commands: ask, count,
images, monitors, jobs, the mode commands, messages and the hub
(command-wiring.ts, hub-wiring.ts and their siblings).
| Module | Owns |
|---|---|
|
The session’s mode state - mode id, tool names, applied-model ledger, plan
entry, status counters, last context, last-seen model - behind methods.
|
|
The governed memory store: load/save/archive, |
|
Spawn tracking, output contracts and their enforcement on foreground
results and fetched background reports, sidecar collection, the |
|
|
|
The advisory judge: authorizer registration, per-ask normalisation and stamping, status counters, the adjudication trace, the warm-up. |
The session hooks are registered in one place, registerSessionHooks in
session-wiring.ts, so their order is one visible list. At session start:
the model roles resolve (before the mode applies its model, and before
pi-workflow and pi-agents read the bridge), plan review is cleared,
contracts and memory load, the controller restores mode and resumed model
(reading the resumed model before any apply), the judge captures its
registry and warms, the startup announcement, then the startup notices,
the scratch root’s exclude line, the model-roles notice and the context
budget. Modules register their own tools, commands and
tool-execution hooks, which are order-independent. The pure logic each
module wires lives beside it (plan-mode.ts, memory.ts,
agent-contract.ts, yield-tool.ts, authorize.ts, authorize-paths.ts, judge.ts,
review-pane.ts) and is tested without pi.
The life of one action
Every tool call the agent attempts flows through the same pipeline. Each
stage either decides or passes the question down; the first decision wins.
The authorizer’s stages are the rows of GATE_STAGES in
packages/pi-modes/authorize.ts, by the names below; a test holds this list
to that table.
agent wants to run something
│
├─ workflow guards (tool-call seam, every mode)
│ commit format · --no-verify · main-branch · SPDX · debt markers ·
│ reflection pause [block, or FIX the input in place]
│
├─ permission engine (vendored, deterministic)
│ decomposes bash, resolves paths, applies the seeded routing
│
└─ "ask" → our authorizer chain link:
1. delegation gate may this mode spawn that agent? (list lookup)
2. plan draft the one file plan mode may write
3. rule deny a deny rule on any part of the line → refused
4. registry an install of a name no registry has → refused
5. pending a step waiting on the human: their reply decides
6. high consequence operator-named → ask the human (~1 ms)
7. rule allow one command an allow rule names → allow (~1 ms)
8. plain line every command cleared → allow (~1 ms)
9. scratch write really under .pi/scratch/ → allow
10. workspace write really inside the repo → allow
11. workspace read really inside the repo → allow (~1 ms)
12. outside write really outside the repo and temp → refused
13. no judge the mode runs none → ask the human
14. denial threshold too many refusals → ask the human
15. judge one question: is this dangerous? (~5 s)
7 to 11 stand back, for the judge, when the safety valve names the
action, it carries a secret-shaped value, or a file tool names a
credential-shaped file
└─ anything deferred → /pending in auto and plan (pendingAsks:
"queue"), else the human's normal permission prompt
Two details that took real debugging to learn, recorded so nobody relearns them:
-
The permission engine matches rules against decomposed pieces of a bash command, but hands the authorizer the full command as evidence: an ask’s
details.commandis the matched unit (echo xforecho x | sh), and the whole line travels inpayload.evidence[]under the labelfull command. Rules and the judge here use both, so a pipeline cannot hide its dangerous half — and a rule pattern containing a pipe can never fire, because no decomposed unit contains one. -
write/editasks carry their destination in a different field thanreadasks; the extension normalises this before anything matches.
The bridge between pi-modes and pi-workflow
ADR-004 forbids the two packages importing each other: pi-workflow’s
guards must decide correctly with `pi-modes absent, and pi-modes must not
depend on a package whose release cadence it does not control. What they
share instead is a small object pi-modes publishes at
Symbol.for("gadhs:pi-modes-runtime") on globalThis at session start and
withdraws at shutdown; pi-workflow looks it up per call and falls back to a
no-op when it is absent (runtime-bridge.ts, modesBridge()).
What crosses it, and in which direction (every member past the first four
is optional, so an older pi-modes simply lacks it):
| Member | Direction | Purpose |
|---|---|---|
|
modes → workflow |
Annotates traces and logs with the current mode. Never a decision input: the guards run identically in every mode. |
|
modes → workflow |
One diagnostics stream for both packages (diagnostics.adoc#diagnostics), so a guard’s record and the mode’s sit in one file. |
|
modes → workflow |
A guard’s deny or defer becomes a status-line count and an inline trace; the decision was already made before the call. |
|
modes → workflow |
Where the plan draft lives, so the
cold review reads the same file |
|
modes → workflow |
The sha256 of the draft you approved, and when, so a commit of those exact bytes is not reviewed a second time. |
|
modes → workflow |
When the session last entered plan mode — part of the plan review’s round key, so leaving and re-entering starts a new plan and a fresh round. |
|
modes → workflow |
The session’s thinking level, which the cold reviewer thinks at (clamped to its model). |
|
modes → workflow |
Whether the plan draft was last
written before this plan mode began (#659): an earlier plan’s, which
|
|
modes → workflow |
A reviewer role’s model for this user (#715): the configured one first, then pi-modes' candidates through whichever sources the user can reach. |
|
workflow → modes |
The one member that runs the
other way: the outcome of each plan review (verdict, reviewer, duration,
the reviewer’s words, the exact text reviewed), so the approval pane can
show it beside the plan. Matched by the plan text on the |
The workspace slot sits beside the bridge (#489, ADR-006): a second
globalThis key, Symbol.for("gadhs:workspace"), where a remote workspace
(pi over SSH, #488) publishes itself. It is no bridge member, because both
packages reach it through the library @gadhs/pi-workspace, which each
depends on by name, as both depend on @gadhs/pi-bash.
workspaceFor(cwd) gives the published workspace when cwd is under it,
and the local one otherwise. So a guard reads the workspace from whichever
host holds it, and with nothing published it behaves exactly as it does
today.
Two properties the design leans on. Decisions never cross it: everything
above is observation or location, so a missing or stale bridge cannot weaken
a commit guard — standalone pi-workflow (no pi-modes installed) blocks
exactly what the bundled one blocks, pinned in
packages/pi-workflow/test/standalone.test.ts. The one exception is the plan
review: it reads the draft at planDraftPath, so with no bridge it has no
plan to read and is skipped (plan_review.skipped).
It is withdrawn at shutdown, by its owner only: a reinitialised pi-modes
republishes fresh callbacks, and a withdrawn bridge leaves the no-op
fallback rather than a stale closure over a dead session. An instance
publishes only into an empty slot and withdraws only the bridge it
published (#228). pi-subagents runs every extension again for each child,
in the same process, and shuts the child down when it ends. A child that
published replaced its parent’s bridge while it ran, and deleted it when it
ended, so every later plan review in the parent was skipped. pi shuts the
old instance down before it rebuilds on reload, /new, resume or fork, so
the slot is empty whenever a top-level session starts.
Observability
Everything that decides, logs: inline traces in the transcript (who blocked
what, and why), a status line (mode, enforcement, verdict counts, running
helpers), a review log readable with node tools/task.mjs verdicts --why,
and an always-on diagnostics stream (~/.pi/agent/gadhs-diagnostics/,
read with /diag; diagnostics.adoc#diagnostics) for lifecycle and run questions.
One principle binds every layer that rewrites an action rather than adjudicating it: the rewrite must be declared to downstream reviewers as a labelled fact. The commit guard’s mechanically appended trailer is announced to the reflection reviewer as tooling; an undeclared mutation is indistinguishable from scope drift, and a reviewer that flags it is right.
Key decisions
-
ADR-001 — TypeScript toolchain (pnpm, Biome, vitest, Node task runner).
-
ADR-002 — downstream-in-spirit of claude-quickstart: same standards, native pi mechanisms instead of copied files and shell hooks.
-
ADR-003 — agent configuration lives in
@gadhs/pi; claude-quickstart sunsets as the agent vehicle and keeps Rust project bootstrapping. Amends ADR-002’s sync-cutover direction. -
ADR-004 — package boundaries: policy (
pi-modes), workflow enforcement (pi-workflow), content (pi-guidance,pi-agents) and the remote client’s box side (pi-remote) are separate packages with separate review postures; the eval harness stops shipping. Amended for #206: logic two enforcement packages share becomes a library (pi-bash) rather than copies held equal by test. -
ADR-005 — one first-party Vertex provider for every publisher, delegating the wire to code that already speaks it.
-
ADR-006 — remote execution runs the agent locally and the workspace over system SSH with a remote helper. One
Workspaceinterface (pi-workspace, a library) is the seam every workspace-touching file moves onto, andpi-ssh(an extension) is the SSH side (#488).
Rejected alternatives
-
A Defender exclusion per Windows box instead of bundling (#801). It removes the same cost (a tree read in 4 s where it took 125 to 186 s), but it is an administrator’s setting on every box and stops Defender scanning code that pi runs.
-
@gotgenes/pi-subagents-worktrees— a worktree’d child loses the whole permission stack, and its failure path bypasses commit hooks. Revisit only alongside a writing subagent and upstream fixes.