pi-coding-agent
Operate the Pi coding agent CLI — install, extensions, Jev.
- License 许可
- MIT
- 最近更新
- 2026-11-14
- Stars
- ★ 4
- Forks
- 1
01 前言 Front Matter
- name
- pi-coding-agent
- version
- 1.0.0
- description
- Operate the Pi coding agent CLI — install, extensions, Jev.
02 资源文件 3
- 参考文档references/extension-tool-api.md4.2 KB
- 参考文档references/mcp-server-interpreter-tls.md5.1 KB
- 脚本scripts/pi-skills-diagnostics.mjs3.5 KB
03 SKILL.md 正文
Pi Coding Agent
The coding-agent harness the fleet owner wants for steadfaste (replacing hermes).
@earendil-works/pi-coding-agent — a MANAGED install, not an npm global (see
Install below). The reference for pi + Jev
integration is github.com/disler/ten-levels-of-jev (30 tested Jev use cases in
10 levels; levels 6–10 put Jev inside pi).
Install — a MANAGED install, NOT an npm global (corrected 2026-10-02)
Pi installs itself into its own agent directory and pins each release; there is no
npm install -g. Measured on a live host:
~/.pi/agent/bin/pi launcher (sh): reads the version, execs the release
~/.pi/agent/install/current-version the authoritative version string (1.0.0 here)
~/.pi/agent/install/managed-install.json {kind: pi-managed-install, layout: releases-v1,
entrypoint: symlink -> <user bin dir>/pi}
~/.pi/agent/install/releases/<v>/node_modules/.bin/pi the real executable
~/.local/share/pi-node/current/bin Node.js that PI installs and manages
Consequences that cost time and must not be re-learned:
command -v piis NOT a reliable probe. The entrypoint is a symlink into the user's bin dir (a linuxbrewbin/on one measured host). When that dir is not on PATH,pilooks missing to every caller while being installed and working. Invoke the launcher directly —~/.pi/agent/bin/pi— or read~/.pi/agent/install/current-versionwithout executing anything.- Pi's Node is deliberately NOT on shell profiles. The launcher puts
~/.local/share/pi-node/current/binon PATH for itself and its children, sonodeandnpmresolve correctly inside pi and nowhere else. Do not "fix" that by exporting it globally. - Extension type defs live in the release, not an npm root:
V=$(cat ~/.pi/agent/install/current-version)then$HOME/.pi/agent/install/releases/$V/node_modules/@earendil-works/pi-coding-agent/dist/... - Never infer the version from a doc or a package name — read
current-version(or the launcher's--version). A harness registry claiming a shipped version can be stale on any given host — MEASURE it: one host read 1.2.0 (with both 1.1.0 and 1.2.0 present underreleases/) while the registry's ownwhy:prose still described 1.0.0. Read the type defs from the release you just measured, never from the prose about it. - Verify:
~/.pi/agent/bin/pi --versionand--help(read/bash/edit/write tools, plus thepi install/remove/list/config/authextension commands).
Core
- Built-in tools: read, bash, edit, write.
pi install <source>/pi remove <source>manage extension sources;pi listshows installed extensions.- An extension is loaded as
pi -e extensions/<name>.ts --tools read,bash,edit,write[,<jev tools>]— the--toolsallowlist is explicit; only listed tools are available.
stdout shape non-interactive — MEASURED, do not guess
A non-interactive pi turn writes EXACTLY the assistant's final answer to stdout and nothing else — verified with a plain prompt and with a prompt that used the bash tool:
$ ~/.pi/agent/bin/pi --model <m> "List three fruits, one per line, numbered 1. 2. 3."
1. Apple
2. Banana
3. Cherry
- Chatter goes to stderr and pi's own log, never to stdout. So a wrapper that uses stdout verbatim is CORRECT, and one that takes "the last line" only TRUNCATES every multi-line answer down to its final line — a reply that arrives but is not complete. Verify stdout and stderr separately before choosing any output-shaping mode.
- A fresh
--session-idprints a benign stderr warning —Warning: No project session found with id '<id>'; creating a new session with that id.— and still exits 0. That is how a per-chat session gets created, not a failure to report. - Call the launcher by absolute path from a service or wrapper.
~/.pi/agent/bin/piis the launcher; thepisymlink in a user bin dir is not on a service PATH. Wrappers pass an ARGV LIST rather than a shell line, so nothing expands~/$HOME— a relative or guessed path becomes a silent per-message no-op. Pin the session identity too (e.g. aFLEET_SESSION_KEY): a harness started outside a git repo cannot derive repo/branch and every chat otherwise collapses onto ONE session.
Driving pi from another process — control calls go over RPC, never a prompt
A wrapper that only sends prompts is missing half the interface, and the missing half
fails in ways that read as pi being broken (working adapter to copy:
ops/scripts/fleet_gateway/pi_control.py in steadfaste-fleet).
- A built-in slash command sent as a prompt is a NO-OP.
/compact,/model,/new,/restart,/settingsare handled only in the interactive/RPC surfaces; as a prompt they become conversation (a forwarded/newis answered as prose while every bit of context stays). Session and state operations go over RPC mode:pi --mode rpctakes one JSON record per line on stdin ({"type":"get_state"},{"type":"compact"},{"type":"set_model", …}) and answers with aresponserecord on stdout — correlate by theidyou sent, never by response order. - Pass
--no-mcpfor a control call. pi connects its MCP servers at RPC startup, and with them enabled the control call sat ALIVE and SILENT (no stdout, no stderr) for the whole deadline on ~40% of runs; the same call answered 8/8 in ~1.2 s with--no-mcp. A control call uses no MCP tool, so those servers are pure risk there. - Watch the process EXIT as well as EOF. EOF is not the only end of an answer:
pi's MCP children inherit its stdio, so a lingering grandchild holds the write end of
the pipe open — no data, no EOF — and a reader waiting only for EOF blocks for its
full deadline. Start pi in its own process group (
start_new_session=True) and kill the GROUP on timeout, so a wedged control call does not also leak children. compactnever answers for a session whose transcript does not exist yet (45 s+, repeated), whileget_stateon the same id answers in ~1.2 s and creates it. Ask for the state first and answer "no conversation yet" — a chat that has just started a fresh session is exactly this case, and it is the common one.- Give a check three outcomes, not two:
0ok ·1a NEGATIVE answer ·3could not verify.--offline --list-models <pattern>printsNo models matching "x"and still exits 0, so a verdict read off the exit code is wrong in both directions — decide from the OUTPUT, and make "pi cannot be run at all" its own outcome rather than a failed check. The same split lets a caller refuse a bad model name instead of breaking every later turn with it.
Extension API (the Jev-hook surface)
Read the installed type defs before writing a hook — never infer the signature.
V=$(cat ~/.pi/agent/install/current-version)
P="$HOME/.pi/agent/install/releases/$V/node_modules/@earendil-works/pi-coding-agent"
sed -n '1,60p' "$P"/dist/core/extensions/types.d.ts # + grep the event interfaces
grep -n -A20 'registerTool' "$P"/dist/core/extensions/types.d.ts # the tool registration contract
grep -n -A8 'interface ToolDefinition' "$P"/dist/core/extensions/types.d.ts
# AgentToolResult is NOT in this package — it comes from the agent core:
grep -rn -A12 'interface AgentToolResult' "$P"/../pi-agent-core/dist/types.d.ts
Read ToolDefinition FIRST. It is the contract the extension must satisfy, and a
doc or an older example that disagrees with it is what breaks the harness silently.
- Hooks —
pi.on("tool_call" | "tool_result" | "turn_end" | "before_agent_start" | "session_before_compact", fn). Atool_callhook canreturn { block: true, reason }to stop a tool call before it runs; the agent sees only the reason + a notice that the block is final. - The handler's FIRST parameter is the EVENT, not a ctx:
ExtensionHandler<E> = (event: E, ctx: ExtensionContext) => R. Readingctx.<thing>off that first parameter yieldsundefined. - Injection is the RETURN VALUE.
before_agent_startreturnsBeforeAgentStartEventResult({ message?, systemPrompt? }); there is noctx.addSystemPrompt(). To add context, return an augmentedsystemPrompt(or amessage). - Event payloads carry the data:
turn_end→{ turnIndex, message, toolResults, entries, outcome };before_agent_start→{ prompt, images, systemPrompt, systemPromptOptions }. Derive what you need from the event. - Tools —
pi.registerTool({ name, label, description, parameters, execute }).execute(toolCallId, params, signal?, onUpdate?)returns anAgentToolResult:{ content: [{ type: "text", text }], details }.runis the pi 0.87.1 shape and is silently ignored on 1.0.0 — every call then fails withdefinition.execute is not a function, which an agent reads as "memory is broken" when the store is fine and the tool WIRING is not.parametersmust be an object schema ({ type: "object", properties, required }); a bare param→schema map ({peer:{type:"string"}}) is not validatable, so a correctexecutestill fails. Build the schema AND the argument extraction from ONE properties map so the two cannot drift apart. Tool descriptions carry the question schema. - Verify a hook fires AND does its job — a stderr marker in the handler proves the hook ran, not that the effect landed. Assert the effect (did the injected text appear? did the row have content?).
- Compaction —
.pi/settings.jsonsetscompaction.keepRecentTokenslow so compaction has material;ctx.compact()wraps pi's compaction;ctx.getContextUsage()feeds the numbers.
Exact type shapes, the probe commands, and the executable-guard recipe:
references/extension-tool-api.md.
- Side channel — report every decision on stderr as
JEV_EVENTlines (and as session entries) so a run is auditable line-by-line (tool call, hook decision, Jev call, model, cost, context).
Fleet context (memory + session)
Pi >= 0.99 / 1.0 has an MCP client (pi 1.0.0, reproduced: pi mcp list reports
fleet-context: connected, N tools): it reads
mcpServers from ~/.pi/agent/mcp.json (user scope) and .pi/mcp.json (trusted
projects only), the same shape as Claude Code. Governance is therefore an MCP
registration — never hand-write a lock:
bash ~/steadfaste-fleet/ops/scripts/install/install-pi-mcp.sh # loop-governance, tasks, executor, agent-bus, fleet-context
pi mcp list # expect 5 servers, state "connected"
Verify a host VERSION-AWARE — never by assuming the route.
bash ~/steadfaste-fleet/ops/scripts/manage/audit-pi-integration.sh reports PASS/FAIL
per layer (MCP servers, skills, extension, governance gate, agent.env),
reads the installed version from the Pi install itself, and checks the REGISTERED
skills path and its count instead of a hardcoded list. Auditing
with the MCP checklist on a Pi that has no MCP client reports FAIL for something
that route cannot deliver — the failure is in the checklist, not the host. A server
missing from mcp.json on a non-orchestrator host is usually a DEPLOY-SCOPE bug
(a server registered register_orch ships only to orchestrators), not a broken
installer: install-pi-mcp.sh warns and registers the rest, so 3-of-4 looks normal.
The SKILLS half — the adapter must be RUN, not merely deployed
Pi advertises each skill's NAME + DESCRIPTION at startup and loads the body on demand.
Exposure is ALL skills, from the fleet-owned published tree — NOT a curated subset.
The manifest no longer governs what a coding agent can read; it stays the record of the
ritual skills Hermes must load before a write. Do not "restore" a curated set from
skills.yaml#always — a subset here is exactly what was removed, and the operator asked for
every harness to see every skill.
How Pi enumerates — read from its own loader (dist/core/skills.js), never assumed.
Re-read it when the version moves:
Resolve the loader from the INSTALLED release, never a hardcoded version path. Pi
updates itself — a current-version observed moving 1.3.0 → 1.4.0 mid-session — so a
probe that imports releases/<old>/…/dist/core/skills.js silently measures the OLD
loader and reports rules that no longer apply. Read
~/.pi/agent/install/current-version and import
releases/$V/node_modules/@earendil-works/pi-coding-agent/dist/core/skills.js. Before
blaming a version move for changed behaviour, diff the two releases' skills.js:
byte-identical files mean the enumeration rules did not move and the difference is
somewhere else.
Reading the loader tells you the RULES; running it tells you what an agent actually
gets. scripts/pi-skills-diagnostics.mjs imports loadSkills from the installed
release and prints, for a tree you name: the skill count, every diagnostic grouped by
message, and each name collision with its winner and loser. Point it at
~/.agents/skills to reproduce a host's report verbatim (node <skill>/scripts/pi-skills-diagnostics.mjs),
or at an extracted older revision to prove a fix changed the outcome — same tool, two
trees. It exits 1 when diagnostics exist, so it is usable as a gate.
Diagnostics are WARNINGS, not refusals: a refused skill shows up as description is required (or a YAML parse message) and is simply absent from the loaded set, so count
the loaded skills too — a tree whose file count dropped is how a silent refusal
becomes visible.
- It FOLLOWS symlinks. A symlinked ROOT is read, and a symlinked skill directory is
recursed into (
entry.isSymbolicLink()→statSync()→ recurse into it). Pointingskillsat a symlinked published tree works; a per-skill link farm is unnecessary. - A directory containing
SKILL.mdIS one skill and recursion STOPS there. Never put aSKILL.mdat the root of a tree you want enumerated — the rest of the tree becomes invisible. - It honours
.gitignore/.ignore/.fdignoreAT THE SKILLS ROOT (ig.ignores(relPath)). A stray ignore file silently hides skills while the registration looks perfect, which is why a--checkmust assert the COUNT the agent can see, never merely that the path is written intosettings.json. - Direct
*.mdchildren load ONLY at the ROOT.includeRootFilesis true only for the top-level call, so aDESCRIPTION.mdsitting beside a category's skill directories is NOT a skill — a false lead when chasing a name collision. Only a*.mddirectly in the registered tree is read as a skill. - Dot-entries are SKIPPED (
entry.name.startsWith(".")), so a.archive/of retired skills inside the tree is never enumerated and aSKILL.mdsitting there is NOT the collision it looks like. Before "cleaning up" a dot-directory to silence a loader diagnostic, check whether the loader can see it at all — for Pi it cannot. - A
descriptionis REQUIRED, or the file is not a skill at all.loadSkillFromFilereturnsskill: nullwhen the description is absent or blank, so the name never enters the index and the body is unreachable — the file is REFUSED, not merely unindexed. This is why a deprecated redirect stub with no description is dead weight: its "load X instead" text reaches nobody. Andnamefalls back to the PARENT DIRECTORY name when frontmatter omits it, which is how a directory-derived name silently collides with a declared one. - Symlink visibility is PER-READER — never generalise it from one probe. Measured on a single
tree: a symlinked ROOT is visible to
pathlib.rglob/os.walkbut INVISIBLE to plainfind(no-L), which reports zero; a per-skill symlink FARM is invisible to plainrglob/os.walk(onlyfollowlinks=Truesees it). Pi happens to follow both, so its loader is the authority for Pi — read it, and assert the COUNT the agent can see rather than trusting a mode that worked for a different reader. - The cross-client standard path is
~/.agents/skills, read natively by Codex, Cursor, Copilot CLI, OpenCode and Antigravity. A harness that reads only a private path (~/.pi/agent/settings.json,~/.claude/skills) needs a pointer to it.
bash ~/steadfaste-fleet/ops/scripts/install/install-pi-integration.sh # wire it
bash ~/steadfaste-fleet/ops/scripts/install/install-pi-integration.sh --check # rc 0 ONLY if Pi can see EVERY skill
bash ~/steadfaste-fleet/ops/scripts/manage/audit-pi-integration.sh # per-layer audit
It writes ~/.pi/agent/settings.json — "extensions": [<fleet-context.ts>, <fleet-governance.ts>]
and "skills": ["~/.agents/skills"] — and RETIRES a pre-existing ~/.pi/agent/cortex-skills
link farm when one is found: a stale farm keeps Pi loading a curated subset beside the whole
tree. Idempotent, and it preserves the user's other keys. It no longer reads skills.yaml at
all — the manifest is fleet-owned at the REPO ROOT (skills.yaml, synced to
~/.steadfaste-fleet/skills.yaml by fleet-update.sh) and is the record of Hermes's ritual set,
not the source of a coding agent's exposure.
Drive it with fleet pi instead of remembering script names (a thin driver over the same
scripts — repo-then-deployed resolution, the owner's rc passed through unchanged):
fleet pi install # user scope: MCP servers + both extensions + the published skills tree
fleet pi check # installer --check (registration AND visible count) + the per-layer audit
fleet pi skills # what Pi is pointed at, then the delegated visibility verdict
fleet harness install pi --dir <project> is the PROJECT-scope command; fleet pi is the
HOST-scope one (every Pi project on the machine).
- Registering is not executing. A deploy that COPIES an installer into
~/.steadfaste-fleet/scripts/has wired nothing, so a host with Pi installed can sit unwired with no signal at all. Gate the run on PRESENCE (~/.pi/agent/bin/pior the~/.pi/agentdir), run BOTH halves (install-pi-mcp.sh,install-pi-integration.sh), and report the outcome: a host without Pi is not a fault; a host with Pi that comes out of a deploy unwired is. The doctor'sPi integrationline is the drift guard that keeps it from going quiet again. - Point it at the PUBLISHED tree; never hand-build a bridge. A bespoke loader (a
/tmpbuilder script, a JSON index, a shell script that fixes up links) has no owner: not deployed, not verified, gone with the machine. The supported route is the published tree (~/.agents/skills, produced byops/scripts/manage/publish-agent-skills.pyfrom the fleet-owned defaults) registered once at user scope. Wire the WHOLE library deliberately, and expect its cost at startup: every installed skill's name + description is preloaded, so the size of that tree IS the session's context cost. - The skills half needs PyYAML and must not pick its interpreter by PATH.
command -v python3is the interpreter most likely to LACK it, so the installer reportsPyYAML requiredand skips the skills half on a host that has everything — resolve throughops/scripts/lib/python-with-module.sh --print yamlfirst and keep a bare PATH pick as the last resort only.
The memory/session TOOLS also come from that MCP server — the SAME
fleet-context-mcp.py Claude Code and Codex use, so the schemas are DERIVED
from the store contract and there is no per-harness tool list left to drift.
The extension keeps ONLY the lifecycle triggers, which MCP cannot provide:
bash ~/steadfaste-fleet/ops/scripts/install/install-pi-mcp.sh # + fleet-context
cp ~/steadfaste-fleet/ops/install/harnesses/pi/extensions/fleet-context.ts extensions/
pi -e extensions/fleet-context.ts --tools read,bash,edit,write
An older Pi (<= 0.87, no MCP client) reaches the same governance through the
loop-gov CLI instead.
The extension registers NO tools and wires only the lifecycle:
before_agent_start→ restore + inject the checkpoint (a fresh session resumes) AND inject any standing rule you want in EVERY session (see "Standing rules are INJECTED" below); cover BOTH branches — fresh and resume-with-no-snapshot — or a restored session silently misses the rule.turn_end→ write a checkpoint — the harness owns WHEN, never the modelsession_before_compact→ checkpoint before continuity is losttool_result→ record the tool event for tools a gate asks about. The git hook is GLOBAL, so a Pi commit is gated by the same reflexion gate as a Hermes one, and that gate reads HC's store — not the harness's own DB. With notool_resulthook a Pi session has no recorded evidence and every commit is refused no matter how well the agent behaved.
Standing rules are INJECTED, not loaded — the third binding surface
Pi's standing context = skill NAMES+descriptions + what the harness injects; a rule inside a skill body binds only if the agent happens to load it, and SOUL/MEMORY/USER.md are never read by Pi. Three surfaces reach EVERY Pi session, cheapest-effective first:
before_agent_startsystemPrompt injection (fleet-context extension) — the ONLY surface that is truly always-on; it is PAID as context on every turn, so keep it to a compact checklist (~7 lines; the pre-ship checklist is the exemplar: right-first-time, survey-before-build, test-edge-cases, evidence-before-done, doctor-clean, plan-review-first, escalate-review-first). Inject in BOTH branches — fresh AND resume-with-no-snapshot: the verifier setsFLEET_STUB_EMPTY_RESTORE=1to force the no-snapshot branch and asserts the checklist appears in each output, or a restore silently misses the rule.- AGENTS.md / CLAUDE.md — zero persistent token cost; the place for durable prose.
- The commit-time ritual gate — a discipline listed in the ritual loop
(
reflexion-check survey-before-action prove-before-create agent-contract) is REFUSED-until-loaded; the only surface with teeth.
Behaviour rules for the agent: insurance at (1), durable prose at (2), the hard rule at (3) — never only in a skill body it may never load.
The WRITE GATE — a SECOND extension, because pi's tools are not Hermes' tools
extensions/fleet-governance.ts (added 2026-10-14, titus). Its tool_call handler
blocks a write-capable NATIVE tool call when no governance lock covers the session's
repo. Load it with the harness: bash install-pi-integration.sh registers both files.
Why the existing layers did not cover this — verify before believing either way.
- The Hermes enforcer plugin (
~/.hermes/plugins/governance-enforcer/) is a Hermes plugin. It runs in the Hermes agent loop, so pi's nativeread/bash/edit/writenever cross it. Registering loop-governance over MCP gives pi the ritual, not a gate: an MCP server is a tool surface and cannot see the host's own tools. - The commit-time hook DOES carry a lock check (
pre-commit-score, "Level 3"), so a claim that it has none is wrong — but its refusal is scopedIS_FLEET_REPO && !LOCK_FOUND, i.e.~/steadfaste-fleetonly, deliberately, so manual human commits in client repos are not blocked. The RITUAL gate is NOT so scoped: the reflexion/survey loop demands the ritual skills in EVERY repo since 2026-10-29, skipping only no-session (human) commits — so a Pi session IS disciplined in its project repos, by a gate placed where the agent actually works.
It adds no semantics. The verdict comes from the shared implementation —
loop-gov.py check_repo_lock '{"repo_path":"<repo>"}', which is loop-gov-mcp.py's
own _check_repo_lock + _live_locks (staleness rule included). rc 0 = covered,
1 = refusal, 3 = unreachable. Never re-implement "does a lock cover this repo" in a
harness: the git hook already carries one copy and two copies drift.
-
Classify bash by COMMAND, never by shell syntax. A metachar rule (
;|>…) is a bypass:cp,mv,rm,tee,dd,mkdir,touchcontain none of them. The gate uses a read-only ALLOWLIST with deny-by-default, so anything not on it — needs a lock. Investigation tools (docker ps/logs/inspect/stats, journalctl, ss/netstat, curl GET, systemctl status, pip/npm list) ARE on it — the gate protects against CHANGES, not against investigation. Read-only COMPOUNDS (ls | grep foo,docker logs c | tail -20) are lock-free too: every|/&&/;segment must independently match (the enforcer's model). A redirect, a substitution, a second write-class segment, or a mutating flag inside a read primitive (find -exec, sort -o, date -s, journalctl --vacuum-*, docker run/exec, systemctl start, curl -d/-o) makes the whole thing a write. -
Fail CLOSED on every cannot-verify path (CLI missing, governance unreachable, no repo resolvable), with the cost stated in the block message and NO agent-side override. A gate that reads "could not check" as "carry on" fails open exactly when the host is broken.
-
Resolve the governed repo from the CALL's own arguments first, then
FLEET_SESSION_REPO, then the process cwd. Atool_callhook is handed the tool input and no session cwd, so path-args-only resolution leaves every path-less command (git commit -m …, a bare compound) with no repo — and a session launched outside the checkout can never name the tree its call touches, including thecd <repo> && git rev-parse --show-toplevelan agent would use to PROVE it. The measured failure is a total deadlock: every write refused with "cannot determine the repo" while the agent was standing in the repo, and the one command that would have settled it was itself the blocked write. Take the repo from file-shaped inputs (path,file_path,filePath,filename,target) and from absolute paths named inside a shell command, trying the path and then its directory — a FILE is not a git cwd. -
Find the repo root by WALKING UP for a
.gitentry; never require thegitbinary to find it. A macOS launcher (app, service, GUI) commonly runs with a PATH that lacks/opt/homebrew/bin, soexecFileSync("git", …)raises ENOENT while git works fine in the operator's own shell — and the gate then reports "not in a git repo" about a folder that is one. Walk withfs.statSync(path.join(dir, ".git"))(a.gitFILE counts: worktree or submodule) and hand git only what a walk cannot see (bare repo,GIT_DIR). Finding where a repo STARTS needs no git; only reading it does. -
A fail-closed refusal must CARRY the reason it could not verify. Keep stderr, the exit code and the path tried, and print them in the block. That is the difference between "git is not on this process's PATH (ENOENT)" and "this folder is not a repo" — without it the operator is told the wrong thing and cannot fix it, and the next diagnostic re-derives what the code already knew.
-
Prove it by EXECUTING the extension:
node ops/install/harnesses/pi/verify-governance-extension.mjsloads it through pi's own jiti loader, hands it a stubpi, fires synthetictool_callevents and asserts both directions — plus the no-metacharacter write commands above.tests/test_pi_governance_gate.pyadditionally requires the guard to FAIL when pointed at a gate that blocks nothing (PI_GOV_EXT=<broken>), and at the REAL extension with only the named-lock rendering removed; a guard that has never failed is a happy path. -
A refusal names the live locks it did NOT match.
check_repo_lockreturnsother_locks(task_id, agent, session_id, repo_path, status, heartbeat_at) besidelive_lock_count, and the block message renders the first three as "Live locks on this host — none covers this repo:" with a… and N moreremainder. A lock that records norepo_pathis named as covering nothing rather than dropped. The harness only RENDERS what the predicate reported — it must never parse lock files to work out whose lock is blocking. -
A stub proves the HANDLER; only a real session proves the WIRING. The guard above hands the extension a synthetic
pi, so it passes green even on a gate pi never calls — those are two separate claims, and the second is the one that matters. Run one real turn in a scratch project repo and read the gate's OWN log (~/.steadfaste-fleet/logs/pi-governance.log, oneGOV_VERDICTline per decision) rather than the agent's prose summary. Expectrefusedon the first write and thenallowed, because the block namesbegin_changeas the remedy and the agent simply complies — self-remediation is the gate working, not the gate failing. A gate that only ever blocked would be a deadlock. Watch the log, not the file listing: the turn's stdout is the agent's SELF-REPORT, and the write it claims may have been refused and retried. -
A Pi session's governance lock is tagged from the SESSION's repo, never from the host's
~/steadfaste-fleet(2026-10-09, titus). Pi injects no repo identity, so_derive_slug()resolves it asFLEET_SESSION_REPO, else the MCP child's working directory — the project you launched Pi in. Before that fix a Pi session working in a project repo was locked assteadfaste-fleet, and the close gate refused forever with "the lock's repo cannot contain this session's work": the lock stays HELD on a refusal, and its prescribed remedy (an enforcer injection) does not exist on Pi, so only the operator could delete~/.steadfaste-fleet/state/.governance-sess_*.json. Launch Pi from the project (cd repo && pi), or pinFLEET_SESSION_REPOin the MCPenvblock when the cwd is not the project. It needs a DEPLOY, not a pull: the harness runs the deployed copy (~/.steadfaste-fleet/tools/loop-governance/loop-gov-mcp.py). Verify withpython3 tests/run_non_hermes_lock_release_repro.py(pre-fix / working-tree / DEPLOYED in one run; it exits non-zero unless the lock is released). Full write-up:docs/troubleshooting.md.
Do NOT register the shared tools in the extension. They used to live there as a
hand-written tool() list with hand-written parameter maps — a SECOND definition of
tools that already existed in the contract, and the copy that broke silently when pi
moved 0.87.1 → 1.0.0. Two definitions of one capability means the runtime resolves one
and the other becomes a phantom. Tools stay in the shared MCP server; only the
triggers stay in the extension.
The COMMIT-time ritual gate — where DISCIPLINE binds (all repos)
Beyond the write lock, a Pi commit is judged by the same pre-commit ritual gate as
Hermes — in EVERY repo. reflexion-check.py --skill <name> is generic, and the
gate's loop demands task-orient execute-right verify-and-ship for a governed session. The session split is what makes "all repos"
safe: a Pi session holds a begin_change lock, so it is JUDGED anywhere; a human
commit has no session and is skipped (--skip-no-session). A discipline meant to
change Pi's behaviour belongs HERE — a skill in the loop that the gate refuses until
the agent loads (loading = reading the SKILL.md, recorded by the tool_result
hook) — never only in a skill body it may never load.
Consequence for guidance placement: the only files a non-Hermes agent always has in context are AGENTS.md (and CLAUDE.md for Claude). SOUL.md / MEMORY.md / USER.md are never read by Pi, and skills are name-only until the agent chooses to load one — so a rule living only in a SOUL trait or a skill's body reaches NO coding agent. Put behaviour rules for Pi in AGENTS.md/CLAUDE.md (a short "Core Operating Rules" block is the pattern), and make them bind by putting the discipline into the ritual-gate loop.
Harness index: ops/install/harnesses/INDEX.md · Adding another harness:
registry.yaml + generate-harnesses.py · Runbook:
docs/runbooks/context-integration.md.
Cortex-gateway — answer a Telegram bot with pi (the command backend)
The standalone fleet-gateway (a systemd/launchd unit, decoupled from
hermes-gateway.service) serves a Telegram bot with pi as a kind: command
backend. pi itself needs no new adapter — it is DECLARED, not coded:
- Config/example:
ops/scripts/gateway-pi.example.yaml→ copy to~/.steadfaste-fleet/gateway.yaml(OUTSIDE the repo).commandis an ARGV LIST, so use the ABSOLUTE pi launcher path (/home/<user>/.local/bin/pietc.) — a relative or~-containing path is a per-message silent no-op. Useoutput: raw(pi's stdout is exactly the answer),session: per_chatwithFLEET_SESSION_KEY={session_id}, and atimeout_sthat covers a real coding turn (300s+), not a chat reply. Slash commands (/compact,/model…) are the GATEWAY's to handle via pi RPC (fleet_gateway/pi_control.py), never forwarded as prompts. - A second Telegram bot must use a DISTINCT token var — never
TELEGRAM_BOT_TOKEN.fleet-gateway.servicerunsguard_distinct_token.pyasExecStartPre, which REFUSES to start whengateway.yaml'sbots[].token_refis the live bot's var/name — two pollers on one bot token get a Telegram 409 Conflict and the casualty is the LIVE channel. Give the pi bot its own env token (e.g.MOSESPI_BOT_TOKEN=PI_BOT_TOKEN) and reference that;guard_distinct_token.pyconfirms it is distinct (prints the value's hash, never the value) before the unit starts. - The sender allowlist IS the security perimeter — a bot answered by pi can
execute bash, so set
TELEGRAM_ALLOWED_USERS(andTELEGRAM_HOME_CHANNEL) to the operator's chat id ONLY; likewiseGATEWAY_SECRET(HMAC signing key) is mandatory — the daemon refuses to start without it, because an empty key makes every bus signature forgeable. The bot+config are assembled per host: env vars into the canonical fleet env (~/steadfaste-fleet/.env),gateway.yamlfrom the example, thenenable --nowthe unit. Full reference:docs/templates/ fleet-gateway.service+docs/design/fleet-gateway.md(CR5 pi = the record, live on the second-bot@Esther0001Bot). TELEGRAM_API_BASEis required and fails CLOSED — anactiveunit is not a WORKING gateway. The transport resolves the API base at call time and refuses to build a URL without it (TELEGRAM_API_BASE is not set — refusing to build a Telegram API URL), so the unit starts, reportsactive, and then backs off on every poll. Set it in the fleet env (TELEGRAM_API_BASE=https://api.telegram.orgfor the standard API) — Hermes's own gateway supplies this internally, so a migration surfaces it as a NEW requirement. Verify a working gateway from the JOURNAL, notsystemctl is-active:journalctl --user -u fleet-gateway.servicemust show a real dispatched turn and no recurringpoll error … backing off. Likewise a pi turn that exits non-zero withNo API key found for openrouteris the provider key missing, not the gateway — wireauth.jsonvia theenv-value.sh!commandpattern (see "Configure a provider" below) and prove it withpi auth check --provider openrouter+ one real turn before blaming the unit.- The unit must run the FLEET VENV python, not
/usr/bin/python3. The template's defaultExecStart=/usr/bin/python3 …/daemon.pycrash-loops (Restart=alwaysspins it) onImportError: psycopg package requiredthe moment the bot-lock layer tries to reach the PGMQ Postgres — the system python has neither psycopg nor the fleet deps. Repoint bothExecStartPre/ExecStartat<host>/.steadfaste-fleet/venv/bin/python3, and make surepsycopg[binary]is installed in that venv (the fleet venv historically lacks it — the same gap that keepsfleet-update.shfrom exiting clean).pg_isready -h 127.0.0.1 -p <pg-port>confirms the bus Postgres is reachable before blaming psycopg. The venv's dashesmcp/jsonschema/idnaare present; psycopg is the usual missing one.
Configure a provider (OpenRouter + a model)
Verified against the installed package docs — docs/providers.md,
docs/settings.md, docs/configuration.md — not inferred:
# <agent-dir>/auth.json — {"<provider>": {"type": "api_key", "key": "... | !command"}}
# <agent-dir>/settings.json — {"defaultProvider": ..., "defaultModel": ...}
# <agent-dir>/models.json — custom/compatible models and overrides
Set the model defaults (preserve existing keys — extensions, skills):
{"defaultProvider": "openrouter", "defaultModel": "deepseek/deepseek-flash-latest"}
Mode-specific models (fleet policy): the coding default is the fast
deepseek-flash-latest; the adversarial reviewer uses the strongest tier,
deepseek-v4-pro (ops/scripts/manage/reviewer-agent-pi.sh, overridable with
REVIEWER_PI_MODEL). Every coding agent can override per agent in its own
gateway.yaml backend model: field, and per chat via /model. A reviewer
should never silently drop to the cheap/fast default.
Do NOT source an env file to supply the key. Pi's docs support a !command
precisely so the resolved key is never written to disk, but the obvious command —
bash -lc 'set -a; . ~/.hermes/.env; printf %s $OPENROUTER_API_KEY' — hands the
coding agent EVERY secret in that file, and this skill's own pitfall says the agent
can print its own environment. Supply exactly one variable:
{"openrouter": {"type": "api_key",
"key": "!bash ~/.steadfaste-fleet/scripts/env-value.sh OPENROUTER_API_KEY"}}
env-value.sh prints one named value (fleet env first, then the Hermes env, first
match wins), fails closed when absent, and refuses a name that isn't
^[A-Z][A-Z0-9_]*$ so it can't become a pattern. Point it at a Hermes-only key and
copy that key into the fleet env: no harness should reach into a Hermes-owned file
for a provider key.
Verify all three, in this order — the last one is the only real proof:
pi auth check --provider openrouter # ready
pi --list-models kimi # the model, with context/thinking capabilities
pi --model "openrouter/<vendor>/<model>" "Reply with exactly: ready" # a real turn
pi auth check --model <id> without the provider qualifier reports not_ready even
when the model is fine — check the provider-qualified form.
Jev integration (the cost-routing hooks)
The five high-value Jev hooks in the pi loop, from ten-levels-of-jev and mapped in
steadfaste docs/design/coding-cost-routing.md:
- task-routing classifier (before any model is chosen — the biggest saving)
- destructive-command gate (before tool execution)
- compaction scoring (when context fills — prune lowest-scored instead of a summariser LLM)
- cheap file reads (judge a file without reading it into context — $0.00049 vs $0.091)
- output-type screening (after an LLM response)
Web search — pi has NO online tool until a package supplies one
Measured 2026-10-15 (pi 1.2.0): the built-ins are read, bash, powershell,
edit, write, grep, find, ls, plus codemode/tool_search — and
tool_search ranks the LOCAL tool registry (deferred/MCP tools), never the
network. The five fleet MCP servers expose no search either. So "research
this" and "review this repo" had no online path at all, and the gateway-served
agent is no exception: the gateway only spawns this same pi.
- Install (pinned + age-gated):
pi install npm:pi-web-access@<version>. It registersweb_search,source_check,fetch_contentandget_search_content— search, URL/PDF/YouTube fetching, and GitHub URLs are CLONED locally so the agent reads real files instead of rendered HTML. Free is the requirement, not a nicety — build the keyless chain first and treat a keyed provider as an opt-in upgrade; never introduce a paid dependency for a capability the fleet already gets for nothing. - Pick the pin by MEASUREMENT, never from the README. The latest release is
usually days old and fails the 14-day package age gate, and the gate is not
bypassed for convenience: enumerate the versions, sort them as SEMVER (a
lexical sort puts
0.5.1after0.41.0and hands you a six-month-old build), and take the newest one that passes.
Then bump later through the same gate — the pinned spec is a variable inpython3 -c "import json,urllib.request,datetime,sys;\ d=json.load(urllib.request.urlopen('https://registry.npmjs.org/pi-web-access'));\ now=datetime.datetime.now(datetime.timezone.utc);\ k=lambda v: tuple(int(x) for x in v.split('.') if x.isdigit());\ rows=[(k(v),v,ts,(now-datetime.datetime.fromisoformat(ts.replace('Z','+00:00'))).days) \ for v,ts in d['time'].items() if v not in ('created','modified')];\ rows.sort();\ print([(v,a) for _,v,_,a in rows if a>=14][-3:])" python3 ops/scripts/health/check-package-age.py npm pi-web-access==<chosen> # rc 0 = allowedinstall-pi-integration.sh(PI_WEB_SEARCH_PACKAGE=...), so a bump is one env-overridable value, not an edit scattered through the script. - Prove it with a REAL turn, not
pi list. A registered extension and a working search are two different claims: run one turn in a scratch repo and read which PROVIDER answered and the URLs it returned (04-search-exa.txt/05-search-ddg.txtunderdocs/evidence/are the captured shape). Run it from the contract's own cwd too when the consumer is a service — the gateway spawns pi from its deploy dir, so a probe that only works in a project directory proves nothing about the gateway-served agent. - Free path, no API key: Exa's keyless MCP free tier plus DuckDuckGo's
keyless HTML endpoint.
~/.pi/agent/web-search.json:{"searchRouting": {"providers": ["exa", "duckduckgo"], "fallbackOn": ["unsupported", "transient", "quota", "network", "invalid-response"]}} autois NOT the free path. With no config the tool answersNo search provider available …and lists only KEYED providers — an agent reads that as a broken tool rather than a missing config. Keyless DuckDuckGo is explicit-only (never chosen byauto, never inprovider: "all"), so name it insearchRoutinginstead of relying on the default chain.pi installwrites a package declaration, not a working tool. Pi manages its own npm root (~/.pi/agent/npm/node_modules/<pkg>); a declaration with nothing on disk loads no extension. Check both halves — the declaration insettings.jsonAND the directory.- A web tool needs NO governance lock.
fleet-governance.tsgates onlywrite/editand non-read-onlybash; every non-native tool (extension or MCP) passes by design, so search/fetch work in an unlocked session. - Wiring:
ops/scripts/install/install-pi-integration.shdeclares the package, installs it when the directory is absent, and writesweb-search.jsononly when no config exists (an operator's keyed file is never clobbered).ops/scripts/manage/audit-pi-integration.shLayer 6 FAILs when either half is missing or the chain has no keyless provider;tests/test_pi_registration_installer.shcovers it.
Several pi agents in ONE repo — project-scoped state, and the commit sweep
pi keeps USER scope in ~/.pi/agent, but for a TRUSTED PROJECT it also writes
.pi/settings.json and .pi/mcp.json inside the checkout, and the fleet extensions add
to that (the context extension checkpoints at turn_end, so those writes happen every turn).
Hermes keeps all of it in ~/.hermes, so this hazard does not exist for Hermes agents and
nobody who has only run Hermes will expect it.
With more than one pi session in the same repo:
- each session's
.pi/files appear as untracked files under the other's feet; - the first agent to run a broad add (
git add -A,git add .) orgit commit -asweeps up files it never wrote — which the operator reports as "a sweep of the peer's files when the first one tries to commit", and reasonably blames on governance.
Rules:
- Ignore
.pi/in every repo pi runs in, and prove it:git check-ignore -v .pi/settings.jsonmust name the rule, andgit ls-files .pimust be empty — a.pipath already committed defeats a new ignore and needsgit rm -r --cached .pi. - Never
git commit -aon a tree another session may be editing. Commit by pathspec and assert the staged set first (git diff --cached --name-only). No.gitignoreprevents sweeping a peer's SOURCE edits; only the pathspec does. - When commits on a host keep carrying files nobody wrote, measure what the HARNESS writes
into the tree before suspecting the git hooks. The Hermes hooks stage nothing (no
git add,stash,checkout --,reset, and nocommit -ain the commit path), so a sweep on a pi host points at pi's own project state, not at the gate.
Pitfalls
- A presence probe can be wrong about a managed install.
command -v pireports "missing" on a host where Pi is installed and working, because the entrypoint is a symlink into a bin dir that need not be on PATH. When a probe says a tool is absent, check the install LAYOUT (launcher,current-version,releases/) before reporting it missing to anyone — a false "not installed" sends the user chasing a non-problem, and the correction costs more than the check did. - Local small models (qwen2.5:3b) are weak at tool-calling — use offline/local for generation and let pi do the loop; a ROUTINE task that needs tool-chaining routes to a hosted workhorse rather than forcing the local model to tool-call.
- A block notice is an instruction, not a control — an agent was observed routing around a write gate by writing the same file via a bash heredoc. The deterministic gate remains the authority; Jev gates add scrutiny, never remove it.
- The agent can read its own environment — its bash tool can print every env
var it was given. Hand pi only shell basics + the Jev/provider keys + Jev settings;
treat
.sessions/as sensitive. - Never let the agent author its own Jev question blocks at runtime (steadfaste MN-3: the question is the policy). The questions are Steward-ratified Decision Class config; the agent reaches for Jev, it does not write the questions.
- Fail closed on routing — an undecidable/unknown/missing classification routes pessimistically to the most capable (most expensive) tier, never a silent cheap default.
- An optional chain over a guessed API hides the defect —
event.completed?.()returnedundefinedagainst a non-existent method, so every checkpoint was written EMPTY while the code looked defensive. When a hook must produce output, assert the output is non-empty (warn loudly with the observed keys) rather than letting?.be the difference between working and silent. - Verify a hook's or tool's EFFECT without an LLM run. A host with no provider
ready cannot run a turn, so don't wait on one to test wiring: load the extension
with pi's OWN TypeScript loader (it ships jiti in its release
node_modules), call its default export with a fakepi({ on, registerTool }) that captures the handlers/tools, fire a synthetic event in Pi's real shape, and assert the effect landed (a store row exists) — a stderr marker alone proves only that the handler ran. - A guard that greps cannot see a signature or a schema shape — EXECUTE the wiring.
Guards asserting that tool NAMES exist and that the shared CLI is called all passed
while every tool was dead, because the defect was the tool definition's SHAPE. Load
the real extension, hand it a stub
pi, and CALLexecute(id, params)against a throwaway CLI — never the real store. Then prove the guard discriminates: run it against the PRE-FIX extension and require it to FAIL (TypeError: <tool>.execute is not a function). A guard that has never failed on the broken artifact is a happy path, not a guard. Recipe and exact shapes:references/extension-tool-api.md. ToolResultEventBasecarriesinput/content/isErrorbut NOTtoolName— only the concrete variants (BashToolResultEvent, …) declare it. ReadtoolNamedefensively in a generictool_resulthandler.- Never put
*/inside a block comment — a GLOB will close it early. Writing an identifier likemem_*/session_*(or anyfoo_*/bar) in a/** … */header ends the comment at the*/, so the rest parses as code and the extension fails to LOAD (ParseError: Missing semicolon, orSyntaxError: Unexpected token '*'). Pi then reports the tools as missing, which reads like a wiring problem rather than a typo. Writememory/session, or space it (mem_* / session_*). The same trap applies to any glob you paste into a JSDoc/TSDoc comment. python3may not be on pi's PATH on macOS — Homebrew is/opt/homebrew/bin(Apple Silicon) or/usr/local/bin(Intel), and a GUI-launched pi sees a narrower PATH than your shell. Make the interpreter overridable (e.g.FLEET_CONTEXT_PYTHON) instead of hardcodingpython3.- An MCP entry's interpreter needs its TLS dependencies, not just the module you probed.
python-with-module.sh --print mcpprovesmcpimports and says nothing about the CA bundle the server's HTTP client needs, so an entry can resolve clean and still start DEAD on TLS. TheCould not find a suitable TLS CA certificate bundlemessage is raised byte-identically by bothrequestsandhttpx, so it names no library — and never justify KEEPING a package with "pip would break": pip vendors its own certifi/requests/urllib3/truststore and is unaffected. An interpreter resolution, the import-chain rule for deciding a dependency is load-bearing, and the old-venv-path failure after a home-dir migration:references/mcp-server-interpreter-tls.md.
04 同仓库更多 Skills
macbook-linux-maintenance
Legacy MacBook Linux fixes: GPU wedge, reboot hang, thermal.
governance-regression-triage
Triage a host's governance issues: what changed.
enforcement-immutability
Use when enforcement files lose their immutable flag.
steadfaste-fleet-repo-deploy
Use when committing to the steadfaste-fleet repo.
steadfaste-fleet-maintenance
Maintain an installed Steadfaste Fleet instance — update both the upstream Hermes Agent and the fleet repo layer, merge diverged histories, sync skills safely, and troubleshoot common issues. Covers the dual-update workflow (hermes update + fleet-update.sh), encrypted brain data backup, mycortex import, and recovery techniques.
fleet-preflight
DEPRECATED alias — merged into survey-before-action (2026-08-20). Load survey-before-action instead; its "Repo-Specific Pre-Flight" section covers git search, Hermes boundary, and deployment verification.