diff --git a/.github/SECURITY.md b/.github/SECURITY.md
index 17701216..447bcf8c 100644
--- a/.github/SECURITY.md
+++ b/.github/SECURITY.md
@@ -2,4 +2,4 @@
Report suspected vulnerabilities privately through GitHub Security Advisories. Do not open a public issue containing exploit details, secrets, or sensitive logs.
-The maintained security, trust-boundary, and recovery reference is [docs/REFERENCE.md](../docs/REFERENCE.md#security-and-trust-boundaries).
+The maintained security, trust-boundary, and recovery reference is [docs/REFERENCE.md](../docs/REFERENCE.md#security-boundary).
diff --git a/README.md b/README.md
index ee4924d8..a5bf888a 100644
--- a/README.md
+++ b/README.md
@@ -3,13 +3,15 @@
Durable agent loops, workflows, tasks, subagent orchestration, and background monitoring for Pi.
+pi-loop adds loops to Pi: prompts that wake the agent again on a schedule, on an event, or at its own pace toward a goal. It also provides workflows (one goal with ordered phases), tasks, subagent orchestration (a finite batch of independent subagent work, also called a "swarm"), and monitors (background commands that wake the agent when they succeed, fail, or become inactive).
+
## Install
```bash
pi install npm:@trevonistrevon/pi-loop
```
-pi-loop runs only while Pi is active. Persisted controller intent is not an always-on worker; ordinary pending wakes and monitor handles/output are memory-only. See the [runtime continuity matrix](./docs/RUNTIME_CONTINUITY.md) before relying on restart or unattended operation.
+pi-loop runs only while Pi is active. Persisted controller intent is not an always-on worker. Ordinary pending wakes and monitor handles/output are memory-only. See the [runtime continuity matrix](./docs/RUNTIME_CONTINUITY.md) before relying on restart or unattended operation.
## Quick start
@@ -31,7 +33,9 @@ LoopList
LoopDelete id="1"
```
-`/loop event tasks:created ...` is treated as an explicit task-backlog worker: it adopts existing unfinished tasks, coalesces task-creation bursts, and re-wakes after each agent turn until the backlog drains. Tool callers opt into the same behavior with `taskBacklog=true`. Worker wakes are action-first: `TaskList`, claim/resume, concrete same-turn work, validation, then evidence—not a state report or promise to start on a later wake.
+`/loop event tasks:created ...` is treated as an explicit task-backlog worker: it adopts existing unfinished tasks, coalesces task-creation bursts, and re-wakes after each agent turn until the backlog drains. Tool callers opt into the same behavior with `taskBacklog=true`.
+
+Worker wakes are action-first: `TaskList`, claim/resume, concrete same-turn work, validation, then evidence. A worker wake is not a state report or a promise to start on a later wake.
Run work in the background and wake the agent when it succeeds, fails, or becomes inactive:
@@ -72,7 +76,13 @@ OrchestrationGet id="1"
| `MonitorCreate`, `MonitorList`, `MonitorStop` | Run and inspect background commands |
| `TaskCreate`, `TaskList`, `TaskClaim`, `TaskHeartbeat`, `TaskUpdate`, `TaskDelete` | Native fallback task management |
-Choose one owner: workflows for one goal with ordered phases/outcomes/rework/handoff, standalone tasks for independently completable backlog items, and dynamic loops for a self-paced goal without phase routing. Persist unfinished task/loop progress or workflow plan changes in that owner, then continue while work remains actionable.
+Choose one owner:
+
+- workflows for one goal with ordered phases/outcomes/rework/handoff
+- standalone tasks for independently completable backlog items
+- dynamic loops for a self-paced goal without phase routing
+
+Persist unfinished task/loop progress or workflow plan changes in that owner, then continue while work remains actionable.
See the [usage guide](./docs/USAGE_GUIDE.md) for operator workflows and the [reference](./docs/REFERENCE.md) for authority, persistence, mutation, RPC, and recovery boundaries.
@@ -82,8 +92,8 @@ See the [usage guide](./docs/USAGE_GUIDE.md) for operator workflows and the [ref
PI_LOOP_CONTEXT=compact pi
```
-Compact mode shortens tool metadata and retains controller/ownership guidance.
-`LoopHelp` retrieves original contracts without executing or activating tools.
+Compact mode shortens tool metadata and keeps the controller/ownership guidance.
+`LoopHelp` retrieves the original contracts without executing or activating tools.
Default behavior is unchanged. See [compact context](./docs/REFERENCE.md#compact-context)
for native code-mode settings and measurement limits.
@@ -102,4 +112,4 @@ See [testing](./docs/TESTING.md) for local, property, package, benchmark, and li
## License
-MIT — [LICENSE](./LICENSE)
+MIT. See [LICENSE](./LICENSE).
diff --git a/docs/REFERENCE.md b/docs/REFERENCE.md
index 4bc68d9c..a98d3737 100644
--- a/docs/REFERENCE.md
+++ b/docs/REFERENCE.md
@@ -11,9 +11,9 @@ pi-loop separates controller, standalone-task, worker-execution, and monitor aut
| Orchestration worker execution and global concurrency | protocol-v2 `pi-subagents` | provider-owned |
| Running monitors | `MonitorManager` | process memory |
-Workflow state work is embedded in `LoopStore` as `WorkflowExecutionRecord`. It never appears in TaskStore, `/tasks`, task RPC, `TaskClaim`, or `TaskUpdate`. Standalone tasks never control workflow transitions. Finite orchestration intent, dispatch reservations, local capacity, and evidence are embedded in LoopStore; they never discover or project tasks or workflow executions. `pi-subagents` owns worker execution and its global queue.
+Workflow state work is embedded in `LoopStore` as `WorkflowExecutionRecord`. It never appears in TaskStore, `/tasks`, task RPC, `TaskClaim`, or `TaskUpdate`. Standalone tasks never control workflow transitions. Finite orchestration intent, dispatch reservations, local capacity, and evidence are embedded in LoopStore. They never discover or project tasks or workflow executions. `pi-subagents` owns worker execution and its global queue.
-Notification buffers and monitor process handles are memory-only. Orchestration wake intent survives buffer clearing/restart until valid acknowledgement, unless cancelled or retired by expiry; delivery remains at-least-once across a crash. Persisted controllers recover when Pi resumes; they do not execute while Pi is absent.
+Notification buffers and monitor process handles are memory-only. Orchestration wake intent survives buffer clearing/restart until valid acknowledgement, unless cancelled or retired by expiry. Delivery remains at-least-once across a crash. Persisted controllers recover when Pi resumes, and they do not execute while Pi is absent.
## Runtime map
@@ -27,7 +27,17 @@ Notification buffers and monitor process handles are memory-only. Orchestration
- `src/rpc/`: vendored cross-extension RPC contract
- `src/ui/`: status widget and tool rendering
-File-backed stores use PID locks, unique temporary snapshots, fsync, atomic snapshot rename, and previous-snapshot recovery. Lock publication never replaces a destination: an initialized PID/UUID owner file is hard-linked into directory scaffolding, and a writer enters only when its claim is the sole directory entry. Scaffolding alone grants no authority. Contenders withdraw only their own claims; recovery reclaims individually dead owner claims while live or unknown entries remain fences. Legacy file/directory owners stay supported. This protocol requires local-filesystem hard links and coherent directory enumeration; arbitrary network filesystems are not guaranteed. Corrupt state fails visibly when no valid snapshot exists.
+File-backed stores use PID locks, unique temporary snapshots, fsync, atomic snapshot rename, and previous-snapshot recovery.
+
+Lock publication never replaces a destination:
+
+- An initialized PID/UUID owner file is hard-linked into directory scaffolding, and a writer enters only when its claim is the sole directory entry.
+- Scaffolding alone grants no authority.
+- Contenders withdraw only their own claims.
+- Recovery reclaims individually dead owner claims, while live or unknown entries remain fences.
+- Legacy file/directory owners stay supported.
+
+This protocol requires local-filesystem hard links and coherent directory enumeration. Arbitrary network filesystems are not guaranteed. Corrupt state fails visibly when no valid snapshot exists.
## Scope
@@ -37,7 +47,9 @@ File-backed stores use PID locks, unique temporary snapshots, fsync, atomic snap
- `session` (default): isolated by Pi session ID;
- `project`: shared in the working directory.
-Project scope shares durable state but does not yet elect one scheduler owner across concurrent Pi runtimes. Workflow execution leases prevent duplicate phase work; they are separate from the planned project scheduler fence. Subagent orchestration rejects memory, project, disabled, and custom-path stores; it supports only default file-backed session scope. See [runtime continuity](./RUNTIME_CONTINUITY.md) for the retention/delivery matrix and safe recovery.
+Project scope shares durable state but does not yet elect one scheduler owner across concurrent Pi runtimes. Workflow execution leases prevent duplicate phase work. They are separate from the planned project scheduler fence.
+
+Subagent orchestration rejects memory, project, disabled, and custom-path stores. It supports only default file-backed session scope. See [runtime continuity](./RUNTIME_CONTINUITY.md) for the retention/delivery matrix and safe recovery.
## Compact context
@@ -45,21 +57,21 @@ Project scope shares durable state but does not yet elect one scheduler owner ac
PI_LOOP_CONTEXT=compact pi
```
-The extension reads `PI_LOOP_CONTEXT` at load time. Only `compact` opts in;
-unset or other values keep full metadata. Restart or reload after changing it.
+The extension reads `PI_LOOP_CONTEXT` at load time. Only `compact` opts in.
+Unset or other values keep full metadata. Restart or reload after changing it.
Storage scope, validation constraints, execution, permissions and existing tool
activation/exposure stay unchanged. External `pi-tasks` metadata is not rewritten.
Compact mode removes parameter-schema descriptions and replaces verbose tool
copy with short summaries. One stable prompt section retains controller choice,
ownership, progress and pause rules. `LoopHelp({})` lists available original
-contracts; `LoopHelp({tool:"WorkflowCreate"})` returns the original description,
+contracts. `LoopHelp({tool:"WorkflowCreate"})` returns the original description,
parameter schema and guidelines. Lookup filters inactive and non-owned tools.
It never executes, registers or activates the requested tool. Keep `LoopHelp`
active for contract lookup.
Native Pi code mode is optional. On Pi 1.4.0, add these settings to a configuration
-you choose; pi-loop does not write settings or enable code mode:
+you choose (pi-loop does not write settings or enable code mode):
```json
{
@@ -70,7 +82,7 @@ you choose; pi-loop does not write settings or enable code mode:
Merge the settings with your existing tool selection. Native `only` affects the
whole tool loadout, not just pi-loop. It retains callability while omitting direct
-declarations. The compact controller guide survives a zero inline budget; scripts
+declarations. The compact controller guide survives a zero inline budget. Scripts
retrieve contracts through `tools.LoopHelp({tool:"WorkflowCreate"})`.
The tradeoff is deferred documentation: lookup adds tool results and possibly model
@@ -81,20 +93,50 @@ and [routing evaluation](./CONTROLLER_ROUTING_EVAL.md#native-discovery-compariso
## Loop model
-`LoopEntry.status` is `active` or `paused`. New pauses persist optional provenance as `pause:{kind,at,reason?}`. Kinds distinguish `administrative`, `controller_limit`, `semantic_terminal`, and `orchestration_settlement`; older paused snapshots may remain unattributed. Resume clears the record. Triggers are:
+`LoopEntry.status` is `active` or `paused`. New pauses persist optional provenance as `pause:{kind,at,reason?}`. Kinds distinguish `administrative`, `controller_limit`, `semantic_terminal`, and `orchestration_settlement`. Older paused snapshots may remain unattributed. Resume clears the record.
+
+Triggers are:
- cron: `{type:"cron", schedule}`
- event: `{type:"event", source, filter?}`
- hybrid: `{type:"hybrid", cron, event, debounceMs}`
- dynamic: `{type:"dynamic"}`
-`LoopCreate` creates ordinary controllers. Use dynamic loops for one evolving goal without named phase/outcome routing; use workflows for ordered phases, conditional outcomes, rework, or durable handoff; use standalone tasks for independently completable backlog items. Free-text `/loop ` controllers have no implicit fire-count cap; finite budgets require an explicit `LoopCreate maxFires`. `LoopUpdate` is only for dynamic controllers that are neither workflow nor orchestration owned and must persist `continue` after empty or unchanged iterations while work remains. `LoopDelete` pauses or removes ordinary/workflow controllers and cancellation-fences orchestration before stopping its workers. New loops expire after seven days by default; `PI_LOOP_EXPIRES_IN` changes that default and each creation tool accepts an `expiresIn` override. Durations are positive integer `s`, `m`, `h`, or `d` values and may exceed seven days. `LoopList` exposes the immutable ISO `expiresAt` boundary. Workflow presentation derives `claimed` (live lease, not observed execution), `waiting` (monitor attached), `paused`, `idle`, or ephemeral `stopped` activity from authoritative workflow fields and reports activity duration, wall-clock age, and state age without persisting duplicate UI state. Expiry and stale event/hybrid retirement during session recovery emit `loops:expired` plus a hidden notification with `deleted` or `paused` disposition. Fire limits bound repeated execution.
+`LoopCreate` creates ordinary controllers. Which controller to use:
+
+- Use dynamic loops for one evolving goal without named phase/outcome routing.
+- Use workflows for ordered phases, conditional outcomes, rework, or durable handoff.
+- Use standalone tasks for independently completable backlog items.
+
+Fire limits bound repeated execution. Free-text `/loop ` controllers have no implicit fire-count cap. Finite budgets require an explicit `LoopCreate maxFires`.
+
+`LoopUpdate` is only for dynamic controllers that are neither workflow nor orchestration owned and must persist `continue` after empty or unchanged iterations while work remains. `LoopDelete` pauses or removes ordinary/workflow controllers. It cancellation-fences orchestration before stopping its workers.
+
+New loops expire after seven days by default. `PI_LOOP_EXPIRES_IN` changes that default, and each creation tool accepts an `expiresIn` override. Durations are positive integer `s`, `m`, `h`, or `d` values and may exceed seven days. `LoopList` exposes the immutable ISO `expiresAt` boundary. Expiry and stale event/hybrid retirement during session recovery emit `loops:expired` plus a hidden notification with `deleted` or `paused` disposition.
-Wake delivery is idle-driven. A due timer or event mutates loop state, emits `loop:fire`, buffers a generation-tagged notification, and sends a hidden Pi message when delivery is safe. Immediately before a buffered workflow wake is sent, the runtime re-reads `LoopStore` and requires the controller status, state, transition sequence, and execution ID to match the queued snapshot; compatible definition revisions refresh the message from current state; deleted, transitioned, paused, or reissued work is dropped even within the same session generation. Retirement follows the same generation-fenced notification path after the store mutation and emits a typed `loops:expired` payload whose reason distinguishes `expires_at` from `resume_event_stale`. Pending fire and retirement notifications are memory-only; they are not a durable event ledger across process death. Stale extension contexts are probed before fire mutation.
+Workflow presentation derives one of these activities from authoritative workflow fields:
+
+- `claimed` (live lease, not observed execution)
+- `waiting` (monitor attached)
+- `paused`
+- `idle`
+- `stopped` (ephemeral)
+
+It also reports activity duration, wall-clock age, and state age. None of this is persisted as duplicate UI state.
+
+Wake delivery is idle-driven. A due timer or event mutates loop state, emits `loop:fire`, buffers a generation-tagged notification, and sends a hidden Pi message when delivery is safe. Stale extension contexts are probed before fire mutation.
+
+Immediately before a buffered workflow wake is sent, the runtime re-reads `LoopStore`. It requires the controller status, state, transition sequence, and execution ID to match the queued snapshot. Compatible definition revisions refresh the message from current state. Deleted, transitioned, paused, or reissued work is dropped, even within the same session generation.
+
+Retirement follows the same generation-fenced notification path after the store mutation. It emits a typed `loops:expired` payload whose reason distinguishes `expires_at` from `resume_event_stale`. Pending fire and retirement notifications are memory-only. They are not a durable event ledger across process death.
## Subagent orchestration model
-`OrchestrationCreate` persists an explicit finite batch of independent work directly in one dynamic `LoopEntry`. It requires the default file-backed session scope and a compatible subagent provider before writing state: `@tintinweb/pi-subagents` (protocol v2) or the npm `pi-subagents` package (RPC v1). `OrchestrationCreate` and `OrchestrationGet` are registered only once one of them answers the probe (at activation, at `session_start`, or when it broadcasts `subagents:ready`); without one the model is not offered them, and persisted batches remain visible through `LoopList` and cancellable through `LoopDelete`. Worker access goes through the `SubagentProvider` interface in `src/runtime/subagent-provider.ts`, which has two adapters. Both are probed together; protocol v2 is preferred when both answer, and the first selection is kept for the runtime's lifetime because persisted dispatches carry that provider's worker ids. Only the selected provider's lifecycle events are heard.
+`OrchestrationCreate` persists an explicit finite batch of independent work directly in one dynamic `LoopEntry`. Before writing state, it requires the default file-backed session scope and a compatible subagent provider: `@tintinweb/pi-subagents` (protocol v2) or the npm `pi-subagents` package (RPC v1).
+
+`OrchestrationCreate` and `OrchestrationGet` are registered only once one of the providers answers the probe (at activation, at `session_start`, or when it broadcasts `subagents:ready`). Without a provider the model is not offered these tools, and persisted batches remain visible through `LoopList` and cancellable through `LoopDelete`.
+
+Worker access goes through the `SubagentProvider` interface in `src/runtime/subagent-provider.ts`, which has two adapters. Both are probed together, and protocol v2 is preferred when both answer. The first selection is kept for the runtime's lifetime because persisted dispatches carry that provider's worker ids. Only the selected provider's lifecycle events are heard.
| | `@tintinweb/pi-subagents` (protocol v2) | npm `pi-subagents` (RPC v1) |
|---|---|---|
@@ -107,15 +149,40 @@ Wake delivery is idle-driven. A due timer or event mutates loop state, emits `lo
| `stopped` / interrupted (`paused`) run | uncertain | uncertain |
| Consume | supported | unsupported; results stay provider-owned |
-Under RPC v1 the window is limited only by errors, timeouts and its ceiling. A launch that provider refuses for good (`invalid_params`, or an `Unknown agent` error) is counted as the item's failure: it spends the attempt, never shrinks the window, and never seeds a later batch. Any other proved launch failure remains an admission rejection. Its completion event is delivered at least once and may repeat for a run that pauses and later stops; a repeat for an already settled dispatch is ignored. It does not discover TaskStore records, execute workflow phases, or use the generic scheduler.
+Under RPC v1 the window is limited only by errors, timeouts and its ceiling. A launch that provider refuses for good (`invalid_params`, or an `Unknown agent` error) is counted as the item's failure: it spends the attempt, never shrinks the window, and never seeds a later batch. Any other proved launch failure remains an admission rejection. Its completion event is delivered at least once and may repeat for a run that pauses and later stops. A repeat for an already settled dispatch is ignored. It does not discover TaskStore records, execute workflow phases, or use the generic scheduler.
The parent `agent_end`, existing 30-second heartbeat, session recovery, and direct `subagents:started|completed|failed` events drive reconciliation. Before each spawn, LoopStore records a generated dispatch ID and consumes local capacity. Spawn forces background execution, disables inherited extension tools, and leaves global queue/concurrency authority with `pi-subagents`. `spawning`, `queued`, and `running` all count against the local limit.
### ACK-clocked pacing
-`pacing: "aimd"` is the default for new batches. It replaces fixed local capacity with a persisted window modelled on TCP Reno. `concurrency` and the eight-worker fixed-pacing limit do not apply; the window starts at `min(3, batch size)` dispatches in flight (the fixed-pacing default, so a small batch starts no slower than fixed; cf. RFC 6928), unless this session already ran one. `OrchestrationCreate` seeds a new aimd batch from the most recent settled aimd batch in the session's LoopStore (not `active`, no running work) with the same `model`, updated within 30 minutes and with at least one signal: after a loss it starts at `max(ssthresh, floor(cwnd))` with `ssthresh` there (additive growth); without a loss at `max(3, floor(cwnd))` with slow start kept. The seed is clamped to the new batch's ceiling, and the create result names the batch it learned from. Nothing is shared across sessions and is bounded by feedback and a ceiling: the batch size (at most 32 items) when every item declares `verify`, otherwise `min(8, batch size)`, because an unverified non-empty answer counts as an ACK. Beyond pi-subagents' own background pool, workers queue in the provider; that queue time may not appear in worker duration, so the delay signal can be blind to it. Without per-dispatch output-token usage and a tool-use count there is no delay signal at all, and only errors and timeouts limit growth. Default resolution happens once, in `OrchestrationCreate`: an explicit `pacing` wins; otherwise an explicit `concurrency` means `fixed`; otherwise `PI_LOOP_PACING` (default `aimd`, invalid values fail activation). The resolved pacing is stored with the batch. A persisted batch without a window is `fixed`, so batches created before the default changed keep fixed pacing after upgrade. `fixed` pacing persists no window.
+`pacing: "aimd"` is the default for new batches. It replaces fixed local capacity with a persisted window modelled on TCP Reno. `concurrency` and the eight-worker fixed-pacing limit do not apply.
+
+The window starts at `min(3, batch size)` dispatches in flight (the fixed-pacing default, so a small batch starts no slower than fixed; cf. RFC 6928), unless this session already ran one. `OrchestrationCreate` seeds a new aimd batch from the most recent settled aimd batch in the session's LoopStore (not `active`, no running work) with the same `model`, updated within 30 minutes and with at least one signal. The seeded start depends on whether that batch saw a loss:
-Work items may declare `verify`, a command run through `sh` in the session cwd after the worker reports completion (same authority as `MonitorCreate`; five-minute timeout; bounded output tail). Workers are told the check in their prompt. On completion the dispatch becomes `verifying`: the worker's result and usage are persisted and the dispatch keeps holding window capacity until the verifier exits; exit 0 is the ACK. The verdict follows the shell's exit status even if a background child keeps output open. A declared verifier that fails, is killed, or cannot start makes the item fail and retry within `maxAttempts`; the retry prompt includes the failing exit status and output tail. A final verification failure always wakes the parent, because the provider has already reported the worker as successful. Cancellation, expiry, and shutdown abort in-flight verifiers; after shutdown or owner adoption, a `verifying` dispatch is re-verified rather than marked uncertain, and cancelling it records the completed worker without a verdict.
+- After a loss, the new batch starts at `max(ssthresh, floor(cwnd))` with `ssthresh` there (additive growth).
+- Without a loss, it starts at `max(3, floor(cwnd))` with slow start kept.
+
+The seed is clamped to the new batch's ceiling, and the create result names the batch it learned from.
+
+Nothing is shared across sessions and is bounded by feedback and a ceiling: the batch size (at most 32 items) when every item declares `verify`, otherwise `min(8, batch size)`, because an unverified non-empty answer counts as an ACK.
+
+Beyond pi-subagents' own background pool, workers queue in the provider. That queue time may not appear in worker duration, so the delay signal can be blind to it. Without per-dispatch output-token usage and a tool-use count there is no delay signal at all, and only errors and timeouts limit growth.
+
+Default resolution happens once, in `OrchestrationCreate`:
+
+1. An explicit `pacing` wins.
+2. Otherwise an explicit `concurrency` means `fixed`.
+3. Otherwise `PI_LOOP_PACING` decides (default `aimd`, invalid values fail activation).
+
+The resolved pacing is stored with the batch. A persisted batch without a window is `fixed`, so batches created before the default changed keep fixed pacing after upgrade. `fixed` pacing persists no window.
+
+Work items may declare `verify`, a command run through `sh` in the session cwd after the worker reports completion (same authority as `MonitorCreate`; five-minute timeout; bounded output tail). Workers are told the check in their prompt.
+
+On completion the dispatch becomes `verifying`. The worker's result and usage are persisted, and the dispatch keeps holding window capacity until the verifier exits. Exit 0 is the ACK. The verdict follows the shell's exit status even if a background child keeps output open.
+
+A declared verifier that fails, is killed, or cannot start makes the item fail and retry within `maxAttempts`. The retry prompt includes the failing exit status and output tail. A final verification failure always wakes the parent, because the provider has already reported the worker as successful.
+
+Cancellation, expiry, and shutdown abort in-flight verifiers. After shutdown or owner adoption, a `verifying` dispatch is re-verified rather than marked uncertain. Cancelling it records the completed worker without a verdict.
Each settlement is classified before it reaches the window:
@@ -127,19 +194,66 @@ Each settlement is classified before it reaches the window:
| congestion | overload errors (429, 503, rate limit, connection reset), spawn failure, or two consecutive first-attempt completions above twice the observed per-output-token floor for work with a similar tool-use count | once per window (work dispatched before the last cut cannot cut again): keep 0.7 of the window for an admission rejection (a spawn failure, or an overload from a worker that ran no tools and streamed no output: nothing was lost), halve otherwise |
| timeout | timeout errors | collapse to one; `ssthresh` halves once per window (RFC 5681) |
-A failed worker whose error is classified as congestion (overload errors above; delay congestion only ever arises on completions) and that reported zero tool uses, or a proved spawn failure whose error text names congestion (a reset or refused connection, not pi-subagents' own validation errors), is re-sent without spending one of the item's `maxAttempts`, under both pacing modes. A spawn reply that cannot be recorded makes the dispatch `uncertain`, never a spawn failure, because the worker may be running. The item records it in `congestionRetries`; `attemptCount - congestionRetries` is charged. Each item may be re-sent this way at most 3 times, and the batch at most once per work item in total; beyond that, congestion losses are charged like any failure. A worker that ran tools, or whose tool count is unknown, may have changed the workspace, so its congestion loss is charged. Timeouts are always charged: a worker past its own deadline may be the task's fault. Re-sends are dispatched like any pending item, inside the window; pi's own provider retry and backoff have already run before a worker reports overload. A re-send that succeeds is a first-attempt ACK: only charged retries are ambiguous under Karn's rule. Downgrade note: a batch that used a free re-send has `attemptCount > maxAttempts`, which pi-loop releases before this change reject when loading the session LoopStore; delete such batches before downgrading.
+Two kinds of failure are re-sent without spending one of the item's `maxAttempts`, under both pacing modes:
+
+- A failed worker whose error is classified as congestion (overload errors above; delay congestion only ever arises on completions) and that reported zero tool uses.
+- A proved spawn failure whose error text names congestion (a reset or refused connection, not pi-subagents' own validation errors).
+
+A spawn reply that cannot be recorded makes the dispatch `uncertain`, never a spawn failure, because the worker may be running.
+
+The item records the re-send in `congestionRetries`, and `attemptCount - congestionRetries` is charged. Each item may be re-sent this way at most 3 times, and the batch at most once per work item in total. Beyond that, congestion losses are charged like any failure.
+
+A worker that ran tools, or whose tool count is unknown, may have changed the workspace, so its congestion loss is charged. Timeouts are always charged: a worker past its own deadline may be the task's fault.
+
+Re-sends are dispatched like any pending item, inside the window. Pi's own provider retry and backoff have already run before a worker reports overload. A re-send that succeeds is a first-attempt ACK: only charged retries are ambiguous under Karn's rule.
+
+Downgrade note: a batch that used a free re-send has `attemptCount > maxAttempts`. Releases of pi-loop before this change reject such a batch when loading the session LoopStore, so delete such batches before downgrading.
-Uncertain dispatches do not change the window; they already block all dispatch. Signals come only from lifecycle and verifier evidence, never from the parent model, so identical event sequences produce identical capacity. Error classification is pattern-based on provider error text and can misclassify. Worker duration includes the task's own tool time, so a sample is compared only with the floor of its own tool-use class (none, 1-4, 5-16, more), and the second consecutive slow sample of a class cuts the window. Slow runs are tracked per class: work of another class neither extends nor clears one. A run that continues after its cut does not cut again and does not grow the window; a later cut needs a fast sample of that class first, then two more slow ones. The signal remains a heuristic: tool calls of very different cost within one class still look alike. `npm run sim:ack-window` compares both modes in a synthetic model, including scenarios where aimd is slower than a well-chosen fixed value; `benchmarks/live-pacing.mjs` runs the comparison against a real model server.
+Uncertain dispatches do not change the window: they already block all dispatch. Signals come only from lifecycle and verifier evidence, never from the parent model, so identical event sequences produce identical capacity. Error classification is pattern-based on provider error text and can misclassify.
-Lifecycle callbacks CAS loop revision, owner runtime/generation, work ID, dispatch ID, attempt, and agent ID. Normal terminal evidence is bounded and persisted with `provider_owned` completion status; pi-loop does not call `subagents:rpc:consume`, so the provider retains its native completion surface. Protocol-v2 stop replies and `stopped`/`aborted` lifecycle statuses acknowledge cancellation, not quiescence. They become non-retryable, non-consumable `uncertain` dispatches before stop RPCs run. A late spawn reply may attach its exact cleanup identity without restoring execution. Proved failures retry only within `maxAttempts`; a spawn timeout is ambiguous without upstream status/list or idempotent dispatch keys, so it becomes `uncertain` and is never retried automatically.
+Worker duration includes the task's own tool time, so a sample is compared only with the floor of its own tool-use class (none, 1-4, 5-16, more). The second consecutive slow sample of a class cuts the window. Slow runs are tracked per class: work of another class neither extends nor clears one. A run that continues after its cut does not cut again and does not grow the window. A later cut needs a fast sample of that class first, then two more slow ones. The signal remains a heuristic: tool calls of very different cost within one class still look alike.
-Completion bursts refill capacity without a pi-loop parent wake. When every terminal dispatch is provider-owned, pi-loop pauses the controller and acknowledges its aggregate wake internally so only the provider's native completion path runs. Uncertain dispatches and failures without a provider-owned terminal result retain the durable hidden wake until `pi.sendMessage` succeeds, unless cancelled or retired by expiry; a crash before acknowledgement may duplicate that delivery. Completed/attention controllers pause for `OrchestrationGet` inspection and explicit deletion. Presentation labels controller status as `active`, `needs attention`, `complete`, or `cancelled` while preserving reducer vocabulary in persisted state. Progress separates local `reserved` capacity from pending work and last-reported dispatch observations (`starting`, `queued`, `reported running`); none proves current worker liveness. An active controller shows the reservation count against its current capacity as `N/W in flight` (the aimd window, or the fixed concurrency); a controller that is no longer dispatching shows `N reserved`. "Swarm" is the user-facing keyword for this surface: the tool description and its prompt guidelines route a swarm, fan-out, or parallel subagents over a finite list of independent items here; send one delegation, a chain whose steps need earlier results, or foreground work to the provider's own tool; forbid sending the same items through both; say that `WorkflowCreate` owns ordered phases and rework while a phase's state may run its swarm here, and name `TaskCreate` for an unrequested backlog; and explain `verify`. A batch created while its session holds a live claim on exactly one active workflow records that workflow, execution and state as its `phase`, and the create result names it. With no claim, an expired claim, a paused workflow, or more than one claim, the batch is unlinked. The link groups the batch under that phase in progress views and has no effect on dispatch, workflow admission, or transitions. A listing row for a work item ends with the evidence held for it: `verify ok` or `verify failed (exit N)`, the reported duration, and the reported token total; a field is omitted when nothing was reported. The progress panel lists up to five work items under each orchestration. When an aimd batch is larger than its unverified ceiling, the create result says the window is capped and that declaring `verify` on every item lifts it. When a fixed batch of several items is held to one worker, the create result says it is serial and that omitting `concurrency` lifts that. The status line and progress panel count an orchestration only while it is `active` or `needs attention`; a `complete` or `cancelled` batch leaves both at once and stays stored for `OrchestrationGet`, `LoopList` and `/loop` until deleted or expired. Provider-native `SubagentWorkflow` UI and execution remain a separate provider-owned surface.
+`npm run sim:ack-window` compares both modes in a synthetic model, including scenarios where aimd is slower than a well-chosen fixed value. `benchmarks/live-pacing.mjs` runs the comparison against a real model server.
-Session shutdown/switch invalidates lifecycle callbacks, persists unresolved work as uncertain, and best-effort requests cancellation before store rebinding. Any unresolved dispatch history prevents controller deletion under the Store lock; cancelled batches stay paused and inspectable. Late completion events do not clear this safety latch. Protocol v2 provides no safe automatic clearance or deletion route. Legacy `stopped`/`interrupted` records normalize to non-consumable uncertainty; previously launched retries or consumed evidence cannot be undone, and missing historical stop provenance cannot be reconstructed. A new runtime cannot adopt an unexpired foreign owner lease; after expiry it marks active dispatches uncertain rather than risking duplicates. Project scope, dynamic work addition, dependency graphs, cross-session election, and exact-once dispatch are not implemented.
+Lifecycle callbacks CAS loop revision, owner runtime/generation, work ID, dispatch ID, attempt, and agent ID. Normal terminal evidence is bounded and persisted with `provider_owned` completion status. pi-loop does not call `subagents:rpc:consume`, so the provider retains its native completion surface.
+
+Protocol-v2 stop replies and `stopped`/`aborted` lifecycle statuses acknowledge cancellation, not quiescence. They become non-retryable, non-consumable `uncertain` dispatches before stop RPCs run. A late spawn reply may attach its exact cleanup identity without restoring execution.
+
+Proved failures retry only within `maxAttempts`. A spawn timeout is ambiguous without upstream status/list or idempotent dispatch keys, so it becomes `uncertain` and is never retried automatically.
+
+Completion bursts refill capacity without a pi-loop parent wake. When every terminal dispatch is provider-owned, pi-loop pauses the controller and acknowledges its aggregate wake internally so only the provider's native completion path runs. Uncertain dispatches and failures without a provider-owned terminal result retain the durable hidden wake until `pi.sendMessage` succeeds, unless cancelled or retired by expiry. A crash before acknowledgement may duplicate that delivery. Completed/attention controllers pause for `OrchestrationGet` inspection and explicit deletion.
+
+Presentation labels controller status as `active`, `needs attention`, `complete`, or `cancelled` while preserving reducer vocabulary in persisted state. Progress separates local `reserved` capacity from pending work and last-reported dispatch observations (`starting`, `queued`, `reported running`). None proves current worker liveness. An active controller shows the reservation count against its current capacity as `N/W in flight` (the aimd window, or the fixed concurrency). A controller that is no longer dispatching shows `N reserved`.
+
+"Swarm" is the user-facing keyword for this surface. The tool description and its prompt guidelines:
+
+- route a swarm, fan-out, or parallel subagents over a finite list of independent items here
+- send one delegation, a chain whose steps need earlier results, or foreground work to the provider's own tool
+- forbid sending the same items through both
+- say that `WorkflowCreate` owns ordered phases and rework while a phase's state may run its swarm here, and name `TaskCreate` for an unrequested backlog
+- explain `verify`
+
+A batch created while its session holds a live claim on exactly one active workflow records that workflow, execution and state as its `phase`, and the create result names it. With no claim, an expired claim, a paused workflow, or more than one claim, the batch is unlinked. The link groups the batch under that phase in progress views and has no effect on dispatch, workflow admission, or transitions.
+
+A listing row for a work item ends with the evidence held for it: `verify ok` or `verify failed (exit N)`, the reported duration, and the reported token total. A field is omitted when nothing was reported. The progress panel lists up to five work items under each orchestration.
+
+When an aimd batch is larger than its unverified ceiling, the create result says the window is capped and that declaring `verify` on every item lifts it. When a fixed batch of several items is held to one worker, the create result says it is serial and that omitting `concurrency` lifts that.
+
+The status line and progress panel count an orchestration only while it is `active` or `needs attention`. A `complete` or `cancelled` batch leaves both at once and stays stored for `OrchestrationGet`, `LoopList` and `/loop` until deleted or expired. Provider-native `SubagentWorkflow` UI and execution remain a separate provider-owned surface.
+
+Session shutdown/switch invalidates lifecycle callbacks, persists unresolved work as uncertain, and best-effort requests cancellation before store rebinding.
+
+Any unresolved dispatch history prevents controller deletion under the Store lock. Cancelled batches stay paused and inspectable. Late completion events do not clear this safety latch. Protocol v2 provides no safe automatic clearance or deletion route.
+
+Legacy `stopped`/`interrupted` records normalize to non-consumable uncertainty. Previously launched retries or consumed evidence cannot be undone, and missing historical stop provenance cannot be reconstructed.
+
+A new runtime cannot adopt an unexpired foreign owner lease. After expiry it marks active dispatches uncertain rather than risking duplicates.
+
+Project scope, dynamic work addition, dependency graphs, cross-session election, and exact-once dispatch are not implemented.
## Workflow model
-`WorkflowDefinition.version` is 1. Every state in a newly created definition must be reachable from `initialState`; reachable cycles are valid, and terminal reachability remains a separate policy. A state contains:
+`WorkflowDefinition.version` is 1. Every state in a newly created definition must be reachable from `initialState`. Reachable cycles are valid, and terminal reachability remains a separate policy. A state contains:
- `prompt`
- optional embedded `task:{subject,description}`
@@ -154,13 +268,24 @@ A run persists current state, transition sequence, attempts, state fire counts,
The initial task execution is leased to the creating runtime. Every destination execution, including self-loop retries, starts unowned. `WorkflowClaim` claims unowned work, renews the same owner, or takes over an expired lease. Live foreign ownership fails closed.
-`WorkflowTransition` validates the current lease, declared available outcome, attempt limit, active execution, pause authority, and definition revision. Ordinary active transitions proceed directly. Administrative and unattributed pauses require explicit resume. A controller-wide limit permits only a terminal transition; a state-local cadence limit permits an evidenced transition out of the exhausted state and resumes that destination atomically. Self-transitions never bypass a pause. A transition into a `paused` terminal state additionally requires `claim:{class,provider,subject,fact,expected}`. A trusted provider observes the fact outside the LoopStore lock; admission rejects missing, unavailable, stale, expired, conflicting, contradicted, or cross-context observations without writing. The built-in `monitor` provider exposes only `status`, `exitCode`, and `stopReason`; monitor output is never evidence. Admission confirms the exact fact, not whether workflow policy should treat that fact as a blocker—the declared edge remains the workflow author's policy. No user-authority provider is built in, and machine providers cannot grant `user_authority`, so those claims fail closed. After confirmation, the existing state/revision/execution CAS protects the locked transition.
+`WorkflowTransition` validates the current lease, declared available outcome, attempt limit, active execution, pause authority, and definition revision. Ordinary active transitions proceed directly. Pauses and limits change that:
+
+- Administrative and unattributed pauses require explicit resume.
+- A controller-wide limit permits only a terminal transition.
+- A state-local cadence limit permits an evidenced transition out of the exhausted state and resumes that destination atomically.
+- Self-transitions never bypass a pause.
-No pending claim or general evidence ledger is persisted. A confirmed transition stores only a bounded admission receipt on `lastTransition` (claim class/provider/subject/fact/expected value, provider versions, and decision time). After restart, callers inspect current state and explicitly resubmit; stale context is rejected. One locked transition write settles source work, records evidence and the receipt, advances state, and creates the destination execution. A missing or exhausted route is handled through `WorkflowRevise`, not a fabricated transition. Completed terminals delete the controller; paused terminals preserve it with `semantic_terminal` pause provenance and represent a declared blocker—not a progress notification.
+A transition into a `paused` terminal state also requires `claim:{class,provider,subject,fact,expected}`. A trusted provider observes the fact outside the LoopStore lock. Admission rejects missing, unavailable, stale, expired, conflicting, contradicted, or cross-context observations without writing. The built-in `monitor` provider exposes only `status`, `exitCode`, and `stopReason`. Monitor output is never evidence.
+
+Admission confirms the exact fact, not whether workflow policy should treat that fact as a blocker. The declared edge remains the workflow author's policy. No user-authority provider is built in, and machine providers cannot grant `user_authority`, so those claims fail closed. After confirmation, the existing state/revision/execution CAS protects the locked transition.
+
+No pending claim or general evidence ledger is persisted. A confirmed transition stores only a bounded admission receipt on `lastTransition` (claim class/provider/subject/fact/expected value, provider versions, and decision time). After restart, callers inspect current state and explicitly resubmit, and stale context is rejected.
+
+One locked transition write settles source work, records evidence and the receipt, advances state, and creates the destination execution. A missing or exhausted route is handled through `WorkflowRevise`, not a fabricated transition. Completed terminals delete the controller. Paused terminals preserve it with `semantic_terminal` pause provenance and represent a declared blocker, not a progress notification.
### Adaptive revision
-`WorkflowRevise` accepts exact `expectedRevision`, `expectedState`, and `expectedTransitionSeq` plus a reason and 1–64 typed changes:
+`WorkflowRevise` accepts exact `expectedRevision`, `expectedState`, and `expectedTransitionSeq` plus a reason and 1 to 64 typed changes:
- `add_state`
- `revise_state` for non-current state content
@@ -168,24 +293,53 @@ No pending claim or general evidence ledger is persisted. A confirmed transition
- `add_transition`
- `redirect_transition` with `expectedTo`
-Graph revision is additive: no remove, rename, or full-definition replacement. Added states must be reachable and rejoin prior or terminal work. Redirected routes must retain a path to their prior target. `revise_state` still rejects the current state; callers must choose `reissue_state` explicitly rather than mutating instructions beneath an execution.
+Graph revision is additive: no remove, rename, or full-definition replacement. Added states must be reachable and rejoin prior or terminal work. Redirected routes must retain a path to their prior target. `revise_state` still rejects the current state. Callers must choose `reissue_state` explicitly rather than mutating instructions beneath an execution.
+
+Acceptance appends the prior definition, reason, actor, timestamp, and patch to immutable history, then increments `definitionRevision`. Ordinary revisions preserve the current execution, lease, counters, and scheduler state.
-Acceptance appends the prior definition, reason, actor, timestamp, and patch to immutable history, then increments `definitionRevision`. Ordinary revisions preserve the current execution, lease, counters, and scheduler state. `reissue_state` is the bounded exception: it targets only the current nonterminal state. On an active controller it cancels any old execution into `executionHistory`, creates a fresh execution ID under the still-valid owner lease, resets state-entry/fire timing, keeps transition sequence and attempt count unchanged, then re-arms the active trigger and queues a fresh idle wake after persistence. Through an administrative pause it performs the same replacement atomically but leaves the controller paused with no trigger or wake, so `/loop` resume delivers only the fresh instruction. `controller_limit` and other non-administrative pauses reject reissue; semantic terminals reject revision entirely. Reissuing taskless work may create an unowned task execution that must be claimed. Reissued `maxAttempts` may equal but never undercut the current attempt; state-local fire limits apply to the reset fire count. The revision and fresh execution ID fence stale transition attempts. Revision never creates standalone workflow tasks. Maximum definition size is 65,536 UTF-8 bytes; there is no lifetime revision-count cap.
+`reissue_state` is the bounded exception: it targets only the current nonterminal state. Its effect depends on the controller's status:
-Every accepted revision retains its full prior definition and patch; history is never silently pruned. This is application-managed local history, not tamper-evident storage or a complete transition ledger. Completion and explicit deletion remove the controller and its authoritative history; expiry pauses workflows and retains it. Snapshot size and mutation/reload costs grow with retained history. Removing the count cap does not remove definition-size, change-list, CAS, lease, expiry, or execution-budget checks.
+- On an active controller it cancels any old execution into `executionHistory`, creates a fresh execution ID under the still-valid owner lease, resets state-entry/fire timing, and keeps transition sequence and attempt count unchanged. It then re-arms the active trigger and queues a fresh idle wake after persistence.
+- Through an administrative pause it performs the same replacement atomically but leaves the controller paused with no trigger or wake, so `/loop` resume delivers only the fresh instruction.
+- `controller_limit` and other non-administrative pauses reject reissue.
+- Semantic terminals reject revision entirely.
+
+Reissuing taskless work may create an unowned task execution that must be claimed. Reissued `maxAttempts` may equal but never undercut the current attempt. State-local fire limits apply to the reset fire count. The revision and fresh execution ID fence stale transition attempts.
+
+Revision never creates standalone workflow tasks. Maximum definition size is 65,536 UTF-8 bytes. There is no lifetime revision-count cap.
+
+Every accepted revision retains its full prior definition and patch, and history is never silently pruned. This is application-managed local history, not tamper-evident storage or a complete transition ledger. Completion and explicit deletion remove the controller and its authoritative history. Expiry pauses workflows and retains it. Snapshot size and mutation/reload costs grow with retained history. Removing the count cap does not remove definition-size, change-list, CAS, lease, expiry, or execution-budget checks.
The public `revision_limit_reached` failure-code literal is retained for TypeScript source compatibility but is deprecated and no longer emitted.
-Revision and transition race through the same LoopStore lock. Revision-first makes a stale transition fail its definition CAS; transition-first makes a stale revision fail state/sequence CAS.
+Revision and transition race through the same LoopStore lock. Revision-first makes a stale transition fail its definition CAS. Transition-first makes a stale revision fail state/sequence CAS.
### Verified outcomes
-A state may declare `verify: { : { command, onFail? } }`. `WorkflowTransition` for a verified outcome runs `command` through `sh` in the session cwd (same authority as `MonitorCreate`) before the LoopStore mutation, then applies the transition with the same state/sequence/revision/execution CAS as blocker admission. Exit 0 records an `environmental` admission (`provider: "verify"`, `fact: "exit_code"`, `expected: 0`). On failure, without `onFail` the transition is rejected and state is preserved; with `onFail` the harness takes that outcome, subject to its target's `maxAttempts`, with the exit status and output tail as evidence. The tool result shows the verdict and output tail either way. A verifier that cannot start counts as a failure; a context change during the check leaves the transition unresolved. Constraints: verified outcomes must be declared in `on`, cannot target a paused terminal (use blocker admission), and `onFail` must be a different declared outcome that is not itself verified. `revise_state` does not change `verify`; `add_state` may declare it.
+A state may declare `verify: { : { command, onFail? } }`. `WorkflowTransition` for a verified outcome runs `command` through `sh` in the session cwd (same authority as `MonitorCreate`) before the LoopStore mutation. It then applies the transition with the same state/sequence/revision/execution CAS as blocker admission.
+
+Results:
+
+- Exit 0 records an `environmental` admission (`provider: "verify"`, `fact: "exit_code"`, `expected: 0`).
+- On failure without `onFail`, the transition is rejected and state is preserved.
+- On failure with `onFail`, the harness takes that outcome, subject to its target's `maxAttempts`, with the exit status and output tail as evidence.
+
+The tool result shows the verdict and output tail either way. A verifier that cannot start counts as a failure. A context change during the check leaves the transition unresolved.
+
+Constraints:
+
+- Verified outcomes must be declared in `on`.
+- Verified outcomes cannot target a paused terminal (use blocker admission).
+- `onFail` must be a different declared outcome that is not itself verified.
+
+`revise_state` does not change `verify`. `add_state` may declare it.
## Standalone tasks
-Native task statuses are `pending`, `in_progress`, `completed`, and `closed`. `TaskClaim` starts or resumes unfinished work and returns a renewable bearer claim ID. `TaskHeartbeat` renews it. Subject/description edits, terminal updates, and deletion of live claimed work require that ID. Missing, wrong, or expired bearers reject before mutation; expired claims may be taken over. In `/tasks`, the operator may release a claim only after its lease has expired (confirmation required): the task can then be completed, closed, deleted, or returned to `pending`. A live claim is never overridden and still requires its token.
+Native task statuses are `pending`, `in_progress`, `completed`, and `closed`. `TaskClaim` starts or resumes unfinished work and returns a renewable bearer claim ID. `TaskHeartbeat` renews it. Subject/description edits, terminal updates, and deletion of live claimed work require that ID. Missing, wrong, or expired bearers reject before mutation. Expired claims may be taken over.
+
+In `/tasks`, the operator may release a claim only after its lease has expired (confirmation required). The task can then be completed, closed, deleted, or returned to `pending`. A live claim is never overridden and still requires its token.
Standalone tasks are independently completable backlog items. Related work that advances one evolving goal through ordered phases, conditional outcomes, rework, or durable handoff belongs in a workflow instead. Task prerequisites are description conventions, not first-class graph fields. Backlog workers use `TaskGet` to follow them, and unfinished handoffs persist material progress and next action through `TaskUpdate`.
@@ -195,11 +349,15 @@ pi-loop probes external `pi-tasks` through protocol-v2 RPC. When unavailable, th
Workflow summaries and `/loop` inspection show up to three warning witnesses, with an explicit omitted count. `diagnoseWorkflowGraph(run)` from `@trevonistrevon/pi-loop/api` returns full structured witnesses for closed nonterminal components, nonterminal dead ends, and a current-state terminal route cut off by already-exhausted destinations. It reuses outcome availability rules and does not mutate or reject workflows.
-These are warning-only structural and point-in-time checks, not a liveness proof or a prerequisite engine. A reachable exit is not mandatory; an intentional ongoing cycle may still be valid. Diagnostics do not simulate future attempt increments, leases, evidence admission, fire/expiry limits, or future revisions. Revise only when finite completion is intended, preserving the existing revision/transition authority checks.
+These are warning-only structural and point-in-time checks, not a liveness proof or a prerequisite engine. A reachable exit is not mandatory, and an intentional ongoing cycle may still be valid. Diagnostics do not simulate future attempt increments, leases, evidence admission, fire/expiry limits, or future revisions. Revise only when finite completion is intended, preserving the existing revision/transition authority checks.
## Monitors
-`MonitorCreate` spawns a detached process group, buffers bounded output, emits rate-limited progress, and records terminal status in memory. Its `timeout` is a renewable inactivity threshold: stdout/stderr bytes, JSONL progress, and `MonitorUpdate` renew the deadline; total runtime alone never stops an active monitor. `MonitorStop` sends TERM then KILL fallback. `onDone` creates a one-shot completion wake; without `onDone` or `workflowId`, a one-shot failure alert wakes the agent if the monitor exits nonzero, is killed by a signal, fails to spawn, or times out (a clean exit or manual stop retires it quietly). A terminating signal is recorded as `signal`. If the shell exits but a background grandchild keeps its stdio open, the monitor settles after a 2s grace instead of waiting for `close`. `workflowId` pauses a workflow state's cadence until terminal monitor outcome.
+`MonitorCreate` spawns a detached process group, buffers bounded output, emits rate-limited progress, and records terminal status in memory. Its `timeout` is a renewable inactivity threshold. Stdout/stderr bytes, JSONL progress, and `MonitorUpdate` renew the deadline. Total runtime alone never stops an active monitor. `MonitorStop` sends TERM then KILL fallback.
+
+`onDone` creates a one-shot completion wake. Without `onDone` or `workflowId`, a one-shot failure alert wakes the agent if the monitor exits nonzero, is killed by a signal, fails to spawn, or times out (a clean exit or manual stop retires it quietly). `workflowId` pauses a workflow state's cadence until terminal monitor outcome.
+
+A terminating signal is recorded as `signal`. If the shell exits but a background grandchild keeps its stdio open, the monitor settles after a 2s grace instead of waiting for `close`.
Monitor events:
@@ -245,4 +403,4 @@ Daemon execution, an ordinary durable wake outbox, project scheduler fencing, an
## Security boundary
-Report vulnerabilities through GitHub private vulnerability reporting, never a public issue containing exploit details or secrets. CI and releases audit all dependencies. Do not use `npm audit fix --force`; update Pi and Pi TUI pins together and validate the resulting API contract.
+Report vulnerabilities through GitHub private vulnerability reporting, never a public issue containing exploit details or secrets. CI and releases audit all dependencies. Do not use `npm audit fix --force`. Update Pi and Pi TUI pins together and validate the resulting API contract.
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 88bc269c..aea0cbea 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -9,7 +9,9 @@ npm install
npm run hooks:install
```
-Contributions use focused branches and signed, thematic commits. Open the first pull request against `master`; dependent pull requests target their predecessor branch. Run the local gate at every PR tip and relevant checks at each intermediate commit. Push normally with hooks; do not rewrite published stack history. Contributions are MIT licensed.
+Contributions use focused branches and signed, thematic commits. Open the first pull request against `master`. Dependent pull requests target their predecessor branch.
+
+Run the local gate at every PR tip and the relevant checks at each intermediate commit. Push normally with hooks, and do not rewrite published stack history. Contributions are MIT licensed.
## Local gate
@@ -25,7 +27,7 @@ npm audit --audit-level=moderate
git diff --check
```
-Lint currently reports two established optional-chain warnings; new warnings are not accepted.
+Lint currently reports two established optional-chain warnings. New warnings are not accepted.
## Test layers
@@ -43,14 +45,16 @@ Lint currently reports two established optional-chain warnings; new warnings are
| Tool context | `npm run profile:tools` | Native SDK declarations, instructions, discovery and result sizes |
| Fuzz profile | `npm run profile:fuzz` | Allowlisted property-worker CPU capture and campaign evidence |
-Unit tests use Vitest, fake timers for schedules, in-memory stores for pure behavior, temporary files for persistence/restart, and one shared Pi event-bus mock. Vitest pins `PI_LOOP_CONTEXT=full`; compact-profile tests opt in explicitly rather than inheriting the caller's shell.
+Unit tests use Vitest, fake timers for schedules, in-memory stores for pure behavior, temporary files for persistence/restart, and one shared Pi event-bus mock.
+
+Vitest pins `PI_LOOP_CONTEXT=full`. Compact-profile tests opt in explicitly and do not inherit the caller's shell.
## Harness review campaigns
See [bounded review campaigns](./HARNESS_REVIEW_CAMPAIGNS.md) for the test-only
coverage/closure reference policy and traceable boundary inventory. Failed or
skipped mandatory discovery is incomplete, never a clean review. The inventory
-checks references; the normal suite executes the underlying regressions.
+checks references. The normal suite executes the underlying regressions.
## Native code mode
@@ -60,18 +64,25 @@ npx vitest run test/native-codemode.test.ts
The suite uses the pinned Pi SDK's session and native code-mode extension with a
scripted provider. It makes no remote model calls and reads no user credentials
-or project context. Stores use memory; SDK files use isolated temporary directories.
+or project context. Stores use memory. SDK files use isolated temporary directories.
+
+Coverage includes:
-Coverage includes absent/inactive code mode, `on` and `only` request declarations,
-first-request native task availability, task claim/completion, zero-inline-budget
-guideline discovery, inactive-tool exclusion, nested validation and permission
-checks, and text business rejections. Fixture prompts fence automatic wake runs before
-provider requests, retain cancellation counts, and wait for settlement. Each session
-emits shutdown and is disposed.
+- absent/inactive code mode;
+- `on` and `only` request declarations;
+- first-request native task availability;
+- task claim/completion;
+- zero-inline-budget guideline discovery;
+- inactive-tool exclusion;
+- nested validation and permission checks;
+- text business rejections.
+
+Fixture prompts fence automatic wake runs before provider requests, retain cancellation
+counts, and wait for settlement. Each session emits shutdown and is disposed.
These tests establish SDK conformance, not model routing quality, provider cache
behavior, token savings, or compatibility with untested Pi versions. Tool exposure
-remains `direct`; discovery does not activate tools.
+remains `direct`. Discovery does not activate tools.
## Workflow coverage
@@ -102,7 +113,22 @@ test/property/workflow.property.test.ts
## Subagent orchestration coverage
-The orchestration suites prove finite-batch bounds, capacity reservation before spawn, reducer/store CAS immutability, lifecycle identity, early-start replay, bounded settlement before consume, retry/uncertainty policy, durable wake acknowledgement, session teardown, cancellation, scheduler exclusion, tool scope gating, compact presentation, and extension wiring.
+The orchestration suites prove:
+
+- finite-batch bounds;
+- capacity reservation before spawn;
+- reducer/store CAS immutability;
+- lifecycle identity;
+- early-start replay;
+- bounded settlement before consume;
+- retry/uncertainty policy;
+- durable wake acknowledgement;
+- session teardown;
+- cancellation;
+- scheduler exclusion;
+- tool scope gating;
+- compact presentation;
+- extension wiring.
Primary files:
@@ -114,17 +140,17 @@ test/orchestration-tools.test.ts
test/property/orchestration.property.test.ts
```
-Deterministic integration tests own timeout ambiguity and exact lifecycle ordering because upstream lacks status/list and idempotent dispatch keys. The opt-in live scenario additionally validates the supported protocol-v2 spawn, settlement, consume, and active-cancellation path against a real provider.
+Deterministic integration tests own timeout ambiguity and exact lifecycle ordering because upstream lacks status/list and idempotent dispatch keys. The opt-in live scenario also validates the supported protocol-v2 spawn, settlement, consume, and active-cancellation path against a real provider.
## Task-backlog coverage
A backlog wake must call `TaskList`, inspect `TaskGet`, claim or resume one task, perform work, run observable validation, and settle the task in the same turn. Tests reject status-only progress, missing claims, reasoning-only validation, and deferral to a later wake.
-Description-declared prerequisites are followed through `TaskGet`; TaskStore has no dependency-edge field.
+Description-declared prerequisites are followed through `TaskGet`. TaskStore has no dependency-edge field.
## Live E2E
-Live tests are opt-in and run in isolated temporary workspaces. Stateful workflow and backlog scenarios use project scope; orchestration uses default file-backed session scope.
+Live tests are opt-in and run in isolated temporary workspaces. Stateful workflow and backlog scenarios use project scope. Orchestration uses default file-backed session scope.
```bash
PI_LOOP_LIVE_MODEL="openai-codex/gpt-5.6-sol:minimal" npm run test:e2e
@@ -170,9 +196,10 @@ same six prompts across direct, `only`/3,000 and `only`/zero arms:
PI_LOOP_NATIVE_ROUTING_MODEL="provider/model" npm run test:e2e:routing:native
```
-The native comparison is separate opt-in, keeps Pi credentials in memory, and
-runs 18 sessions. Without its model variable it reports `SKIP`, not a pass. See
-[controller routing evaluation](./CONTROLLER_ROUTING_EVAL.md) for inventories,
+The native comparison is a separate opt-in. It keeps Pi credentials in memory and
+runs 18 sessions. Without its model variable it reports `SKIP`, not a pass.
+
+See [controller routing evaluation](./CONTROLLER_ROUTING_EVAL.md) for inventories,
observation boundaries, judgment rules and artifact paths.
Subagent orchestration scenario:
@@ -183,7 +210,12 @@ PI_LOOP_LIVE_SUBAGENTS_EXTENSION="$HOME/.pi/agent/npm/node_modules/@tintinweb/pi
npm run test:e2e:orchestration
```
-It runs in a temporary workspace with default file-backed session scope, proves two isolated workers settle with durable consumed evidence, then creates and cancels an active worker. The extension path defaults to the standard user package location when `PI_LOOP_LIVE_SUBAGENTS_EXTENSION` is omitted.
+The scenario runs in a temporary workspace with default file-backed session scope. It does two things:
+
+1. It proves that two isolated workers settle with durable consumed evidence.
+2. It creates and cancels an active worker.
+
+The extension path defaults to the standard user package location when `PI_LOOP_LIVE_SUBAGENTS_EXTENSION` is omitted.
Protocol v2 provider (`@tintinweb/pi-subagents`) wire check, no model spend:
@@ -191,7 +223,22 @@ Protocol v2 provider (`@tintinweb/pi-subagents`) wire check, no model spend:
PI_LOOP_LIVE_V2=1 npm run test:e2e:orchestration:v2
```
-That provider runs workers inside the parent process with the parent's model, and this check's parent model is a scripted fixture, so workers answer from the same script and nothing is sent to a model provider. It checks provider detection and tool registration, a two-item batch with `maxTurns` through spawn, `subagents:started`, `subagents:completed`, usage evidence (including the tool-use count the delay signal needs) and provider-owned settlement, then cancels a worker that is busy in a tool call and requires an accepted stop, a `stopped` failure event and a retained controller. `PI_LOOP_LIVE_SUBAGENTS_EXTENSION` selects the entrypoint. The model-driven `test:e2e:orchestration` scenario above remains the check of a real parent model using these tools.
+Why it spends nothing: that provider runs workers inside the parent process with the parent's model, and this check's parent model is a scripted fixture. So workers answer from the same script and nothing is sent to a model provider.
+
+The check does the following:
+
+1. It checks provider detection and tool registration.
+2. It follows a two-item batch with `maxTurns` through these stages:
+ - spawn;
+ - `subagents:started`;
+ - `subagents:completed`;
+ - usage evidence (including the tool-use count the delay signal needs);
+ - provider-owned settlement.
+3. It cancels a worker that is busy in a tool call. This step requires an accepted stop, a `stopped` failure event and a retained controller.
+
+`PI_LOOP_LIVE_SUBAGENTS_EXTENSION` selects the entrypoint.
+
+The model-driven `test:e2e:orchestration` scenario above remains the check of a real parent model using these tools.
RPC v1 provider (npm `pi-subagents`) check:
@@ -204,9 +251,30 @@ PI_LOOP_LIVE_V1=1 PI_LOOP_LIVE_V1_AGENT_DIR="$HOME/.pi/agent" PI_LOOP_LIVE_MODEL
npm run test:e2e:orchestration:v1
```
-The parent session is scripted (no parent inference) and loads the real provider from `PI_LOOP_LIVE_SUBAGENTS_V1_EXTENSION` (default: the standard user package location). It checks provider detection and tool registration, `maxTurns` rejection, an unknown agent as a proved launch failure, and one launch through run id, `subagent:async-started`, `subagent:async-complete` and settlement. With real credentials it also cancels an active worker and checks that the provider accepted the stop request, reported the run `stopped`, and that the controller was retained rather than deleted. The provider keeps a headless parent turn open while its workers run, so the check cancels through pi-loop's own tool executor instead of a second parent turn. The report is written to `.artifacts/live-orchestration-v1/report.json`.
+The parent session is scripted (no parent inference). It loads the real provider from `PI_LOOP_LIVE_SUBAGENTS_V1_EXTENSION` (default: the standard user package location).
-Without `PI_LOOP_LIVE_MODEL` (or `PI_LOOP_LIVE_V1=1` for the RPC v1 check), live scripts exit with `SKIP`. Reports are bounded JSON under `.artifacts/` and do not record credentials; claim IDs are redacted where applicable.
+The check verifies:
+
+- provider detection and tool registration;
+- `maxTurns` rejection;
+- an unknown agent as a proved launch failure;
+- one launch, followed through these stages:
+ - run id;
+ - `subagent:async-started`;
+ - `subagent:async-complete`;
+ - settlement.
+
+With real credentials it also cancels an active worker and checks that:
+
+- the provider accepted the stop request;
+- the provider reported the run `stopped`;
+- the controller was retained and not deleted.
+
+The provider keeps a headless parent turn open while its workers run. For that reason the check cancels through pi-loop's own tool executor instead of a second parent turn.
+
+The report is written to `.artifacts/live-orchestration-v1/report.json`.
+
+Without `PI_LOOP_LIVE_MODEL` (or `PI_LOOP_LIVE_V1=1` for the RPC v1 check), live scripts exit with `SKIP`. Reports are bounded JSON under `.artifacts/` and do not record credentials. Claim IDs are redacted where applicable.
## Property and fuzz replay
@@ -235,7 +303,11 @@ npm run bench:compare
npm run profile:core
```
-Core workloads live in `benchmarks/workloads.ts`. The `progressPanel` workload measures one side-panel frame (store reads, layout, framing) over four twelve-state workflows and 200 tasks. `bench:baseline` writes `.artifacts/benchmarks/baseline.json`; `bench:compare` reports throughput changes. Load `.cpuprofile` files in a V8-compatible viewer. Compare only the same machine, Node version, architecture, timezone, and power state.
+Core workloads live in `benchmarks/workloads.ts`. The `progressPanel` workload measures one side-panel frame (store reads, layout, framing) over four twelve-state workflows and 200 tasks.
+
+`bench:baseline` writes `.artifacts/benchmarks/baseline.json`, and `bench:compare` reports throughput changes. Load `.cpuprofile` files in a V8-compatible viewer.
+
+Compare only the same machine, Node version, architecture, timezone, and power state.
### Tool context
@@ -246,32 +318,54 @@ npm run profile:tools -- --out .artifacts/profiles/tool-context-compact --contex
npx vitest run test/native-codemode.test.ts test/tool-context-profile.test.ts test/compact-context.test.ts test/tool-context-registration.test.ts
```
-The fixed matrix runs code mode absent, registered but inactive, and `on`/`only`
-with Pi's estimated-token inline budgets of 3,000 and zero. Each isolated SDK session sends an initial
-request, a repeated request, and read-only list calls. Active code-mode cases also
-request three controller declarations, a three-hit search, and callable tool names.
-The provider is scripted. Native model helpers and external extensions are disabled;
-no remote model or operator configuration is used. `--context full|compact` selects
-pi-loop metadata explicitly rather than inheriting the operator environment.
-Compact discovery retrieves three original controller contracts through `LoopHelp`;
-full mode uses native declaration discovery. These outputs are not byte-identical.
+What the matrix runs:
+
+- The fixed matrix runs code mode absent, registered but inactive, and `on`/`only`
+ with Pi's estimated-token inline budgets of 3,000 and zero.
+- Each isolated SDK session sends an initial request, a repeated request, and
+ read-only list calls.
+- Active code-mode cases also request three controller declarations, a three-hit
+ search, and callable tool names.
+
+The provider is scripted. Native model helpers and external extensions are disabled.
+No remote model or operator configuration is used.
+
+`--context full|compact` selects pi-loop metadata explicitly and does not inherit the
+operator environment. Compact discovery retrieves three original controller contracts
+through `LoopHelp`. Full mode uses native declaration discovery. These outputs are not
+byte-identical.
Each unique run directory contains `report.json` and six request capture files.
-The report records source hashes, SDK versions, registered/active/callable/declared
-tools, per-tool schema/description sizes, effective instructions, transcript sizes,
-and discovery/result traffic. Counts use UTF-16 code units and UTF-8 bytes before
-synthetic workspace paths are replaced in saved captures. JSON metrics include
-serialization overhead. Instructions, declarations and transcript metrics overlap;
-do not sum them. Capture-file checksums cover the saved, normalized files.
+The report records:
+
+- source hashes;
+- SDK versions;
+- registered/active/callable/declared tools;
+- per-tool schema/description sizes;
+- effective instructions;
+- transcript sizes;
+- discovery/result traffic.
+
+How to read the counts:
+
+- Counts use UTF-16 code units and UTF-8 bytes before synthetic workspace paths are
+ replaced in saved captures.
+- JSON metrics include serialization overhead.
+- Instructions, declarations and transcript metrics overlap. Do not sum them.
+- Capture-file checksums cover the saved, normalized files.
Limits: 12 requests per case, 2 MiB per original request, 16 MiB per artifact.
Exceeding a limit fails without truncation. Case failures retain an incomplete
report and completed-case artifacts. Temporary SDK workspaces are removed.
-This is the native SDK provider boundary, not a provider's HTTP payload. Token
-counts and cache reuse remain `null`; fixture usage zeros are not measurements.
-Disabled cases have no discovery stage, so total traffic is not an equivalent-work
-savings comparison. Read-only profiling does not change exposure or activate tools.
+What the profile does and does not measure:
+
+- This is the native SDK provider boundary, not a provider's HTTP payload.
+- Token counts and cache reuse remain `null`. Fixture usage zeros are not measurements.
+- Disabled cases have no discovery stage, so total traffic is not an equivalent-work
+ savings comparison.
+- Read-only profiling does not change exposure or activate tools.
+
Compact acceptance includes the extra help declaration and retained prompt section
in its direct-request budget. Default metadata, all 21 existing schemas, late native
tasks, inactive/external contract exclusions and native ownership checks have
@@ -299,11 +393,14 @@ npx vitest run test/tool-copy-budget.test.ts test/tool-context-profile.test.ts
`test/fixtures/tool-context-budget.json` fixes per-tool and aggregate UTF-8 ceilings
for descriptions, input-schema JSON, schema-description text and declaration JSON.
-Per-tool ceilings add 10%, rounded up to 32 bytes; aggregate ceilings round up to
-100 bytes. Review fixture changes explicitly; tests never rebaseline themselves.
-The older combined description/guideline character budget remains independent.
+Per-tool ceilings add 10%, rounded up to 32 bytes. Aggregate ceilings round up to
+100 bytes.
+
+Review fixture changes explicitly. Tests never rebaseline themselves. The older
+combined description/guideline character budget remains independent.
+
Schema-description text walks schema-bearing keywords, not enum/example/default
-instance data or referenced documents. Fields overlap; do not sum them or call them
+instance data or referenced documents. Fields overlap. Do not sum them or call them
tokens. Mutation controls check schema-only inflation and Unicode parameter copy.
### Startup
@@ -314,9 +411,25 @@ Keep the prior compiled `dist` tree for comparison. Both builds must resolve the
npm run profile:startup -- --baseline /path/to/prior/dist/index.js --candidate dist/index.js --profiles
```
-The default is 15 measured rounds after 3 warmups, serial fresh processes, alternating case order. `--rounds` accepts 3–100; `--warmups` accepts 0–10. `--cli` selects a compiled Pi CLI. `--out` selects the artifact root; default `.artifacts/profiles/startup`. Each run owns a unique directory.
+The default is 15 measured rounds after 3 warmups, serial fresh processes, alternating case order. Options:
+
+- `--rounds` accepts 3 to 100.
+- `--warmups` accepts 0 to 10.
+- `--cli` selects a compiled Pi CLI.
+- `--out` selects the artifact root (default `.artifacts/profiles/startup`).
+
+Each run owns a unique directory.
+
+`report.json` retains raw wall time, physical child status, CPU/RSS, versions, static graph hashes, paired medians and a seeded bootstrap interval. Owned wrappers require affirmative factory-return receipts.
+
+CPU-profile children run separately, and their timings do not enter comparisons. Profiles are capped at 64 MiB before write.
-`report.json` retains raw wall time, physical child status, CPU/RSS, versions, static graph hashes, paired medians and a seeded bootstrap interval. Owned wrappers require affirmative factory-return receipts. CPU-profile children run separately; their timings do not enter comparisons. Profiles are capped at 64 MiB before write. Static graphs are not observed runtime-loading traces. CLI `--list-models` is not TUI first render or first-request latency. Do not run timing comparisons alongside fuzz campaigns or gates.
+Limits on what the results mean:
+
+- Static graphs are not observed runtime-loading traces.
+- CLI `--list-models` is not TUI first render or first-request latency.
+
+Do not run timing comparisons alongside fuzz campaigns or gates.
### Fuzz workers
@@ -326,22 +439,48 @@ npm run profile:fuzz -- --suite monitor-runtime --runs 100 --seed 130363 \
--test fault-injected --path '0'
```
-Suites: `monitor-runtime`, `monitor-inactivity`, `monitor-native`, `workflow-restart`. Runs and seeds are positive safe integers. The runner caps cases at 1,000; native cases retain their existing cap of 64. Replay requires an explicit seed and a pattern selecting exactly one property, with no control tests. Each invocation runs one serial Vitest child without a shell or retries.
+Suites: `monitor-runtime`, `monitor-inactivity`, `monitor-native`, `workflow-restart`.
+
+Inputs and runs:
+
+- Runs and seeds are positive safe integers.
+- The runner caps cases at 1,000. Native cases retain their existing cap of 64.
+- Replay requires an explicit seed and a pattern selecting exactly one property, with no control tests.
+- Each invocation runs one serial Vitest child without a shell or retries.
+
+Artifacts and caps:
+
+- Artifacts default to `.artifacts/profiles/fuzz/-/`. `--out` changes the root.
+- `--timeout-ms` defaults to and cannot exceed 600,000.
+- Retained output is capped at 1 MiB per stream. Hashes also cover observed discarded bytes.
+- Worker profiles are capped at 64 MiB before write.
+
+What `summary.json` reports:
+
+- It links raw campaign/reporter files and checksums.
+- It distinguishes requested, capped, and observed counts.
+- Unreported counters remain `null`.
+
+Failed, interrupted, skipped, missing-profile and missing-source-identity runs do not pass. Primary assertion logs survive reporting failures.
+
+What profiling covers:
-Artifacts default to `.artifacts/profiles/fuzz/-/`. `--out` changes the root. `--timeout-ms` defaults to and cannot exceed 600,000. Retained output is capped at 1 MiB per stream; hashes also cover observed discarded bytes. Worker profiles are capped at 64 MiB before write.
+- Profiling is opt-in through `PI_LOOP_FUZZ_PROFILE_DIR`, set by the runner. Normal tests do not start an inspector.
+- Capture covers suite hooks in the actual property worker, not startup, the coordinator, or native descendants.
+- Worker RSS is a process-lifetime high-water mark.
-`summary.json` links raw campaign/reporter files and checksums. It distinguishes requested, capped, and observed counts. Unreported counters remain `null`. Failed, interrupted, skipped, missing-profile and missing-source-identity runs do not pass. Primary assertion logs survive reporting failures. Profiling is opt-in through `PI_LOOP_FUZZ_PROFILE_DIR`, set by the runner; normal tests do not start an inspector. Capture covers suite hooks in the actual property worker, not startup, the coordinator, or native descendants. Worker RSS is a process-lifetime high-water mark. Native POSIX skips are not Windows passes. Timing and profiles do not certify correctness.
+Native POSIX skips are not Windows passes. Timing and profiles do not certify correctness.
## Change evidence
Follow `AGENTS.md` for the testing contract:
- Bug: behavioral regression fails on unchanged code, nearby control passes, same regression passes after repair.
-- Feature: acceptance expectations precede implementation; test the affected surface and applicable boundaries.
+- Feature: acceptance expectations precede implementation. Test the affected surface and applicable boundaries.
- Invariant: independently test authority, ownership, rejection, lifecycle, bounds, and persistence properties that must remain unchanged.
-- Model-facing guidance: validate examples and misuse deterministically; report bounded live model/fixture/attempt evidence separately. A text match is not a model-behavior result.
+- Model-facing guidance: validate examples and misuse deterministically. Report bounded live model/fixture/attempt evidence separately. A text match is not a model-behavior result.
-Name the expectations and invariants in the PR body. Record exact red/green commands and limitations. Compilation, fixture, or provider failures do not establish a product defect; skipped live checks do not pass.
+Name the expectations and invariants in the PR body. Record exact red/green commands and limitations. Compilation, fixture, or provider failures do not establish a product defect. Skipped live checks do not pass.
## Change-specific minimums
diff --git a/docs/USAGE_GUIDE.md b/docs/USAGE_GUIDE.md
index be65084b..20d1e307 100644
--- a/docs/USAGE_GUIDE.md
+++ b/docs/USAGE_GUIDE.md
@@ -1,6 +1,6 @@
# pi-loop usage guide
-`pi-loop` re-wakes a pi agent from schedules and events, runs self-paced goal loops, and monitors background commands. This guide covers the operational details; see the [README](../README.md) for installation and a quick start.
+`pi-loop` re-wakes a pi agent from schedules and events, runs self-paced goal loops, and monitors background commands. This guide covers the operational details. See the [README](../README.md) for installation and a quick start.
## Loops
@@ -16,7 +16,13 @@ LoopCreate trigger="0 9 * * 1-5" prompt="Review weekday alerts" maxFires=10
Intervals such as `5m`, `2h`, and `1d` are converted to cron expressions. Full five-field cron expressions are also accepted. Cron and hybrid loops track their next fire time and deliver only when the agent is idle.
-Use `maxFires` for polling or other bounded work so a loop cannot run indefinitely. New loops expire after seven days by default. Set `PI_LOOP_EXPIRES_IN` (for example, `14d`) to change the runtime default, or pass `expiresIn` to `LoopCreate`, `WorkflowCreate`, or `OrchestrationCreate`; explicit durations may exceed seven days. Existing controllers retain their persisted absolute `expiresAt`. Values must be positive safe-integer durations whose resulting deadline fits JavaScript's valid date range; invalid runtime configuration fails extension activation instead of falling back. `LoopList` exposes each controller's exact boundary. Expiry and stale event/hybrid retirement during session recovery emit `loops:expired` and a hidden Pi wake that reports whether the controller was deleted or paused. Renewal is explicit: recreate the loop only when its schedule is still required.
+Use `maxFires` for polling or other bounded work so a loop cannot run indefinitely.
+
+New loops expire after seven days by default. Set `PI_LOOP_EXPIRES_IN` (for example, `14d`) to change the runtime default, or pass `expiresIn` to `LoopCreate`, `WorkflowCreate`, or `OrchestrationCreate`. Explicit durations may exceed seven days. Existing controllers retain their persisted absolute `expiresAt`. `LoopList` exposes each controller's exact boundary.
+
+Values must be positive safe-integer durations whose resulting deadline fits JavaScript's valid date range. Invalid runtime configuration fails extension activation instead of falling back.
+
+Expiry and stale event/hybrid retirement during session recovery emit `loops:expired` and a hidden Pi wake that reports whether the controller was deleted or paused. Renewal is explicit: recreate the loop only when its schedule is still required.
### Event loops
@@ -27,7 +33,7 @@ Event loops react to pi events instead of polling:
LoopCreate trigger="tool_execution_end" prompt="Review the completed tool call" triggerType="event" recurring=true
```
-`LoopCreate` event loops are one-shot by default. Set `recurring=true` to keep listening. Prefer events when a relevant source exists; use hybrid triggers when an event needs a scheduled safety net.
+`LoopCreate` event loops are one-shot by default. Set `recurring=true` to keep listening. Prefer events when a relevant source exists. Use hybrid triggers when an event needs a scheduled safety net.
### Hybrid loops
@@ -41,13 +47,13 @@ LoopCreate trigger="cron:5m event:tasks:created" prompt="Process pending tasks"
Open `/loop` → `View loops` and select a controller. The detail view shows its kind, resolved storage scope, authority, expiry, reported next fire, fire budget, pause provenance, and supported next action. Workflow and orchestration details remain available below the lifecycle fields. Hybrid detail retains the event source and debounce window, not the event filter.
-Inspection does not claim work, resume a controller, or schedule a wake. A live workflow lease is not proof of execution; fire counts are accounting, not delivered-wake counts. Expired, terminal, and orchestration controllers do not offer generic resume. A `controller_limit` pause at an exhausted budget also blocks resume. Custom `PI_LOOP` files are labelled separately from session storage; paths and event filters are not displayed in the lifecycle fields.
+Inspection does not claim work, resume a controller, or schedule a wake. A live workflow lease is not proof of execution. Fire counts are accounting, not delivered-wake counts. Expired, terminal, and orchestration controllers do not offer generic resume. A `controller_limit` pause at an exhausted budget also blocks resume. Custom `PI_LOOP` files are labelled separately from session storage. Paths and event filters are not displayed in the lifecycle fields.
### Choosing one controller
Choose one durable owner before decomposing work:
-- use `WorkflowCreate` when one goal has ordered phases, conditional outcomes, rework, or durable handoff—even if those phases are described as tasks;
+- use `WorkflowCreate` when one goal has ordered phases, conditional outcomes, rework, or durable handoff, even if those phases are described as tasks;
- use multiple `TaskCreate` calls for independently completable items in a flat or manually assigned backlog;
- use a dynamic `LoopCreate` for one evolving, self-paced goal that does not need named phase/outcome routing;
- use `taskBacklog` only when autonomous processing of standalone tasks was explicitly requested.
@@ -62,7 +68,7 @@ Free text passed to `/loop` creates a self-paced dynamic goal:
/loop finish the release
```
-The first wake is immediate when the agent is idle. Free-text dynamic goals have no implicit fire-count cap; they remain bounded by the recurring-loop lifetime and explicit completion or deletion. Use `LoopCreate maxFires=...` when a finite fire budget is required. After each iteration, the agent calls `LoopUpdate`:
+The first wake is immediate when the agent is idle. Free-text dynamic goals have no implicit fire-count cap. They remain bounded by the recurring-loop lifetime and explicit completion or deletion. Use `LoopCreate maxFires=...` when a finite fire budget is required. After each iteration, the agent calls `LoopUpdate`:
```text
LoopUpdate id="1" status="continue" state="Tests pass; reviewing package"
@@ -106,7 +112,7 @@ WorkflowCreate goal="Fix the regression" definition='{
}'
```
-The initial state must be non-terminal. Each wake presents the current state, state instructions, the active workflow execution (subject + lease owner/expiry), allowed outcomes, and — after the first transition — the last transition and its recorded evidence, so the next state can act on what the previous one found. The agent finishes the state by selecting one declared outcome:
+The initial state must be non-terminal. Each wake presents the current state, state instructions, the active workflow execution (subject + lease owner/expiry), and allowed outcomes. After the first transition, it also presents the last transition and its recorded evidence, so the next state can act on what the previous one found. The agent finishes the state by selecting one declared outcome:
```text
WorkflowTransition id="1" outcome="root_cause_found" evidence="A null config reaches the parser."
@@ -114,9 +120,19 @@ WorkflowTransition id="1" outcome="tests_pass" evidence="Targeted and full test
WorkflowTransition id="1" outcome="blocked" evidence="Monitor #m1 failed." claim='{"class":"environmental","provider":"monitor","subject":"m1","fact":"status","expected":"error"}'
```
-`WorkflowTransition` validates the branch, settles the current execution, records evidence, and activates the next state's execution in the same locked write. A `paused` terminal target requires the typed claim shown above. The provider runs before the LoopStore lock, observations are scoped to the current workflow/state/revision/execution/workspace, and the final write uses the existing CAS. The built-in `monitor` provider exposes only `status`, `exitCode`, and `stopReason`; raw output is never admission evidence. Missing, stale, conflicting, contradicted, or unavailable evidence leaves every store unchanged. User-authority claims fail closed because machine evidence cannot manufacture consent.
+`WorkflowTransition` validates the branch, settles the current execution, records evidence, and activates the next state's execution in the same locked write. A `paused` terminal target requires the typed claim shown above.
+
+The provider runs before the LoopStore lock, observations are scoped to the current workflow/state/revision/execution/workspace, and the final write uses the existing CAS. The built-in `monitor` provider exposes only `status`, `exitCode`, and `stopReason`. Raw output is never admission evidence. Missing, stale, conflicting, contradicted, or unavailable evidence leaves every store unchanged. User-authority claims fail closed because machine evidence cannot manufacture consent.
+
+Newly entered task phases start unowned so another agent sharing project scope can claim the next phase immediately. Whichever agent continues must call `WorkflowClaim id="1"` first. Workflow work is embedded in the loop controller: never call `TaskClaim` or `TaskUpdate` for it. `WorkflowClaim` also renews the current runtime's lease or takes over an expired lease after a restart.
+
+A self-loop requires `maxAttempts`, creates a fresh unowned attempt execution, and increments the displayed attempt count. Legacy unbounded self-loops fail closed at transition time until revised. When a target reaches `maxAttempts`, only outcomes leading to that target become unavailable. Other declared outcomes remain selectable. LoopList and workflow wakes omit outcomes whose target state has exhausted `maxAttempts`.
-Newly entered task phases start unowned so another agent sharing project scope can claim the next phase immediately; whichever agent continues must call `WorkflowClaim id="1"` first. Workflow work is embedded in the loop controller — never call `TaskClaim` or `TaskUpdate` for it. `WorkflowClaim` also renews the current runtime's lease or takes over an expired lease after a restart. A self-loop requires `maxAttempts`, creates a fresh unowned attempt execution, and increments the displayed attempt count. Legacy unbounded self-loops fail closed at transition time until revised. When a target reaches `maxAttempts`, only outcomes leading to that target become unavailable; other declared outcomes remain selectable. Reaching a `completed` terminal state deletes the workflow loop; reaching an admitted `paused` terminal state preserves it with `semantic_terminal` pause provenance. Administrative, controller-limit, and orchestration-settlement pauses carry distinct provenance; legacy snapshots may be unattributed. Administrative and unattributed pauses require explicit resume, while self-transitions never bypass controller limits. Terminal workflow states cannot be resumed. Task status does not guess an outcome—the model selects one explicitly. LoopList and workflow wakes omit outcomes whose target state has exhausted `maxAttempts`.
+Reaching a `completed` terminal state deletes the workflow loop. Reaching an admitted `paused` terminal state preserves it with `semantic_terminal` pause provenance. Terminal workflow states cannot be resumed.
+
+Administrative, controller-limit, and orchestration-settlement pauses carry distinct provenance. Legacy snapshots may be unattributed. Administrative and unattributed pauses require explicit resume, while self-transitions never bypass controller limits.
+
+Task status does not guess an outcome: the model selects one explicitly.
#### Verified outcomes
@@ -131,7 +147,7 @@ A state can require a command to exit 0 before an outcome is accepted, so the mo
}
```
-`WorkflowTransition outcome="tests_pass"` runs `npm test` in the session cwd (same authority as `MonitorCreate`) before the transition is written. Exit 0 advances to `done` with the check recorded as admission evidence. A failure takes `onFail` with the exit status and output tail as evidence; without `onFail` the transition is rejected and the state is unchanged. The tool result shows the verdict and output tail either way. Verified outcomes cannot target a paused terminal, and `onFail` must be a different, unverified outcome. Details are in [REFERENCE.md](REFERENCE.md#verified-outcomes).
+`WorkflowTransition outcome="tests_pass"` runs `npm test` in the session cwd (same authority as `MonitorCreate`) before the transition is written. Exit 0 advances to `done` with the check recorded as admission evidence. A failure takes `onFail` with the exit status and output tail as evidence. Without `onFail`, the transition is rejected and the state is unchanged. The tool result shows the verdict and output tail either way. Verified outcomes cannot target a paused terminal, and `onFail` must be a different, unverified outcome. Details are in [REFERENCE.md](REFERENCE.md#verified-outcomes).
When active work discovers a missing prerequisite or supersedes future instructions, inspect `LoopList` and submit one typed revision against its exact definition revision, state, and transition sequence:
@@ -151,13 +167,26 @@ WorkflowRevise id="1" expectedRevision=2 expectedState="open-pr" expectedTransit
]'
```
-Reissue atomically cancels the superseded execution into history, creates fresh current work under the still-valid lease, resets state timing, and queues a fresh wake without fabricating a transition. An administrative pause can be reissued in place: the replacement waits paused, and `/loop` resume wakes only the fresh instruction. `controller_limit` and other non-administrative pauses reject reissue because resuming them does not renew the exhausted controller; semantic terminals cannot be revised. Taskless work that gains a task starts unowned and requires `WorkflowClaim`. Stale revision, state, sequence, lease, and execution authority fail closed. Workflow revision never creates standalone tasks. See the [reference](./REFERENCE.md#adaptive-revision) for operation and graph rules.
+Reissue atomically cancels the superseded execution into history, creates fresh current work under the still-valid lease, resets state timing, and queues a fresh wake without fabricating a transition. An administrative pause can be reissued in place: the replacement waits paused, and `/loop` resume wakes only the fresh instruction. `controller_limit` and other non-administrative pauses reject reissue because resuming them does not renew the exhausted controller. Semantic terminals cannot be revised.
+
+Taskless work that gains a task starts unowned and requires `WorkflowClaim`. Stale revision, state, sequence, lease, and execution authority fail closed. Workflow revision never creates standalone tasks. See the [reference](./REFERENCE.md#adaptive-revision) for operation and graph rules.
+
+A missing prerequisite, missing route, or exhausted route is a plan gap, not automatically a blocker. Persist an actionable recovery route with `WorkflowRevise`, then continue through the revised transition and claim while work remains actionable. Call `WorkflowTransition` only when an available declared outcome is supported by evidence. Never fabricate one. Do not stop or move the controller to terminal `paused` merely to report progress. Environmental blockers require trusted admission. If user authority is required, report the exact decision needed. Machine observations cannot authorize the transition.
+
+To repeat a state until evidence supports an outcome, add a cron-only state policy: `"loop":{"schedule":"0 7 * * *","maxFires":10,"startImmediately":false}`. Only the active state's policy is armed. State policies do not wake immediately unless `startImmediately` is `true`. Scheduled wakes retain the active execution. `WorkflowTransition` remains the only operation that settles it and unlocks the destination execution and cadence.
+
+Below the fire cap, a no-change iteration leaves the workflow active. Do not encode no change as an immediate self-transition. Persist material future-plan changes with `WorkflowRevise`.
-A missing prerequisite, missing route, or exhausted route is a plan gap—not automatically a blocker. Persist an actionable recovery route with `WorkflowRevise`, then continue through the revised transition and claim while work remains actionable. Call `WorkflowTransition` only when an available declared outcome is supported by evidence; never fabricate one. Do not stop or move the controller to terminal `paused` merely to report progress. Environmental blockers require trusted admission. If user authority is required, report the exact decision needed; machine observations cannot authorize the transition.
+Reaching the state-local `maxFires` pauses the workflow and schedules no next cadence. An evidenced transition to a different state resumes atomically. A workflow-wide cap permits only a terminal transition. Otherwise revise in a bounded recovery state/route, then transition and claim it.
-To repeat a state until evidence supports an outcome, add a cron-only state policy: `"loop":{"schedule":"0 7 * * *","maxFires":10,"startImmediately":false}`. Only the active state's policy is armed. Scheduled wakes retain the active execution; `WorkflowTransition` remains the only operation that settles it and unlocks the destination execution and cadence. Below the fire cap, a no-change iteration leaves the workflow active; do not encode no change as an immediate self-transition. Persist material future-plan changes with `WorkflowRevise`. Reaching the state-local `maxFires` pauses the workflow and schedules no next cadence; an evidenced transition to a different state resumes atomically. A workflow-wide cap permits only a terminal transition. Otherwise revise in a bounded recovery state/route, then transition and claim it. State policies do not wake immediately unless `startImmediately` is `true`.
+`LoopList` includes workflow state, active execution, transition evidence, valid outcomes, wall-clock workflow age, current-state age, and derived activity alongside ordinary loops. Activity is one of:
-`LoopList` includes workflow state, active execution, transition evidence, valid outcomes, wall-clock workflow age, current-state age, and derived activity alongside ordinary loops. Activity is `claimed` while a task execution has a live lease (ownership, not observed execution), `waiting` while a monitor is attached, `paused` when the controller is durably paused, and otherwise `idle` while awaiting a claim, outcome, or non-task wake. Lease expiry returns claimed work to idle; these labels do not alter authority or scheduling. A completed transition reports an ephemeral `stopped` snapshot, then the workflow remains deleted rather than retaining a UI-only tombstone.
+- `claimed` while a task execution has a live lease (ownership, not observed execution);
+- `waiting` while a monitor is attached;
+- `paused` when the controller is durably paused;
+- `idle` otherwise, while awaiting a claim, outcome, or non-task wake.
+
+Lease expiry returns claimed work to idle. These labels do not alter authority or scheduling. A completed transition reports an ephemeral `stopped` snapshot, then the workflow remains deleted rather than retaining a UI-only tombstone.
### Inspecting and stopping loops
@@ -180,15 +209,29 @@ OrchestrationCreate goal="Review release readiness" work='[
]' concurrency=2 maxAttempts=2 maxTurns=12
```
-This surface requires the default file-backed session scope and a subagent provider: `@tintinweb/pi-subagents` (protocol v2) or the unscoped npm `pi-subagents` package (RPC v1). Its tools are registered only when one answers. With the npm `pi-subagents` package, work without an `agentType` runs as its generic `delegate` agent, `maxTurns` is not offered and is rejected if sent (that provider has no turn limit), and pacing reacts only to errors and timeouts; see the provider table in the reference. It rejects memory/project scope, `PI_LOOP=off`, and custom `PI_LOOP` paths. The batch is stored only in `LoopStore`; it does not create standalone tasks or delegate workflow states.
+This surface requires the default file-backed session scope and a subagent provider: `@tintinweb/pi-subagents` (protocol v2) or the unscoped npm `pi-subagents` package (RPC v1). Its tools are registered only when one of these providers answers. The surface rejects memory/project scope, `PI_LOOP=off`, and custom `PI_LOOP` paths. The batch is stored only in `LoopStore`. It does not create standalone tasks or delegate workflow states.
+
+With the npm `pi-subagents` package:
+
+- work without an `agentType` runs as its generic `delegate` agent;
+- `maxTurns` is not offered and is rejected if sent (that provider has no turn limit);
+- pacing reacts only to errors and timeouts.
+
+See the provider table in the reference.
+
+A work item may carry a `label`: a display name of at most 40 characters that listings show in place of the prompt snippet. It is never sent to the worker. Control characters are collapsed, a blank label is dropped, and a longer one is clipped.
+
+Work items must be independent. The controller does not model dependencies or protect overlapping filesystem writes. Each spawned worker is background, does not inherit parent context, and is isolated from extension tools, so it cannot call pi-loop task/workflow/controller tools. The optional `agentType`, `model`, and `maxTurns` fields are the only invocation overrides.
-A work item may carry a `label`: a display name of at most 40 characters that listings show in place of the prompt snippet. It is never sent to the worker; control characters are collapsed, a blank label is dropped, and a longer one is clipped. Work items must be independent. The controller does not model dependencies or protect overlapping filesystem writes. Each spawned worker is background, does not inherit parent context, and is isolated from extension tools, so it cannot call pi-loop task/workflow/controller tools. The optional `agentType`, `model`, and `maxTurns` fields are the only invocation overrides.
+Batches are paced adaptively by default (see below). Passing `concurrency` selects fixed pacing: it bounds spawning/queued/running dispatches to that many, while pi-subagents keeps its own global concurrency ceiling.
-Batches are paced adaptively by default (see below). Passing `concurrency` selects fixed pacing: it bounds spawning/queued/running dispatches to that many, while pi-subagents keeps its own global concurrency ceiling. A proved worker failure retries up to `maxAttempts`. An overload that struck before the worker ran any tool, or a spawn that failed on a dropped connection, is re-sent without spending an attempt (at most 3 times per item and once per item across the batch). A spawn RPC timeout becomes `uncertain` and requires parent review because upstream has no status/list query or idempotent dispatch key.
+A proved worker failure retries up to `maxAttempts`. An overload that struck before the worker ran any tool, or a spawn that failed on a dropped connection, is re-sent without spending an attempt (at most 3 times per item and once per item across the batch).
+
+A spawn RPC timeout becomes `uncertain` and requires parent review because upstream has no status/list query or idempotent dispatch key.
#### Verified work and adaptive pacing
-A work item may declare `verify`, a shell command that must exit 0 before the item counts as complete. The worker is told the check; a failing check retries the item with the exit status and output tail in the next prompt:
+A work item may declare `verify`, a shell command that must exit 0 before the item counts as complete. The worker is told the check. A failing check retries the item with the exit status and output tail in the next prompt:
```text
OrchestrationCreate goal="Port the parsers" work='[
@@ -199,7 +242,17 @@ OrchestrationCreate goal="Port the parsers" work='[
`verify` runs in the session cwd with the same authority as `MonitorCreate`. While it runs, the dispatch shows as `verifying` and still holds capacity.
-Pacing defaults to `aimd`: a window that starts at three workers (or the batch size, if smaller; or where the session's last aimd batch for the same model settled, if it ran in the past 30 minutes), grows on verified completions, shrinks on overload errors or sustained slowdown (to 0.7 when the provider refused work before it ran, to half when work was lost), and collapses to one on timeouts. It is bounded by the batch size when every item declares `verify`, otherwise by 8 workers, so it finds the real limit (a local model server, a provider rate limit) without being told. Task failures do not shrink the window. Pass `concurrency=N` or `pacing="fixed"` for a fixed worker count, or set `PI_LOOP_PACING=fixed` to make fixed the default; an explicit `pacing` always wins. Batches created before this default keep the pacing they were stored with. Signal classification, the delay heuristic, and its limits are in [REFERENCE.md](REFERENCE.md#ack-clocked-pacing).
+Pacing defaults to `aimd`, which keeps a window of workers:
+
+- The window starts at three workers, or at the batch size if that is smaller, or where the session's last aimd batch for the same model settled if that batch ran in the past 30 minutes.
+- It grows on verified completions.
+- It shrinks on overload errors or sustained slowdown: to 0.7 when the provider refused work before it ran, and to half when work was lost.
+- It collapses to one on timeouts.
+- Task failures do not shrink it.
+
+The window is bounded by the batch size when every item declares `verify`, otherwise by 8 workers, so it finds the real limit (a local model server, a provider rate limit) without being told.
+
+Pass `concurrency=N` or `pacing="fixed"` for a fixed worker count, or set `PI_LOOP_PACING=fixed` to make fixed the default. An explicit `pacing` always wins. Batches created before this default keep the pacing they were stored with. Signal classification, the delay heuristic, and its limits are in [REFERENCE.md](REFERENCE.md#ack-clocked-pacing).
Inspect compact progress with `LoopList` and durable evidence with:
@@ -208,11 +261,21 @@ OrchestrationGet id="1"
OrchestrationGet id="1" workId="2"
```
-These surfaces call the controller an **orchestration**: `active`, `needs attention`, `complete`, or `cancelled`. Work is `pending` (undispatched), `reserved` (occupying local capacity), `complete`, `failed`, `uncertain`, or `cancelled`. While the controller is still dispatching, progress shows reserved work against what may be dispatched right now as `N/W in flight`: `W` is the current aimd window, or the fixed concurrency. Progress separately shows dispatch observations: `starting`, `queued`, or `reported running`. Observations may be stale and do not establish current liveness or quiescence; detailed attempts and provider-owned results remain available. The status line and progress panel show a batch only while it is `active` or `needs attention`, so the count drops when a batch completes or is cancelled. The `/loop` inspector, `LoopList` and `OrchestrationGet` keep completed and cancelled batches until explicit deletion. This durable batch is distinct from provider-native `SubagentWorkflow`, whose FleetView, conversations, and transcripts remain provider-owned.
+These surfaces call the controller an **orchestration**: `active`, `needs attention`, `complete`, or `cancelled`. Work is `pending` (undispatched), `reserved` (occupying local capacity), `complete`, `failed`, `uncertain`, or `cancelled`.
+
+While the controller is still dispatching, progress shows reserved work against what may be dispatched right now as `N/W in flight`, where `W` is the current aimd window or the fixed concurrency. Progress separately shows dispatch observations: `starting`, `queued`, or `reported running`. Observations may be stale and do not establish current liveness or quiescence. Detailed attempts and provider-owned results remain available.
+
+The status line and progress panel show a batch only while it is `active` or `needs attention`, so the count drops when a batch completes or is cancelled. The `/loop` inspector, `LoopList` and `OrchestrationGet` keep completed and cancelled batches until explicit deletion.
-The parent is not woken merely to refill capacity. Normal terminal results are persisted with provider-owned completion status, are not consumed, and do not also generate a pi-loop aggregate wake; the provider's native output is the sole completion path. A durable pi-loop wake remains for uncertain dispatches or failures with no provider-owned terminal result. Completed and attention batches pause for inspection; `LoopUpdate` cannot mutate them. `LoopDelete` first records cancellation and pauses the controller, then requests cancellation of known workers. A delete request retains the paused controller whenever any dispatch has unconfirmed execution; the tool reports this explicitly. Inspect retained agent/dispatch identities with `OrchestrationGet`. Protocol v2 cannot prove safe automatic cleanup; repeated deletion does not erase uncertainty.
+This durable batch is distinct from provider-native `SubagentWorkflow`, whose FleetView, conversations, and transcripts remain provider-owned.
-Session shutdown/switch records uncertainty and requests cancellation before rebinding storage. Stop acknowledgement, `stopped` status, and lease expiry do not prove termination or safe replay. No automatic retry or consume follows those signals. Legacy stop/interruption records become uncertain on load; already consumed output or previously launched retries cannot be recovered or undone. A crashed runtime cannot safely reconstruct an upstream worker, so ownership-expiry recovery fails closed instead of redispatching it.
+The parent is not woken merely to refill capacity. Normal terminal results are persisted with provider-owned completion status, are not consumed, and do not also generate a pi-loop aggregate wake. The provider's native output is the sole completion path. A durable pi-loop wake remains for uncertain dispatches or failures with no provider-owned terminal result.
+
+Completed and attention batches pause for inspection, and `LoopUpdate` cannot mutate them.
+
+`LoopDelete` first records cancellation and pauses the controller, then requests cancellation of known workers. A delete request retains the paused controller whenever any dispatch has unconfirmed execution, and the tool reports this explicitly. Inspect retained agent/dispatch identities with `OrchestrationGet`. Protocol v2 cannot prove safe automatic cleanup, and repeated deletion does not erase uncertainty.
+
+Session shutdown/switch records uncertainty and requests cancellation before rebinding storage. Stop acknowledgement, `stopped` status, and lease expiry do not prove termination or safe replay. No automatic retry or consume follows those signals. Legacy stop/interruption records become uncertain on load. Already consumed output or previously launched retries cannot be recovered or undone. A crashed runtime cannot safely reconstruct an upstream worker, so ownership-expiry recovery fails closed instead of redispatching it.
## Background monitors
@@ -227,9 +290,11 @@ Output is buffered and emitted as `monitor:output`. A monitor finishes as one of
- clean exit: emits `monitor:done`
- nonzero exit or spawn failure: emits `monitor:error`
- inactivity timeout: stops the process after no output or structured progress, emits `monitor:error`, and wakes the agent after reaping when its callback controller is still unexpired
-- explicit `MonitorStop`: cancels the monitor without an `onDone` wake; workflow-owned monitors resume their current state with `status=stopped`
+- explicit `MonitorStop`: cancels the monitor without an `onDone` wake. Workflow-owned monitors resume their current state with `status=stopped`
-Pass `onDone` whenever the agent should resume work after success or failure. Its one-shot wake also fires on timeout; monitors without `onDone` send a timeout-only alert while that callback controller remains unexpired. `timeout` is an inactivity threshold, not a total-runtime limit: stdout/stderr bytes, JSONL progress, and `MonitorUpdate` renew it. The default is five quiet minutes; use `timeout=0` to disable stale detection.
+Pass `onDone` whenever the agent should resume work after success or failure. Its one-shot wake also fires on timeout. Monitors without `onDone` send a timeout-only alert while that callback controller remains unexpired.
+
+`timeout` is an inactivity threshold, not a total-runtime limit: stdout/stderr bytes, JSONL progress, and `MonitorUpdate` renew it. The default is five quiet minutes. Use `timeout=0` to disable stale detection.
For a monitor launched from an active workflow, use `workflowId` instead of `onDone`:
@@ -237,9 +302,11 @@ For a monitor launched from an active workflow, use `workflowId` instead of `onD
MonitorCreate command="npm test" description="Validate release" workflowId="29"
```
-The workflow pauses its cadence while the monitor runs. Monitor completion and timeout-alert loops use the same configured loop lifetime as every other new controller. If that boundary arrives before the monitor settles, expiry retirement wins and the completion wake is not delivered; choose an `expiresIn` that covers the expected monitor lifetime. While the same Pi runtime remains active, success, failure, timeout, or explicit `MonitorStop` resumes the same state once with status, stop reason, exit code, and output count; inspect the result and call `WorkflowTransition` with a declared outcome. At or after the controller's expiry boundary, monitor completion retires the workflow before clearing the wait, rearming, or waking it. Do not poll with `LoopUpdate` while it waits.
+The workflow pauses its cadence while the monitor runs. Do not poll with `LoopUpdate` while it waits. While the same Pi runtime remains active, success, failure, timeout, or explicit `MonitorStop` resumes the same state once with status, stop reason, exit code, and output count. Inspect the result and call `WorkflowTransition` with a declared outcome.
+
+Monitor completion and timeout-alert loops use the same configured loop lifetime as every other new controller. If that boundary arrives before the monitor settles, expiry retirement wins and the completion wake is not delivered. Choose an `expiresIn` that covers the expected monitor lifetime. At or after the controller's expiry boundary, monitor completion retires the workflow before clearing the wait, rearming, or waking it.
-A session shutdown or switch interrupts the monitor: its in-memory process and wait are discarded without a terminal workflow wake. In session or project scope, inspect the resumed workflow and start a new monitor if the work still needs to run; memory-scoped workflows are discarded.
+A session shutdown or switch interrupts the monitor: its in-memory process and wait are discarded without a terminal workflow wake. In session or project scope, inspect the resumed workflow and start a new monitor if the work still needs to run. Memory-scoped workflows are discarded.
```text
MonitorList
@@ -256,7 +323,7 @@ When [@tintinweb/pi-tasks](https://github.com/tintinweb/pi-tasks) is available,
### Native fallback
-If no `pi-tasks` has answered the startup ping by `session_start` (which runs after every extension has loaded), `pi-loop` registers the native tools right there, before the first request is built, so the tool set — and with it the provider's cached prompt prefix — is the same for every request of the session. A six-second timer remains as a backstop for hosts that never emit `session_start`. The native tools are:
+If no `pi-tasks` has answered the startup ping by `session_start` (which runs after every extension has loaded), `pi-loop` registers the native tools right there, before the first request is built. The tool set, and with it the provider's cached prompt prefix, is therefore the same for every request of the session. A six-second timer remains as a backstop for hosts that never emit `session_start`. The native tools are:
```text
TaskCreate subject="Fix deploy polling" description="Replace polling with an event-driven loop"
@@ -269,7 +336,11 @@ TaskUpdate id="1" status="closed" claimId="" # abandon without comple
TaskDelete id="1"
```
-The native provider is selected for the session and exposes `/tasks`, compact status-line tracking, persisted task state, lifecycle events, and task RPC replies. Standalone tasks are for independently completable backlog items; use a workflow instead when related items are ordered phases of one evolving goal. `TaskClaim` provides one live owner per task, renewable heartbeats, and takeover only after lease expiry. It also moves the task to `in_progress`; a following `TaskUpdate status="in_progress"` is harmless but redundant. Claimed subject/description edits and terminal updates require the exact live claim token; an expired token must be replaced by reclaiming the task. Before handing off unfinished work, update its description with material progress, discovered dependencies, and the next action. `closed` is terminal like `completed`, is excluded from pending backlog work, and deliberately does not emit `tasks:completed`; use it when work is intentionally abandoned.
+The native provider is selected for the session and exposes `/tasks`, compact status-line tracking, persisted task state, lifecycle events, and task RPC replies. Standalone tasks are for independently completable backlog items. Use a workflow instead when related items are ordered phases of one evolving goal.
+
+`TaskClaim` provides one live owner per task, renewable heartbeats, and takeover only after lease expiry. It also moves the task to `in_progress`, so a following `TaskUpdate status="in_progress"` is harmless but redundant. Claimed subject/description edits and terminal updates require the exact live claim token. An expired token must be replaced by reclaiming the task. Before handing off unfinished work, update its description with material progress, discovered dependencies, and the next action.
+
+`closed` is terminal like `completed`, is excluded from pending backlog work, and deliberately does not emit `tasks:completed`. Use it when work is intentionally abandoned.
See the [reference](./REFERENCE.md#mutation-guarantees) for ownership and mutation boundaries.
@@ -279,7 +350,7 @@ Set `taskBacklog=true` on a recurring `tasks:created` event loop to process unfi
Each wake is action-first: call `TaskList`, inspect `TaskGet`, claim or resume one task, perform concrete work, run observable validation, and settle it in the same turn. Status prose and future-tense promises are not progress. Empty backlogs and verified live-owner blockers are the only no-work exits.
-Workers bootstrap existing work, coalesce repeated create events, resume eligible `in_progress` tasks before unrelated pending work, and delete themselves when the queue drains. They pause visibly at the default 25-fire cap. Prerequisites are a description convention (for example, “depends on #2”), not first-class TaskStore edges; use `TaskGet` to follow them. `autoTask` is separate and creates a new task on each ordinary loop fire.
+Workers bootstrap existing work, coalesce repeated create events, resume eligible `in_progress` tasks before unrelated pending work, and delete themselves when the queue drains. They pause visibly at the default 25-fire cap. Prerequisites are a description convention (for example, “depends on #2”), not first-class TaskStore edges. Use `TaskGet` to follow them. `autoTask` is separate and creates a new task on each ordinary loop fire.
## Events
@@ -293,7 +364,7 @@ Monitor events:
Loop lifecycle events:
-- `loops:expired` — `{loopId, prompt, trigger, recurring, createdAt, expiresAt, expiredAt, disposition, source, reason}` where `reason` is `expires_at` or `resume_event_stale`
+- `loops:expired`: `{loopId, prompt, trigger, recurring, createdAt, expiresAt, expiredAt, disposition, source, reason}`, where `reason` is `expires_at` or `resume_event_stale`
- `loops:autodeleted`
Native task lifecycle events:
@@ -307,11 +378,11 @@ Native task lifecycle events:
- `tasks:deleted`
- `tasks:backlog_empty`
-Task event payloads include `previousStatus`. Transition events report the status before the transition; details-only `tasks:updated` events report the status current at edit time.
+Task event payloads include `previousStatus`. Transition events report the status before the transition. Details-only `tasks:updated` events report the status current at edit time.
## Cross-extension task RPC
-External consumers should import only from `@trevonistrevon/pi-loop/api`; deep `src/` imports are blocked by the package export map.
+External consumers should import only from `@trevonistrevon/pi-loop/api`. Deep `src/` imports are blocked by the package export map.
```ts
import { TASKS_RPC, rpcCall } from "@trevonistrevon/pi-loop/api";
@@ -354,14 +425,61 @@ Scope behavior:
- `memory`: keeps all state ephemeral
- `project`: shares persisted automation across sessions in the repository
-Session files live under `.pi/loops/` and `.pi/tasks/`. Keep `session` as the normal default; use `project` only when shared automation is intentional.
+Session files live under `.pi/loops/` and `.pi/tasks/`. Keep `session` as the normal default. Use `project` only when shared automation is intentional.
## Status line and limits
-The TUI status line summarizes ordinary loops, workflows, orchestrations, running monitors, and native tasks. A single workflow shows its derived activity duration, current state and state age, and total wall-clock age; paused workflows remain visible. Use `LoopList`, `OrchestrationGet`, `MonitorList`, and `/tasks` for detail. Ordinary active-loop `age` is wall-clock time since creation; paused ordinary loops omit age and show available pause provenance. The status clears when no work is active.
+The TUI status line summarizes ordinary loops, workflows, orchestrations, running monitors, and native tasks. The status clears when no work is active. Use `LoopList`, `OrchestrationGet`, `MonitorList`, and `/tasks` for detail.
+
+- A single workflow shows its derived activity duration, current state and state age, and total wall-clock age. Paused workflows remain visible.
+- Ordinary active-loop `age` is wall-clock time since creation. Paused ordinary loops omit age and show available pause provenance.
+
+Workflow tool cards, `LoopList`, and `TaskList` stay at two lines while collapsed: the summary, then one dense preview such as `✓plan ▸ [implement] ▸ review ▸ done │ CLAIMED 4m │ try 1/3 │ » pass|retry`. The preview shows:
+
+- the state trail (visited states marked, the current state bracketed);
+- derived activity, using the same status word as the summary;
+- the attempt;
+- the available outcomes.
+
+Idle work without a live lease is flagged `(unclaimed)`. Several workflows or tasks share a one-line roster. The preview is display metadata only and never changes model-facing tool text.
+
+Colors come from the active pi theme, so custom themes apply. The default glyphs are box-drawing, basic shapes, and Latin-1 characters that effectively every monospace font draws. A terminal cannot report its font and a missing icon renders blank, so Nerd Font icons are opt-in (`PI_LOOP_GLYPHS=nerd` or `NERD_FONT=1`). They are accents only: brackets and separators stay portable.
+
+A non-UTF-8 locale or `TERM=linux|dumb` selects ASCII. `/loop glyphs [nerd|unicode|ascii]` switches the set and prints a sample. It applies to cards created afterwards.
+
+On terminals at least 110 columns wide, a narrow progress panel docks at the top-right while a workflow, orchestration, running monitor, or native task is in progress. It never takes keyboard focus and disappears when nothing is in progress.
+
+Each workflow is a vertical state trail followed by its available outcomes. Workflows that are paused or unclaimed are listed first. The trail marks each state:
+
+- `✓` visited;
+- `▶` current, with derived activity and attempt;
+- `○` not yet entered.
+
+A swarm started from a workflow phase is listed under that phase's row instead of on its own. A finished phase shows its latest swarm's `done/total`, and a `∑` line under the workflow title totals agents and reported tokens across its swarms. A swarm whose workflow is gone, or whose phase row is not on screen, is listed on its own.
+
+Each orchestration (at most two) is a header with its progress and in-flight count, followed by up to five work items named by `label` or prompt:
+
+- `●` in flight, with its last reported dispatch state, elapsed time and attempt;
+- `✗` failed;
+- `?` uncertain;
+- `○` pending;
+- `✓` complete, with duration and token count when the provider reported them;
+- `–` cancelled.
+
+In-flight items are listed first and finished ones last, and a final `… N more` line counts the items not shown. The reported state is the last one received, not proof a worker is running.
+
+Running monitors (at most three, oldest first) show id, elapsed time, description or command, and their last output line, with a `quiet` flag after five minutes without output. Monitor state is process-local, so nothing is shown for monitors from a previous pi process. Monitor output is untrusted and stripped of control bytes before display.
+
+Native tasks show `done/total`, in-progress work first, and flag a claim whose lease has expired.
+
+The panel is presentation only: it reads the same LoopStore and TaskStore snapshots as the status line and never claims work, resumes a controller, or schedules a wake. Task rows come only from standalone tasks, monitor rows only from this process's MonitorManager, and workflow rows only from LoopStore. Durations refresh on state changes and the existing 30-second heartbeat, and every minute while a monitor runs.
+
+Because the panel overlays the transcript's right edge, hide it with `/loop panel off` (or `/loop panel` to toggle), or start pi with `PI_LOOP_PANEL=off`.
-Workflow tool cards, `LoopList`, and `TaskList` stay at two lines while collapsed: the summary, then one dense preview such as `✓plan ▸ [implement] ▸ review ▸ done │ CLAIMED 4m │ try 1/3 │ » pass|retry`. It shows the state trail (visited states marked, the current state bracketed), derived activity using the same status word as the summary, attempt, and available outcomes; idle work without a live lease is flagged `(unclaimed)`. Several workflows or tasks share a one-line roster. The preview is display metadata only and never changes model-facing tool text. Colors come from the active pi theme, so custom themes apply. The default glyphs are box-drawing, basic shapes, and Latin-1 characters that effectively every monospace font draws. A terminal cannot report its font and a missing icon renders blank, so Nerd Font icons are opt-in (`PI_LOOP_GLYPHS=nerd` or `NERD_FONT=1`) and are accents only: brackets and separators stay portable. A non-UTF-8 locale or `TERM=linux|dumb` selects ASCII. `/loop glyphs [nerd|unicode|ascii]` switches the set and prints a sample; it applies to cards created afterwards.
+The runtime allows at most 25 loops and 25 running monitors. Completed and cancelled orchestrations kept for inspection do not count toward the 25. Up to 100 of them are retained, after which a new orchestration is refused until some are deleted with `LoopDelete`.
-On terminals at least 110 columns wide, a narrow progress panel docks at the top-right while a workflow, orchestration, running monitor, or native task is in progress. It never takes keyboard focus and disappears when nothing is in progress. Each workflow is a vertical state trail (`✓` visited, `▶` current with derived activity and attempt, `○` not yet entered) followed by its available outcomes; workflows that are paused or unclaimed are listed first. A swarm started from a workflow phase is listed under that phase's row instead of on its own; a finished phase shows its latest swarm's `done/total`, and a `∑` line under the workflow title totals agents and reported tokens across its swarms. A swarm whose workflow is gone, or whose phase row is not on screen, is listed on its own. Each orchestration (at most two) is a header with its progress and in-flight count, followed by up to five work items named by `label` or prompt: `●` in flight with its last reported dispatch state, elapsed time and attempt; `✗` failed; `?` uncertain; `○` pending; `✓` complete with duration and token count when the provider reported them; `–` cancelled. In-flight items are listed first and finished ones last, and a final `… N more` line counts the items not shown. The reported state is the last one received, not proof a worker is running. Running monitors (at most three, oldest first) show id, elapsed time, description or command, and their last output line, with a `quiet` flag after five minutes without output; monitor state is process-local, so nothing is shown for monitors from a previous pi process. Native tasks show `done/total`, in-progress work first, and flag a claim whose lease has expired. The panel is presentation only: it reads the same LoopStore and TaskStore snapshots as the status line and never claims work, resumes a controller, or schedules a wake. Task rows come only from standalone tasks, monitor rows only from this process's MonitorManager, and workflow rows only from LoopStore. Monitor output is untrusted and stripped of control bytes before display. Durations refresh on state changes and the existing 30-second heartbeat, and every minute while a monitor runs. Because it overlays the transcript's right edge, hide it with `/loop panel off` (or `/loop panel` to toggle), or start pi with `PI_LOOP_PANEL=off`.
+Each orchestration batch allows up to:
-The runtime allows at most 25 loops and 25 running monitors. Completed and cancelled orchestrations kept for inspection do not count toward the 25; up to 100 of them are retained, after which a new orchestration is refused until some are deleted with `LoopDelete`. Each orchestration batch allows up to 32 work items, 8 local workers under fixed pacing (under `aimd`, the batch size when every item declares `verify`, otherwise 8), and 3 attempts per item, plus up to 3 overload re-sends per item that do not count as attempts.
+- 32 work items;
+- 8 local workers under fixed pacing (under `aimd`, the batch size when every item declares `verify`, otherwise 8);
+- 3 attempts per item, plus up to 3 overload re-sends per item that do not count as attempts.