# Agent Instructions

The [relocation ledger](docs/agent-contract-relocation.md) maps every pre-compaction paragraph to its owning contract or test. Keep this file as durable development policy, not a second copy of the product manuals.

## Ownership and semantics

- Require matching Pi coding-agent, agent-core, AI and TUI packages at ≥1.0.0; pin the local verification stack to 1.0.0 and preserve the documented limits of fixture evidence.
- Keep `index.ts` minimal, independent domains in `lib/` with same-named tests, architecture checks in `tests/invariants.test.ts`, and Pi lifecycle composition in `lib/extension.ts`; delegate low-level mechanics to their owners. See [composition](docs/architecture.md#composition).
- Keep Off the genuinely new-session default, with Passive and Active opt-in; Off removes State Flow model tools/context without deleting memory. Modes belong to the current session; global mode is only a new-session default. Passive declares both tools even without memory, but contributes protocol/projected state only with a validated view. See [mode behavior](docs/usage.md#active-passive-and-configured-off) and [configuration](docs/usage.md#configuration).
- Preserve Pi's native tool loop, trace and foreign context; the context domain alone projects the raw scope overlay. Freeze/rebase the head only at specified boundaries, retain current-run trajectory and stable-position tail notices, and never give projection IDs or guessed user anchors publication/compaction authority. See [Pi lifecycle](docs/architecture.md#pi-lifecycle) and [projection evidence](docs/performance.md#context-projection-and-trajectory-selection).
- Store only present known `intents`, `contract`, `working`, `artifacts`, `response`, `lazy` fields; preserve nonempty nested data and retained causal identities. Normalize empty object fields/planes only in supplied scopes and response-owned Session, before ownership and after cascades/compilation; preserve array slots and exact current/historical reads. Model projection may omit legacy empty branches. Missing planes and empty response do not become fabricated stored defaults; malformed evidence fails closed. Keep lazy bodies out of automatic projection and Session as the sole author of new responses. See [semantic state](docs/architecture.md#semantic-state) and [temporal model](docs/architecture.md#temporal-model).
- Respect global → CWD → session ownership, scope-local deletion and inherited fallbacks; scope does not confer instruction authority. Registered Skill ownership follows Pi source provenance, not path shape. See [semantic state](docs/architecture.md#semantic-state) and [artifact routing](docs/architecture.md#artifact-routing).
- Artifacts name exact registered source paths; observe only regular non-symlink files, never discover directories or read unrelated bodies. Preserve hidden per-scope provenance, exact-owner compilation, stable fingerprint checks and separate Skill hashes; unavailable sources are not proof of deletion. See [artifact routing](docs/architecture.md#artifact-routing).
- Preserve session config/runtime, per-scope metadata, lineage and provenance outside model-patchable state; decode legacy mode evidence read-only, never mix representations or normalize storage eagerly. See [storage and identity](docs/architecture.md#storage-and-identity) and [mode compatibility](docs/compatibility.md#mode-configuration-compatibility).
- Keep one opaque composed causal lineage, anchored checkpoint/tail materialization, configured hot-history folding and independent owner revisions; never invent earlier history or rebuild discarded offsets. Historical reads are observational, and `effective[n]`/owner materializations select the same causal boundary. See [temporal model](docs/architecture.md#temporal-model) and [model tools](docs/architecture.md#model-tools).

## Publication and lifecycle

- Treat canonical scope files as semantic authority and Git only as optional backup. Classify complete, wholly absent, partial and malformed cohorts before recovery; absent shared pairs may initialize only under accepted authority, while incomplete/private evidence fails closed. Never repair through ad-hoc writes. See [storage recovery](docs/usage.md#storage-and-recovery) and [transaction rule](docs/filesystem-recovery.md#transaction-rule).
- Keep exact regular-file, byte-CAS and lock-serialized publication with cancelable waits, single-use callback-scoped capabilities and guarded rollback. Never hold exclusion across inference, source acquisition or Git; do not steal interrupted locks, claim kernel-atomic multi-file publication or promise power-loss durability. See [asynchronous transaction](docs/architecture.md#asynchronous-storage-transaction) and [durability boundary](docs/filesystem-recovery.md#power-loss-durability).
- Attach Off branches through native policy bookkeeping only, deferring memory acquisition and recovery diagnostics until explicit Passive/Active. Preserve pending Off forks across cold reload with child-owned native markers, without reading the parent header/store until acquisition. Memory never depends on the Pi step: it is the current same-session JSON state, advanced only by accepted `patch_state`/lifecycle publications. Startup, reload, resume and tree navigation validate and accept current same-session memory; native checkpoints supply only mode and run lifecycle, never a revision to rewind to. A fork copies its parent's current memory into a fresh child owner. Never substitute empty, Git, foreign or fabricated memory when current files are missing, corrupt or contradictory. Only accepted candidates install cache, checkpoint and mode. Unreadable current memory under Active retains Active policy, visibly reports `active (blocked)` and fences live inference through public Abort until accepted Active/Passive or explicit Off; never silently expose native history or an inactive indicator as fallback. See [Pi lifecycle](docs/architecture.md#pi-lifecycle) and [fork contract](docs/fork-contract.md).
- Persist each material semantic change and its affected revisions exactly once, including accepted Session responses. Optional settled-turn Git backup may capture only already-accepted owned files, leave unrelated index/worktree data intact and push without force or semantic side effects. Defer busy backup when the host provides no settlement operation signal rather than blocking Abort; never move it to `turn_end` or add a durable push queue. Off cancels owned captures/pushes and suppresses late reporting; normal agent-operation completion must not cancel an independently admitted push, and foreign callers' pushes retain ownership. See [optional Git backup](docs/architecture.md#optional-git-backup).
- Accept one atomic `patch_state` cohort across supplied scopes against current shared memory; reject empty scopes, unknown/retired grammar and model-authored `response`. Correct no-ops create no transition. Enforce the single-call inference barrier before sibling tools execute and retain conservative model-facing reconciliation when a result cannot be predicted. See [model tools](docs/architecture.md#model-tools) and [Pi lifecycle](docs/architecture.md#pi-lifecycle).
- Reconcile the actual accepted ordinary answer at `turn_end` with response-owned cancellation and one accepted lifecycle publication; do not request private repair inference, ceremonial finalization patches or roll back accepted memory after cancellation. See [Pi lifecycle](docs/architecture.md#pi-lifecycle).
- Capture specifications without writes at `before_agent_start`, then await one cancellable preparation acceptance before active inference; abort failed context preparation through Pi's public hook. Keep user text at user authority and state as fallible data. Preserve an existing conversation for exactly one bootstrap run, not forever. See [Pi lifecycle](docs/architecture.md#pi-lifecycle) and [pre-inference cancellation](docs/compatibility.md#pre-inference-cancellation).
- Make Start await coherent current-head acceptance; unaccepted Off-to-Active retains deferred history and cannot confer current-memory authority on a superseding Passive choice. Passive selects local policy before asynchronous runtime-only persistence; preserve its independently owned fork/restoration work. Off instead cancels owned memory waits, clears semantic caches and records only native mode/continuation/fork bookkeeping without canonical I/O. Preserve already accepted publications and carried write fences; failed Passive persistence uses a native fence, never a substitute semantic checkpoint; a later explicit Passive retries current-memory acceptance and clears the fence only after acceptance. Off exposes no frozen handoff. See [lifecycle planes](docs/architecture.md#lifecycle-planes) and [lifecycle operations](docs/usage.md#lifecycle-operations).
- Request completed-history native compaction only after an accepted non-bootstrap settled run, public usage ≥24,000 tokens and a uniquely captured first-user anchor; retain the complete latest run and foreign context. Use per-request owned markers, cancel stale/inactive owned hooks without default summary fallback, and prevent old completion from clearing a new plan. Await its native callback before returning, and leave Pi manual/threshold compaction and append-only history alone. See [lifecycle planes](docs/architecture.md#lifecycle-planes).
- Contribute only State Flow's compact normative system-prompt section through Pi's section membrane; refresh it with current mode without overwriting foreign sections, forced-prompt precedence or native message identities. Never invent a continuation scheduler. See [lifecycle planes](docs/architecture.md#lifecycle-planes) and [host context compatibility](docs/compatibility.md#context-tools-and-provider-input).

## Model and operator boundaries

- Treat state as a decision-relevant handoff, not a transcript: distinguish user requirements, confirmed decisions, observations, hypotheses, chosen intents and remaining checks. Revalidate volatile external effects before repeating actions; memory is neither an action ledger nor proof of current reality. See [operational guidance](docs/architecture.md#operational-guidance-and-memory-curation) and the [memory Skill](skills/state-flow-memory/SKILL.md).
- Resolve semantic `$` paths and structured references only when needed; never confer authority or existence by reference alone, scan to find broken references, automatically search all history or restore deleted values from hints. Sole exception: a structured `{"$ref"}` inside an `intents` entry owns its same-scope `working`/`lazy` object-key target, so deleting that intent key deletes the target after authored operations in the same atomic cohort unless a remaining same-scope intent references it, an ancestor or a descendant. That bounded read of one scope's `intents` plane never validates, rejects, warns, archives or crosses scopes; textual `$path` mentions and structured references outside `intents` stay non-owning. See [model tools](docs/architecture.md#model-tools), [intent ownership](docs/lazy-state.md#intent-ownership) and [lazy navigation](docs/usage.md#lazy-navigation-and-historical-reading).
- Keep Skill acquisition optional and exact-path/provenance-derived; successful reads alone are volatile, and attempted durable compilations require scoped validated output plus runtime-owned hash evidence. See [artifact routing](docs/architecture.md#artifact-routing).
- Reconcile touched state without automatic whole-store audits. Dedicated curation needs a user request; intra-store moves use one verified multi-scope patch, and external transfers need verified destination acceptance before source deletion. See [operational guidance](docs/architecture.md#operational-guidance-and-memory-curation) and the [memory Skill](skills/state-flow-memory/SKILL.md).
- Keep opt-in diagnostic categories, failure elision/privacy and barrier-only names-only records outside canonical state; logging failures cannot change accepted state. Preserve a blank line between every tool name and its output. See [diagnostic privacy](docs/usage.md#diagnostic-logging-and-privacy) and [barrier diagnostics](docs/architecture.md#pi-lifecycle).
- Keep public patch outputs and staged drafts detached from caller/accepted values; private path-copying must not leak mutable objects or weaken CAS. Reject stored null in documented semantic planes while preserving valid nested object-key deletions. See [storage and identity](docs/architecture.md#storage-and-identity) and [model tools](docs/architecture.md#model-tools).
- Do not add project schemas, state/patch byte caps, dynamic growth pressure, action authorization, automatic reference hydration or strict boundedness claims for state, the turn specification, the current-run trajectory or Pi's external trace. See [model tools](docs/architecture.md#model-tools) and [operational boundaries](README.md#operational-boundaries).
- Keep terminal status observational and mode-derived; no source maintenance or invented empty view on inspection. Explicit Off inspection uses disposable current-store readers, validates private/Effective authority, and must not install cache or alter deferred branch/fork policy; automatic callbacks and rejected queued tools remain memory-inert even with logging enabled. Optional Git, Telegram and diagnostics degrade without fabricated success or weakened memory ownership. The optional `lib/telegram.ts` presentation leaf alone may consume pi-telegram's public membranes; core semantics/storage/inference remain transport-agnostic. See [status and controls](docs/usage.md#status-and-controls) and [observability](docs/architecture.md#observability).

## Delivery discipline

- Keep the exact-tag [release workflow](.github/workflows/release.yml) as sole npm Trusted Publisher and GitHub Release owner; align version, lockfile, tag and changelog, with no long-lived npm-token fallback. Keep generated `dist/` tracked, rebuild after final source/package edits and verify source/build parity and npm inventory. See [validation boundaries](docs/architecture.md#validation-boundaries).
- Keep opt-in measurements under `benchmarks/`, excluded from normal tests/packaging, with source-bound workload identities. Native scripted-provider tests assert callback completion outside the provider; startup/tree and cancellation fixtures await the right ownership boundary. See [benchmark guide](benchmarks/README.md) and [temporal witnesses](docs/temporal-acceptance.md#required-properties-and-witnesses).
- Keep README/docs current rather than copying chronology out of CHANGELOG; preserve SKILL.state attribution for inherited explicit-state ideas. Exercise malformed/predecessor storage only in temporary repositories, never the user's active data. Run `npm run validate` after retained code changes and the canonical ABCd context validator after context edits. See [documentation index](docs/README.md) and [validation procedure](docs/compatibility.md#validation-procedure).
