# Delegation contract (minimum stable Pi 1.5.2)

Reference for operators and extension/UI consumers. Authoritative types and execution registry: [`src/coordinator.ts`](../src/coordinator.ts); profiles/grants: [`src/profiles.ts`](../src/profiles.ts); finite policy: [`src/scheduling.ts`](../src/scheduling.ts); public model/auth adapter: [`src/model-adapter.ts`](../src/model-adapter.ts); model tool/lifecycle: [`src/pi-extended-subagents.ts`](../src/pi-extended-subagents.ts). The native interfaces remain supported alongside the bounded orchestration compatibility surface below; this is not full OMP/pi-subagents API parity.

## Supported host

Delegated execution requires **stable Pi 1.5.2 or newer**, checked through the SDK's public
`VERSION` export. Newer stable patch, minor and major versions are allowed; standard build
metadata has equal precedence. **Tested host: Pi 1.5.2**, independently of the minimum;
allowing future stable versions is not a tested compatibility guarantee.
Below-minimum, prerelease, malformed and unknown versions fail closed before launch/preflight
content reads, child identity allocation, task-directory setup or child model requests.
This covers `delegate_task`, compatibility `subagent` launches, resume, followup, revive,
steering/model-delivering messages and direct coordinator execution. Public tool arguments
and results are unchanged; unsupported execution errors name the detected version and minimum stable version.

Registration is not rejected wholesale: root status, stop, cleanup and diagnostics remain
available where the host can load the extension. This does not promise module-load
compatibility with arbitrary ancient SDKs. Required `"*"` host peer ranges follow Pi's
packaging contract, not the execution support window; development SDK packages remain pinned.
This restriction is a breaking change in 0.2.0. To migrate from 0.1.x, let active tasks drain,
install stable Pi 1.5.2 or newer, update the extension to `@howarewoo/pi-subagents@0.2.0`
and restart Pi.

## Native orchestration compatibility

The model-only `subagent` tool is registered and described through Pi's public `promptSnippet`/`promptGuidelines` at startup. These describe native worker delegation to the model without requiring any external workflow package or provider-specific user reminder. With an explicit tool allowlist, include `subagent`. Load only one provider of that name: Pi uses the first registered extension, and this package does not disable, reprioritize or uninstall other providers.

- Launch: `{agent,task,cwd?,model?,limits?,async?}`. `agent` is required: `general`, `scout`, `review`, `implementation`, a configured custom profile name, or explicit compatibility name `worker` for the configured `implementation` profile. Unknown names reject, not silently mapped. Authority and prompts still resolve through the existing profiles; no ambient Markdown agent loading or implicit role/model fallback is added. Explicit operator profile chains apply independently.
- Batch: `{tasks:[{agent,task,cwd?,model?,limits?}],cwd?,async?}`. Shared cwd is the default for items lacking one. Existing whole-batch preflight, FIFO limits, ordered outcomes and caller-coordinated shared writes apply.
- `async` defaults true; false waits for final results. Accepted calls return immediately with exact `id:"UUID@generation"`, `taskId` (original UUID), generation and normal snapshot fields/artifact references. Control handles never prefix-match or resolve to the latest generation. Native `delegate_task` retains its UUID+generation output and foreground default.
- Read/control: `{action:"agents"}` or `"list"`; `{action:"status"|"stop",id}`; `{action:"steer"|"resume",id,message}`. Status can inspect a historical generation; mutations refuse stale handles. Resume continues a drained paused or successfully completed (idle/parked) assignment in the same conversation and generation, without increasing session count. Completed runtime graphs are reconstructed from the retained canonical SessionManager, preserving system context and actual tool history in the same transcript; no previous-result-summary or fresh-context fallback is allowed. Stopped, cancelled, retired or unavailable conversations, and failed conversations without a fallback reset, reject without starting new work. Use explicit `delegate_coordinate` followup/revive for fresh work. Native coordination remains available for richer inbox/wait/park behavior.
- Model overrides accept the native exact selection object or `provider/id[:effort]`. Omitted effort uses the parent's selected effort; overrides still require exact operator grants, availability/auth/scope and supported effort. Bare model IDs and unknown providers are not guessed. Omitting model retains ordinary parent/profile routing.

All successful root async paths wake the owning parent: `delegate_task(background:true)`,
`subagent` async launch/batch, direct `delegate_coordinate resume/followup/revive`, and
`subagent resume`. Each launch call sends exactly one ordered single/batch window-outcome
custom message after **all actual drain**; each resume or renewal sends one for its new
execution window. Followup/revive report the returned new generation, not its predecessor.
Delivery uses public `sendMessage(...,{triggerTurn:true,deliverAs:"followUp"})`: an idle
parent starts a model turn; a busy parent queues the outcome as a follow-up. This is
automatic, not a model-selected wake option, and may add parent model turns and provider
charges. Foreground calls return results without an extra notice; rejected operations and
status/inbox/wait/steer calls register none. Paused, failed and cancelled drained outcomes
also notify while the owning runtime remains live. Pause is not success or authority to
resume. A wake requests a turn, not guaranteed task continuation, acknowledgment, automatic
resume, retry or replacement work. No polling, forced continuation loop or detached worker
survives parent shutdown; closing/replaced-runtime callbacks are suppressed.

**Breaking behavior in 0.4.0:** native background and direct resume notices now request a
turn, and followup/revive now notify and request a turn. Drain active tasks, install
`@howarewoo/pi-subagents@0.4.0`, then restart Pi. No configuration migration or grant/host
change is required. Existing installed runtimes are not changed by updating a checkout.

The coordinator owns workspace allocation, shared-write coordination, Git/PR publication and retirement under the active workflow. Supply a complete task and accessible skill/reference paths: general inherits available skills and restricted reviewed leaf capabilities as specified below; workers never inherit parent instructions/history or context files. No scripts/workflow engine, supervisor RPC, automatic worktree lifecycle, external CLI worker, retained-run migration or blanket competitor API parity is promised.

## Explicit working directory

Native task items and compatibility calls accept optional `cwd`, an existing directory relative to the root parent cwd or absolute. Admission canonicalizes it before allocating any identity or session. Missing/non-directory paths reject the whole batch. Nested tasks default to their immediate parent's workspace; renewal retains the exact original workspace and cannot switch it. Snapshots expose `cwd`, and the child SDK/session prompt and tools use that directory. No process-global cwd is changed.

The public root dispatcher has no per-call cwd override. For a different workspace, [`workspaceArguments`](../src/workspace.ts) resolves builtin file paths against the child directory (including absent search/list paths), and prefixes bash with a quoted `cd -- <cwd> || exit $?` before the original command. A failed cd never executes the command in the root. Root validation, callable builtin provenance checks, permission/result hooks, cancellation and nested-call IDs remain active. Hooks see the actual absolute paths or prefixed command, and their context cwd remains the root parent's. A path approval based on the old relative spelling is not equivalent and may reject; the extension never bypasses that decision.

The adapter rejects `~`/`@` shorthand and nonbreaking-space path spellings when rebinding, rather than silently reproducing private builtin path normalization. Ordinary absolute paths and `..` retain normal filesystem meaning through the parent hooks; there is no path containment or malicious symlink-race protection. This is execution in an explicit workspace, not an OS sandbox, copied filesystem, managed worktree or apply/conflict protocol. Writers and parent tools may run concurrently, including across supplied workspaces; all shared writes are caller-coordinated.

Model/auth, role/skill grants, scheduling and trusted-project policy still resolve in the original parent context. Selecting another cwd does not transfer project trust, load its `.pi/delegation.json`, activate tools or grant resources. Task files are checked relative to the selected workspace, but their content still comes only through the root read dispatcher.

## Input and atomic preflight

`delegate_task` is **model-only**, both on the root and on spawn-enabled children. Native input accepts either:

```json
{ "assignment": "Locate startup code", "profile": "scout", "background": false }
```

or an ordered batch:

```json
{
  "tasks": [
    { "assignment": "Locate startup code", "profile": "scout" },
    { "assignment": "Review lifecycle tests", "profile": "review", "limits": { "requests": 20 } }
  ],
  "background": true
}
```

Exactly one shape is allowed; additional properties are rejected. Assignments must contain non-whitespace text. Each assignment accepts optional exact `model` selection, optional boolean `fallback` task opt-in/disable and `models` allowlist narrowing ([advanced policy contract](advanced-policies.md)), plus `spawn` (role allowlist, including `[]` to disable), `coordination` (selected actions, including `[]` to disable) and `limits` (`deadlineMs`, `requests`, `tools`, `depth`, `spawns`), each of which can only **narrow** the effective grants/limits. `background` belongs to the call, not individual batch items. Nested background calls are explicitly unsupported; use nested foreground.

Every profile/skill/tool/ancestor/limit/batch/queue check for the **whole batch** completes before any new registry identity, setup directory or SDK child is created. Invalid later entries cannot leave earlier launches. Inputs capture the parent physical model/effort by default, an explicitly granted exact selection, or the profile chain's independent physical primary; scope and auth registry remain parent-owned; optional cwd follows the explicit-workspace contract above. All active source/target model scope, grant and effort checks precede admission. Fallback targets with missing catalog entries/configured authentication are skipped, never treated as new grants; an unauthorized target hard-stops the batch. Authentication/provider setup failures after admission are per-assignment failures, not rollback of other accepted work. No launch from incomplete/streamed JSON or speculation exists. Checked file text is resolved before admission (below).

## Checked task-file input

Each item must supply **exactly one** of `assignment` or `taskFile`. The same alternative works for single, batch and authorized nested foreground tasks:

```json
{
  "taskFile": "tasks/review.txt",
  "profile": "review",
  "resultSchema": {
    "type": "object",
    "properties": { "summary": { "type": "string" } },
    "required": ["summary"],
    "additionalProperties": false
  }
}
```

`taskFile` is an explicit path relative to the selected **task workspace cwd** (root parent cwd by default), not the session/transcript directory. Absolute paths, traversal, hidden path components and `node_modules` components are rejected. The denied-component rule applies to both caller spelling and the resolved workspace-relative target before any content dispatch; an ordinary-looking symlink cannot alias hidden or `node_modules` resources. Canonical paths must stay inside that workspace; escaping symlinks fail. Nonescaping aliases to otherwise allowed ordinary files remain supported. Metadata checks require a regular file with 1–50000 bytes. The effective parent must expose genuine callable builtin `read`; the extension obtains **all content through `ctx.executeTool("read",...)`**, preserving validation, permission denials and result hooks. Node is used only for path/metadata checks. No raw filesystem content read, ambient discovery or credential/ignored-tree copying occurs. Operators should explicitly select reviewed task-text files, never secrets.

Only complete single-block text is accepted: native read truncation (including the 2000-line limit), images, empty/whitespace text, NUL, replacement characters and oversized content fail. Consequently valid UTF-8 containing a literal replacement character is conservatively rejected too. Files are instructions as literal **task text**; embedded JSON/frontmatter/tool names never grant profiles, tools, spawn roles, schemas or limits. Nested file reads require both the admitted and currently resolved read grants of the initiator and every ancestor, independently of spawn authorization, and consume the initiator's executable-tool budget in addition to the local delegation invocation. Rejected preflight may have performed permission-checked reads, but creates **no new identities/children** and consumes no spawn quota.

Preflight reads are awaited sequentially so a later failure cannot detach an earlier permission hook. Canonical path and identity/size/mtime/ctime are checked before/after reading. The accepted text is an in-memory admission snapshot: subsequent edits do not update queued tasks. These checks detect ordinary changes, not malicious filesystem races; public read has no atomic no-follow handle/content-identity interface. Trusted operator hooks may transform the read/result. This is not a sandbox or a freshness guarantee against concurrent hostile processes. Do not edit/swap task inputs during preflight.

## Required structured results

`resultSchema` is optional **per assignment**, never authority. Schema-free tasks retain ordinary final text/status/error behavior; no prose is parsed into a purported validated value. When supplied, the child receives the model-only native `submit_result` tool with input `{"value": <actual JSON value>}`. It is child-local, not registered on the parent or callable through the root dispatcher. The tool uses public `@earendil-works/pi-schema` **strict, non-coercing** validation of the value (`"42"` is not an integer). Native tool input validates only the envelope and cannot coerce the inner value towards the requested schema.

Supported finite JSON Schema subset (2020-12 semantics): boolean schemas; `type` with one of `object|array|string|number|integer|boolean|null`; `properties`, `required` (distinct strings), `items`, `additionalProperties` (boolean/schema), `const`, nonempty `enum`, `title`, `description`; finite numeric `minimum`, `maximum`, `exclusiveMinimum`, `exclusiveMaximum`, positive `multipleOf`; nonnegative integer `minLength`, `maxLength`, `minItems`, `maxItems`, `minProperties`, `maxProperties`. Schemas are limited to 16384 serialized characters, 256 schema nodes and depth 16. Unknown keywords, malformed keyword values, references of **any** kind, regexes/patterns, formats, compositions, dynamic/executable schemas and non-JSON type extensions fail before any batch identity/setup. No network reference resolution or arbitrary code evaluation is used. The subset guard only checks supported schema shape; native Pi validation owns value semantics.

Invalid submission returns actionable JSON-Pointer errors (up to 32) and permits correction inside existing request/tool/deadline limits. It does not force retries or give extra budget. The first valid submission is immutable; duplicate submissions are errors and cannot replace it. Submission itself is counted like other executable child tools. The model normally continues to a final assistant response; this tool does not terminate the run or bypass remaining work.

`ChildSnapshot.outcome? = {validation:"awaiting"|"invalid"|"submitted",attempts,errors,value?,finalized}` separates submission from ordinary `result`, `status` and `error`. Attempts count native value-validation attempts, not malformed envelopes or rejected duplicates. `submitted` means the value passed validation, **not task success**. Until prompt/tools/descendants drain, `finalized:false` and no final artifact reference exists. After disposal `finalized:true` means the protocol is closed, including missing/invalid/cancelled/setup-failed cases. A successful schema-required task requires terminal `status:"settled"`, `disposed:true`, `outcome.validation:"submitted"`, and successful artifact persistence. A missing/invalid submission at normal prompt completion fails with a missing-required-result error. Provider failures, cancellation, limits and shutdown take priority over submission; retained submitted data on a failed/cancelled snapshot is evidence, never successful output. A captured child closure checks its current registry entry/lifetime before acceptance; no UUID/generation-targetable submission API exists. Each renewed generation starts with fresh submission state.

## Full output artifacts and previews

New task and successor-generation directories are created exclusively with POSIX mode `0700`, as are their extension-owned `agent/` and `transcripts/` directories. The SDK manages transcript files inside that private directory. Existing records/files, parent session directories and global storage permissions are not changed; Windows privacy depends on filesystem ACLs rather than these POSIX mode bits (see [security policy](../SECURITY.md)). After prompt resolution and descendant/tool drain, the registry enters `draining` while it publishes fixed-name artifacts alongside `agent/` and `transcripts/`:

- `result.txt`: exact concatenation (no added separators or trimming) of text blocks in the **last assistant message**, including an empty result for a tool-only/aborted last message. It is not the entire conversation. Existing `result` still uses Pi's final-assistant-text helper and retains its historical whitespace trimming/fallback semantics.
- `structured.json`: JSON serialization of the first accepted structured value, if any; it is not reconstructed from prose or a schema. Read it as JSON to recover the exact submitted value, not original wire formatting.

`artifacts? = {text?:absolutePath,structured?:absolutePath,error?:string}` references only fully written files. Temporary files use exclusive creation and mode 0600; hard-link publication is atomic and refuses existing destinations, then removes its temporary name. Fixed filenames are runtime-checked, never model-selected. No overwrite, old-record reuse, migration, generalized backend, logging/upload or provider/credential-object dump is added. Persistence errors are explicit, cannot yield successful full-artifact claims and fail an otherwise successful task; earlier provider/limit reasons remain primary. A successfully written text artifact can remain available if structured persistence fails. Setup/queued cancellation has no final artifacts; failed/cancelled prompt completion may retain output as evidence. Availability is indicated by references, not inferred from path existence or `submitted` state. Atomic publication is not an fsync/crash-durability promise; shared-checkout tools/external processes can still tamper with files outside this protocol's guarantees.

Model-facing previews clip large text fields and structured JSON to 2048 characters with explicit truncation labels, then apply native 50KB/2000-line truncation. An ordered references header precedes output bodies so controls/artifact/transcript locations are discoverable even when prose is long. Extreme batches/path lengths can still require the `subagent` status action or Hub Details for one identity; tool `details` retain full detached snapshots, values, final text and each batch identity. Background still sends only one final completion message per call. These files can contain sensitive task/model/tool output and need the same handling as SDK transcripts.

## Subagent Profiles and explicit spawn grants

`Profile = {name,description,prompt,tools,skills,leafTools?,spawn?,coordination?}`; omitted spawn is empty. `BuiltinTool` is `read|grep|find|ls|write|edit|bash`. Bundled `scout` and `review` have ceilings of the first four; `general` and `implementation` have ceilings of all seven. These are maximum allowlists, not required tool loadouts. Central admission intersects each role's effective operator/project/request ceiling with **live `ExtensionToolContext.tools`**, then checks genuine builtin provenance before ancestry and renewal checks. Registered-but-inactive direct builtins are not callable rights and are never auto-activated. Under Pi's ordinary default `read,bash,edit,write` loadout, scouts receive only `read`; general and implementation receive `read,write,edit,bash` (role order). `ChildSnapshot.tools` records the admitted effective **builtin** set; owned schema submission, explicit coordination and nested delegation capabilities remain separately granted as before. An empty effective builtin set rejects the entire batch before identity/setup, even when owned tools exist. All four bundled profiles default to **`scout` and `review` spawn targets only**, bounded by total absolute depth two (root 0, child 1, grandchild 2). These grants do not bypass callable-builtin intersection, permission hooks, ancestor subset checks, spawn budgets or immediate nested-capacity admission.

`resolveProfile(name,cwd,trusted,operatorDir?,availableSkills?)` resolves bundled → operator → trusted project. Operator config is public `getAgentDir()/delegation.json`; trusted project config is `CONFIG_DIR_NAME/delegation.json`. Root keys retain the four flat bundled profile overrides and optional `scheduling`; additive `customProfiles` and global-only `projectRoleCeilings` / `projectSpawnTargets` are described below. Profile fields include `description`, `prompt`, `tools`, `skills`, `leafTools`, `spawn`, `coordination`, `models`, `model`, `prewalk`, `fallback`. Absent arrays inherit; explicit `[]` removes grants. Operator tools can only narrow bundled tools. Operator skills grant exact absolute readable, distinct Pi skill Markdown files. Only the operator can add spawn role grants beyond the bundled `scout`/`review` defaults. For example, this intentionally lower-concurrency configuration adds general-to-general nesting:

```json
{
  "scheduling": { "concurrency": 2, "depth": 2, "spawns": 4 },
  "general": { "tools": ["read", "grep", "find", "ls"], "spawn": ["general"] }
}
```

This read-only narrowing permits a general child to delegate a general grandchild if one additional slot is available. It does not enable arbitrary tools, profiles, models or ambient resources. A trusted project may only narrow operator tools, leaf tools, skills, spawn roles and policy maximums; it cannot re-enable anything removed. Untrusted project config is ignored. Project prompt/description specialization never expands executable authority. Unknown fields, malformed profiles (including invalid siblings in the resolved catalog), missing skills and loader diagnostics fail visibly. Configured custom roles use the same runtime/ancestor/admitted-grant checks. General supports only the restricted leaf grants below. Exact model/effort and builtin one-way prewalk policy are specified in the [advanced policy ledger](advanced-policies.md).

Descendant preflight requires an active, non-cancelling ancestor, an explicitly granted target role, allowed absolute depth and remaining direct-child spawn count. Target builtin tools, reviewed leaf tools, skills **and spawn role grants** must all be subsets of the delegating ancestor's effective grants; incompatible profiles reject rather than regain root authority. Request narrowing is inherited. Before nested task-file content dispatch and again before child admission, current operator/trusted-project spawn grants and capability ceilings are checked for the initiator and every ancestor, in addition to their original admitted ceilings. Revoked read or spawn authority denies before the task-file content reaches the root read dispatcher; malformed policy fails closed. Each child's admitted direct-child count is lifetime cumulative (including cancelled/failed children); rejected batches consume no spawn count.

### Custom definitions and project-role ceilings

Flat bundled-role overrides are unchanged. `customProfiles` maps bounded names to independent definitions. Names match `^[a-z][a-z0-9-]{0,63}$` and cannot shadow bundled names, `worker`, configuration metadata or prototype-sensitive names (`constructor`, `prototype`, `__proto__`). Unknown roles and invalid later batch entries reject before any launch. Both delegation tools and native `agents` discovery read current effective configuration without extension reload; listing a role grants no permission to spawn it.

Example operator `delegation.json` (no skill files or provider requests needed):

```json
{
  "customProfiles": {
    "docs-audit": {
      "description": "Audit documentation against source",
      "prompt": "Inspect the supplied documentation and report concrete discrepancies.",
      "tools": ["read"],
      "skills": [],
      "spawn": [],
      "coordination": []
    }
  },
  "projectRoleCeilings": ["scout"],
  "projectSpawnTargets": { "release-audit": "scout" },
  "general": { "spawn": ["scout", "review", "docs-audit", "release-audit"] }
}
```

The last line is an **explicit** operator spawn grant, not an effect of creating or registering a name. `docs-audit` is global; `release-audit` is a conditional registered local target, not a global profile. Custom definitions require explicit `description`, `prompt`, `tools`, `skills`, `spawn`, `coordination`, including empty arrays. Global custom tools may select supported builtins; bundled overrides still cannot exceed their bundled ceilings. Optional exact model fields follow the existing [model/prewalk/fallback rules](advanced-policies.md). A copied profile is expanded once. Custom roles never gain general-only automatic skills, reviewed leaf forwarding, parent instructions/history, executable/MCP resources or implicit spawn grants by resembling `general`.

Example trusted-project `CONFIG_DIR_NAME/delegation.json`, paired with that operator example:

```json
{
  "customProfiles": {
    "docs-audit": { "prompt": "Audit this project's documentation only." },
    "release-audit": {
      "ceiling": "scout",
      "description": "Project release evidence audit",
      "prompt": "Independently inspect the supplied release evidence and report gaps.",
      "tools": ["read"],
      "skills": [],
      "spawn": [],
      "coordination": []
    }
  }
}
```

`docs-audit` is a project override of a global custom: **no `ceiling` marker**. `release-audit` is project-local and requires a current operator-allowlisted global ceiling. Absent/empty `projectRoleCeilings` disables local creation. Projects cannot set that authorization list. Allowlist members are bundled/global custom roles, never local names; there is no content-inheritance graph. A later global/local collision carrying a local marker rejects rather than silently converting the definition.

Local explicit grants must satisfy both the current global ceiling and its current project narrowing. Instructions remain independent. Local omission of `models` does not bypass an explicit ceiling allowlist: inherited physical-parent selection is bounded too, without minting an explicit override grant. An incompatible tightened/removed ceiling fails closed; nothing is silently pruned. Fallback targets must be an allowed ordered subsequence and prewalk must satisfy existing target restrictions. Untrusted project config is ignored entirely at admission and is not used as authority by the editor.

`projectSpawnTargets` is a **global-only** map of exact project-local target names to their required already-allowlisted global ceilings. Absent/`{}` disables this additional authorization. Registered names must pass the same custom-name checks and cannot collide with any bundled/global role, alias or metadata/prototype-sensitive key. Projects cannot supply or expand the registry. A present trusted local definition must use the exact registered ceiling and satisfy global plus current project-narrowed authority; name/ceiling substitution rejects.

**Scope: all trusted projects using this operator policy.** Different trusted projects can provide their own independent instructions for that exact name under the bound ceiling. There is no workspace/path binding, wildcard, implicit ceiling-to-local mapping or new task API. A separate explicit parent `spawn` entry remains mandatory. Registration does not create a profile, local definition, incoming grant for every parent, or discovery placeholder. Registrations may name targets absent from the current workspace: discovery lists actual effective roles only; missing/untrusted targets reject at actual launch, including whole-batch preflight before insertion. Root local launches remain independent of incoming registration.

Resolver-only `projectCeiling`, `projectSpawnAuthorized` and `inheritedModelCeiling` snapshot metadata are not accepted profile configuration keys; one-time copies strip them and retain the explicitly chosen local `ceiling` reference.

Incoming registration, current parent spawn edges, local ceiling identity and all existing ancestor/admitted capability/model/budget checks continue to apply during nesting, execution and retained renewal/resume. A later registry/spawn addition never expands an already admitted parent's grant. Binding substitution requires stopping the old identity and launching a newly authorized one rather than silently changing its authority or retained prompt.

| Field                                      | Selected-layer reset versus explicit value                                                                                                                                                            |
| ------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `description`, `prompt`                    | Bundled/global-custom project overrides may unset to inherit; empty text is explicit. Independent definitions require text fields and do not inherit ceiling content.                                 |
| `tools`, `skills`, `spawn`, `coordination` | Overrides may unset to inherit. `[]` explicitly removes grants. Independent definitions require these arrays. Skills are exact absolute readable, distinct Pi skill files, not discovery directories. |
| `leafTools`                                | General only; explicit reviewed names, `[]` removes them. Custom copies strip leaf forwarding.                                                                                                        |
| `models`                                   | Unset permits inherited physical selection, not arbitrary explicit overrides. `[]` denies all selections. A local inherited-model ceiling remains enforced independently.                             |
| `model`, `prewalk`                         | Exact provider/id/effort rows require model grants. Reset deletes the selected layer key; a project can re-inherit global policy, not turn it off. No `null`/`false` off sentinel is accepted.        |
| `fallback`                                 | Unset inherits in an override; `false` explicitly disables; otherwise a finite nonempty ordered exact chain. It cannot coexist with prewalk.                                                          |
| `ceiling`                                  | Required authority reference on project-local definitions only, not a content/copy reference or global-custom override marker.                                                                        |

The TUI exposes these fields in a persistent Inspector. Ordinary instructions, permission membership, default/prewalk, exact grants and routing actions commit through one in-memory FIFO per editing destination. Each semantic intent carries its original profile/field and exact target identity; no numeric row identity, coalescing or captured whole-file save is queued. The UI keeps the last verified raw layer/catalog, pending intents and projected values distinct. Single-line Enter/blur commits once, multiline uses native editor submission, and membership/model/move actions commit immediately. Ctrl+Left reaches native Input/Editor word navigation. Multiline Tab suspends a changed native buffer and focuses the profile rail; unchanged buffers create no draft. Suspended drafts retain their original fixed destination, profile and field, not a row index. Named Resume controls and draft markers remain available across profile browsing; reopening a drafted field restores the native buffer/caret rather than the projected preview. Escape while editing explicitly cancels only that active buffer, never other drafts or earlier accepted saves. These unsubmitted drafts are Inspector-local memory, not accepted intents or durable storage.

Membership rows (`[x]` / `[ ]`) accept Space as an alias for configured selection-confirm, with exactly one ordinary autosave intent. The alias is browse-only and does not act on navigation, model grants, reset/revoke or disabled/hidden controls. Printable Space, j/k and `?` remain text in native inputs and catalog search. Contextual hints name opening/editing versus immediate saves, reset/revoke, disabled actions and structural review; native text-submit bindings remain distinct from selection-confirm.

Each head rebuilds against the retained `ProfileConfigDraft` baseline, rechecks newly selected model eligibility against fresh host metadata, and independently verifies its save before the next head starts. Saved unavailable rows are retained and do not block unrelated changes, reorder or removal. Global Add atomically ensures the exact grant and route; grants permit explicit overrides too. Final chain removal saves `fallback:false`, keeps grants, and exposes the Advanced default/parent route with possible admission denial. Effort replacement keeps the old grant. Explicit compound switches resolve prewalk/fallback conflicts; Project cannot mint grants, reorder the operator chain or invent an inherited-prewalk disable sentinel. Standalone grant removal is blocked while chain/default/prewalk depends on it.

Custom create/copy/delete, whole-override reset, local ceilings and global registration/authority remain separate explicit structural transactions. They drain/freeze ordinary autosaves before opening and resynchronize on return; no parallel ordinary save path remains. Registration review names old/new authorization and cross-trusted-project reach, even without a local target or effective permission-array change. Registered spawn names remain conditional and separate parent grants are never silently added. Structural interdependencies may be corrected in their temporary transaction before review/save; ordinary fields retain item autosave, with unsubmitted native text held separately until explicit submission. Close, destination/structural transitions and resetting/replacing a drafted field first identify affected destination/profile/field owners and offer keep (default) versus explicit discard-and-continue; this never submits drafts. Ordinary browsing and unrelated membership changes require no draft disposition.

Every save replaces only the selected file. Scheduling/unrelated values survive (JSON formatting may change); scheduling has no editor. Both relevant baselines (content, existence and file identity/mode metadata) are checked before replacement, and in-process saves serialize. Same-directory exclusive temporary writes plus rename prevent partial JSON reads. Symlink/nonregular targets are refused; regular-file permissions survive and new files use private `0600` mode. After replacement, saved content and combined policy/skills are independently reread/rechecked. Project snapshot phases recheck current trust before initiating inspection/content reads, including after awaited open/stat; a read already initiated while trusted cannot be undone.

Known pre-replacement failure retains the attempted value as Not saved and pauses mutations/tail execution. It suspends any unrelated active text, including unfinished exact-entry input, without clearing its buffer; repeated failure notifications do not duplicate or erase drafts. Recovery focuses Retry or Reload. Drafts stay available through named Resume controls while mutations are frozen, but native submit/blur never enqueues paused text. Retry revalidates that same accepted head; Revert discards it and all later unsaved actions with a count, never prior verified saves. Neither Retry nor Revert submits or discards independent drafts, and successful recovery does not automatically resume them. A later explicit submission rechecks current validation/trust against the original owner.

Conflict, any trust change, or completed/unknown replacement requires explicit Reload. With drafts, Reload identifies affected owners and discloses both queued-unsaved and draft counts; keep/default or Escape does nothing, explicit discard-and-continue abandons them. Reload first abandons the whole accepted unsaved tail, then rereads only currently allowed layers without replay/merge/force-write/rollback. Old-layer drafts are not carried into a new baseline. Unsupported/malformed input requires external repair; failed Reload is closable read-only and does not resurrect a confirmed discard. Errors expose operation/path/replacement and available observed disk facts. After draft disposition, normal close/destination/structural navigation drains and freezes new mutations, then navigates after verification; any failure cancels navigation permanently until a new request. Other profiles remain readable during recovery. Draft/exit controls fit the physical 80×24 baseline (72×21 overlay); below baseline, safe resize-only fallback hints distinguish cancelling active text from keeping suspended drafts. Resize itself never discards or submits.

This is not compare-and-swap against external writers: the final-check/rename race remains. Skill files/task usage may also change after checks. No cross-process lock, watcher, durable journal or power-loss durability promise is added. Force-quit can lose unsaved queued/unfinished input; verified saves remain.

Bundled definitions cannot be deleted. Reset removes an override separately. Custom deletion blocks local spawn references, project overrides, ceiling authorization/references, incoming registrations (as target or ceiling), and nonterminal or reusable coordinator tasks including descendants. The UI can stage **explicitly selected** same-file reference removals with deletion, never cross-file cascades or automatic rewrites. Other-file references require a separate repair; active/reusable tasks require existing stop/drain controls. Superseded generations cannot resume under existing identity checks; immutable nonresumable history does not block once the current identity is retired. For local-definition deletion, first explicitly remove global parent spawn references and the exact registration in a global save; then reopen the project draft and delete the local definition. An older project draft conflicts after that authority change and must be reopened/reviewed. Resetting/removing a registration while conditional parent references remain is an editable invalid draft, not an automatic cascade. The custom-ceiling deletion dialog keeps related conditional spawn references visible even after registration removal, and cancel/undo restores the staged deletion changes. Rebinding an existing local target may require explicit disable (remove incoming refs/registration), separate project ceiling repair, then re-registration and re-grant; no multi-file save is invented. Other workspaces/processes are not scanned and may retain references that fail on later admission.

Saved instructions apply to newly built sessions, not retained prompt replacement. Runtime revalidation and admitted-grant intersections remain authoritative; revocations can deny later operations, and additions do not expand admitted agents. No automatic restart, provider request, skill execution, credential change or tool activation occurs while editing. Old extension versions do not understand the additive custom keys: retain a compatible backup or explicitly remove those entries before rollback; no automatic migration/rollback is performed.

## Capacity and bounded execution

`SchedulingPolicy` values are non-negative safe integers, except concurrency/batch/requests/tools must be positive. `deadlineMs: 0` is the only unlimited sentinel: it disables the deadline. Operators may choose 0 or a positive cap. Trusted projects and task `limits` can set or shorten a positive deadline but cannot use 0 to disable an operator's cap (task `limits.deadlineMs` must be at least 1).

| Field         | Default | Operator ceiling | Meaning                                                                                                                |
| ------------- | ------: | ---------------: | ---------------------------------------------------------------------------------------------------------------------- |
| `concurrency` |      16 |               16 | Active SDK children, including setup, waiting nested parents and draining                                              |
| `queue`       |      32 |              256 | Waiting assignments, accounting for ordinary FIFO capacity                                                             |
| `batch`       |      16 |               64 | Assignments admitted by one call                                                                                       |
| `depth`       |       2 |                4 | Maximum absolute descendant depth (root = 0, child = 1, grandchild = 2); 0/1 disables nesting                          |
| `spawns`      |       8 |               32 | Admitted direct children per child lifetime; 0 disables spawning                                                       |
| `deadlineMs`  |       0 |         86400000 | Per-window elapsed time from admission/resume, including queue/setup/work drain; paused time excluded; 0 = no deadline |
| `requests`    |     200 |             1000 | Direct child dispatches into the parent model registry per execution window                                            |
| `tools`       |     500 |             1000 | Executable child tool invocations per execution window, including local delegation                                     |

Operator `scheduling` can choose within ceilings; trusted project can only narrow operator values. Request `limits` can only narrow execution/depth/spawn values, not raise concurrency or queue capacity. Policy is resolved at invocation; changes affect subsequent admission/dequeue, not already running work or previously captured task limits. Reducing concurrency does not evict already admitted active children; no new setup starts until they drain below the new maximum.

One FIFO scheduler lives **inside the authoritative registry**, not in a second execution-state service. Identity allocation/order follows input order. Queue admission/dequeue is synchronous, before asynchronous SDK setup. Writers and readers share ordinary FIFO capacity; parent mutations neither reserve capacity nor block child admission. Setup, running, nested waiting, pausing and draining each retain a permit until actual drain; only then may pause or disposal release it.

### Nested allocation: no lending and no overcommit

A parent waiting in its child-local `delegate_task` retains its permit. Nested batches are admitted **only if the entire batch can dispatch immediately**, with no older queued assignment and sufficient free slots. Otherwise they fail visibly before descendant setup (`Nested capacity unavailable; no permit lending`). This also prevents nested siblings waiting on a full pool. There is no borrowed capacity, hidden fanout or simulated completion. Writer descendants are allowed under writer ancestors only with valid explicit spawn/tool/model/depth grants and immediate capacity. Child-local model-only tools are registered through public SDK `customTools`; they are not calls to the root's model-only tool via `ctx.executeTool`.

### Limit outcomes and cancellation

Deadlines are off by default; a configured deadline pauses rather than cancels. `queued|setup|running → pausing → paused` stops new dispatch, aborts SDK work and waits for actual subtree drain before releasing capacity. Snapshots expose `pauseReason` (`deadline` or `ancestor deadline`), `retainedContext`, `window`, cumulative request/tool/spawn counters, the current window's `windowStart` baseline, and unfinalized structured submission state. Paused is neither success nor failure; no final outcome artifacts are published. A drained paused snapshot instead carries `partial:true` and, when the retained conversation has assistant text, `partialText`: a bounded (2048-character) preview of its last nonempty assistant text. A queued assignment can pause before any session/transcript exists (no `partialText`).

Root-only `delegate_coordinate` `{action:"resume",target:{id,generation},assignment:"Continue…"}` or `subagent` `{action:"resume",id:"UUID@generation",message:"Continue…"}` appends that message to the retained SDK conversation. UUID, generation, assignment, workspace, selected model/prewalk state, role instructions, all prior SDK messages/tool calls/results remain intact. A paused window retains its provisional structured submission state. Completed windows retain immutable result/outcome/artifact references in `completedWindows`; their existing files are never replaced. A resumed completed structured assignment requires a new submission (the previous validated value is evidence, not the new window's result). Later completed-window artifacts are published exclusively under `window-N/` inside the same task directory. Each explicit resume starts a fresh execution window (still bounded by originally admitted and current limits): a fresh deadline if one is configured, and fresh request/tool budgets equal to the window's limits. Snapshot `telemetry.requests` and `toolCalls` stay cumulative; `windowStart` holds their values when the current window began. Spawn counts are **not** replenished. Each generation permits at most 64 execution windows, bounding completion evidence and notifications. A pre-session queued pause starts the original assignment followed by the continuation when dispatched. After a completed prewalk handoff, resume validates the retained current model and current/admitted lineage grants, not the obsolete admission model; it neither broadens model grants nor rearms prewalk. No automatic replay, undo, process freezing, restart or cross-parent recovery is provided.

An ancestor deadline marks its entire active subtree before draining any member. Resume the exact original parent generation first, then explicitly resume selected children; resuming a parent does not resume descendants. Existing no-permit-lending, ancestry and admission rules still apply. Parent completion retires active/paused children, but preserves successfully completed retained child conversations for later explicit resume once that exact parent generation is running again. Explicit stop/retirement remains effective even across parent resume; failed/cancelled children cannot resume.

Resume rechecks operator/trusted-project limits and grants, ancestor spawn/capability ceilings, model availability/authentication, callable tools/provenance and capacity admission. It never broadens original admission. A revoked retained grant rejects rather than silently changing the admitted SDK tool/resource graph; restore the grant or stop and launch a newly authorized identity. Policy/auth/capacity/restoration failure leaves the paused or completed conversation intact with an actionable tool error; unchained tasks receive no fallback model or replacement agent. Chained tasks retain and revalidate their route and cumulative failure/attempt state; a changed chain requires a root-only `delegate_coordinate` `reset_fallback`. Concurrent duplicate resumes reject atomically. Stop/shutdown wins a concurrent pending resume and disposes retained sessions.

At 80% of either budget, if normal work can still continue, the next model request includes a one-time wrap-up warning for the window. When the child reaches the report reserve, its next model request asks it to report using the evidence it already has. The warning and wrap-up instructions ride on requests the child would already make; they do not start a new turn on their own.

- The reserve is one model request for a prose report, or up to two if a required structured result is still pending. When triggered by the tool budget, wrap-up still allows only that many reporting requests, not the whole unused request balance.
- When the tool budget triggers wrap-up, it normally leaves one tool slot that only `submit_result` can use. A batch of regular tools cannot crowd out a structured report. Report-only mode blocks new work. A one-call prose task can still run its only tool; a one-request prose task cannot set aside a separate reporting request.
- A valid structured submission during wrap-up can finish without another model request. Prose does not satisfy a structured schema. Reports are best-effort: invalid or ignored wrap-up attempts, stop, shutdown, and deadlines can still prevent a result. Each explicit resume starts a new window with its own warning and reserve.
- A window that settles after wrap-up was triggered carries `partial:true`; its `result` and artifacts are the wrap-up report. Explicit resume clears `partial`/`partialText` for the new window.

Requests/tools remain hard caps. An attempted dispatch beyond a hard cap, or continued model requests after the report reserve is spent, uses the existing cancellation path with `status:"cancelled"`, `limitReason` (`requests` or `tools`), and explanatory `error`. Stop before setup cancels without SDK setup/transcript. Request guards check **before forwarding** to the parent's public registry. Counts include failed dispatches but not rejected over-limit dispatches, auth preflight or provider-internal retries/subrequests. Tool guards count entered, granted custom-tool executions, including permission-denied forwarded calls. Calls blocked by the report reserve and malformed/unknown calls rejected by Pi before execution do not count.

Deadlines initiate abort; they do **not** promise a maximum drain time. Public auth/provider/permission code that ignores cancellation must return before setup/tools release their capacity. No fake timeout races away from unabortable initialization, force-kills unrelated processes, or reuses an occupied permit while old tools remain active. SDK-owned tool cancellation uses actual abort signals and public `abort()`/prompt completion. Abrupt process death is not recoverable cleanup.

## Profile-owned fallback routing

See the [operator configuration and recovery reference](advanced-policies.md#profile-owned-fallback-chains).
`models` grants never define order. `fallback` on a profile is a bounded exact ordered chain;
a trusted project may disable it (`false`) or supply an ordered subsequence. Task `fallback`
is boolean: `false` disables, `true` opts an explicit `model` into its chain suffix. Without
an explicit task model, an enabled profile starts at its own first available authorized
target regardless of a physical or virtual parent selection. Task `models` only removes
destinations. Fallback plus prewalk rejects before admission.

Two same-model retries precede advancement on eligible transient/quota/credit failures;
success clears the failure count, not the sticky route. Every dispatched attempt consumes
one cumulative direct request. Authorization is revalidated before attempts/resume;
unavailable entries are skipped, unauthorized entries stop, and exhausted chains never
wrap. Failed streaming drafts remain raw evidence but are omitted from model projection;
completed SDK tools/results are retained without replay. Cancellation/deadlines include
abortable backoff. `fallback.attempts[].usageKnown` flags unmeasured failed usage.

Snapshots add `fallback:{chain,index,failures,exhausted,skipped,attempts}`. `index` is zero-based and equals the chain length when exhausted. `chain` stores exact
target identity rather than silently remapping indices when configuration changes. Recovery
context edits and `subagent-fallback-recovery` custom entries preserve audit evidence.
Root-only `delegate_coordinate` `reset_fallback` requires an idle/paused retained child,
sends no request, and changes no limits/counters/deadline. Child actors are rejected.
After a reset, a failed chained window can explicitly resume with its failed
window preserved in `completedWindows`; ordinary failed/stopped/cancelled identities retain
their existing rejection behavior. Retained route state lasts only until parent shutdown.
New followup/revival generations start a newly validated chain, not an inherited active
backup. There is no cross-package routing/config/state or main-session reset coupling.

## Public model/auth/resource boundary

`parentModelRuntime(context,agentDir,onRequest?)` creates a child runtime with empty `InMemoryCredentialStore`, `modelsPath:null`, scoped cache path and network catalog refresh disabled. Native adapters list only the independently selected physical model and explicitly admitted prewalk/chain targets. Its `stream` and `streamSimple` forward into the **root parent's public ModelRegistry**, preserving configured provider composition, auth, headers, environment and OAuth refresh. Preflight uses public `hasConfiguredAuth` and `getApiKeyAndHeaders`; values are never copied to artifacts. Every descendant uses this same captured public adapter, with its own admitted physical model/effort selection. No implicit model/cost substitution or private imports. Generic `pi-virtual` inheritance fails visibly; a profile chain or explicitly authorized physical profile/task selection does not reconstruct or invoke the parent router.

`childResources(prompt,skills)` owns the complete loader. It supplies only the role prompt and explicit skill metadata, with empty extensions/MCP/context files/prompts/themes. Pi automatic compaction (default thresholds) and same-model native retry (two retries, provider retries zero) are enabled for every child; summary requests and every retry attempt pass the same counted dispatch gate. A summary request that would leave fewer than two requests in the current budget window, or any during wrap-up, is refused so it cannot spend the report reserve; the context then stays uncompacted. The JSONL transcript retains pre-compaction entries. Each child uses the selected workspace cwd, with separate scoped agent/cache/transcript directories; grants and project trust remain parent-owned. This is **not a sandbox** against arbitrary JavaScript, process environment access or hostile code.

Forwarded root builtins must be callable, genuine `builtin:<name>` tools (not overrides). Only the effective subset is checked: an inactive replacement outside that subset is not forwarded, while a callable replacement rejects admission. Each invocation rechecks the invoked tool’s current callability and provenance, so subsequent deactivation/replacement cannot fall through to an old backend or a custom override. Descendant builtin definitions forward only their admitted tool names through the original parent's public `ctx.executeTool`, retaining schema validation, operator permission hooks, activation revocation and nested-call IDs. They do not call raw builtin `execute` implementations. Local `delegate_task` receives normal SDK model-tool validation/exposure and then full policy/ancestor admission checks; no parent model-only exposure is bypassed. General skill and leaf inheritance is restricted as described below.

## Registry, controls and final delivery

`DelegationCoordinator(root,parentId)` owns all generations/entries. Public seams:

- `ChildRef = {id:string,generation:number}`. UUIDs are never reassigned to another agent; generation starts at 1 and increases on admitted reassignment. Mutating controls reject unknown/stale references; historical snapshot reads remain pinned.
- `ChildSnapshot`: identity, real `parentId`, optional `parentGeneration` for descendants, absolute `depth`, `status`, profile, canonical workspace `cwd`, assignment, activity, bounded progress (4096 characters), final text, actual model/effort, optional `prewalk:{target,status}` (`armed`, `handed-off`, `suppressed-exact` or `no-op`), direct `telemetry`, optional error/transcript, `limits`, `limitReason?`, `toolCalls`, `writerLease`, and `disposed`. Optional `partial`/`partialText` mark a paused or wrap-up-reported window (see [limit outcomes](#limit-outcomes-and-cancellation)); ordinary completed windows omit them. Background notices and task cards show the marker and a sanitized, width-bounded preview.
- Lifecycle: `queued → setup → running → settled|failed|cancelled`, plus `pausing → paused → queued` for explicit deadline continuation; cancellation of active work exposes `draining` until it actually ends. Queued work can cancel directly. `disposed` is a resource fact, not a guessed outcome. `writerLease` is deprecated and always false in new snapshots; it is not write capability. Historical snapshots may retain historical values. Parents cannot finalize/dispose before descendants/tools drain.
- `RegistryEvent = {type:"changed"|"sdk",child,event?:AgentSessionEvent}`. Detached snapshots; observer exceptions cannot fail execution. `subscribe` returns unsubscribe. `list()` retains identity admission order and returns current generations only; `snapshot(ref?)` reads a pinned current/historical generation or latest identity; `generations(id)` returns detached immutable history plus current generation. `agents()` separately reports current presence. Pi event bus `delegation:registry` exposes the same events, including disposal at shutdown. Consumers unsubscribe on runtime replacement.
- `configure(policy)` validates finite scheduler policy. `admit(StartTask[])` synchronously validates the whole batch and returns ordered identities; `start(StartTask)` is the single helper, awaiting abortable setup if dispatched immediately, otherwise acknowledging queued admission. Model tool uses `admit` for both input shapes. Every `StartTask`, including direct SDK integration, requires `assertTools(names)`, a synchronous provenance validator backed by the originating extension’s public `pi.getAllTools()` metadata. Missing validators reject at runtime. This is a trusted integration seam, not a model/operator policy option or a sandbox for arbitrary extension JavaScript.
- `wait(ref)` resolves the current window snapshot after drained pause or disposal, including setup failure; `stop(ref)` aborts and drains a subtree. `stopMany(refs)` marks the entire cancellation set before any sibling dequeue and then drains it; already settled results are preserved. Repeated stop is harmless. `steer(ref,text)` requires running state and uses Pi `queued|handled` semantics.
- `shutdown()` closes admission/dequeue immediately, cancels/drains/disposes all entries and clears observers idempotently. Bare SDK `session.dispose()` does not replace host lifecycle dispatch. `reopenTranscript(ref)` inspects a new transcript; it does not revive work.

Prompt resolution, not low-level `agent_end`, accepts final results after SDK work settles. SDK assistant errors/setup exceptions are failed; abort/limit/shutdown intent cannot become success. Failure of one admitted assignment **does not cancel unrelated batch siblings**: every input receives its own outcome. Caller foreground cancellation marks all unsettled assignments then drains their subtrees; settled outcomes remain settled. Operator stop targets only its pinned subtree.

Foreground returns one ordered window-outcome batch after window drain (single input returns one snapshot), whether paused (`disposed:false`) or completed after disposal. Partial tool updates are observations, not window-outcome deliveries. Background returns ordered accepted snapshots/identities immediately (possibly queued/setup), and emits **one window-outcome custom message per call**, containing all ordered outcomes after window drain (paused or completed). Both native and compatibility delivery wake the parent with `triggerTurn:true,deliverAs:"followUp"`. It does not also deliver per-item completion messages. Background no longer follows the initiating tool's signal after acceptance; stop/shutdown still own it. Old-runtime shutdown suppresses its final custom delivery; work never survives reload. Output previews use Pi 50KB/2000-line truncation. Tool `details` retain full snapshots/transcript references (`ChildSnapshot` for single, `{children:ChildSnapshot[]}` for batch); full model/tool evidence is in actual SDK JSONL; final text/structured artifacts follow the protocol above.

`/subagent-profiles` resolves current-workspace operator and trusted-project settings through the shared admission profile/skill validator. TUI starts at a read-only compact overview. Tab selects profiles/settings; 1–4 jump to Profile, Model, Access and Advanced. Enter opens a setting’s complete details; `e` explicitly chooses Global or already trusted Project and pins its exact path while profiles remain browsable in the editable rail. The editable overview uses the same labels and grouping. Description/Instructions use native Input/Editor in focused details; Tools, Skills and General’s Reviewed tools open full membership lists. Delegation separates Spawn targets and Coordination. Models lists the chain as rows: the default `provider/id` with its effort right-aligned, then `↳ provider/id:effort` fallbacks, with exact identity and any warning in the help line. Keys act on the selected row: ←/→ previews a supported eligible effort (skipping efforts other chain rows use; only granted ones at 64 grants) that Enter saves as one replace-target, while Escape, moving the selection, switching profile or opening the picker discards it. With nothing previewed, Enter opens the picker to replace that target in place with any accessible selection not already in the chain. Shift+↑/↓ or `[`/`]` move it (the selection follows), `x`/Delete remove it (the last target's row discloses `fallback:false` first), and `f` adds. Project refuses every key except removal with its reason and saves nothing. Add opens the model picker: a title naming the operation with its destination/grant/save disclosures, a provider tab strip (Alt+←/→ or Tab/Shift+Tab), an always-focused native search Input where every printable key (including Space, j/k and `?`) is text, and `provider/id` rows with optional reasoning, context and price columns from the host snapshot (dropped price-first when narrow). Chain additions and replacements list models with an existing exact grant first, above a divider. Enter opens an inline effort strip over all supported efforts; ineligible ones stay inspectable with their exact reason and cannot be chosen. Enter on an eligible effort rechecks a fresh host snapshot before returning the selection; Escape steps back from the strip to the list, then cancels. Ctrl+R rereads only the host snapshot. F1 exposes scrollable exact-ID, full supported-effort, eligibility and matching hidden-model reasons without forcing secondary metadata into the selection viewport; F1/Escape returns to the same picker state, and Enter in details never accepts a hidden selection. Advanced contains default/prewalk, exact model grants, source diagnostics and structural operations. Normal selected-setting help is bounded separately from scrollable disclosures and recovery. Opening/closing details and browsing never enqueue an intent; Escape cancels unfinished input or a previewed effort first, then returns to the preceding setting row before outer close. Ordinary item changes autosave; pending/saving/verified state and exceptional Retry/Revert/Reload recovery are visible. Only structural Advanced transactions retain explicit review/save. Narrow layouts stack; tiny/short layouts request resize and never activate hidden controls. See the [configuration/editor contract](#custom-definitions-and-project-role-ceilings).

Profile/model layouts budget for a physical 80×24 terminal through the 90% overlay (72×21 Inspector, 68×14 nested catalog). At that size secondary diagnostics compact before eligible results disappear; no eligible results still produces an honest empty state. Pane entry follows the selected action label. Activation rechecks current rendered geometry and requires that bounded label, not its full value, warning or trailing spacer, to be visible. Exact grants use bounded numbered removal labels with the selected full provider/ID/effort and warning in scrollable content; dispatch remains bound to the exact target, never the displayed number. Required-by-routing checks are unchanged. Subminimum resize-only output preserves local back/cancel and refuses hidden actions; resizing never enqueues an intent.

General skill resolution uses public command-context base skill metadata, never parent prompt text or context files; per-turn prompt changes can differ at admission. Command context cannot establish callable tools; active declarations are not proof of callability. RPC/JSON/print retain the read-only structured `{toolPolicy, profiles}` message and cannot enter the editor. Invalid config or granted skills fails resolution; task snapshot/details `tools` reports the admitted effective builtin set. Commands are `/subagent-profiles`, `/subagent-stop id generation` and `/subagent-hub`; outside the TUI, `/subagent-hub` prints the registry list as a delegation message. `/subagent-status`, `/subagent-steer` and `/subagent-fallback-reset` were removed without aliases. Hub/widget remain registry consumers, not grant editors; queued/draining states are shown without fabricated completion.

### Direct versus subtree telemetry

`telemetry = {requests:number|null,tokens:SessionStats["tokens"]|null,cost:number|null,context:ContextUsage|null}`. Null means unavailable, not zero; genuine reported zero stays zero. Token/cost/context values are SDK-reported; no precision promise for billing or provider internals. Request counts are direct registry dispatches for that entry. Each descendant has its **own direct telemetry**; ancestors never absorb descendant charges as tool `usage`. Sum direct registry values once across the chosen subtree. Parent tool usage/footer is not an aggregate delegation bill. No subtree total is synthesized.

## Live-parent messaging, waits and presence

`delegate_coordinate` is a native **model-only** tool registered with Pi conflict handling, not a pi-subagents alias. It must be enabled if the host uses an explicit tool allowlist. Root has current-registry controls; children get a child-local closure only when their effective profile grants at least one action. Inputs never accept sender/parent/runtime/generation overrides for the actor. Child invocation still counts against that generation's tool/deadline/request limits.

Operator `coordination` grants selected `message`, `inbox`, `wait` actions; absent/empty is off. Trusted project and task request arrays only narrow operator grants. Descendants cannot regain any ancestor action. Every message, inbox read and wait authorization reloads current initiator/ancestor policy and checks the original admitted action ceilings too. Denial sends no message, consumes no inbox and allocates no waiter. Cancellation, pause, shutdown and stale generations are rechecked after policy-loading awaits before protected effects. Live revocation governs subsequent actions: it does not forcibly cancel already in-flight work, retract accepted messages or roll back completed effects. Addressing is restricted to exact-generation parent, direct children and siblings whose parent UUID+generation match. Identities must be explicitly supplied in task/message context: there is no child registry enumeration, transcript read or arbitrary resource lookup. Only direct children may address root by omitting `target`; root cannot message itself. Root-only `status`, `stop`, `park`, `resume`, `followup`, `revive` are rejected from child closures even if model input names them.

| Action                | Inputs and behavior                                                                                                                                                                                                                                                                                              |
| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `message`             | `target?:ChildRef`, nonblank `text` (at most 4096 UTF-8 bytes), `mode?:"inbox"                                                                                                                                                                                                                                   | "steer" | "followUp"` (default inbox). Requires a running recipient. Omitted target means root inbox, never arbitrary supervisor RPC. |
| `inbox`               | Destructively reads only the actor's mailbox. Successful tool output exposes messages to that actor's model. No automatic root inference is triggered.                                                                                                                                                           |
| `wait`                | Required `timeoutMs:1..60000`; optional `target` for one drained window outcome (paused or terminal), or `messageId` for one known receipt, or neither for own inbox. Target and messageId together reject. Receipts are visible only to their originating sender/recipient.                                     |
| `status`              | Root-only pinned `target`; returns `{snapshot,generations,agents}`. Snapshot/history describe assignments; agents describes current presence. Full detached details, bounded text preview.                                                                                                                       |
| `stop`                | Root-only pinned current `target`; closes idle/parked presence or aborts/drains active subtree. Completed outcomes/files are unchanged. Stopped identities cannot revive.                                                                                                                                        |
| `reset_fallback`      | Root-only pinned idle/paused retained `target` with a profile fallback chain. Revalidates current/admitted grants and scopes, selects the first available target, sends no model request and leaves attempts, limits, budgets and deadline unchanged. Returns the snapshot; resume separately.                   |
| `park`                | Root-only current disposed idle target; records parked presence. Active parking rejects: stop active work explicitly. No live SDK session, shell or permit is retained while idle or parked.                                                                                                                     |
| `resume`              | Root-only drained paused or successfully completed `target` and nonblank `assignment` continuation. Returns the same identity/window snapshot and sends one wake-enabled outcome notification after that resumed window drains. No schema replacement or descendant auto-resume.                                 |
| `followup` / `revive` | Root-only current target and nonblank `assignment`, optional supported `resultSchema`. Followup requires idle; revive requires parked. Returns the new admitted snapshot, not final success. Sends one wake-enabled outcome notification after the returned new generation drains; wait/status remain available. |

A message returns `{id,sender,recipient,text,mode,status,error?}`. `accepted` means mailbox admission, `queued` means the public SDK accepted a steer/followUp, `handled` means an SDK input handler consumed it, `delivered` means the exact message entered the recipient transcript or an inbox tool/wait returned it. None means model acknowledgment, understanding or assignment completion. `not-running` means no running recipient (including an undelivered receipt whose recipient ended), and `error` preserves delivery errors. Unknown/foreign/stale identities or receipts reject visibly, not as apparent successful delivery. Inbox messages are not automatically steered; steer/followUp are also retained in the bounded mailbox. Their `delivered` state comes from actual SDK user-message events, not queue acceptance. Message text is literal prefixed data, not tool authority.

At most **64 messages per mailbox**, **512 admitted messages per parent runtime**, **64 pending waiters**, and **64 generations per identity**. Consumption frees mailbox slots, not receipt-retention budget; exhaustion rejects without silent eviction. All are parent-lifetime memory only, not a broker or durable service. Wait uses registry/message events and a native timeout/abort listener, never polling. It returns `outcome` (identity/status/optional limitReason and pauseReason only, no peer result/transcript), `messages`, `message` receipt, `timeout`, `cancelled` or `shutdown`. Cancellation/limits/shutdown close child action admission and wake pending waiters. Paused/terminal outcomes resolve immediately; SDK sessions waiting in tools retain their actual permits. Self/ancestor/dependency-cycle waits reject, including pending sibling delivery receipts; child waits on queued work reject rather than lend permits. Pending root-receipt waits from children are unsupported (a foreground parent may already be waiting for that child); send without waiting for acknowledgment or wait for an explicit reply in the child's inbox. Root outcome waits may await queued work, bounded by the explicit timeout. Timed-out/cancelled waits do not cancel targets; use stop explicitly.

### New assignments, generations and immutable history

Completed-agent renewal is distinct from paused continuation. After real tools/descendants/artifacts drain, resources dispose and a non-cancelled generation has **idle presence**; explicit park changes only presence to **parked**. Active presence covers queued/setup/running/draining; deadline transitions expose pausing/paused presence separately. Cancellation/shutdown/stop produces **stopped presence** without rewriting completed assignment status. Completed generations never gain more transcript entries or overwritten artifacts.

Followup/revive re-resolve operator/trusted-project policy and selected root model/auth/resources at invocation. Effective grants are intersected with the previous admitted/request-narrowed grants and, for descendants, each current effective ancestor definition and its admitted authority. Removed grants are not restored on later generations, including builtin tools absent from the original callable parent subset. Later parent activation can benefit a newly admitted identity, not expand old identity/generation ceilings. Missing resources/auth or an empty effective builtin set or incompatible policy fail honestly. A new assignment retains the prior schema unless a new supported schema is supplied; no previous submitted value/attempts/status/result/telemetry can satisfy it. Model/tool/deadline budgets restart per assignment, bounded by current policy and previous execution limits. Direct-child spawn consumption remains cumulative for the identity and each descendant renewal consumes another slot of the live parent's remaining lifetime spawn budget.

The UUID stays stable and generation increments atomically **only after** synchronous admission checks. Concurrent renewals race on the original reference; exactly one can replace it. A newly owned generation directory `<id>-g<N>` holds its SDK session, `agent/`, transcript and exclusive artifacts. Generation 1 keeps `<id>/`. For these completed-agent fresh generations, no old files are opened for continuation, consulted, replayed, appended or migrated. The new prompt contains only the new explicit assignment plus current role/resources and identity; provide any relevant prior conclusions explicitly. This deliberately avoids retained-conversation replay/tool execution and does not claim a warm resumed Pi session.

Descendant renewal requires its **exact original** `parentId+parentGeneration` still active, non-cancelling and authorized. Current ancestor spawn roles, depth/limits, remaining spawn count, immediate nested capacity and ancestry all revalidate before generation mutation/setup. Replaced/disposed/stopped ancestors reject; the caller must delegate a new identity through an authorized live parent, never reparent the old one. Explicit parent stop closes descendant idle/parked presence too. Successful parent completion does not retire already-successful retained descendant conversations; their explicit resume still requires the exact original active parent generation. Old callbacks, steering, stops, submissions, message delivery and waits capture the originating entry/reference, never retarget by latest UUID. Wait outcomes remain pinned even if a later generation is admitted. Shutdown/reload closes all presence and waiters, drains actual resources and suppresses old-runtime final messages; no cross-parent/process revival exists.

## Caller-coordinated shared writes

Multiple writers, reviewed leaf calls and parent tools may run together by default, within existing concurrency/FIFO/grant limits. There is no exclusive lease, parent mutation blocking, file ownership, automatic merge or new config. The required boolean `ChildSnapshot.writerLease` is deprecated and always false for new snapshots; historical snapshots may retain historical values. It never indicates write capability. Original parent permission hooks, builtin provenance, reviewed-leaf trust/root-workspace restrictions and cwd adaptation remain unchanged.

Assign independent responsibilities and coordinate shared operations, including Git index mutations, generated outputs, shell side effects and same-file updates. A separate cwd is not containment. Reads/reviews during writes are not stable snapshots: rerun verification after coordinated changes finish. Manual `!`/`!!`, external terminals/editors, unrelated sessions and arbitrary extension JavaScript are also uncoordinated; no wrapper or OS lock is installed.

Cancellation is not rollback. Completed writes remain; in-flight tools retain capacity until actual drain. Stop/drain affected work, inspect the current checkout, deliberately reconcile conflicts, and verify before retry/resume. Never automatically retry mutations as conflict recovery. Let active children drain before reloading/restarting to load changed source; no hot coordinator migration is provided.

## Storage and fleet observation

Only new `delegation/<parent-id>/<task-id>/{agent,transcripts,result.txt,structured.json}` data under the parent session directory is created (successors use `<task-id>-g<generation>`). No historical proof/run data is read, mutated or migrated. Registry lifetime is the parent runtime, never durable recovery. Transcripts/artifacts can contain sensitive content and require the same care as parent transcripts.

The joined fleet widget, ordered single/batch result cards and `/subagent-hub` consume this registry, not a second executor. `createdAt` is admission epoch milliseconds; `endedAt` is null until actual disposal, then its epoch. `writerLease` is a deprecated boolean, always false in new snapshots. Tree indentation follows real depth; inspector supplies full parent UUID+parentGeneration. Queue entries may have no transcript. Terminal status is separate from idle/parked/stopped presence. History retains immutable snapshots and detached finalized SDK messages when old SDK graphs are released; `messages(ref)` returns detached public SDK messages for exactly that current/historical generation, empty before session setup. No replay, arbitrary file reading or copied artifact store is involved. Full readonly transcript/tools omit opaque provider payloads, signatures and image data; image omission is explicit. Cards label truncation; inspector scrolls full text/structured values and artifact references. Usage is direct per selected generation, never parent-plus-descendant totals.

Subagent Hub is opened with `/subagent-hub`; outside the TUI the same command prints the current registry list instead. Below the reading area, the Hub's right-hand column has a steering composer for the selected generation: it states whether steering is available, the configured confirm key focuses it for a running target, confirm sends and cancel leaves without sending. Beneath the composer, a display-only status row mirrors Pi's main footer for the selected generation: direct usage on the left (`↑input ↓output Rcache-read Wcache-write $cost pct%/window`, with `≥$` for a known cost subtotal and `?/window` when the context percentage is unknown) and the current `provider/id · effort X` right-aligned. Zero or unknown usage is omitted, never synthesized. At narrow widths model/effort outrank usage: whole usage parts drop (cache, input, output, cost, then context), then the provider, then the model text truncates. The status row yields before the reading area would drop below two rows, is excluded from wheel scrolling and controls nothing. The **Subagents** widget renders no rows while the current registry is empty, including before first use and after a runtime reset; admitted queued/setup work and retained terminal tasks remain visible. The bounded above-editor widget is a semantic subagent tree (role/assignment, actual status, direct stats, newest activity), not another authority surface. Queue counts are collapsed, live resources prioritized, terminal tasks counted in the summary and active overflow counted. Compact summaries keep failures explicit as a count plus `failed`, distinct from `settled` and `cancelled` without relying on color. Summary-only output includes `/subagent-hub` at practical widths such as 55 columns, inline or in a spare row within the existing budget (at most five rows, further bounded by terminal height). A one-row budget prioritizes failures and discovery over secondary totals; displayed counts remain exact, not a claim that omitted statuses are zero. Unknown usage is omitted; requests are not labeled turns, no context percentage is synthesized, and elapsed is admission-to-disposal at render time without a new timer. Lease-specific runtime warnings are not shown, including for historical snapshots. Visual-only pinned reference attribution is in the README; no reference runtime/source/assets are imported.

A full-width, border-colored rule separates the Hub panes from a visible footer, consuming one row within the existing height budget. Tiny browse layouts hide both footer and rule. Pinned target identities and their controls remain indivisible; insufficient space shows a resize/configured-cancel placeholder instead of actionable controls. Compact browse hints name the configured confirm key for `Steer`, `m Inbox`, `x Stop`, `/ Filter`, Tab's next view and all configured cancel close bindings. Default Escape/Ctrl+C close in browse mode; Enter never closes; configurable actions use the injected keys, including unbound states, without installing fallback keys. Browse `?` opens scrollable observation-only help; `?` or configured cancel returns without changing the selected identity, view, tool-expansion preference or READING offset. Help blocks underlying controls, including the steering composer and mouse-wheel thread scrolling. Printable `?`, j/k and Space remain native input text. Navigation, help, resize, closing and disposal never stop or otherwise control work.

Hub names are snapshot-derived assignment headlines plus role, not a naming registry or new identity. Every selection/control still uses the original UUID+generation; details and pinned controls expose that full reference, and identity filtering remains supported. Stop, steer, inbox, wait and park feedback captures the original reference and a sanitized task label, never the later selection or generation. Pending, success and failure notices retain that context while browsing or filtering; the single global notice may be replaced by a later notice, not retained as action history. Long notices are bounded and explicitly mark truncation; their original exact target precedes the result. Stop success follows actual drain. Inbox receipt states and queued/handled steering never claim model acknowledgment. Disposed openings do not request renders from late completions. The primary thread uses the same publicly exported user/assistant/tool component classes as main Pi chat, standard builtin renderer-only definitions and injected host TUI/cwd. Tools preserves complete sanitized arguments/result text even where native builtin presentation suppresses success prose. Native edit previews never read files here: only recorded sanitized diff/firstChangedLine details are admitted. No arbitrary tool details, opaque signatures or image payloads are forwarded to renderers. Public default Markdown/thinking and collapsed/expanded tool presentation is supported; parent-private renderer resolver chains, third-party overrides, Markdown transformers and private hide-thinking/outputPad state are unavailable, not emulated. Native SGR is retained; terminal-control output, hyperlinks and shell zones are excluded.

Each Hub opening starts with tool output **collapsed**, independently of main chat. In thread browse mode, the configured `app.tools.expand` action (default **Ctrl+O**) toggles all native tool blocks. Footer help shows the active key(s) and expansion state; empty bindings show `unbound` and do not install a fallback shortcut. One Hub-local preference covers roster/generation selection and tab switches, including newly arriving, streamed, reconstructed and failed/aborted tool output. Closing/reopening resets it; nothing is persisted or synchronized to main chat. Native collapsed rendering varies by tool and can suppress result text entirely. Tools remains the full sanitized inspection path.

Expansion is unavailable in Details/Tools, search, steer/message editing and stop confirmation. Toggling never executes tools, changes stored messages/results or sends control actions. LIVE recalculates its tail; READING remains detached and retains the first visible surviving message/tool and its relative line where possible. If collapse hides that line, the tool’s surviving header/summary is shown; offsets clamp safely without switching to LIVE.

| Capability                                                                                                        | Supported surface / precise restriction                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| ----------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Fleet/roster/tree/history, physical model/effort/prewalk, limits, schema validation/value/artifacts, direct usage | Persistent widget + native cards + Hub thread/details/tools; the Hub status row shows the selected generation's current model/effort and direct usage. Wide Hub: capped left generation roster, dominant right thread; compact Hub: selected-generation header and full-width thread. Current fleet counts exclude old generations; history rows remain individually selectable.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| Filter/search and scrolling                                                                                       | `/` searches roster content including result/progress, not a filesystem or full-transcript search engine. Tab cycles thread/details/tools (thread default). Thread opens/follows the latest output (LIVE); upward scroll/Home detaches (READING) without following appended output, End or reaching bottom resumes. Details/Tools open at top without auto-follow. j/k line-scroll, Ctrl+u/d and configured PgUp/PgDn page-scroll, Home/End top/bottom independently of ↑↓ roster selection. Aliases never intercept native input editing. Public fullscreen normalized wheel scrolls only the reading viewport; other wheel inside the Hub is consumed, not forwarded to main chat. Regular mode leaves wheel/scrollback to the terminal; keyboard fallback is required. No mouse-mode or host-setting changes. Prefilled filters start editing at the end using public native Input handling. |
| Steering                                                                                                          | Hub thread-column composer (configured confirm key focuses it, pinned original UUID+generation, running only; empty drafts send nothing; a draft for a target that stopped is kept and not sent) or the native `subagent` steer action. Public SDK queued/handled is not model acknowledgment.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| Root inbox message                                                                                                | Hub `m` → existing root `message` authority, bounded native mailbox; receipt shows actual state, never model acknowledgment. Model tool additionally supports steer/followUp modes, inbox consumption and receipt waits.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| Outcome wait                                                                                                      | Hub `w` → native event wait with explicit 1000ms bound; native tool supports 1–60000ms outcome/inbox/receipt waits with existing deadlock/refusal rules.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| Stop subtree                                                                                                      | Hub `x` → pinned target → `y` confirmation → existing stop/drain, retaining capacity until actual drain. Queued/setup/running/paused UI targets supported; historical/pausing/draining/disposed UI targets refuse, including transitions during pinned input. `/subagent-stop` and native root stop retain existing semantics.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| Park                                                                                                              | Hub `p` or native root tool; only disposed idle current identity with valid original parent. No warm SDK retained.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| Followup/revive                                                                                                   | **Native model-issued `delegate_coordinate` followup/revive only**. Idle/parked assignments use fresh session/generation/current narrowed authority. `subagent` resume continues paused or successfully completed conversations with full restored context and unchanged identity/generation/session count. Both require the exact active original parent for descendants. Hub command context lacks `tools/executeTool`: it cannot safely start a generation; f/r only explain refusal, allocate nothing and dispatch nothing.                                                                                                                                                                                                                                                                                                                                                                 |
| Child coordination/spawn/model authority                                                                          | Coordination/model authority remains operator default-off; spawn defaults to scout/review only. All remain project/request/ancestor subset-only; the UI cannot mint grants or impersonate a child.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| Manual !/!!, external editors/terminals, arbitrary extension JS                                                   | Uncoordinated; caller-coordinated shared writes, never a shell ban/wrapper/sandbox.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| Supplied workspace / production isolation                                                                         | Explicit path/shell-cwd adaptation through root hooks is supported for existing supplied workspaces. Filesystem sandboxing, managed worktrees, copying/apply and cleanup remain unimplemented; cwd is not a resource grant.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| Retained incremental advisor                                                                                      | **EXCLUDED** from current product scope, not pending an owner contract or a current release gate. No advisor implementation/substitute; explicit ordinary `review` delegation remains supported. Reference evidence is retained in the advanced policy ledger, not an automatic implementation plan.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| Probes/speculation/workpool/executable extensions/MCP/historical consultation                                     | Runtime loading/full MCP inheritance remains unsupported/parked per advanced policy ledger; restricted general leaf forwarding is specified below. No ambient/history/sensitive scan or new provider inference.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| Restart recovery, cross-parent messaging/revival, automatic idle TTL/warm replay                                  | Unsupported. Parent shutdown still aborts/drains/disposes.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |

UI strings are sanitized against terminal controls/ANSI/bidi; native display-column helpers bound multiline layouts and resizing. Neutral backgrounds preserve active theme lightness with zero chroma and restore after truncation/style resets. This is not installed/full parity/production publication or human visual acceptance. Native draft stack [1,2,4] remains a linear UI fork relative to local scheduler/outcomes/coordination/advanced branches. No graph revision or publication was performed here.

## Restricted general inheritance

General retains its existing analysis prompt and the supplied assignment; it does **not** copy parent system instructions, context files or history. Available skills come from the parent's public `before_agent_start.systemPromptOptions.skills` metadata. Bundled → operator → trusted root-project narrowing still applies; explicit `skills:[]` removes inheritance. Skills advertise exact validated paths, not eagerly copied instruction bodies. Other roles keep their explicit skill grants and scout/review remain read-only.

Only the operator can mint `general.leafTools`, an exact-name allowlist of **reviewed leaf implementations**. For example, after reviewing an installed extension/MCP tool that never dispatches other Pi tools or alters session/tool/model state:

```json
{
  "general": {
    "leafTools": ["mcp__docs__lookup"]
  }
}
```

This does not connect/reload MCP, load extensions into children, or activate parent tools. The tool must already have public metadata and be live callable (`ctx.tools`). Trusted project configuration may remove leaf grants but cannot add them. Missing operator review is an explicit denial, not a universal ban on extension tools. Review is a trust assertion about code/server behavior, not a verified security annotation.

Classification is deliberately fail-closed:

- Genuine callable builtins are admitted through the existing builtin ceiling/provenance check.
- Reviewed callable non-builtin leaves are admitted only in the root workspace. Leaf calls may run concurrently, regardless of `readOnlyHint`.
- `reachesTools` tools are denied regardless of what that function returns or what is granted: the SDK cannot restrict their nested dispatcher to this child's ceiling.
- `codemode`, `tool_search`, `delegate_task`, `delegate_coordinate`, `subagent`, and `submit_result` cannot be forwarded. Child-owned controls still use their existing separate grants.
- Hidden/model-only tools, builtins outside the profile ceiling, builtin replacements, unreviewed/unknown implementations and non-builtin tools for a different cwd are denied. MCP namespace names or annotations alone do not authorize a tool.

`ChildSnapshot.tools` retains its **builtin-only** meaning. Additive `leafTools`, `skills` (exact paths), and `capabilityDenials:[{name,reason}]` describe the admitted ceiling and rejected tool inventory. These are admission records, not promises of continued availability. No builtin rights are manufactured by leaf grants; the existing nonempty effective builtin requirement remains.

Before each forwarded call the coordinator checks cancellation, live callability, builtin provenance or leaf classification/provenance, and current role/ancestor tool configuration. The public root `ctx.executeTool` preserves argument validation, permission/result hooks and SDK nested-call IDs; it is never replaced with raw tool execution. Revocation blocks subsequent dispatch, not effects already performed or already in flight. Renewal intersects previous leaf/skill ceilings and descendants must remain ancestor subsets. Per-child call budgets and cancellation/drain still cover the forwarded leaf call.

**Trust limitation:** extensions execute trusted JavaScript with full process permissions and their original root context/closures. The public SDK does not provide a child-specific execution context or enforce `reachesTools` declarations. A false leaf assertion, malicious extension, undeclared nested dispatch, or server-side orchestration cannot be sandboxed here. Do not grant such implementations. Metadata/provenance checks detect visibility/classification/source changes, not arbitrary code replacement under identical public metadata. Full automatic inheritance and general tool-to-tool forwarding remain unsupported. Custom cwd adaptation applies only to genuine builtins; custom tools are never represented as rebound.
