# pi-background-tasks Test Plan

This package follows the package-local maintainer navigation:

- `BACKGROUND-TASKS-INSTRUCTIONS.md` — required agent gateway/read order
- [`docs/operations/testing.md`](docs/operations/testing.md) — gate selection and isolation
- [`docs/operations/releasing.md`](docs/operations/releasing.md) — release/payload maintenance

The table below remains the exhaustive acceptance source. Do not replace it with a generic summary.

## Package

| Field | Value |
|---|---|
| Package | `pi-background-tasks` |
| Extension entrypoint | `extensions/background-tasks.ts` |
| Public commands | `/bg`, `/jobs`, `/logs`, `/kill`, `/tasks`, `/bg-tasks`, `/bg-clear`, `/bg-update`, `/fusion`, `/fusion-models` |
| Public tools | `bg_run`, `bg_delegate`, `bg_result`, `bg_run_pi_attested`, `bg_status`, `bg_logs`, `bg_kill`, `fusion_reason`, `fusion_investigate`, `fusion_research`, `fusion_validate` |
| Extension EventBus API | `pi-background-tasks:request:v1`, `pi-background-tasks:response:v1`, `pi-background-tasks:terminal:v1`; schemas exported from `src/core/extension-api.ts` |
| Shortcuts | `Shift+Down`; optional fallback `Ctrl+Alt+C` |
| Custom UI | footer status + focused bottom dock overlay |
| Custom provider | no |
| Runtime files/state | `.pi/tasks/<session-id>-<pid>/<task-id>.output`, `.pi/tasks/<session-id>-<pid>/<task-id>.json`; attested Pi opt-in adds `.pi-events.jsonl`, `.stderr`, `.pi-telemetry-wrapper.cjs`, `.attestation.json`; Fusion adds private `.pi/fusion/<session-id>-<pid>/<run-id>/` manifests/prompts/events/stderr/responses/evaluation/merged/error artifacts plus `context-omission-ledger.json` and `budget-plan.json` plus global `fusion-models.json` |
| Maintainer docs/gateway | `BACKGROUND-TASKS-INSTRUCTIONS.md`, `docs/api/eventbus-v1.md`, `docs/concepts/context-projection-and-budgeting.md`, `docs/subsystems/child-launch-durability-and-safety.md`, `docs/reference/runtime-contracts.md`, `docs/operations/{troubleshooting,testing,releasing}.md`, `TESTING.md`, `TEST_PLAN.md`, `PUBLISHING.md` |

## Required gates

| Gate | Command | Required in default `npm run test`? | Status |
|---|---|---:|---|
| Typecheck | `npm run typecheck` | yes | implemented |
| Unit | `npm run test:unit` | yes | implemented |
| SDK | `npm run test:sdk` | yes | implemented |
| RPC | `npm run test:rpc` | yes | implemented |
| Component | `npm run test:component` | yes | implemented |
| Package | `npm run test:package` | yes | implemented |
| PTY/TUI | `npm run test:pty` | full gate | implemented (answers pi's Kitty keyboard-protocol negotiation; auto-skips with a loud reason on hosts that cannot deliver raw-mode Node stdin via `/usr/bin/expect`) |
| Scripted provider | `npm run test:agent-loop` | full gate | implemented |
| Hook contract | `npm run test:hook-contract` | yes | implemented; drives a real Pi agent loop and compares observed `context`/`tool_result` behaviour against committed evidence. Fails loudly if Pi's hook semantics change rather than regenerating them |
| Pack dry run | `npm run pack:dry-run` | release gate | implemented |
| Smoke | `npm run smoke` | no | implemented; isolated load-only |
| Large-context smoke | `npm run smoke:large-context` | release gate | implemented; rebuilds the production failure byte composition, proves the pre-fix input is rejected and the post-fix projection fits all four stages against the smallest configured route, with no inference and no child spawn |
| Live subscription evidence | `npx tsx scripts/delegate-live-run.ts` | release gate | implemented; one real subscription-OAuth child on the parent's current route, large seeded session, hash-verified answer, and explicit leak checks. Caught two defects no offline gate did (undelivered prompt, seed-not-prompt budgeting), both now pinned by unit and mutation tests |
| Compatibility | `npm run test:compat` | release gate | implemented; exact Pi `0.81.1`, `0.82.1`, `0.83.0` pack/install plus `/jobs`, `/fusion`, and `/fusion-models` surfaces, per-version `agent_settled`/`before_provider_request` declarations, Anthropic cache-adapter contracts, and bundled-TypeBox peer verification, removed-TypeBox-API scan of installed package bytes, followed by a current-host real `fusion_reason` session-stat and replay witness |
| Docs verification | `npm run docs:verify` | prepack/release gate | implemented; offline docs freshness, generated region/index/manifest/link/reachability/coverage checks with advisory attestation state; optional `docs:verify:attestations` enforces fresh receipts |
| Docs tests | `npm run test:docs` | targeted docs gate | implemented; docs-gate unit/package tests |
| Payload policy | `npm run payload:check` | prepack/release gate | implemented; package payload/docs/assets exclusions and inclusions |
| Release version sanity | `npm run release:check-version` | release gate | implemented; package version/tag sanity without advertising nonexistent tags |
| Docs/gateway focused checks | frontmatter/link/version checks plus package docs gate when allowed | docs-only gate | implemented operationally; verifies `docs/**/*.md` frontmatter shape, package-local links, no standalone parent `../EXTENSION_*` links, package version wording from `package.json`, observed git tags, and documents current `docs:generate`/`docs:verify`/attestation workflow |

## Fusion v1 public surface coverage

Fusion v1 is a breaking public API release. Public tools are exactly `fusion_reason`, `fusion_investigate`, `fusion_research`, and `fusion_validate`; `fusion_brainstorm` is retired, removed from active tools on `session_start`, and not reactivated in resumed sessions. `/fusion` remains and maps to `fusion_reason` with no-tool candidates. `/fusion-models` remains shared.

| Public surface | Contract |
|---|---|
| `fusion_reason({prompt})` | closed schema, visible-session projection with no candidate tools, no `capability` |
| `fusion_investigate({objective, background, deliverable, scope?, constraints?})` | closed schema, optional arrays normalize to `[]`, clean-context read-only investigation |
| `fusion_research({... sources:[{url,purpose}]})` | non-empty public `http(s)` sources, no credentials, canonical duplicate rejection; targeted URL fetch, not search, with URL exfiltration warning |
| `fusion_validate({objective, background, changeSummary, scope, acceptanceCriteria, verification, knownLimitations?, exclusions?})` | `scope` and `acceptanceCriteria` non-empty; `verification.status:'provided'` requires evidence and no reason; `not_run` requires reason and no evidence; advisory/read-only, not a build/test substitute |

SDK/RPC/scripted-provider/package/compatibility coverage asserts exactly four tools in discovery and active-tool repair, no public capability mode, direct `/fusion` result behavior, usage propagation, cancellation/shutdown, legacy v4 rendering, packed files, TypeBox enum schemas, and actionable legacy `fusion_validate({prompt})` migration errors.

## Feature coverage matrix

| Feature | Public surface | Unit | SDK | RPC | Component | PTY | Package | Scripted provider | Notes |
|---|---|---:|---:|---:|---:|---:|---:|---:|---|
| Start background command from UI command | `/bg` | yes |  | yes |  | yes |  |  | Unit covers `--name` and `--agent`; RPC/PTY start real processes. |
| List tasks | `/jobs` |  |  | yes |  |  |  |  | RPC asserts running and killed task rows. |
| Show bounded logs | `/logs <id> [maxBytes]` | yes |  | yes |  |  |  |  | Unit covers bounded reads; RPC verifies output/path. |
| Kill running task | `/kill <id>` |  | yes | yes |  |  |  |  | SDK tool and RPC slash command. |
| Open task manager fallback | `/tasks`, `/bg-tasks` |  |  | discovery | yes | yes |  |  | Component covers dock; PTY covers `/tasks` and `/bg-tasks`. |
| Start background command from LLM tool | `bg_run` | yes | yes |  |  |  |  | yes | Unit derives all notification/wake modes from one typed helper. SDK exercises the registered tool's effective system prompt, descriptions, non-terminating behavior, and all four launch-receipt combinations. The scripted provider verifies a default launch yields without sleep/status/log polling before one terminal-event follow-up. |
| Attested direct Pi producer | `bg_run_pi_attested` | yes | yes |  |  |  | type/schema |  | Unit covers 128-bit ids, exact direct argv, raw events/stderr, provider/model/session capture from Pi JSON, OAuth observation via ModelRegistry, prompt/report/source hash laws, completion visibility only after durable sidecar creation, malformed-event rejection, and no sidecar for ordinary tasks. SDK runs a fake Pi CLI through the public tool and verifies one complete flat attestation. |
| Inspect task status | `bg_status` |  | yes |  |  |  |  | yes | SDK uses exact IDs for deterministic lifecycle observations and verifies the model-facing contract calls status a point-in-time inspection rather than a wait primitive. Scripted-provider ordinary waiting makes zero status calls. |
| Read task logs | `bg_logs` | yes | yes |  |  |  |  | yes | SDK verifies bounded content and the model-facing no-wait-loop contract. Scripted-provider ordinary waiting makes zero log calls. |
| Stop task from LLM tool | `bg_kill` |  | yes |  |  |  |  |  | Covers running kill and already-finished loud failure. |
| Fusion command direct result | `/fusion`, `fusion-result` custom message | yes | yes | yes |  | yes | yes |  | Core unit covers deterministic v2 conversation-projection construction, explicit image omission markers without raw image data, direct final-text child argv/stdin/compact-metadata parsing, exact multi-block answer reconstruction, artifacts, pre-abort handling, and orchestration. SDK runs real `/fusion` against a fake child `pi`, verifies exactly five child text-mode invocations, hidden prompt persistence, visible exact merged custom message, no parent assistant rewrite, renderer output, progress/status behavior, no-argument editor flow, editor cancellation, and malformed config causing zero children. RPC verifies command discovery, `/fusion <prompt>` with U+2028/U+2029 content, custom-message result emission, no parent `agent_start`, no-argument editor protocol, malformed config/child failure visibility, and child isolation flags. PTY verifies `/fusion` renders the exact merged answer directly in a real TUI. Compatibility smoke runs `/fusion` through every supported Pi version with the installed package entrypoint. |
| Fusion v1 tool result | `fusion_reason`, `fusion_investigate`, `fusion_research`, `fusion_validate` | yes | yes |  |  | current-host stats/replay | yes | yes | Exactly four tools are registered/activated; `fusion_brainstorm` is removed from active tools. No public `capability` exists. BUG-182 coverage pins the exact host `Usage` contract, complete cost-component aggregation, v4 result rendering, exact merged text, progress, context exclusion, and final details. The compatibility gate drives a real current-host RPC agent through `fusion_reason`, verifies persisted tool usage, invokes the same session-stat path used by the footer, then reopens the durable session and verifies identical stats. |
| Fusion Anthropic child sanitization | `@ravshansbox/pi-anthropic-sps` dependency, child `--extension` argv | yes |  |  |  |  | yes |  | Unit proves a Claude route receives exactly two `--extension` paths with the sanitizer first and the package runtime governor/metadata extension second, so final provider-payload measurement occurs after sanitization; every non-Anthropic provider still receives exactly one and never resolves the sanitizer at all, and that the real installed package resolves to an existing file through its manifest `pi.extensions[0]`. Resolution failures are each pinned as loud errors: package unresolvable, manifest unreadable, manifest not JSON, missing `pi` section, empty `pi.extensions`, blank entry, and a declared file that does not exist. Package guards require the sanitizer to be a declared dependency and require the provider gate so non-Anthropic child argv cannot drift. |
| Fusion validation workflow | structured `fusion_validate`, workflow profiles, `fusion-manifest.v4`, `fusion-result.v5` | yes | yes |  |  |  | yes |  | Public validation rejects legacy `{prompt}` with a migration error, enforces non-empty `scope`/`acceptanceCriteria`, and loudly validates `verification` cross-fields (`provided` ↔ evidence, `not_run` ↔ reason). Core validate orchestration is clean/read-only/advisory, enforces source-finding accounting including singleton, duplicate, exclusion, and merger add/drop cases, and remains no build/test substitute claim. |
| Fusion context boundaries | canonical input `fusion-input.v5`, reason `context-omission-ledger.json`, clean-task inputs | yes | yes | yes |  |  | yes |  | Unit covers reason/session projection for a >1 MB synthetic tool-heavy session, verbatim user/assistant text, thinking exclusion, zero tool-payload preview bytes, exact and stable omission counts/byte totals/hashes, compact tuple round-trip, receipt-to-ledger reconciliation, active-tool-call-leaf and sibling-call exclusion, and byte-identical repeated construction. Clean-task tests assert investigate/research/validate inputs omit parent system prompt, conversation projection, and omission ledger, stay byte-identical across unrelated parent sessions, and keep parent sentinels out of every clean downstream prompt and artifact. SDK/RPC verify clean validate stdin has no `conversation_projection` or transcript while `/fusion`/reason preserve the projected-conversation path. |
| Fusion stage budgets | `budget-plan.json` (v4 per-stage forecasts), typed `prompt_budget_exceeded_forecast` / `prompt_budget_exceeded_measured` | yes |  |  |  |  |  |  | Unit covers the per-family affine estimator, additive segment accounting, multibyte 1.0-token/byte charging, unknown-provider floor visibility, per-route reservation of `max(Fusion output contract, model maximum output)`, byte-capacity route selection, scope guards for small windows, input-only fatal preflight versus warning-only reservations, rejection of unknown/zero/negative/too-small context windows, boundary accept at exactly the limit and reject one byte past, the child system prompt counted as input, per-stage forecasts built from the real prompt builders against each stage's own route, reservation warnings, breach-detector artifacts, safe prompts completing all five calls, persisted route/plan snapshots including negative slack on fatal rejection, and the reproduced 1 MB failure shape now fitting the smallest configured budget. Errors carry stage, measured size, allowed size, limiting model, estimator source, and remediation in both structured detail and message text. |
| Fusion fixed-purpose profiles | `/fusion`, `fusion_reason`, `fusion_investigate`, `fusion_research`, `fusion_validate`, candidate child argv | yes | yes | yes |  |  | yes |  | Public surface has no caller-selected capability. SDK/RPC pin `/fusion` to reason/no-tool candidates; investigate is read-only, research is targeted URL fetch with public http(s) source validation, and evaluator/merger remain no-tools by stage policy. Package guards reject extra keys and verify schemas are closed. |
| Fusion research web fetch | `fusion_web_fetch({ url, extract? })`, `candidate-<slot>.attempt-<n>.tool-calls.jsonl` | yes |  |  |  |  | yes | live child | Unit covers the closed schema surface through the child extension, registration only when research mode is enabled, unsupported schemes and URL credentials failing before network access, blocked DNS classes, a mixed public-plus-blocked DNS answer failing loudly, a redirect to a blocked address failing loudly, redirect-loop limit failure, Content-Length and streamed-body response caps, unsupported content types, Markdown extraction preserving links/headings/tables/code blocks, script/style stripping, text/plain passthrough with hash and byte count, UTF-8-safe output truncation, and typed timeout. Unit also proves the resolver is consulted once and the connection is pinned to that vetted address, undeclared research URLs are rejected before fetch with only the attempted URL hash audited, and that audit metadata records `url`, `final_url`, `http_status`, `response_bytes`, and `content_sha256` without raw page content. Package guards require `fusion_web_fetch` registration behind the research env flag. Live verification fetched `https://example.com/`, reported the page H1, read a repository constant, and refused instruction-like text from both a repo file and the fetched page. |
| Fusion multi-message transcript validation | `*.events.jsonl`, `fusion-child-settlement.v2`, stop reasons `toolUse`/`stop` plus recovered retry markers | yes |  |  |  |  |  |  | Unit accepts a multi-message tool loop, validates increasing cache-observation request ordinals, reconstructs stdout from the final assistant message only, and sums usage across all compact metadata records. Terminal `agent_settled` emits exactly one settlement binding ordered record bytes/count/final hash. Non-final `toolUse` remains normal; non-final `error` is accepted only when it has zero content and usage, is followed by final `stop`, and its ordinal is hash-bound in the settlement. Final/non-zero errors, `length`, `aborted`, `pending`, missing/duplicate/tampered/failed settlements, and pre-settlement shutdown fail loudly. |
| Fusion runtime context governor | `pi-background-tasks.fusion-runtime-guard.v1`, typed `child_runtime_budget_exceeded` | yes |  |  |  |  |  | scripted provider | Unit proves every exact final provider payload is serialized, hashed, and conservatively estimated against `contextWindow - max(32,768, model.maxTokens) - 4,096`; request 128/tool call 192 are allowed and the next is refused; malformed/duplicate frames and clean-looking post-refusal output fail closed; parent errors preserve observed usage. A real local-HTTP Pi loop through the production `openai-codex-responses` adapter proves earlier payload transforms reach the later governor and `ctx.abort()` prevents network transport. |
| Fusion stale-action watchdog | `FUSION_CHILD_IDLE_TIMEOUT_MS`, child process lifecycle | yes |  |  |  |  |  |  | Unit proves a child with no stdout or stderr activity fails as `child_timeout` with the stalled-child message and is terminated; stderr activity resets the watchdog and allows success; the 30-minute absolute timeout path remains distinct and is not reported as a stalled child. |
| Fusion candidate tool-call audit log | `candidate-<slot>.attempt-<n>.tool-calls.jsonl`, `*.seal.json`, `pi-background-tasks.fusion-tool-call.v1` | yes |  |  |  |  |  |  | Unit proves completed tool calls are logged with tool name, byte counts, and hashes while raw arguments/results containing a secret never appear. Children are independently bounded to 192 attempted tool calls and 8 MiB aggregate tool-result bytes; a limit refusal emits structured evidence, aborts, and cannot publish a complete seal. Repeated low-level `agent_end` boundaries publish no seal; terminal `agent_settled` exclusively seals the complete log after all retry/compaction/follow-up work. The 46-call incident regression proves a 22-call prefix is never sealed and duplicate settlement fails without replacement. Shutdown before settlement writes failed evidence and latches process failure. The parent rejects extension diagnostics and missing/failed/mismatched seals and independently rejects aggregate result bytes above 8 MiB. A trailing partial line, ordinal gap, duplicate ordinal, wrong schema version, and inspect-child partial log all fail loudly. |
| Pi/TypeBox compatibility | `peerDependencies`, packed bytes | yes |  |  |  |  | yes |  | Unit pins typebox as a `"*"` peer that is neither a runtime nor bundled dependency, requires the resolved TypeBox to be Pi 0.83's 1.3.x line, requires all four supported Pi/TUI lines in the peer range, scans all package TypeScript for the seven removed TypeBox APIs, and compiles the shipped tool schema plus nullable-array/nullable-string and optional-field shapes under TypeBox 1.3. The release compat gate repeats the removed-API scan against installed package bytes per Pi version. |
| Pi hook contract | `npm run test:hook-contract`, `tests/scripted-provider/pi-hook-contract-evidence.json`, `src/core/delegate/hook-contract-evidence.json` |  |  |  |  |  | evidence parity | yes | Executes real Pi agent loops and records, rather than assumes: Fusion `before_provider_request` transformations chain in extension load order through the Codex transport adapter and abort before local HTTP transport; Delegate `context` fires once before every model call in load order; returned messages reach the provider; **throwing** in `context` does NOT block dispatch (Pi catches and continues); `ctx.abort()` does not skip the call site but delivers an already-aborted signal and terminates the run; `tool_result` fires before the transcript entry, chains in load order, replacement reaches the provider while the original does not, and toolCallId/role/`isError` survive. Handler ordering across two separate probe extensions is pinned. The evidence file is compared, never silently regenerated, and a package test asserts the shipped copy is byte-identical. |
| Delegate context seeding | `bg_delegate` seed `pi-background-tasks.delegate-seed.v1`, `seed.json`, `context-omission-ledger.json` | yes | yes |  |  |  | mutation guard | yes | Unit covers verbatim visible user/assistant text, complete exclusion of thinking/tool-call arguments/tool-result payloads, marker-only images with no raw bytes anywhere in the seed, exclusion of the in-flight `bg_delegate` call **and every sibling call in the same assistant message** (two delegates launched together get byte-identical projected history), the prompt preserved exactly and marked `explicit_text` authority, zero payload-preview bytes, byte-identical construction across repeated builds and across separate processes via a fixed-leaf fixture, and refusal of a blank prompt. Receive-side verification rejects a single mutated byte, a foreign task identity, a structurally malformed seed whose hash matches, a directive whose hash disagrees with its text, and an unsupported capability. SDK proves the projected parent text actually reaches the child. |
| Delegate route pinning | `bg_delegate` `route`, `route_attestations` | yes | yes |  |  |  | mutation guard | yes | Unit covers defaulting to the parent current model, explicit pinning, refusal of an unavailable route with `route_unresolved` and no substitution, refusal of a route with no declared context window with `route_capacity_unknown` rather than assuming one, and refusal when neither is available. The result package rejects a mismatched route, a mismatched attestation, and a package carrying no attestation at all. The scripted-provider gate proves an observed route drift prevents a success commit entirely. The mutation guard fails if a fallback list or first-available selection appears. |
| Delegate budget and guard | `budget-plan.json`, typed `seed_budget_exceeded` / `provider_context_budget_exhausted` | yes | yes |  |  |  | mutation guard | yes | Unit covers reserve subtraction, exact-boundary accept and one-byte-past reject, the child system prompt counted as input, multi-byte UTF-8 measured by bytes, refusal of unusable windows without defaulting, and a total runtime governor that cannot throw from inside a hook. Preflight rejection is proven to create **zero** children and **zero** artifacts for hook-contract, budget, and blank-prompt refusals, with the artifact directory verified absent. The scripted-provider gate proves an over-budget model call is blocked in a real agent loop and produces a typed terminal record with no committed result. |
| Delegate tool-result spilling | `spill/` artifacts, `pi-background-tasks.delegate-receipt.v1`, `delegate_read_artifact` | yes | yes |  |  |  | mutation guard | yes | Unit proves a 2 MB payload is written in full, hashed, and represented by a receipt carrying `(turn_sequence, source_call_index, tool_call_id)` assigned before execution, so parallel spills completing out of order cannot be mis-associated; an aggregate-cap refusal writes nothing and emits no receipt; bounded range reads return exactly the requested bytes; a range past end-of-file, a path escaping the artifact directory, and non-positive lengths are refused rather than shortened. The scripted-provider gate proves in a real agent loop that the raw payload never enters the transcript, the transcript instead carries a receipt naming the hash and stating nothing was truncated, and an over-long range read fails loudly. |
| Delegate result commit and `bg_result` | `result.json` (`pi-background-tasks.delegate-result.v1`), `bg_result` | yes | yes |  |  |  | mutation guard | yes | The single atomically-committed package is the sole answer data plane: temp-write, file fsync, and rename, with the rename as the commit point; POSIX additionally fsyncs the parent directory while Windows explicitly lacks that portable directory-entry guarantee. Unit covers round-trip verification, multi-block concatenation, exact preservation of U+2028/U+2029/emoji/unnormalized sequences, refusal of lone surrogates rather than U+FFFD substitution, detection of block-hash, aggregate-hash, declared-length, and non-strict-base64 corruption, foreign identity/seed rejection, and explicitly unavailable usage that is never reported as zero. Terminal evaluation treats a zero-exit child with no committed package as typed `child_exited_without_commit`, reports the child-recorded reason when present, and classifies a killed task as cancelled. SDK covers not-ready (non-blocking), completed, corrupted, route-drift, and unknown-task paths, and proves an oversized answer degrades to an artifact reference while an explicit inline request fails with `result_too_large_for_inline` and is never truncated. |
| Delegate isolation boundary | child argv, `--session-id`, `--session-dir`, `--tools` | yes | yes |  |  |  | mutation guard | yes | Unit proves the child receives its own session id and a task-owned session directory, no `--continue`/`--resume`/`--session`/`--fork`, only the inspect tool set, an explicit denylist covering `bash`/`edit`/`write`/`bg_delegate` and all current/retired Fusion tools, disabled discovery of extensions/skills/prompt templates/themes/context files, exactly one explicitly loaded package guard extension, explicit provider/model with no `--api-key`, and parent session identity stripped from the child environment. SDK verifies the same facts from the argv and environment the child actually observed. |
| Fusion artifact byte immutability | `canonical-input.json`, `context-omission-ledger.json`, `budget-plan.json` | yes |  |  |  |  | shared-source guard |  | A 28-case differential corpus is rendered to raw bytes and compared against a committed golden file that is never auto-updated once present, and separately against `tests/oracle/fusion-context-pre-extraction.ts`, a verbatim pre-extraction copy of the projection engine used as an **independent oracle**. Equivalence covers canonical input, ledger, and budget-plan bytes, `Object.is` comparison of budget floats including `utilization`, field-for-field accounting parity, ledger root hashes, and identical error type and message for unknown blocks and blank requests. The package guard now scans the shared `context/` modules, not only the Fusion facade, and pins both the shared divisor definition and Fusion's binding to it. |
| Fusion model selector | `/fusion-models`, `fusion-models.json`, `FusionModelSelector` | yes | yes | yes | yes | yes | yes |  | Unit covers strict config parsing, duplicates, slash-containing model IDs, stale model failures, `$current`, atomic save, inter-process lock/revision compare-and-swap, and deterministic concurrent-save conflict. Component covers all five slots, duplicate selection, searchable model list, stale display, reset/save/cancel, persistence errors, and width safety. SDK drives the real command in a synthetic TUI context without `ctx.mode` to cover old Pi compatibility and verifies duplicate `$current`/explicit model persistence; SDK also verifies headless no-UI rejection. RPC verifies non-TUI notification without hanging, PTY verifies the real selector opens in a TUI, and compatibility smoke verifies print-mode rejection for every supported Pi version. |
| Fusion child isolation/lifecycle | child `pi --mode text`, private compact metadata extension, shutdown cleanup, `.pi/fusion` artifacts | yes | yes | yes |  | current-host stats/replay | yes |  | BUG-180 coverage proves final-text transport, reasoning exclusion, strict response reconstruction, unchanged caps, isolation, process cleanup, failure artifacts, and lifecycle semantics. BUG-182 preserves all token and cost components and proves successful plus failed/cancelled attempt costs aggregate exactly once. Claude cache coverage pins default one-hour retention, explicit short/none/long policy, model fallback, no-marker compaction preservation, four-breakpoint enforcement, sanitizer-before-normalizer ordering, and hash-bound cache observations in child-result v3/settlement v2 artifacts. SDK/RPC verify public child isolation; session shutdown tracks initializing and live runs. |
| Extension request/response service | `pi-background-tasks:request:v1` → `pi-background-tasks:response:v1` | yes | yes |  |  |  | yes |  | Unit covers closed-frame validation, capability handshake, unknown keys, unknown operation, duplicate request IDs, missing `session_start`, shutdown refusal, strict `run.payload`, strict malformed frames, and unsubscribe. SDK loads the real extension with a shared `createEventBus()`, starts `printf api-ok`, reads bounded logs, lists status, starts and kills a real sleep task, and checks malformed/unknown/duplicate controls without model/provider calls. Package tests assert `src/core/extension-api.ts` ships. |
| Terminal EventBus publication | `pi-background-tasks:terminal:v1` | yes | yes |  |  |  | yes |  | Registry unit proves one terminal snapshot after durable metadata when EventBus emit succeeds and loud/retriable delivery failure. Because retry after a listener throws may redeliver to an earlier listener, consumers must deduplicate by task id. Extension API unit proves one strict terminal frame correlated by task id after the run response for immediate, normal, failed, timeout, and killed tasks; SDK observes one terminal event for a completed task and one for a killed task through the real extension service. |
| Completion notification | custom message `background-task-notification` | yes | yes |  | renderer via typecheck |  |  | yes | BUG-181 unit/SDK coverage pins the durable-terminal guidance and truthful effective delivery receipts. Scripted provider loads the shipped extension, conditionally attempts the old `bg_status` poll when the real system prompt/descriptions/receipt are incomplete, and proves the fixed contract instead yields with exactly one `bg_run`, one terminal notification, and one default follow-up. Notification-only, notification-disabled, failed-task, and display-only `/bg` paths remain covered. |
| Footer status | `ctx.ui.setStatus` |  | load path + clear command/shortcut + mixed states/focused label |  | render semantics | yes |  |  | SDK verifies `/bg-clear` hint, failed/stopped/done combinations, running combinations, and focused label; PTY verifies Shift+Down dock path after footer-visible task. |
| Explicit agent classification | required `bg_run.isAgent`, `/bg --agent`, task metadata | yes | yes |  |  |  |  | yes | `isAgent:true` is required only for LLM/agent tasks and enables Pi-agent telemetry wrapping when the command invokes plain `pi`; `isAgent:false` is required for scripts/non-agents and prevents wrapping even if the command text looks like `pi -p ...`. |
| Per-task context usage | task row/detail + `bg_status`/metadata/notification snapshots | yes | yes |  | yes |  |  |  | SDK verifies task-owned telemetry is captured, explicitly marked background `pi` invocations are wrapped to emit telemetry, and parent `ctx.getContextUsage()` is not used; component verifies list/detail rendering plus `ctx —` placeholder. |
| Per-task token usage | background Pi-agent telemetry + `bg_status`/metadata/dock row/detail | yes | yes |  | yes |  |  |  | SDK verifies cumulative input/output/cache read/cache write/total token usage from explicit telemetry, fake `isAgent:true` wrapped child events, and real child `pi --mode json` with scripted provider; component verifies row/detail rendering. |
| Per-task tool-use counts | background Pi-agent telemetry + `bg_status`/metadata/dock row/detail | yes | yes |  | yes |  |  |  | SDK verifies total/failed/by-name tool counts from fake and real child Pi `tool_execution_start/end` events, including failed tools; component verifies row/detail rendering. |
| Per-task agent model | background Pi-agent telemetry + `bg_status`/metadata/dock row/detail | yes | yes |  | yes |  |  |  | Unit verifies `formatModelSummary`/snapshot-list rendering and telemetry ingestion of `model`; SDK verifies the model is captured from explicit telemetry, fake `isAgent:true` wrapped child `message_end` events (qualified `provider/model`), and a real child `pi --mode json` run (bare child model re-qualified from `--model`), plus that non-agent tasks report no model; component verifies compact `model <id>` row, fully-qualified `Model:` detail, and the “not reported by this background task” placeholder. |
| Agent activity transcript | wrapped Pi-agent output file + dock detail tail + `bg_logs` | yes | yes |  |  |  |  |  | Unit covers `parseAgentActivity`/`formatAgentActivityLine` for assistant text, reasoning, tool start (arrow + collapsed/truncated arg summary), and tool end (silent success, `✗ tool failed[: error]`), plus blank/invalid/non-activity narrowing. Registry unit verifies wrapped-agent stdout is reconstructed across split chunks into the transcript, `background-task-telemetry`/`-context-usage`/`-activity` control lines are stripped from the output file while still updating telemetry fields, child stderr passes through verbatim, and the trailing partial line is flushed on finalize. SDK verifies fake and real child `pi --mode json` runs render `→ tool`, `✗ tool failed`, and assistant text in `bg_logs` while keeping the telemetry/activity control JSON out of the visible output. |
| Focused dock list | overlay component |  |  |  | yes | yes |  |  | Selection/actions/history tested; PTY covers arrows, page keys, ordering with multiple tasks, failed/unread badges, and `/bg-tasks` fallback. |
| Focused dock detail | overlay component |  |  |  | yes | yes |  |  | Tail read, output box, and return-to-list tested. Component also verifies output-tail scrolling: ↑/↓ + PageUp/PageDown move through the loaded window, scrolling up pauses the live tail and shows a `lines X–Y of N` position, paging back to the bottom resumes follow, and output that fits the window never enters scroll mode. PTY drives the real arrow/page scroll keys in the detail tail. |
| Dock stop selected | `k` |  |  |  | yes |  |  |  | Component. |
| Dock stop all | `a`/`K` |  |  |  | yes | yes |  |  | Component and PTY confirmation. |
| Dock rerun | `R` |  |  |  | yes | yes |  |  | Component plus PTY running/completed/failed/killed rerun paths. |
| Dock close | `x`/`Esc`/`q` |  |  |  | yes | yes |  |  | Component + PTY. |
| Shortcut opens dock | `Shift+Down` |  | registration |  |  | yes |  |  | PTY sends xterm `ESC [ 1 ; 2 B`. |
| Clear finished notices | `/bg-clear`, optional `Ctrl+Alt+C` fallback |  | yes | yes |  |  |  |  | `/bg-clear` is the canonical terminal-independent path and is advertised while unseen finished tasks exist and the dock is closed. SDK invokes the slash-command handler and verifies fallback shortcut registration; RPC verifies `/bg-clear` clears finished notices. Opening a finished task's detail marks that task seen; merely opening the list or closing the dock does not clear other badges. |
| Update-available footer notice | `⬆ v<latest> /bg-update` footer segment + `/bg-update` command | yes | yes | yes |  |  |  |  | Unit covers semver parse/compare/precedence, `isNewerVersion`, `formatUpdateSegment`, npm/`package.json` payload narrowing, injected-fetch success/404/throw/timeout, and `package.json` read/degrade. SDK uses a localhost registry to verify the idle and append-to-active footer segment, `/bg-update` non-installing instructions, and that opt-out (`PI_BG_DISABLE_UPDATE_CHECK=1`), offline (`PI_OFFLINE=1`), already-current, and registry-failure paths render no segment and never throw. RPC verifies `/bg-update` discovery and offline non-installing instructions. The check is one-shot per `session_start`, time-boxed, offline-safe, and never runs on the status tick. |
| Durable file writes | `src/core/durable-fs.ts` (metadata, event/stderr buffers, attestations, delegate/Fusion artifacts, `fusion-models.json`) | yes |  |  |  |  | mutation guard |  | Unit covers single-open write/sync/close ordering, exclusive `wx` temp at `0o600`, direct `w` writes with inherited mode, never reopening a pathname to flush it, temp ownership (never deleting another writer's colliding temp), primary-versus-cleanup error precedence across write/sync/close/rename/remove, `renameCompleted` after post-rename directory failure, the Windows directory-sync skip, real-filesystem overwrite/atomic-replace/concurrency, and fatal `fsync` failures. Ordinary task `.output` uses a streaming writer that is ended/drained before terminal metadata but is not explicitly fsynced; the durable-fs claim does not extend to that stream. Package mutation guards pin the durable helper invariants. Fixes the Windows `EPERM: operation not permitted, fsync` reported in PR #1. |
| Runtime output files | `.pi/tasks/...output` | yes | yes |  |  |  |  |  | SDK asserts existence. |
| Runtime metadata files | `.pi/tasks/...json` | yes | yes |  |  |  |  |  | SDK asserts shape/status/name/context usage; registry unit tests cover metadata failure/update ordering. |
| Timeout kills task | `timeoutSeconds` |  | yes |  |  |  |  |  | SDK. |
| Output cap kills task | `PI_BG_MAX_OUTPUT_BYTES` |  |  | yes |  |  |  |  | RPC runs with a low cap and asserts failed status/log notice. |
| Shutdown cleanup | `session_shutdown` | yes | yes |  |  |  |  |  | SDK asserts multiple running tasks become killed; registry tests cover shared stop/wait behavior. |
| Process lifecycle/races | registry core | yes | yes | yes |  | yes |  | yes | Unit tests cover POSIX process-group fallback, Windows `taskkill /T` then `/T /F` tree termination, SIGKILL escalation, duplicate finalization/notification races, notification/metadata failures, pruning, malformed telemetry, split telemetry chunks, large telemetry records above the old 16KiB buffer, and wrapped-agent transcript/telemetry separation with split-chunk and trailing-partial flush; SDK/RPC cover runtime spawn/timeout/output-cap/shutdown; scripted provider covers wakeup integration. |
| Package manifest | `package.json` |  |  |  |  |  | yes |  | Keywords, `pi.extensions`, files, local smoke/compat scripts, and direct-completion import bans. |
| Pack contents | `npm pack --dry-run` |  |  |  |  |  | yes |  | Runtime files included; tests, fake child helpers, release-only scripts, artifacts, nested tarballs, and `node_modules` excluded. Default tarball install test uses isolated HOME/XDG/npm cache and offline peer-ignore install from the local tarball. |
| Maintainer docs gateway | `BACKGROUND-TASKS-INSTRUCTIONS.md` | docs focused |  |  |  |  |  |  | Gateway requires INDEX → read-before-edit → owning-doc navigation, records current docs generate/verify/attestation workflow, preserves subscription-only frontier routing, parent/child tool separation, durability/integrity, and no self-certification. Logo reference is package-local (`docs/assets/logo.svg`) when the asset-owner file is present. |
| Shared architecture/API/runtime/operations docs | `docs/api`, `docs/concepts`, `docs/subsystems`, `docs/reference`, `docs/operations` | docs focused |  |  |  |  |  |  | The active docs engine validates frontmatter, package-local links/reference links, INDEX reachability, exact behavioral source ownership, generated runtime contracts, deterministic generated regions, and manifest freshness. Semantic receipt state is reported by default and enforced only by the optional strict attestation command. Unsupported extraction and legacy placeholders fail closed. |
| Package maintenance version/tag wording | `PUBLISHING.md`, `docs/operations/releasing.md` | docs focused |  |  |  |  |  |  | Release commands derive `VERSION` from `package.json`; observed git tags stop at `v0.6.0`, so git install/tag certification is separate from npm publishing and no nonexistent v1 tag is advertised. |

## Residual hardening coverage

Lane A residual hardening is now covered by automated tests. No remaining hardening-only gaps are intentionally left open in this plan. Future feature work should add new rows instead of weakening these gates.

| Hardened area | Coverage |
|---|---|
| Extracted process registry | `src/core/registry.ts` has direct unit coverage for state transitions and injected spawn/kill/platform behavior. |
| Agent/script classification | Unit tests cover `isAgent:true` wrapping, `isAgent:false` non-wrapping, `PI_BG_DISABLE_PI_TELEMETRY`, and non-interceptable path-qualified `pi`; SDK verifies required tool schema/runtime validation and real marked Pi telemetry. |
| Process lifecycle/races | Unit tests cover duplicate error/close finalization, output-cap races, duplicate-notification prevention, waiter resolution via stop paths, metadata failure logging, and notification failure reset. |
| Process-tree kill safety | Unit tests cover POSIX process-group kill, child fallback, both-fail loud errors, SIGTERM idempotency, SIGKILL escalation, terminal-SIGKILL semantics (a SIGKILL escalation never re-arms another timer, so a child outliving the grace window cannot produce an unbounded SIGKILL loop), single-escalation-timer behaviour for concurrent stop requests, Windows `taskkill /T` then `/T /F` ordering, duplicate graceful sharing, soft-abort-on-force, explicit force without a timer, exit-128 race recording, soft-failure escalation, loud force failure, no Windows root-only fallback, bounded helper output capture, System32 resolution with no `PATH`, and terminal metadata waiting for in-flight force. |
| Pruning | Unit tests cover oldest-finished pruning while preserving running tasks. |
| Completion follow-up turns | `test:agent-loop` registers a deterministic scripted provider against the shipped extension path and verifies event-driven `bg_run` yielding with no sleep/status/log polling, exactly one default wakeup, notification-only `triggerOnCompletion:false`, `/bg` display-only behavior, `notifyOnCompletion:false`, and failed notification error fields. |
| PTY secondary keys | `test:pty` covers arrows, page keys, `a`/`K`, `R`, `c`, `/bg-tasks`, failed/unread badges, multiple-task ordering, and rerun paths for running/completed/failed/killed tasks. |
| Footer/status combinations | SDK tests cover failed/stopped/done/running combinations, explicit clear, and focused label. |

## Acceptance checklist

- [x] `npm run test` passes offline in isolated temp dirs, including the Pi hook characterisation gate.
- [x] Pi hook behaviour relied on by the delegate child guard is proven by execution and committed as evidence, not inferred from type declarations.
- [x] Fusion's persisted artifact bytes are proven unchanged against an independent pre-extraction oracle.
- [x] Delegate preflight refusal is proven to create zero child processes and zero artifacts.
- [x] No silent truncation, silent fallback, route substitution, unbounded inline answer, synthesized zero usage, fail-open guard hook, or undelivered seed exists on the delegate path, enforced by a mutation guard.
- [x] A guard-hook exception fails closed: it latches terminal state and suppresses content instead of letting the original message set reach the provider.
- [x] An incomplete response (`length`, non-`stop` stop reason) or a whitespace-only answer is never committed as a complete result, because a valid hash proves integrity but not completeness.
- [x] A real subscription-only run demonstrates the whole loop end to end, including that the child used both its read-only tools and the projected conversation.
- [x] `npm run test:full` validates baseline real TUI/PTY behavior.
- [x] `npm run pack:dry-run` passes.
- [x] README claims and all plausible edge cases are exhaustively mapped in this test plan, including Fusion command/tool/model-selector public surfaces and the text-only image omission limitation.
- [x] Every listed edge case has automated coverage at the lowest reliable layer.
- [x] No real LLM/API/network dependency in default tests.
- [x] No dependency on user/global `~/.pi/agent` for SDK/RPC/PTY tests.
- [x] Volatile output is normalized in snapshot-style assertions where applicable.
- [x] Docs/gateway freshness has a focused package-local check path and documents the current package `docs:*` workflow for unconstrained runs.
- [x] Release wording derives from `package.json` version and does not advertise nonexistent git tags.
