<p align="center">
  <a href="https://shittycodingagent.ai">
    <img src="https://shittycodingagent.ai/logo.svg" alt="pi logo" width="128">
  </a>
</p>
<p align="center">
  <a href="https://discord.com/invite/3cU7Bz4UPx"><img alt="Discord" src="https://img.shields.io/badge/discord-community-5865F2?style=flat-square&logo=discord&logoColor=white" /></a>
  <a href="https://www.npmjs.com/package/@apholdings/jensen-code"><img alt="npm" src="https://img.shields.io/npm/v/@apholdings/jensen-code?style=flat-square" /></a>
  <a href="https://github.com/apholdings/jensen-code/actions/workflows/ci.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/apholdings/jensen-code/ci.yml?style=flat-square&branch=main" /></a>
</p>
<p align="center">
  <a href="https://pi.dev">pi.dev</a> domain graciously donated by
  <br /><br />
  <a href="https://exe.dev"><img src="docs/images/exy.png" alt="Exy mascot" width="48" /><br />exe.dev</a>
</p>

Jensen Code 3.0.0 is a durable distributed autonomous agent runtime foundation. It retains the interactive coding harness while adding authoritative Missions, restart-safe execution, Scheduler/Assignment/Worker coordination, remote execution, capability routing, modern MCP, shared inference, logical subagents, durable orchestration, verification/completion authority, Governance/Budgets, and Jensen-owned process stewardship.

The persistent daemon/control plane, trusted remote clients, mobile and device capabilities, voice/STT/TTS, and ambient-assistant services are planned for later Jensen 3.x phases; they are not included in this release.

Jensen can be extended with TypeScript [Extensions](#extensions), [Skills](#skills), [Prompt Templates](#prompt-templates), and [Themes](#themes). Put your extensions, skills, prompt templates, and themes in [Pi Packages](#pi-packages) and share them with others via npm or git.

Pi ships with a canonical policy-bound subagent registry and Cavecrew runtime. The `subagent` extension resolves roles, models, tools, budgets, context packets, and output schemas through that registry; Cavecrew runs read-only investigators, a bounded planner, a transactional builder, and a read-only reviewer. User and workspace Markdown prompts cannot broaden runtime policy.

Pi runs in four modes: interactive, print or JSON, RPC for process integration, and an SDK for embedding in your own apps. See [openclaw/openclaw](https://github.com/openclaw/openclaw) for a real-world SDK integration.

## Table of Contents

- [Quick Start](#quick-start)
- [Providers & Models](#providers--models)
- [Interactive Mode](#interactive-mode)
  - [Editor](#editor)
  - [Commands](#commands)
  - [Keyboard Shortcuts](#keyboard-shortcuts)
  - [Message Queue](#message-queue)
- [Sessions](#sessions)
  - [Branching](#branching)
  - [Compaction](#compaction)
- [Settings](#settings)
- [Context Files](#context-files)
- [Web Research](#web-research)
- [Customization](#customization)
  - [Prompt Templates](#prompt-templates)
  - [Skills](#skills)
  - [Extensions](#extensions)
  - [Themes](#themes)
  - [Pi Packages](#pi-packages)
- [Programmatic Usage](#programmatic-usage)
- [Philosophy](#philosophy)
- [CLI Reference](#cli-reference)

---

## Quick Start

Install or upgrade the public CLI with:

```bash
npm install -g @apholdings/jensen-code@3.0.0
```

Jensen 3.0.0 keeps the default user configuration under `~/.pi/agent` for
compatibility with existing sessions and provider settings. Mission,
orchestration, assignment, and Governance stores use their configured durable
locations; do not copy or edit those stores while a Jensen process owns them.

Authenticate with an API key:

```bash
export ANTHROPIC_API_KEY=sk-ant-...
pi
```

Or use your existing subscription:

```bash
pi
/login  # Then select provider
```

Then just talk to pi. By default, pi gives the model four tools: `read`, `write`, `edit`, and `bash`. The model uses these to fulfill your requests. Add capabilities via [skills](#skills), [prompt templates](#prompt-templates), [extensions](#extensions), or [pi packages](#pi-packages).

**Platform notes:** [Windows](docs/windows.md) | [Termux (Android)](docs/termux.md) | [tmux](docs/tmux.md) | [Terminal setup](docs/terminal-setup.md) | [Shell aliases](docs/shell-aliases.md)

---

## Providers & Models

For each built-in provider, pi maintains a list of tool-capable models, updated with every release. Authenticate via subscription (`/login`) or API key, then select any model from that provider via `/model` (or Ctrl+L).

**Subscriptions:**
- Anthropic Claude Pro/Max
- OpenAI ChatGPT Plus/Pro (Codex)
- GitHub Copilot
- Google Gemini CLI
- Google Antigravity

**API keys:**
- Anthropic
- OpenAI
- Azure OpenAI
- Google Gemini
- Google Vertex
- Amazon Bedrock
- Mistral
- Groq
- Cerebras
- xAI
- OpenRouter
- Vercel AI Gateway
- ZAI
- OpenCode Zen
- OpenCode Go
- Hugging Face
- Kimi For Coding
- MiniMax

See [docs/providers.md](docs/providers.md) for detailed setup instructions.

**Custom providers & models:** Add providers via `~/.pi/agent/models.json` if they speak a supported API (OpenAI, Anthropic, Google). For custom APIs or OAuth, use extensions. See [docs/models.md](docs/models.md) and [docs/custom-provider.md](docs/custom-provider.md).

---

## Interactive Mode

<p align="center"><img src="docs/images/interactive-mode.png" alt="Interactive Mode" width="600"></p>

The interface from top to bottom:

- **Startup header** - Shows shortcuts (`/hotkeys` for all), loaded `JENSEN.md` context files, prompt templates, skills, and extensions
- **Messages** - Your messages, assistant responses, tool calls and results, notifications, errors, and extension UI
- **Editor** - Where you type; border color indicates thinking level
- **Footer** - Working directory, session name, total token/cache usage, cost, context usage, current model

The editor can be temporarily replaced by other UI, like built-in `/settings` or custom UI from extensions (e.g., a Q&A tool that lets the user answer model questions in a structured format). [Extensions](#extensions) can also replace the editor, add widgets above/below it, a status line, custom footer, or overlays.

### Editor

| Feature | How |
|---------|-----|
| File reference | Type `@` to fuzzy-search project files |
| Path completion | Tab to complete paths |
| Multi-line | Shift+Enter (or Ctrl+Enter on Windows Terminal) |
| Images | Ctrl+V to paste (Alt+V on Windows), or drag onto terminal |
| Bash commands | `!command` runs and sends output to LLM, `!!command` runs without sending |

Standard editing keybindings for delete word, undo, etc. See [docs/keybindings.md](docs/keybindings.md).

### Commands

Type `/` in the editor to trigger commands. [Extensions](#extensions) can register custom commands, [skills](#skills) are available as `/skill:name`, and [prompt templates](#prompt-templates) expand via `/templatename`.

| Command | Description |
|---------|-------------|
| `/login`, `/logout` | OAuth authentication |
| `/model` | Switch models |
| `/scoped-models` | Enable/disable models for Ctrl+P cycling |
| `/settings` | Thinking level, theme, message delivery, transport |
| `/resume` | Pick from previous sessions |
| `/new` | Start a new session |
| `/name <name>` | Set session display name |
| `/session` | Show session info (path, tokens, cost) |
| `/tree` | Jump to any point in the session and continue from there |
| `/fork` | Create a new session from the current branch |
| `/compact [prompt]` | Manually compact context, optional custom instructions |
| `/copy` | Copy last assistant message to clipboard |
| `/export [file]` | Export session to HTML file |
| `/share` | Upload as private GitHub gist with shareable HTML link |
| `/reload` | Reload extensions, skills, prompts, context files (themes hot-reload automatically) |
| `/hotkeys` | Show all keyboard shortcuts |
| `/changelog` | Display version history |
| `/quit`, `/exit` | Quit pi |

### Keyboard Shortcuts

See `/hotkeys` for the full list. Customize via `~/.pi/agent/keybindings.json`. See [docs/keybindings.md](docs/keybindings.md).

**Commonly used:**

| Key | Action |
|-----|--------|
| Ctrl+C | Clear editor |
| Ctrl+C twice | Quit |
| Escape | Cancel/abort |
| Escape twice | Open `/tree` |
| Ctrl+L | Open model selector |
| Ctrl+P / Shift+Ctrl+P | Cycle scoped models forward/backward |
| Shift+Tab | Cycle thinking level |
| Ctrl+O | Collapse/expand tool output |
| Ctrl+T | Collapse/expand thinking blocks |

### Message Queue

Submit messages while the agent is working:

- **Enter** queues a *steering* message, delivered after current tool execution (interrupts remaining tools)
- **Alt+Enter** queues a *follow-up* message, delivered only after the agent finishes all work
- **Escape** aborts and restores queued messages to editor
- **Alt+Up** retrieves queued messages back to editor

On Windows Terminal, `Alt+Enter` is fullscreen by default. Remap it in [docs/terminal-setup.md](docs/terminal-setup.md) so pi can receive the follow-up shortcut.

Configure delivery in [settings](docs/settings.md): `steeringMode` and `followUpMode` can be `"one-at-a-time"` (default, waits for response) or `"all"` (delivers all queued at once). `transport` selects provider transport preference (`"sse"`, `"websocket"`, or `"auto"`) for providers that support multiple transports.

---

## Sessions

Sessions are stored as JSONL files with a tree structure. Each entry has an `id` and `parentId`, enabling in-place branching without creating new files. See [docs/session.md](docs/session.md) for file format.

### Management

Sessions auto-save to `~/.pi/agent/sessions/` organized by working directory.

```bash
pi -c                  # Continue most recent session
pi -r                  # Browse and select from past sessions
pi --no-session        # Ephemeral mode (don't save)
pi --session <path>    # Use specific session file or ID
jensen resume <ID>     # Continue a persisted session by exact session ID
```

`jensen resume <SESSION_ID>` resolves a persisted session by its exact ID and
continues it in place: conversation history, model/thinking configuration, and
working directory are restored, and new activity is written under the same
session ID. You can obtain a session ID from `/session` in the TUI or from the
`--resume` session picker.

### Branching

**`/tree`** - Navigate the session tree in-place. Select any previous point, continue from there, and switch between branches. All history preserved in a single file.

<p align="center"><img src="docs/images/tree-view.png" alt="Tree View" width="600"></p>

- Search by typing, fold/unfold and jump between branches with Ctrl+←/Ctrl+→ or Alt+←/Alt+→, page with ←/→
- Filter modes (Ctrl+O): default → no-tools → user-only → labeled-only → all
- Press `l` to label entries as bookmarks

**`/fork`** - Create a new session file from the current branch. Opens a selector, copies history up to the selected point, and places that message in the editor for modification.

### Compaction

Long sessions can exhaust context windows. Compaction summarizes older messages while keeping recent ones.

**Manual:** `/compact` or `/compact <custom instructions>`

**Automatic:** Enabled by default. Triggers on context overflow (recovers and retries) or when approaching the limit (proactive). Configure via `/settings` or `settings.json`.

Compaction is lossy for the active model context. The full history remains in the JSONL file; use `/tree` to revisit. Deterministic checkpoint metadata records the continuation boundary and addressable SHA-256 references for summarized tool evidence, while complete results remain in the durable session tree. Customize compaction behavior via [extensions](#extensions). See [docs/compaction.md](docs/compaction.md) for internals.

---

## Settings

Use `/settings` to modify common options, or edit JSON files directly:

| Location | Scope |
|----------|-------|
| `~/.pi/agent/settings.json` | Global (all projects) |
| `.pi/settings.json` | Project (overrides global) |

See [docs/settings.md](docs/settings.md) for all options.

---

## Context Files

Pi loads instruction files at startup from the global config directory and each directory from the filesystem root down to `cwd`. At each level it uses the first matching file in this order:
- `JENSEN.md` (preferred)
- `AGENTS.md` (legacy fallback)
- `CLAUDE.md`

Use these files for project instructions, conventions, and common commands.

### System Prompt

Replace the default system prompt with `.pi/SYSTEM.md` (project) or `~/.pi/agent/SYSTEM.md` (global). Append without replacing via `APPEND_SYSTEM.md`.

### Cache-Stable Context

Jensen automatically keeps system contracts, repository instructions, skill contracts, and canonical tool definitions in a deterministic stable prefix. Date, cwd, Git branch/worktrees, local documentation paths, user requests, execution state, and tool results are sent in the dynamic suffix. There is no configuration switch; custom system prompts remain compatible, and provider/model changes invalidate cache-continuity assumptions without changing session correctness.

JSON mode emits a metadata-only `context_cache` event after each provider response. RPC `get_session_stats` returns the latest diagnostics in `contextCache`. These include SHA-256 fingerprints, stable/dynamic byte counts, provider, model, change reasons, continuity, and cache token telemetry when the provider reports it. They never include prompt text, API keys, authorization headers, or hidden reasoning.

Telemetry capability varies. Anthropic, OpenAI-compatible APIs including DeepSeek, OpenAI Responses, Google/Gemini CLI/Vertex, and Bedrock are normalized when their response includes cache fields. Other providers and endpoints report cache values as unknown rather than fabricated zero. Cache state never replaces the JSONL session tree, compaction checkpoint, or long-horizon execution state.

---

## Web Research

Jensen provides separate read-only `web_search`, `web_fetch`, and `deep_research` tools. `web_search` targets a private local SearXNG instance and falls back to DuckDuckGo Lite on operational failure. Neither path requires a paid search API or external account. `web_fetch` securely retrieves one public URL with DNS-pinned SSRF protection, redirect revalidation, bounded decompression, deterministic HTML-to-Markdown extraction, JSON/XML/text support, page-addressable PDF extraction, and optional isolated Playwright rendering. `deep_research` runs a bounded multi-query workflow and returns durable evidence IDs, passage coordinates, hashes, contradiction notices, and machine-readable citations.

These tools are off by default. Enable them with `--tools web_search,web_fetch,deep_research,web_research_status` or add those names to `tools.defaultActiveToolNames`. Full pages remain in durable session tool-result details; normal model context receives bounded excerpts and evidence references. All page text and search metadata are structurally marked as untrusted data and cannot relax network policy or authorize tool use.

The default SearXNG endpoint is `http://127.0.0.1:18888`. See [docs/web-research.md](docs/web-research.md) for deployment, configuration, security boundaries, diagnostics, citations, browser installation, privacy, and troubleshooting.

---

## Customization

### Prompt Templates

Reusable prompts as Markdown files. Type `/name` to expand.

```markdown
<!-- ~/.pi/agent/prompts/review.md -->
Review this code for bugs, security issues, and performance problems.
Focus on: {{focus}}
```

Place in `~/.pi/agent/prompts/`, `.pi/prompts/`, or a [pi package](#pi-packages) to share with others. See [docs/prompt-templates.md](docs/prompt-templates.md).

### Skills

On-demand capability packages following the [Agent Skills standard](https://agentskills.io). Invoke via `/skill:name` or let the agent load them automatically.

```markdown
<!-- ~/.pi/agent/skills/my-skill/SKILL.md -->
# My Skill
Use this skill when the user asks about X.

## Steps
1. Do this
2. Then that
```

Place in `~/.pi/agent/skills/`, `~/.agents/skills/`, `.pi/skills/`, or `.agents/skills/` (from `cwd` up through parent directories) or a [pi package](#pi-packages) to share with others. See [docs/skills.md](docs/skills.md).

### Extensions

<p align="center"><img src="docs/images/doom-extension.png" alt="Doom Extension" width="600"></p>

TypeScript modules that extend pi with custom tools, commands, keyboard shortcuts, event handlers, and UI components.

```typescript
export default function (pi: ExtensionAPI) {
  pi.registerTool({ name: "deploy", ... });
  pi.registerCommand("stats", { ... });
  pi.on("tool_call", async (event, ctx) => { ... });
}
```

**What's possible:**
- Custom tools (or replace built-in tools entirely)
- Sub-agents and plan mode
- Custom compaction and summarization
- Permission gates and path protection
- Custom editors and UI components
- Status lines, headers, footers
- Git checkpointing and auto-commit
- SSH and sandbox execution
- MCP server integration
- Make pi look like Claude Code
- Games while waiting (yes, Doom runs)
- ...anything you can dream up

Place in `~/.pi/agent/extensions/`, `.pi/extensions/`, or a [pi package](#pi-packages) to share with others. See [docs/extensions.md](docs/extensions.md) and [examples/extensions/](examples/extensions/).

### Canonical subagents and Cavecrew

Jensen ships one policy-bound subagent registry. Inspect it with `jensen agents list`, `jensen agents inspect <name>`, `jensen agents resolve <name>`, `jensen agents validate`, `jensen agents models`, or `jensen agents aliases`. Skill dependencies can be checked with `jensen skills validate` and `jensen skills dependencies <skill>`; use `jensen doctor subagents` and `jensen doctor skills` through the same diagnostics surface when available.

The built-in roles are `scout`, `cavecrew-investigator`, `planner`, `cavecrew-builder`, `worker`, `cavecrew-reviewer`, `reviewer`, `librarian`, `security`, and `pentester`. Analytical/read-only roles use OpenRouter `deepseek/deepseek-v4-flash-latest`; `worker` and `cavecrew-builder` use OpenRouter `openai/gpt-5.6-luna`. The `~` profile marker is stripped before a provider request and model resolution is recorded. Unknown names fail with a typed error; Jensen never silently substitutes an agent.

`cavecrew-investigator` and `cavecrew-reviewer` are read-only. `cavecrew-builder` is a restricted worker specialization limited to a bounded one- or two-file transactional change, with checkpoint, lease, focused validation, and rollback. Child permissions cannot exceed the parent, and fallback requires explicit policy and approval. User/workspace definitions may shadow packaged resources, but precedence is reported and cannot broaden the canonical policy.

### Workspace Intelligence (1.7.0)

Jensen adds durable, local-first workspace indexing and hybrid lexical/symbolic/
semantic retrieval over the current workspace. See `docs/workspace-intelligence.md`.

- CLI: `jensen index` (status/build/refresh/rebuild/verify/generations/inspect/
  files/symbols/stats/prune), `jensen search` (lexical|symbol|semantic|hybrid|path),
  `jensen retrieval plan|explain`, and `jensen doctor index|embeddings|retrieval`.
- Tools: `workspace_search`, `workspace_search_lexical`, `workspace_search_semantic`,
  `workspace_search_symbols`, `workspace_retrieval_status` (read-only), and
  `workspace_index_refresh`.
- Backend: built-in `node:sqlite` (no new dependency). Embeddings are local by
  default (deterministic fixture); remote embedding is opt-in policy-only.
- Privacy: source is never uploaded by default; secret-sensitive files are
  excluded; the index is disposable/rebuildable and never an execution authority.
- Requires Node.js `>=22.5.0`.

### Themes

Built-in: `dark`, `light`. Themes hot-reload: modify the active theme file and pi immediately applies changes.

Place in `~/.pi/agent/themes/`, `.pi/themes/`, or a [pi package](#pi-packages) to share with others. See [docs/themes.md](docs/themes.md).

### Pi Packages

Bundle and share extensions, skills, prompts, and themes via npm or git. Find packages on [npmjs.com](https://www.npmjs.com/search?q=keywords%3Api-package) or [Discord](https://discord.com/channels/1456806362351669492/1457744485428629628).

> **Security:** Pi packages run with full system access. Extensions execute arbitrary code, and skills can instruct the model to perform any action including running executables. Review source code before installing third-party packages.

```bash
pi install npm:@foo/pi-tools
pi install npm:@foo/pi-tools@1.2.3      # pinned version
pi install git:github.com/user/repo
pi install git:github.com/user/repo@v1  # tag or commit
pi install git:git@github.com:user/repo
pi install git:git@github.com:user/repo@v1  # tag or commit
pi install https://github.com/user/repo
pi install https://github.com/user/repo@v1      # tag or commit
pi install ssh://git@github.com/user/repo
pi install ssh://git@github.com/user/repo@v1    # tag or commit
pi remove npm:@foo/pi-tools
pi list
pi update                               # skips pinned packages
pi config                               # enable/disable extensions, skills, prompts, themes
```

Packages install to `~/.pi/agent/git/` (git) or global npm. Use `-l` for project-local installs (`.pi/git/`, `.pi/npm/`).

Create a package by adding a `pi` key to `package.json`:

```json
{
  "name": "my-pi-package",
  "keywords": ["pi-package"],
  "pi": {
    "extensions": ["./extensions"],
    "skills": ["./skills"],
    "prompts": ["./prompts"],
    "themes": ["./themes"]
  }
}
```

Without a `pi` manifest, pi auto-discovers from conventional directories (`extensions/`, `skills/`, `prompts/`, `themes/`).

See [docs/packages.md](docs/packages.md).

---

## Programmatic Usage

### SDK

```typescript
import { AuthStorage, createAgentSession, ModelRegistry, SessionManager } from "@apholdings/jensen-code";

const { session } = await createAgentSession({
  sessionManager: SessionManager.inMemory(),
  authStorage: AuthStorage.create(),
  modelRegistry: new ModelRegistry(authStorage),
});

await session.prompt("What files are in the current directory?");
```

See [docs/sdk.md](docs/sdk.md) and [examples/sdk/](examples/sdk/).

### RPC Mode

For non-Node.js integrations, use RPC mode over stdin/stdout:

```bash
pi --mode rpc
```

RPC mode uses strict LF-delimited JSONL framing. Clients must split records on `\n` only. Do not use generic line readers like Node `readline`, which also split on Unicode separators inside JSON payloads.

See [docs/rpc.md](docs/rpc.md) for the protocol.

---

## Philosophy

Pi is aggressively extensible so it doesn't have to dictate your workflow. Features that other tools bake in can be built with [extensions](#extensions), [skills](#skills), or installed from third-party [pi packages](#pi-packages). This keeps the core minimal while letting you shape pi to fit how you work.

Jensen 3.0.0 provides MCP, logical subagents, durable orchestration, explicit Missions, and governed completion through Jensen-owned runtime authorities. These are no longer extension-only concepts.

The interactive harness remains extensible and does not provide unrestricted permission popups or background process ownership. Use the documented Mission, Worker, Governance, and process-stewardship paths for durable execution and cleanup.

Read the [blog post](https://mariozechner.at/posts/2025-11-30-pi-coding-agent/) for the full rationale.

---

## Reliable Agent Runtime

Jensen 3.0.0 includes the Reliability Kernel and the durable distributed runtime
around it: the model proposes actions and completion, while Jensen owns state,
execution, evidence, validation, and completion. Durable Missions, the
Scheduler/Assignment/Worker path, remote execution, capability routing, MCP,
Shared Inference, orchestration, Governance/Budgets, restart/reconciliation,
and Jensen-owned process stewardship are available in this release.

The model normalizes output into Jensen-owned actions, validates executable
actions before execution, records observed evidence, runs deterministic
verification, and enforces a Completion Gate so a model cannot self-certify
completion.

**The model proposes completion. Jensen verifies completion.**

### Automatic activation

In Jensen 3.0.0 the Reliability Kernel is **automatic** for normal Jensen agent
sessions. Opening Jensen normally means the kernel is active: real tool calls
flow through reliability hooks, real tool outcomes become authoritative
evidence, the Completion Gate controls live completion, and mission state
persists with the session.

An assistant turn ending is **not** the same as a mission completing. When a
mission is active, the model "stopping" is routed through the Completion Gate;
a premature "done" produces a structured `FINALIZATION_REJECTED` and gives the
model a bounded chance to continue. `jensen resume <SESSION_ID>` restores the
same mission with its criterion and evidence state intact.

See [docs/reliable-agent-runtime.md](docs/reliable-agent-runtime.md) for the
architecture, authority model, lifecycle, and extension points.

---

## Jensen 3.0 runtime boundary

Jensen 3.0.0 is the distributed autonomous agent runtime foundation. It is
not a persistent daemon/control plane, mobile assistant, voice assistant,
IoT platform, public Internet service, or complete cross-platform OS process
supervisor. Those capabilities are planned for later Jensen 3.x phases.

The 3.0 runtime keeps durable Mission state and session storage authoritative.
Existing 2.x session/config formats remain readable where their persisted
schema is supported. Incompatible or corrupted durable state fails closed;
it is never silently converted into fake success. Review remote-execution,
shared-inference, and Governance settings before enabling distributed work.

## Automatic orchestration

`jensen orchestrator preview <PARENT_MISSION_ID>` asks the configured local Qwen planner for a bounded plan without persisting it. `jensen orchestrator start <PARENT_MISSION_ID>` persists the plan and materializes ready child missions; `--proposal JSON` remains an explicit operator/debug override. Materialization creates durable child identities only. Child execution is owned by the configured child execution port, normally the Scheduler -> Assignment -> Worker path, and the port is the only scheduler enqueue authority. Parent completion is terminal only after required children pass their authoritative status/verification gates; all-optional plans complete once every optional child is terminal. Bounded parent drivers perform mandatory terminal cleanup through Scheduler and Assignment, without writing mission state themselves.

The Qwen planner path is wired and deterministic seams are covered by tests, but live Qwen inference remains deferred qualification: production readiness depends on the configured local model, registry, and deployment health rather than this planning contract alone.

## Mission Governance

Governance is a deterministic policy, admission, and decision layer over missions and orchestration. It does not replace Orchestrator, Scheduler, Assignment, Worker, SharedInferenceScheduler, Capability Routing, Mission coordination, Verification, or the Completion Gate. Those authorities still perform their own actions.

Governance keeps independent accounting for logical-agent work, inference requests, tools, executor work, wall-clock, turns, retries, replans, fan-out/depth, cloud spend, and local inference pressure. Local Qwen (`llamacpp-qwen38-bucephalus/qwen3.8-27b`) has no invented monetary price; queue pressure and wall-clock remain observable separately. Paid inference with unknown pricing is `UNKNOWN`, not zero, and a paid hard-cap decision fails closed.

Policy precedence is operator hard caps, mission policy, orchestration/role policy, provider/model defaults, then Jensen defaults. A lower layer can reduce a hard cap but never raise it. Model escalation preserves mission/orchestration/node correlation and is selective: a critical child can move from local Qwen to the configured cloud model without changing Mission identity.

Durable inspection is available without launching work:

```bash
jensen governance policy
jensen governance status <MISSION_ID>
```

The durable ledger is locked and atomic across processes. Retry classes, escalation history, cloud accounting, and consumed limits survive restart. Empty result envelopes use a separately bounded result-only retry; resource/dependency waiting parks without consuming an inference lease or being classified as reasoning stagnation.

## Subagents and Cavecrew

Inspect the canonical registry and skill dependency state with:

```bash
jensen agents list
jensen agents resolve cavecrew-investigator
jensen agents validate
jensen skills validate
jensen skills migrate --preview
jensen cavecrew validate
```

`cavecrew-builder` is limited to two affected files and uses the existing workspace boundary, policy engine, exclusive lease, checkpoint, transaction, focused validation, and rollback lifecycle. Builder edits are serialized; analytical children are read-only and may run in deterministic parallel assignment order. Parent-side validation rejects invalid child structures before results enter orchestration state.

## CLI Reference

```bash
pi [options] [@files...] [messages...]
```

### Package Commands

```bash
pi install <source> [-l]    # Install package, -l for project-local
pi remove <source> [-l]     # Remove package
pi update [source]          # Update packages (skips pinned)
pi list                     # List installed packages
pi config                   # Enable/disable package resources
jensen agents list --json   # Inspect the canonical subagent registry
jensen agents validate      # Validate definitions and fallback references
jensen skills validate      # Validate loaded skill dependencies before use
jensen routing status --json   # Evidence-driven orchestration status
jensen routing decide --task "..." --json   # Produce a routing decision (offline, deterministic)
jensen routing explain <decision-id>        # Explain a past decision with provenance
jensen routing replay <decision-id>         # Replay a decision with zero effects
jensen routing compare <decision-a> <decision-b>
jensen routing policy list|generate|validate|promote|rollback
jensen routing drift status
jensen doctor routing --json                # Read-only routing subsystem diagnostics
jensen eval packs --json    # List built-in and local evaluation packs
jensen eval validate --json # Validate scenario schemas and fixture references
jensen eval run core-runtime --mode fixture --json
jensen doctor eval --json   # Read-only evaluation diagnostics
```

### Evaluation and release gates

Jensen's evaluation runtime treats scenarios, fixtures, candidate configuration, durable events, assertions, and result artifacts as versioned data. Use `jensen eval packs`, `jensen eval scenarios`, and `jensen eval validate` to inspect the built-in deterministic packs. `jensen eval run <scenario-or-pack> --mode offline|fixture|sandbox` runs bounded evaluation; `live` mode is disabled unless `JENSEN_EVAL_LIVE=1`, `--live`, an explicit provider configuration, and a positive cost budget are all supplied.

Deterministic safety and task assertions outrank semantic judges and aggregate metrics. Candidate self-report cannot set a verdict, missing evidence is not a pass, and safety failures cannot be averaged away. Evaluation artifacts are content-addressed and include scenario, candidate, environment, evaluator, and evidence provenance. Baselines are created and promoted explicitly; they are never silently replaced. Repeated runs retain separate artifacts, and flaky results are explicit rather than clean passes. Ordinary CI uses deterministic fixture providers and no paid API.

### Modes

| Flag | Description |
|------|-------------|
| (default) | Interactive mode |
| `-p`, `--print` | Print response and exit |
| `--mode json` | Output all events as JSON lines (see [docs/json.md](docs/json.md)) |
| `--mode rpc` | RPC mode for process integration (see [docs/rpc.md](docs/rpc.md)) |
| `--export <in> [out]` | Export session to HTML |

### Model Options

| Option | Description |
|--------|-------------|
| `--provider <name>` | Provider (anthropic, openai, google, etc.) |
| `--model <pattern>` | Model pattern or ID (supports `provider/id` and optional `:<thinking>`) |
| `--api-key <key>` | API key (overrides env vars) |
| `--thinking <level>` | `off`, `minimal`, `low`, `medium`, `high`, `xhigh` |
| `--models <patterns>` | Comma-separated patterns for Ctrl+P cycling |
| `--list-models [search]` | List available models |

### Session Options

| Option | Description |
|--------|-------------|
| `resume <SESSION_ID>` | Continue a persisted session by exact session ID |
| `-c`, `--continue` | Continue most recent session |
| `-r`, `--resume` | Browse and select session |
| `--session <path>` | Use specific session file or partial UUID |
| `--session-dir <dir>` | Custom session storage directory |
| `--no-session` | Ephemeral mode (don't save) |

### Tool Options

| Option | Description |
|--------|-------------|
| `--tools <list>` | Enable specific built-in tools (default: `read,bash,edit,write`) |
| `--no-tools` | Disable all built-in tools (extension tools still work) |

Available built-in tools: `read`, `bash`, `edit`, `write`, `grep`, `find`, `ls`, `web_search`, `web_fetch`, `deep_research`, `web_research_status`

### Resource Options

| Option | Description |
|--------|-------------|
| `-e`, `--extension <source>` | Load extension from path, npm, or git (repeatable) |
| `--no-extensions` | Disable extension discovery |
| `--skill <path>` | Load skill (repeatable) |
| `--no-skills` | Disable skill discovery |
| `--prompt-template <path>` | Load prompt template (repeatable) |
| `--no-prompt-templates` | Disable prompt template discovery |
| `--theme <path>` | Load theme (repeatable) |
| `--no-themes` | Disable theme discovery |

Combine `--no-*` with explicit flags to load exactly what you need, ignoring settings.json (e.g., `--no-extensions -e ./my-ext.ts`).

### Other Options

| Option | Description |
|--------|-------------|
| `--system-prompt <text>` | Replace default prompt (context files and skills still appended) |
| `--append-system-prompt <text>` | Append to system prompt |
| `--verbose` | Force verbose startup |
| `-h`, `--help` | Show help |
| `-v`, `--version` | Show version |

### File Arguments

Prefix files with `@` to include in the message:

```bash
pi @prompt.md "Answer this"
pi -p @screenshot.png "What's in this image?"
pi @code.ts @test.ts "Review these files"
```

### Examples

```bash
# Interactive with initial prompt
pi "List all .ts files in src/"

# Non-interactive
pi -p "Summarize this codebase"

# Different model
pi --provider openai --model gpt-4o "Help me refactor"

# Model with provider prefix (no --provider needed)
pi --model openai/gpt-4o "Help me refactor"

# Model with thinking level shorthand
pi --model sonnet:high "Solve this complex problem"

# Limit model cycling
pi --models "claude-*,gpt-4o"

# Read-only mode
pi --tools read,grep,find,ls -p "Review the code"

# High thinking level
pi --thinking high "Solve this complex problem"
```

### Environment Variables

| Variable | Description |
|----------|-------------|
| `PI_CODING_AGENT_DIR` | Override config directory (default: `~/.pi/agent`) |
| `PI_PACKAGE_DIR` | Override package directory (useful for Nix/Guix where store paths tokenize poorly) |
| `PI_SKIP_VERSION_CHECK` | Skip version check at startup |
| `PI_CACHE_RETENTION` | Set to `long` for extended prompt cache (Anthropic: 1h, OpenAI: 24h) |
| `JENSEN_SEARXNG_URL` | Private SearXNG endpoint (default: `http://127.0.0.1:18888`) |
| `JENSEN_WEB_SEARCH_PROVIDER` | `auto`, `searxng`, or `duckduckgo-lite` (default: `auto`) |
| `JENSEN_PLAYWRIGHT_EXECUTABLE_PATH` | Optional Chromium executable for isolated rendered extraction |
| `VISUAL`, `EDITOR` | External editor for Ctrl+G |

---

## Contributing & Development

See [CONTRIBUTING.md](../../CONTRIBUTING.md) for guidelines and [docs/development.md](docs/development.md) for setup, forking, and debugging.

---

## License

MIT

## See Also

- [@apholdings/jensen-ai](https://www.npmjs.com/package/@apholdings/jensen-ai): Core LLM toolkit
- [@apholdings/jensen-pods-agent](https://www.npmjs.com/package/@apholdings/jensen-pods-agent): Agent framework
- [@apholdings/jensen-tui](https://www.npmjs.com/package/@apholdings/jensen-tui): Terminal UI components
