Skip to content
pi-c pic implementation plan
Login

pic implementation plan

Status: in force.

Replaces the earlier 11-stage plan (preserved in history at check-in 11f47eadde20), which assumed an embedded context core and front-loaded qualification work. Decisions in force:

Stages

  1. Durable loop: done. Merged at f4faaeff6422. Journal, idempotent admission, replay-safe vs replay-unsafe effects, supervised exec, single-writer fencing, 26-case crash suite (make test-pic).
  2. Real provider: done (details below).
  3. Usable tool set and context assembly: done (details below); landed at 6a67cdb25a60. Exit test (you complete a real task) still open.
  4. Any model: done (details below). Provider-neutral journal, model registry, OpenAI Chat Completions (OpenAI, OpenRouter, OpenAI-compatible servers) and OpenAI Responses adapters.
  5. Sessions: done (details below). Follow-ups, continue, list, name, fork; pic's own compaction (Pi's algorithm, any model); pic export plus ctx ingest upstream.
  6. Clients and release: mostly done. Done: live events, Ctrl-C, line mode, Pi session lines for ctx (now rows in ~/.pic/pic.sqlite), the TUI with Pi's slash commands, the model catalog, user state in SQLite (tickets 2ad667b78b, 467ff3edef), bash output in the journal, the input reader and built-in CA roots, and the platform and executor seams. Open: prompt templates, then skills, then a TUI parity and UX pass; benchmarks and release qualification. The original stage text follows. No daemon: the process running a request is the client, and the journal lets any pic process pick up an unfinished run. In order: live events (--json with Pi's JSON-mode events on stdout; text streamed as it arrives), Ctrl-C cancelling only the current request, an interactive line mode (pic alone: prompt, streamed reply, /compact /fork /sessions /name; the journal lock held per request, not while idle), Pi v3 session files from pic export --pi (ctx archives those), then real daily use (the stage 3 exit test), then benchmarks and release qualification (PGO, Fil-C, MC/DC on the journal and parsers only). A full TUI follows (decided 2026-11-19): a module in the pic binary (src/tui/) that plain pic opens in a terminal; it runs each request as a child pic --json process and knows the run only through Pi's JSON events, so a TUI fault cannot touch a run. Units: width (UTF-8, display width, ANSI-aware wrap), term (raw mode, keys, bracketed paste, size), render (inline differential redraw with synchronized output), editor (multi-line, history, paste markers), app (event loop, transcript, footer, commands, /resume picker). First cut leaves out steering mid-request, @file completion, themes, images and a fullscreen mode. Models follow Pi: a built-in snapshot of Pi's catalog (tools/model-catalog.sh, from pi.dev/api/models) for pic's providers, fresher per-provider lists from pi.dev cached in ~/.pic/models-store.json (ETag, 4 h, used when newer than the snapshot), pic models [--json] [--all] [--refresh], a saved default (pic models --default, ~/.pic/settings.json); in the TUI a picker showing models of providers with a key (Ctrl+L or /model; Enter uses, Ctrl+S also saves the default; Ctrl+P cycles) and a slash menu (Tab completes, Enter runs; /model completes model names).
  7. Optional: running without an operating system. Later, not to be built yet. pic normally runs on a machine with a workspace on disk and bash, and that stays the way it runs. As an option, pic can also be the only process in a microVM (ticket ff1a4dc200): a kernel with no userland, a raw block device holding one SQLite file, and the network, with the project kept as rows through libfossil's cowoco (working copy) and onefile (repository). Details below.
  8. Projects in libfossil: planned (ticket 01e8ad6714, details below). A project's repository and working copy live in ~/.pic/pic.sqlite through onefile and cowoco, with no checkout on disk; bash runs through a local runner.

Option: running without an operating system

What changes: the same as stage 8 (read, write and edit on cowoco rows through pic_executor), minus bash: no programs, no userland, and no POSIX view of the rows. The command tool below replaces bash and is stage 8's local runner pointed at a remote machine.

A separate tool instead of bash (ticket d909e0fe55): in this build it runs a command on a runner machine, and a Fossil check-in is the only thing exchanged (stage 8 uses the same exchange with a local runner):

  1. pic checks in the working copy if it has changes, as a scratch check-in, and pushes it to the runner with Fossil sync.
  2. It sends the effect id, the check-in, the command and a time limit.
  3. The runner (an ordinary machine with fossil and the toolchain) moves its long-lived checkout to that check-in and runs the command. Build outputs stay there, so builds stay incremental.
  4. If tracked files changed (formatters, code generators), the runner checks them in as a child and returns the output and that check-in; pic pulls it and updates its rows.

Rows are never shown as files and no disk is scanned. Because requests are keyed by effect id, after a crash pic asks the runner what happened instead of marking the call's outcome unknown.

Needs: stage 8 (database workspace, check-in step, local runner), a BearSSL sync channel (ticket ff1a4dc200) and a remote runner service.

Open decision (shared with stage 8): where the scratch check-ins live. Proposed: private, pushed only to the runner, if libfossil can make private check-ins (to be verified in stage 8 slice 5); otherwise a clone only the runner holds. Ordinary branches would be simplest but keep every command in project history.

Rejected: no command tool at all (the agent could not build or test); a userland inside the VM over the rows; serving the rows as a network filesystem; WASI toolchains inside pic; CI as the runner (minutes per call, and formatter edits cannot come back).

Stage 8: projects in libfossil

Goal: pic works on a project held in libfossil: clone it, edit it, build it, commit and sync it, with no checkout on disk. Full plan and rationale: https://artifacts.craftdesign.group/v/iGdQUWYgEKFg11HdXfWub#588a107d220bc2385892b353d055a98dd62f35a8bc7bdaaaeaf88896ca5ad414

Decided (2026-11-20):

Slices (each ends in a command and a test that kills it):

  1. Store and clone: pic clone, resumable, rows populated, nothing written outside ~/.pic.
  2. cowoco executor and project mapping: read/write/edit on rows, pic projects, pic status, pic diff; the existing crash suite runs against it.
  3. Commit: pic commit and /commit, exactly-once through a pic-effect tag.
  4. Sync and update: pic sync, pic update; kills mid-push and mid-pull resume.
  5. Local runner and bash: incremental builds, changed files returned as a check-in, a kill after the scratch check-in runs the command once.
  6. zit bridge: pic clone zit:PATH through a local zit serve, never orphaned.
  7. Landings and dogfood: pic land, then work on pi-c from the store for a week (exit test).

Decided (2026-11-20): user state stays in the one store file. A synthetic worst case (8 writers beside back-to-back 100 ms write transactions) measured user-state writes at p50 113 ms, p99 425 ms, max 789 ms, none failing; a real clone holds the lock about 85 ms per round. Instead of splitting, libfossil keeps its write transactions short, and the measurement is repeated with a real clone before revisiting.

Open: where scratch check-ins live (private if libfossil supports it, else a runner-only clone); the zit pipe transport; whether the agent may commit on its own (default no); the rule for untracked files a command creates.

Stage 5: sessions and compaction

Goal: you keep working in one conversation across pic ask calls, branch it, and run it as long as you like on any model, with the journal never losing a turn.

Sessions (Pi's model, in the journal): a session is a path through a tree of entries. Each entry gains parent_seq; a session has a head (its leaf). A new submission's user entry is a child of its session's head, so follow-ups continue the conversation and a request is built from the path from the head back to the root. One admitted submission per session at a time. The session's opening system prompt and tool list are frozen when it starts and reused for every request (append-only histories keep thinking valid and prompt caches warm). Editing AGENTS.md or CLAUDE.md still takes effect in the running session (your call, 2026-11-19): before each request pic compares the project instructions with what the session last saw and, if they changed, journals an "instructions updated" entry with the new text, sent at that point as a mid-conversation system message where the API and model take one, else as a marked block leading the next user message. Appended, never rewritten.

Commands: pic ask TEXT starts a session (Pi's default); pic ask -c TEXT continues the most recent session in the workspace; pic ask --session ID TEXT continues that one; pic sessions lists them (id, name, created, last used, turns, first message); pic name ID NAME; pic fork ID [--at SEQ] starts a new session from a point in another (Pi's /fork; entries are shared, not copied); pic log [ID] prints the conversation.

Compaction (Pi's algorithm, any model): after each reply, when the context estimate (the last reply's usage plus chars/4 for what followed) exceeds the model's context window minus 16384 reserve tokens, pic compacts before the next request; pic compact [ID] [INSTRUCTIONS] does it on demand. The cut keeps about 20000 recent tokens, never separates a tool call from its result, and handles a split turn as Pi does. The summary is a provider request (journaled and retried like any generation) using Pi's summarization and update prompts and conversation serialization, with read and modified files tracked. The compaction entry records the summary, the first kept entry and the tokens before. Requests then send the summary as a user message (Pi's wording), the kept entries, and what followed. Kept entries from before the compaction go out without their thinking, for every provider: current models bind thinking to the full history before it. A context-length error from the provider compacts and retries once.

Landing: trunk now requires the test check; stages land through zit landing open, accepted once CI on the merge is green.

ctx: pic export [--since ENTRY] writes finished entries as JSON lines (conversation, seq, parent, request, role, time, workspace, model, text, tool_calls, tool, call_id, is_error, final; thinking left out). The entry number is the cursor, so no outbox table: export stops before the first entry of any unfinished request, and a reader that keeps the last number it saw never skips or repeats one. ctx reads Pi v3 session files, so pic export --pi [DIR] writes each conversation as one (default ~/.pic/sessions/--<cwd>--/<created>_<id>.jsonl, never Pi's own folder), append-only: entry ids are entry numbers, a fork names its source in parentSession, instruction updates are custom_message (pic.instructions), names are session_info, compactions are Pi compaction entries; ask and the line mode export their conversation after each request (PIC_PI_EXPORT=0 turns that off).

Tests: crash cases for admission into a session, fork, and every compaction commit point; follow-up, continue, fork and frozen-prompt cases per adapter against the fake server; compaction on a long scripted session (cut points, split turn, update of a previous summary, thinking stripped from kept turns, overflow retry); migration of schema-4 journals; benchmarks for path building and compaction; Fil-C.

Stage 4: any model

Goal: pic --model openrouter/<any model> ask …, --model openai/<model> and a local OpenAI-compatible server all work, and one conversation can move between providers turn by turn.

Journal (schema 4): each assistant entry records its origin (provider, api, model) and keeps two forms: the provider's native content, verbatim, for replay to that same provider and model (so signatures and reasoning stay valid), and a neutral content array in Pi's shape (text, thinking with opaque signature/redacted, toolCall with id/name/arguments), produced by the adapter's decoder. Tool calls become effects from the neutral form, the same for every provider.

Cross-provider replay: Pi's transformMessages rules, in one place: a turn from a different provider/api/model is sent from its neutral form; thinking from another model is dropped (signatures are model-bound); tool-call ids are rewritten to the target's limits (Anthropic [A-Za-z0-9_-] up to 64; OpenAI Chat up to 40; Responses call_id|item_id with fc_ item ids), with results rewritten to match; errored or aborted turns are skipped; a call with no result gets No result provided as an error result.

Model registry: built-in providers (anthropic, openai, openrouter, plus Pi's OpenAI-compatible hosts) with base URL, api, key variable and compat; models named provider/model, longest provider prefix first; unknown model ids on a known provider fall back to the provider's defaults (OpenRouter accepts any id). User additions in ~/.pic/models.json, the subset of Pi's schema pic needs: providers.{name}.{baseUrl, api, apiKey ("$VAR"), headers, compat, models[{id, contextWindow, maxTokens, reasoning}]}, which is how a local server is added.

Adapters (each its own decoder on the shared SSE framer and HTTP stack, fuzzed):

Credentials: one variable per provider as Pi names them (ANTHROPIC_API_KEY, OPENAI_API_KEY, OPENROUTER_API_KEY, …) or a models.json apiKey variable; read only for the request, never journaled. Your pic shell function passes the Doppler variables you choose.

Tests: recorded streams per adapter (text, reasoning in each field style, split tool-call deltas, parallel calls, usage, [DONE], errors, truncation), whole and bytewise; a fuzz target per decoder; the fake server driving each adapter end to end, crashes mid-stream included; a cross-provider conversation (Anthropic turn, then OpenAI Chat, then Responses) checked request by request; the key-leak test per provider; Fil-C; benchmarks per decoder. Live smoke runs per provider with your approval of keys and cost.

Status (2026-11-19): done. Registry (13 built-in providers, Pi compat, models.json incl. Pi's own), neutral journal with schema-3 migration, shared HTTP layer, and three adapters (Messages API, Chat Completions, Responses), each with recorded streams, a fuzz target, fake-server cases, crashes mid-stream and the key-leak test; conversations move between every pair of APIs with thinking dropped and tool-call ids normalised identically in calls and results. 147 checks; CI green on every stage-4 check-in; Fil-C passed. Decoder benchmarks found the Chat decoder compiling ten statements per chunk (9.8ms per reply); one cached query brought it to 1.9ms. Live: Anthropic; OpenRouter Chat with DeepSeek, reasoning round-tripped; OpenRouter Responses with gpt-5-nano, encrypted reasoning round-tripped. Still to do outside the code: a direct OpenAI run once its key is in Doppler.

Stage 3: usable tool set and context assembly

Goal: you do real work with pic ask "…" in a project directory, using Pi's default tools, with every tool benchmarked.

Tools match Pi's defaults (read, bash, edit, write) in name, input schema, description, truncation and messages (contracts pinned from reference/pi/packages/coding-agent/src/core/tools). Pi's grep/find/ls are opt-in there and need downloaded ripgrep/fd; bash covers them for now.

Context: system prompt in Pi's section order (preamble, tools, rules, project context, cwd). Project instructions: per directory the first of AGENTS.override.md, AGENTS.md, CLAUDE.md, from the filesystem root down to the workspace, wrapped in <project_instructions path=…>.

Use: pic ask TEXT submits under a fresh key and runs it, with the workspace defaulting to the current directory and the journal to .pic/journal.sqlite; it prints each tool call as it starts and the answer at the end. pic cancel KEY fails an admitted submission. Multi-turn sessions are stage 4.

Benchmarks: make bench-pic on the release build. Per tool: the tool alone (small, medium and large inputs), the durability cost (its two journal commits), and a scripted multi-turn run mixing every tool; median and p95 per call and per turn, plus process start-up. Results go to a per-machine baseline file; a run fails when a median regresses past an agreed tolerance. A tool is not done without its benchmark row.

Tests: contract tests per tool (truncation boundaries, notices, edit errors, overlap, CRLF/BOM), crash cases for edit's plan replay and write's directory creation, the provider suite with the new tool names, Fil-C run.

Status (2026-11-18): tools, context assembly, pic ask/cancel, contract tests (128 checks in make test-pic) and make bench-pic are in; a live pic ask fixed a bug in a scratch project end to end. First baseline (Darwin-arm64, medians): read 1KB 22µs, 10MB 2.4ms; write and edit about 9ms, almost all the durable sync; one journal commit 4.1ms (each tool call makes two); bash true 9ms, down from 60ms after the supervisor stopped sleeping 50ms between exit checks; a whole scripted turn 30-70ms; start-up and check 5ms. Fil-C on hetzner-hel passed every stage 3 suite with no safety errors (teardown verified). Remaining: your real-task exit test.

Stage 2: real provider

Goal: pic run --provider anthropic completes a small task against the live API with the existing write/exec tools, and survives a crash at any point, including mid-stream.

Protocol: Anthropic Messages, streaming SSE, anthropic-version: 2026-10-21. Default model claude-opus-5-5, overridable with --model. That model always thinks: thinking is omitted. max_tokens 64000. Tool inputs are validated by the tools themselves. stop_reason refusal fails the submission, never a tool run; max_tokens without tool calls ends as the answer; pause_turn continues. Deferred until needed: eager_input_streaming, server-side fallbacks, output_config.effort.

Modules:

Journal changes:

Mid-stream crash semantics: a provider request is a billed, replay-unsafe effect, but it has no outside-world side effect, so re-requesting is safe; it only costs money. Decision: the partial stream is never journaled. On recovery, a started generation is marked failed (interrupted) and the turn is re-requested, up to 3 attempts per turn, after which the submission stops with an error. Attempts and any usage seen are recorded, so the cost of a crash is visible. Incremental persistence of partial output is deferred to stage 5, where clients need it.

Status (2026-11-18): everything above is built and tested against a local fake server (make test-pic: 37 crash cases, 14 provider cases including a crash mid-stream and the key-leak test, plus SSE/decoder/HTTP unit tests and two fuzz targets). Live smoke run passed (claude-haiku-5-5, key via doppler run): one turn with two parallel tool calls (write, then exec), then the answer; pic check clean; the key absent from the database. The API added a caller field to tool_use blocks that the fixtures lack; verbatim replay carried it through. Fil-C on hetzner-hel (tools/remote/run.sh mode pic: guarded transient units, verified teardown): the first run caught a varargs over-read in record_reply (six bind types for five values) that ASan and every local test missed; fixed, and run_stmt now rejects a type count that differs from the statement's parameters. The second run passed everything: SSE, decoder and HTTP suites, all crash cases and all provider cases. Stage 2 is complete.

Credentials: the API key comes from ANTHROPIC_API_KEY only, read by src/cred.c (the credential project's helper later). It lives in memory for one request, is never journaled, logged, or put in error text, and request headers are never stored. A test runs with a sentinel key and fails if the bytes appear anywhere in the database, WAL, or output.

Tests (exit criteria):

Out of scope: OpenAI-family decoders (a second decoder later on the same framer), prompt caching tuning, message threads, compaction, token counting.