# pic implementation plan

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:

- The harness owns its own libfossil-hosted SQLite database (`pic_*` tables). ctx is optional and later receives finished turns through an outbox and a `ctx ingest` command added upstream in ctx. Nothing in the harness waits on ctx.
- C core and tests; Make/POSIX shell orchestration; Python frozen at its current helpers.
- Dependencies: vendored libfossil + SQLite, zlib and BearSSL only, each pinned file by file (`vendor/*/SHA256SUMS`). The binary links only libc, libm and pthread. No libcurl, no system TLS, no iconv, no `-ldl`.
- Credentials: API keys and provider-sanctioned OAuth only, never subscription tokens; a separate credential project after stage 2 (`docs/credential-project.md`).
- Every stage ends in a command you can run and a test that crashes it. Qualification extras (MC/DC, Fil-C, PGO, contract registry, remote lifecycle) come back only when a stage needs them.
- Providers (2026-11-18): any model, not one vendor. Required: Anthropic, OpenAI, OpenRouter, and any OpenAI-compatible server (local or hosted); Gemini optional. Everything above the adapters (journal, tools, sessions, compaction) is provider-neutral; provider quirks stay inside their adapter.
- Compaction (2026-11-18): pic's own, Pi's algorithm and prompts, identical for every model. Inside the Anthropic adapter, thinking blocks are stripped from turns kept verbatim after a compaction (current Claude models reject a changed history before a thinking block). Anthropic's server-side compaction may come later as a Claude-only optimisation, never the foundation.

## 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: next, detailed below.** Provider-neutral journal, model registry, OpenAI Chat Completions (OpenAI, OpenRouter, OpenAI-compatible servers) and OpenAI Responses adapters.
5. **Sessions.** Follow-ups, continue, list, name, fork; pic's own compaction (Pi's algorithm, any model); the ctx outbox plus `ctx ingest` upstream.
6. **Clients and release.** print/JSON mode, then TUI; release qualification with PGO, Fil-C, and MC/DC on the journal and parsers only.

## 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):
- `openai-completions`: Chat Completions for OpenAI, OpenRouter and compatible servers. Request: system or developer role, assistant `tool_calls`, `tool` messages, `stream_options.include_usage`, `max_tokens` or `max_completion_tokens`, reasoning parameters by `thinkingFormat` (openai `reasoning_effort`, openrouter `reasoning:{effort}`, deepseek, qwen). Stream: `data:` chunks to `[DONE]`, text and reasoning deltas (`reasoning_content`, `reasoning`, `reasoning_text`, OpenRouter `reasoning_details` kept verbatim for replay), tool calls accumulated by index, usage chunk, `finish_reason` mapped as Pi maps it, in-stream error objects. Compat flags auto-detected from provider and base URL as Pi does (OpenRouter, DeepSeek, Moonshot, Cerebras, Together, xAI, Z.ai…), overridable per model. OpenRouter: Anthropic `cache_control` passthrough for `anthropic/*` models.
- `openai-responses`: OpenAI's own models. Input items (`message`, `function_call`, `function_call_output`, `reasoning` items replayed whole with `encrypted_content`), `store:false`, `include:["reasoning.encrypted_content"]`, `reasoning:{effort, summary}`; stream events from `response.created` to `response.completed`/`incomplete`/`failed`.
- `anthropic-messages`: the existing adapter, moved onto the neutral form for cross-provider input.

**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.

## 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.
- `read {path, offset?, limit?}`: head truncation at 2000 lines or 50KB with Pi's continuation notices. Text only; images later.
- `write {path, content}`: creates parent directories; atomic and durable (temp file, sync, rename, directory sync). Replay-safe.
- `edit {path, edits:[{oldText,newText}]}`: exact unique non-overlapping matches against the original, BOM and CRLF preserved, Pi's error messages. Pi's fuzzy normalisation is deferred. Replay-safe through a journaled plan: the new file content is computed first and stored with the effect when it commits "started", so a replay after a crash writes the same bytes instead of failing to re-match.
- `bash {command, timeout?}`: the existing supervisor; tail truncation at 2000 lines or 50KB; Pi's status lines ("Command exited with code N", "Command timed out after N seconds"). Replay-unsafe, as before.
- Paths resolve like Pi's (relative to the workspace, `~` expanded, absolute allowed). Results carry an explicit error flag, journaled, not inferred from the text.

**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:**
- `net.c`: TCP plus TLS 1.2 on vendored BearSSL (adapted from suit): trust anchors from `$SSL_CERT_FILE` or the system bundle, deadline-bounded name lookup and connect, plain HTTP to loopback only. The only file that includes BearSSL, so the TLS library can be swapped (mbedTLS is the fallback if the API drops TLS 1.2).
- `http.c`: strict HTTP/1.1 response parser (fuzzed) and one-shot POST.
- `provider_anthropic.c`: request from the journal; retries 429/5xx/529 and connection errors with `Retry-After` and capped backoff, only before a stream starts. No retries after any byte of a successful stream.
- `sse.c`: provider-neutral SSE framer (event/data lines, multi-line data, comments, CR/LF variants, size caps). Pure function over bytes; no I/O.
- `anthropic.c`: event decoder (message_start, content_block_start/delta/stop, message_delta, message_stop, ping, error) into an assistant message; request builder.
- JSON uses the vendored SQLite JSON functions (`json_extract`, `json_object`, `json_valid`) on an in-memory connection, not a hand-written parser. SQLite's JSON is already in the binary and fuzzed upstream, and ctx uses the same approach. The hand-written trust boundary is the SSE framer and the event state machine.

**Journal changes:**
- Assistant entries store the provider's raw `content` array verbatim. Requests replay it byte for byte, which keeps thinking signatures valid and the history append-only.
- One assistant message may carry several tool calls: effects gain an ordinal per assistant entry, and the next request sends every tool_result for that turn in one user message.
- New `pic_generation` row per provider request: `intent → started → done | failed`, attempt count, usage, stop reason, provider request id.

**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):**
- A local fake server (C, test-only, plain HTTP on 127.0.0.1) replays recorded SSE fixtures: text answer; single and parallel tool calls; thinking blocks with signatures; `refusal`; `max_tokens`; error event; 429 then success; 5xx exhaustion; connection cut mid-stream; malformed frames.
- Crash points: after generation started; mid-stream (pic killed while the server is streaming); after generation committed. Recovery re-requests; the crash suite verifies attempts, final state, and no duplicate tool runs.
- Fuzz targets for the SSE framer and the event decoder, seeded from the fixtures; saved crashes become regressions.
- Sentinel-key leak test as above.
- `make test-pic` stays green; sanitizer build for all of the above.
- One live smoke run against the real API once the fake-server suite passes: a small task, expected cost cents, run with your approval of the key source.

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