Install
Install with PiG
pig install npm:@woksin/pi-context-budgetInstall with Pi
pi install npm:@woksin/pi-context-budgetPackages run code with your permissions and influence agent behavior. Catalog inclusion is not a security audit. Review the source before installing a third-party package.
Pi manifest JSON
The pi field of package.json.
{
"extensions": [
"./src/extension.ts"
]
}README
Written by the package's publisher, shown as published in version 0.13.0 (README.md). PiG does not review it.
pi-context-budget
Structured context handoffs for pi: keep working in the same session and process while a large conversation is replaced by a concise, verified-state handoff.
Jobs, subagents and session-scoped integrations stay alive. A pi-session wrapper provides a fresh-process fallback when in-process recovery is no longer safe.
Observe by default. Installing the package does not block tools, compact history or restart sessions until you explicitly enable enforcement.
Features
- A
context_handofftool that separates verified facts, hypotheses and user constraints, with git HEAD collected independently. - Observe mode by default, with opt-in enforcement.
- Idle reset and an overflow backstop.
- Optional resume checks.
- A
pi-sessionwrapper that relaunches in a fresh process when needed. - Config in
context-budget.json(orPI_CONTEXT_BUDGET_CONFIG).
Why
Per-turn input cost grows with accumulated context, including cached reads. After a cache expires, rewriting a large context can be substantially more expensive. Long histories can also bury constraints, stale verification results and the next action.
Small synthetic experiments demonstrated automatic continuation across retain-none handoffs, preservation of the cached system/tool prefix, and completion of a sequential state-recall task. The production checks include enforced handoffs, observe-mode no-ops and wrapper relaunch. These are mechanism checks, not production-scale quality or savings guarantees. Handoff quality matters: verified facts, hypotheses and user constraints are deliberately separated, with git HEAD collected independently.
Install
pi install npm:@woksin/pi-context-budget
Or add the package to your pi settings:
{
"packages": ["npm:@woksin/pi-context-budget"]
}
Git/local sources also work:
pi install git:github.com/woksin/pi-context-budget
pi install /path/to/pi-context-budget
Restart pi or use /reload when safe for your other extensions. Installing does not inject code into already-running sessions. Do not reload busy sessions just to add this package.
Requires Node.js 22.19+, Bash and a POSIX system; Windows is not supported. Developed against pi 1.2.0. The host peer uses "*" as recommended for pi packages; this is not a compatibility guarantee for every pi version. Pi supplies its own runtime; the package bundles none of it.
Subagent integrations with explicit extension allowlists must include pi-context-budget (the package short name), and expose the context_handoff tool. A parent-only -e option is not necessarily inherited by children. Load this package in the primary session before starting SDK children. A process-local hosting marker identifies the primary runtime and its concurrently bound SDK children; it is released at primary shutdown so forked/resumed main sessions remain main. Ancestry (parentSession) and UI availability are not child signals. Child-only loading without an instrumented primary is unsupported.
Configure
The configuration path is getAgentDir()/context-budget.json, or PI_CONTEXT_BUDGET_CONFIG. Pi's PI_CODING_AGENT_DIR override is respected. Missing or invalid configuration selects safe observe mode; errors are logged. Configuration reloads at startup and each input.
{
"mode": "observe",
"resumeChecks": {},
"overflowRecovery": true,
"main": { "soft": 300000, "handoff": 400000, "hard": 600000, "minProgress": 50000 },
"subagent": { "soft": 150000, "handoff": 200000, "hard": 300000, "minProgress": 25000 },
"models": {
"provider/model-id": { "main": { "soft": 80000, "handoff": 100000, "hard": 150000, "minProgress": 15000 } }
},
"idleMinutes": 50,
"idleMinTokens": 300000,
"keepRecentTokens": 20000,
"maxHandoffsPerSession": 10,
"loop": { "maxHandoffsWithoutProgress": 2, "withinTurns": 8 }
}
| Field | Meaning |
|---|---|
mode | off, observe (default), or enforce |
overflowRecovery | Recover actual provider context overflow with one compact-and-retry; default true. Explicit mode: "off" disables it, but observe and shared guard-off still recover. Set false to opt out. |
resumeChecks | Optional map of exact session names to trusted shell commands; default {} (disabled). PI_RESUME_CHECK takes precedence. |
enforceCwds | Optional array of absolute directory prefixes/globs. Outside it, enforce becomes observe. Empty array enforces nowhere. |
main, subagent | Soft/handoff/hard thresholds and minimum growth above the measured context floor |
models | Exact provider/model-id overrides, merged separately into main/subagent thresholds |
idleMinutes, idleMinTokens | Minimum idle duration and settle-time context size for pending-work idle recovery |
keepRecentTokens | Eligibility guard for idle compaction; align with pi's compaction setting |
maxHandoffsPerSession | Allow this many budget/hard commits, excluding idle commits. With a wrapper, fall back (relaunch) before another. Without a wrapper the cap is advisory: in-place handoffs and enforcement continue, with a warning each turn (cap_advisory log event) recommending a fresh session |
loop.maxHandoffsWithoutProgress, withinTurns | Fall back after more than this many budget/hard commits in this many turns without a successful non-handoff tool; idle commits are excluded. Without a wrapper, enforcement pauses with a warning every turn until a successful non-handoff tool call (or the window ages out) |
All numbers must be positive and finite; count limits must be integers; require soft <= handoff <= hard. Prefixes match directory boundaries, not adjacent names. Globs use Node path.matchesGlob (*, **, ?, braces/classes); paths must be absolute, without implicit tilde expansion. Use consistent cwd paths rather than symlink aliases.
Choose thresholds for your actual model window. The defaults target large-window models; smaller windows need lower per-model overrides. Keep thresholds comfortably above the system/tool bootstrap size, leaving room for output and handoff generation.
Modes and optional guard integration
- off: telemetry only; no enforcement or automatic action.
- observe: telemetry and
would_*threshold events; the handoff tool is a no-op. No threshold-driven blocks, forced continuations, compactions or relaunches. Actual provider overflow recovery is the separate exception described below. - enforce: the policy below, restricted by
enforceCwdswhen supplied.
Observe runs the same enforce transition on a separate copy, then converts every effect 1:1 to a would_* log. Soft notices, action crossings, handoff/settle/block decisions, hard recovery and idle decisions use the same latches as enforcement. Status phase/action describe that preview (projected: true), not actual activity; measured tokens and handoff counts remain actual. Preview-only commits and latches are discarded when enforcement is activated.
The package optionally reads getAgentDir()/lib/guards.ts if your setup provides a shared isGuardOff(name) API and a context guard. In that integration, /guards off context disables enforcement for the session. The package does not install or modify another extension's guard library. Without that integration, change the configuration to off or observe and submit the next input. Only the user/operator should disable enforcement, never a model following a chat instruction.
Native pi compaction takes precedence: off/observe and guard-off pass manual, threshold and native overflow compaction through unchanged. With overflowRecovery: true (default), an actual provider overflow without native recovery triggers one compact-and-retry in observe, enforce and shared guard-off; explicit mode: "off" disables this. A failed native summarizer in observe/guard-off gets at most one bounded mechanical compaction fallback. Repeated overflow after the retry emits overflow_recovery_exhausted and asks you to reduce context or switch models. Only external user input or a successful assistant turn re-arms recovery; aborts, new input, session changes and shutdown invalidate stale callbacks.
Shared guard-off also emits log-only guard_off_threshold warnings once per handoff/hard crossing, re-armed below each threshold. They never enable the guard or notify the user; explicit off stays silent.
Configured/effective mode differences are shown in the footer, for example
context-budget: configured enforce, effective off (context guard off), and logged once per mismatch transition. Cwd restrictions report cwd restriction. Configuration and policy state are local to each runtime binding: starting an SDK child does not change its parent's mode. There is no package-specific per-session mode override; the optional guard integration is consulted live.
Handoff policy
Subagents and sessions without an active context_handoff tool receive a finish-and-return-final-answer notice instead of handoff instructions; budget thresholds never block their tools or request a handoff continuation. The hard-threshold relaunch, the idle settle steer and the cap and loop notices are off for these sessions too. A main session without a readable tool list keeps full handoff enforcement.
Thresholds are floor-relative. With a known floor, the effective handoff threshold is min(hard, max(handoff, floor + minProgress)) and the effective soft threshold is min(handoff', max(soft, handoff' - (handoff - soft))): soft and handoff are minimums, minProgress is the floor-relative knob, and hard is always absolute and wins. For prompt-heavy installs (floor around 150k) with soft 150000 / handoff 220000 / hard 400000, set main.minProgress: 120000: soft at about 200k, handoff at about 270k, about 120k of progress per reset instead of about 70k. The status file shows effectiveThresholds. The live config is the user's to change; this package never edits it.
- Soft: one UI advisory per crossing asks the agent to finish the current atomic step, update
.ai-work/<task>/STATE.mdand task notes, and prepare a handoff. A model-visible message is appended at the next continuingturn_end(tool results), without an extra provider call; a non-continuing turn only notifies the user. - Handoff: when
tokens >= effective handoff(above), a small state-recording grace window precedes blocking every tool exceptcontext_handoff. The floor is the first assistant usage after bootstrap/compaction; an unknown floor never triggers handoff blocking. Null usage after compaction means fresh context. On a turn that already schedules a next request (tool results), a one-time "handoff required" notice is appended atturn_endwithout requesting an extra turn. - Commit: the handoff tool writes a unique structured summary; the same
turn_endcommits a retain-none compaction and requests automatic continuation. No process/session-id change. A sibling tool that actually finishes after the handoff invalidates it; a blocked sibling does not. - Settle: one continuation asks for a handoff if the agent tries to stop while handoff is required. Internal
agent_startevents do not reset this bound or an idle handoff request; only a genuinely newbefore_agent_startresets external-run state. - Fallback: hard limit without a usable handoff, cap, loop guard or classified persistent/exhausted compaction failure arms recovery. Non-handoff tools remain blocked, even with a wrapper, with accurate end-turn instructions. A valid handoff at hard commits in-process with or without a wrapper; it cannot bypass the loop guard, nor the cap when a wrapper can relaunch. Without a wrapper the cap is advisory (warning each turn, in-place handoffs continue) and the loop guard pauses enforcement until a successful tool call, so neither can deadlock the session. With an owned wrapper, write the marker and request shutdown only at
agent_settled; without one, never shut down.
State-recording grace
Existing configuration files need no change. Optional handoffGrace defaults to { "enabled": true, "calls": 4, "fraction": 0.5 }. calls is a positive integer; fraction must be greater than zero and at most one. Set enabled: false to restore immediate blocking.
Grace ends after the granted call budget or at effective handoff + fraction * (hard - effective handoff), whichever comes first. It never applies at/after hard, during fallback, or with a pending/stored handoff. Only edit/write of canonical .ai-work/**/*.md paths, reads of .ai-work paths, and single simple read-only git status, git diff --no-ext-diff --no-textconv, git log --oneline --no-show-signature, git rev-parse, git branch --show-current or git worktree list commands qualify. Diff requires both safety flags; log permits no patch-producing options or custom formats. These forms disable external diff/textconv/signature helpers and do not page on the tool's non-TTY output. Paths use pi's normalization (@ prefix, home expansion, lexical ..) before symlink resolution. Symlink escapes, shell syntax, global git options (including forced pagination) and unrecognised options fail closed; blocked calls do not consume grace. Grace calls do not count as progress for the handoff loop guard. All other tools remain blocked.
context_handoff
Only three fields are required:
{
"goal": "The task and original request, verbatim where it matters",
"next_step": "The exact next action",
"facts": "Verified HEAD/review SHAs, CI run ids, issue/PR states and completed work",
"user_constraints": "User constraints verbatim",
"hypotheses": "Unverified explanations, explicitly not facts",
"files_to_read": ["/absolute/path/to/task-notes.md"]
}
Optional: decisions (and why), user_constraints, open_items, hypotheses, files_to_read, watch_actions, launch_prompt (the relaunch prompt text, saved to <handoff-id>.launch-prompt.md beside the handoff, or an absolute path to an existing file). Relative files_to_read entries are resolved against the cwd. Validation errors name the field, show the truncated offending value and ask for a corrected re-call.
In enforce mode, manual handoffs must reference existing files_to_read and cover every running job/watch/subagent with watch_actions, for example:
[{"id":"exact-id-or-unique-8-char-prefix","target":"CI result","on_complete":"Read the result and continue","cancel":"Optional cancellation instructions"}]
Each entry needs id, target and on_complete; cancel is optional. At most 20 entries are accepted, with nonempty fields of at most 300 characters and no duplicate ids. Unknown ids are rejected when registries are available; unavailable registries produce warnings. Missing files and uncovered running ids are reported together before writing any handoff or launch-prompt file or running resume checks. Checks inspect at most 20 files. Each rejected attempt logs handoff_rejected; after two rejections, or during hard/loop/cap fallback, objective failures degrade to lint so recovery cannot be trapped. Successful writes and session resets clear the rejection count. Observe/off mode does not validate or write handoffs.
Handoff lint warns when STATE*.md or .ai-work/ state files (excluding handoffs/) predate the latest observed state-changing tool call. This heuristic scans at most 2,000 branch entries; read-only shell segments starting with git inspection commands, file readers/searches, or issue/PR inspection commands are ignored. It is not a freshness guarantee. Emergency recovery never fails objective checks; backstop lint marks missing paths (missing) and warns about uncovered work. Lint is bounded to eight lines, 300 characters each, and 1 KiB overall. Successful tool responses only say warnings were recorded; end the turn without further tools.
Uncommitted drafts lost to further work, a new run, replacement, mode changes or shutdown log handoff_discarded. The next handoff lists at most five discarded drafts in a separate 1 KiB section before lint, preserving complete paths and explicitly counting whole entries omitted for space; this list is in-memory and lost on process relaunch. Committed handoffs are unaffected. After a reset, one watch check includes recorded jobs and declared subagents with their completion actions, plus a per-repository HEAD/branch/dirty comparison and a reminder to re-verify CI/review/issue facts. Missing registries are not evidence that work stopped.
Automatic metadata: timestamp, cwd/repository root, git branch/HEAD, working-tree changes (at most 30 short-status lines) and ahead/behind of the upstream, pending jobs/watches/subagents, and this session's issue claims when the corresponding integrations are present. Repositories touched comes from persisted tool-call paths and simple bash cd/git paths, plus claim branches resolved through local worktrees: cwd first, then newest paths, at most 64 candidates and 8 distinct worktrees. Each repo line is at most 300 UTF-8 bytes (root | branch | short HEAD | dirty count | sync); directory probes are cached and one porcelain-v2 status call per repo shares a 3-second git deadline (800 ms per call). Inspection disables repository-configured fsmonitor commands and optional index locks. Uninspected discovered repos are marked with unknown state, not silently treated as clean. A non-repo cwd points to the repositories below; backoff uses the first discovered repo's HEAD.
Pending questions match only the current session id and earlier session ids recovered from handoff paths (including the wrapper's continue from /absolute/handoff.md prompt)—never cwd alone. User messages since previous handoff (verbatim) contains text blocks after the last completed successful handoff/compaction boundary (or committed handoff timestamp); in-flight and failed handoff calls never cut off earlier requests. Newest requests are retained within 4 KiB; older omissions are counted and one oversized message is cut in the middle with an explicit marker. Emergency backstops prefer structured goal/constraints/read-first fields in the JSON sidecar, with legacy Markdown recovery that preserves nested headings. They cite the prior handoff and session file. Emergency excerpts are byte-bounded: 1 KiB each for goal, facts and read-first paths, 4 KiB for constraints, and 512 bytes for next step. Constraints within that budget remain verbatim; abbreviated fields are marked and the full prior file must be reread. Oversized read-first paths are omitted, never cut into invalid paths. Requests are not repeated in emergency facts, leaving room for fresh automatic state.
Scheduled agents are included only if the subagent registry exposes them; otherwise metadata says scheduled agents: not exposed by registry. Finished jobs lists up to 10 terminal jobs since the last handoff, or the last two hours without a timestamp, newest first (id | label | status | exitCode | logPath, at most 200 characters per line). Missing end timestamps and absent/unreadable registries are noted explicitly. This is registry inventory, not evidence that results were consumed: the section is labeled Finished since last handoff (results not yet acted on). Agent-written facts remain claims until rechecked; automatic git state is recorded separately.
Sensitive data: full job commands, including any inline tokens or credentials, appear in the handoff. Avoid putting secrets in commands and treat handoff files as sensitive.
Files: <repo-root or cwd>/.ai-work/handoffs/<sessionId>-<n>.md plus JSON sidecar. Markdown is capped at 53,248 UTF-8 bytes (52 KiB). The split reserves 12 KiB for narrative. With the expanded automatic sections, budgets are 12 KiB for running jobs/watches, 3 KiB for running subagents, 4 KiB each for user messages and resume-check output, 2 KiB each for finished jobs and questions, 1 KiB each for scheduled agents and working-tree lines, 8 × 300 bytes for repositories, and 768 bytes for claims (plus an omission marker), plus 3 KiB for watch actions, 1 KiB for lint and 1 KiB for discarded references, leaving headroom for metadata, headings and paths. Legacy callers without the new sections retain the 16 KiB jobs and 4 KiB subagent budgets. Unbounded job or claim volume cannot consume the narrative allowance; user constraints are never truncated. Jobs render as id | label | kind | until | intervalSeconds | full command | cwd | logPath; genuinely absent fields are -. Commands stay intact unless their whole line exceeds 600 characters, then that line ends with …(cut, N chars) (N is the original line length). The expanded job budget fits about 20 such lines; further records have an explicit omission count. Oversize is a clear tool error, never silent truncation. Each summary has a unique heading; retain-none compaction replaces previous summaries instead of stacking them. Read the handoff, verify HEAD and external state, then continue from Next step without asking the user to restate the task.
Idle reset
At the last actionable settle boundary, if context is large and work remains pending (jobs, watches or subagents), request a warm-cache handoff. Writing it marks it pending: non-handoff tools are blocked until the same turn_end commits retain-none compaction and automatically continues in the same session. This uses the existing handoff_committed event tagged with source: "idle" and does not wait for idleMinutes; notifications or new runs after that boundary see the reset context. Idle commits do not consume maxHandoffsPerSession or loop limits, including after session restoration; budget and hard commits still count as before. No further idle handoff is requested while a handoff is pending or a stored snapshot remains valid. The idle-input recovery path still awaits compaction before sending a new prompt after idleMinutes when a valid stored handoff and eligible history remain. Skip small/already-compacted history; tolerate pi's Nothing to compact error and pass the prompt through unchanged. Actual non-handoff tool activity and externally started runs invalidate old stored handoffs; blocked calls cannot make a snapshot stale. Cancellation, Nothing to compact and Already compacted are benign in both the hook and callback paths. Transient failures retry only at the next eligible input/automatic compaction boundary, at most twice; a third failure or a persistent owned/automatic error arms fallback. Unowned manual errors are ignored. Successful compaction or a mode/guard change disarms compaction-failure fallback. An idle preview without a prepared handoff is marked requiresHandoff: true; this records the missing prerequisite, not an actual compaction request.
Overflow backstop
In enforce mode the package supplies a still-valid handoff, or a short, bounded mechanical summary of recent user requests plus instructions to re-establish state from files/git. The emergency summary needs neither writable handoff storage nor automatic metadata. Enforce mode never delegates to pi's default summarizer; backstop errors cancel rather than fall through. Inactive modes leave native behavior alone except for the bounded provider overflow recovery described above.
To restore automatic overflow recovery, enable pi compaction and choose model-specific reserves. Example for a 1,000,000-token window with main hard limit 600,000:
{
"compaction": {
"enabled": true,
"keepRecentTokens": 20000,
"modelOverrides": {
"provider/model-id": { "reserveTokens": 380000, "keepRecentTokens": 20000 }
}
}
}
This triggers above 620,000 (window - reserveTokens). Use your actual model id/window and choose reserveTokens = window - (hard + safetyMargin), with positive reserve and adequate output space. Per-model pi settings cannot express distinct main/child reserves. Do not enable automatic compaction in uninstrumented live processes; they could invoke the default summarizer before this hook exists.
Optional resume checks
Set a trusted operator command with PI_RESUME_CHECK='bash /absolute/path/resume-check.sh', or configure exact session names in context-budget.json:
{ "resumeChecks": { "coordinator": "bash /absolute/path/resume-check.sh" } }
The nonempty env value wins, then the current Pi session name is looked up in the map. With neither source, this is completely off. In enforce mode only (respecting cwd restrictions and guard-off, and skipping subagent sessions), bash -c runs in the session cwd immediately before a handoff is written, under ## Resume check, and again after a committed handoff context reset, before the first resumed provider call. Fresh results are injected into that call's context and retained there for subsequent calls until the next reset; the command runs once per boundary, not once per tool. The command inherits the process environment; the extension never sets identity variables globally. Only configure commands you trust (prefer read-only checks).
Combined stdout/stderr is capped so the result, command label and exit status fit within 4 KiB. Nonzero exit, spawn error, truncation and timeout are visible, never a reason to abort the handoff/reset. A 30-second timeout kills the process group, then allows at most one second for output to drain before closing the pipes and returning a timed-out result. Direct child exit also starts a one-second drain limit, so inherited pipes cannot hang the check. Escaped descendants may outlive the check; commands should not daemonize/escape that group. These observations complement, not replace, verification of external state.
pi-session wrapper
The npm package includes a pi-session binary. A pi-managed npm install normally places package binaries under <agentDir>/npm/node_modules/.bin; add that directory to PATH or invoke its binary explicitly. Alternatively install the wrapper on your normal npm PATH:
npm install -g --omit=peer @woksin/pi-context-budget
pi-session --model provider/model-id -- @/absolute/launch.md "initial request"
The extension must also be loaded in pi (via the pi package installation above). An alias is optional; preserve the real pi executable to avoid recursion:
export PI_SESSION_PI="$(command -v pi)"
alias pi=pi-session
Initial arguments are preserved (the wrapper's -- separator is removed). After exit 0 + a valid marker, start a fresh session in the same cwd/terminal with ordinary CLI options, optional @<launchPrompt> and continue from <handoff>. Old messages and resume/session selectors are not replayed. No eval or terminal automation. This continuation path targets terminal/print sessions; RPC clients must manage protocol-driven reconnection themselves (pi RPC rejects @file arguments).
| Environment | Purpose |
|---|---|
PI_SESSION_PI | Real pi executable, default pi |
PI_SESSION_MARKER_DIR | Marker directory; default <PI_CODING_AGENT_DIR or standard agent dir>/relaunch |
PI_SESSION_MAX_RELAUNCHES_PER_HOUR | Rolling-hour limit per wrapper invocation, default 5 |
PI_RELAUNCH_MARKER, PI_SESSION_WRAPPER, PI_SESSION_WRAPPER_PID, PI_SESSION_LAUNCH_ID | Set by wrapper; ownership requires the current PID, exact nonce-bearing marker filename and the primary hosting identity. Do not forge these. |
Markers are <pid>-<random-launch-nonce>.json with cwd, nullable launchPrompt, handoff, nullable sessionFile. Descendant processes inherit the environment but fail the PID check; in-process SDK children fail the hosting check. Fresh nonces prevent retained markers from being mistaken for a later launch after PID reuse. Invalid markers, provider/non-zero exits or limit exhaustion stop without relaunch and retain evidence. Custom value-taking extension options should use --flag=value; built-in value-taking flags are parsed explicitly.
SIGTERM is not an automatic recovery authorization. A signal exit is commonly 143; the zero-exit contract intentionally refuses to relaunch it. Deliberate crash recovery requires inspecting the marker and starting a new wrapper after verifying the old process is gone. Relaunch tears down jobs/subagents and changes session-id claims.
Duplicate back-off and optional state integrations
A new handoff is refused with a tool error and retry after <time> for 15 minutes after the previous handoff when repository HEAD is unchanged and narrative similarity is > 0.9. Similarity is token-set Jaccard (intersection/union) over lowercase Unicode words in goal + facts + next_step, ignoring word order and punctuation. Changed HEAD, sufficiently changed narrative or expiry permits another handoff. Unknown HEAD cannot establish unchanged state. Forced handoffs (handoff threshold or any fallback, including hard limit and compaction failure) always bypass this check; back-off applies only to voluntary/idle handoffs. The comparison metadata persists in tool results and survives session restoration.
Queued notifications and follow-ups never postpone a pending handoff's turn-boundary reset; Pi retains and delivers its queue after the reset.
Optional pi-questions integration reads $PI_QUESTIONS_HOME or <agent dir>/user-questions, without writing anything. Only the newest 200 item directories by modification time are scanned. The latest item revision contributes Pending questions lines for this session's open items only: id | status | title, at most 20 lines of 200 characters. Missing/unreadable stores and corrupt items are silently omitted.
The first resumed provider call compares recorded jobs/watches with the live pi-jobs registry. A Watch check block lists missing work as id | label | full command so it can be re-armed; no block appears when all recorded work is running or the registry is absent/unreadable. Full commands are retained in handoff metadata even when the display line was shortened. This is an observation, not automatic job execution.
Telemetry and integration limits
- Atomic status:
getAgentDir()/context-budget/status/<sessionId>.json(cwd, model, main/child role, tokens, floor, thresholds, last handoff path/time, count, effective/configured mode, policy phase/action, projection flag, fallback and wrapper ownership). - Event logs:
getAgentDir()/context-budget/events.jsonl(crossings, blocks, handoffs, idle/backstop/fallback,would_*and errors, excludingturn) andturns.jsonl(per-turn token/phase samples).PI_CONTEXT_BUDGET_STATE_DIRredirects status and both logs. - Each log rotates before the next append once it reaches 20 MiB (20 × 1024 × 1024 bytes). Archives are
<base>-<UTC stamp>.jsonl, for exampleevents-20260102T030405006Z.jsonl; a rotation within the same millisecond adds a counter (-001,-002, …). Retention keeps the newest 5 event archives / 2 turn archives by stamp and counter, plus each live file: normally about 120 MiB / 60 MiB total. Readevents*.jsonl/turns*.jsonlfor all retained history. - On supported POSIX filesystems, concurrent appends preserve complete JSON lines without duplication; rotation itself loses no lines. An append opened just before a rename lands in the archive. Only archive pruning discards history. A contended lock skips rotation until a later append, so the cap can be exceeded; stale locks older than 10 seconds are rechecked before removal. Rotation failures also defer rotation without blocking appends.
- Existing oversized
events.jsonlfiles rotate on the next append, preserving their old turn events in that archive until it is pruned after 5 later rotations (or manually deleted). Such legacy archives can temporarily exceed the normal size budget. - Status files survive exit: check PID/session identity before assuming liveness. At session start, best-effort pruning removes status records strictly older than 7 days only when their recorded PID is confirmed dead (
ESRCH). Live/unknown PIDs (includingEPERM), missing/invalid PIDs, unreadable/corrupt records, the current session and records with retained relaunch markers are kept. Marker lookup failures also keep the record; handoffs and session files are never pruned. - Status pruning is mkdir-lock protected and throttled to once per 24 hours by
status/.last-prune. Each pass examines at most 5000 records or runs for about 200 ms (individual filesystem operations can overrun); a saved filename cursor lets later passes continue, then wrap. A contended lock defers pruning; stale locks older than 10 seconds are identity-rechecked before removal. Each pass logs one best-effortstatus_prunedevent with counts. Pruning failures never break startup. Hook failures log and continue; telemetry write failures must not prevent a handoff commit. - Read committed session JSONL entries (
type: "compaction",details.kind: "handoff") rather than expectingsession_compactfor turn-end drafts. A file write/commit-intent event alone is not proof that pi appended the boundary. - Optional integrations use the
pi-jobs.liveManagersandpi-subagents:managerSymbol registries, and<agentDir>/issue-work/registry.jsonl. Missing data is labelled unavailable. Job managers are process-wide and can include sibling sessions. WhenlistAgentsis unavailable, the extension discovers ids in this session’s$TMPDIR/pi-subagents-<uid>/<cwd-slug>/<sessionId>/tasks/*.outputdirectory and calls the live registry’sgetRecordfor each id, combined with known tool-result ids. Only authoritative running/queued records render, asid | status | description; stale files do not resurrect finished work. No transcript content is trusted as status. An inaccessible task directory/registry or pending work with no discoverable ids is labelled unavailable; an empty inventory is not an error. Job managers remain process-wide, while task-directory discovery is session-scoped. - In-process subagents inherit the root environment but do not own its wrapper; current child sessions have no shutdown binding. They never write the parent's marker. Hard-limit handoffs can still recover in-process; the cap is advisory without a wrapper and the loop guard self-clears on the next successful tool call; only unrecoverable fallback requires parent/operator intervention.
- No automatic handoff deletion. Files may contain sensitive user constraints, paths and task state; keep them private.
Lifecycle model
src/core.ts contains a pure immutable transition function with named idle, soft-notified, handoff-required, handoff-pending-commit, compacting and fallback-armed states. Pi hooks only translate observations and execute its explicit effects. Inactive threshold policy emits telemetry only; the separate, bounded provider overflow recovery layer is the exception in observe/guard-off. Attempt ids deduplicate pi's failure hook followed by compact's onError, and success/mode changes clear failure recovery. Table-driven tests cover the transition matrix; offline real-pi tests cover internal continuations, native compaction pass-through, cancellation, no-op failures and SDK hosting.
Limits and development
Retain-none compaction discards verbatim history. Structured fields reduce omissions but cannot guarantee losslessness; mechanical fallback is weaker still. Real-scale handoff quality, complete pending-work inventory and TUI idle reset require controlled trials. Print-mode checks do not establish every TUI behavior. Small-window budgets must be configured explicitly.
npm ci --legacy-peer-deps --ignore-scripts
npm install --no-save --no-package-lock --legacy-peer-deps --ignore-scripts @earendil-works/pi-coding-agent@1.2.0
npm run typecheck
npm test
npm run check:shell
npm pack --dry-run
Unit tests use node:test, fake extension contexts and a fake pi executable; they make no provider/network calls. Runtime smoke tests resolve a local peer, then pi's standard user installation roots; PI_RUNTIME_DIR overrides the package root. If no runtime exists, that smoke test skips clearly (CI requires it). Other tests need no runtime. Typechecking does require the host peer.
CI runs Node 22/24, installs the tested pi runtime, typechecks, tests, checks Bash syntax and inspects the npm tarball. To release, bump package.json and lockfile, commit, and publish a GitHub release tagged v<version>. The release workflow reruns CI and uses npm trusted publishing with provenance; configure the npm trusted publisher for this repository, publish.yml and the npm environment. Creating a release is the publication trigger; a normal push is not.
MIT licensed.
Intent-memory storage core (inert)
src/memory/store.ts exports the harness-neutral MemoryStoreCore and FileMemoryStore. Nothing imports this store into the extension yet: existing flags-off behavior is unchanged. Projection, span resolution, request/answer lifecycle hooks and UI authorisation are separate slices; unsupported raw lifecycle events are rejected until their validators exist.
An explicitly constructed store uses <agentDir>/memory/ (default ~/.pi/agent/memory/); PI_MEMORY_HOME overrides this default, and explicit options.home takes precedence over both. Only local filesystems are supported: do not use NFS/SMB homes, where O_APPEND does not guarantee atomic appends. It creates private directories (0700) for journal/<session>.jsonl, answers/<session>.jsonl, blobs/<sha256>.txt, and an append-only events.jsonl (files 0600). Journal bodies over 64 KiB use verified, atomically renamed blobs. Callers must supply already-redacted journal text. Search requires a caller-provided redactor and withholds results when it is absent or fails.
Records carry CRC32 of their JSON body without crc. Each append is one write of "\n" + json + "\n", followed by fsync before reporting success, so a torn tail cannot consume the next record. Readers ignore blank, incomplete, unparsable and CRC-bad lines without rewriting; health() reports blank, torn-tail, corrupt and rejected-event counts. Events are folded by byte position, not UUID order. Writes pre-validate, append, re-fold and report applied, rejected, or conflict with the winning event id.
Directive authority is checked again at fold time against journal provenance. Without an injected EligibilityCheck, automatic directives remain proposed; a valid human /directive source or human UI confirmation can activate them. Orders remain proposed until a human TUI confirmation; sender labels are descriptive, not authenticated. readFolded(), paging and the capability-labelled core conformance suite provide the seam for later projections and alternative backends.
Intent-memory projection (inert)
withProjection(core) in src/memory/project.ts adds project({scopes, session, budgets?}) and listMessages({unresolvedOnly: true, ...}) to any MemoryStoreCore; session is the journal session id. It is not wired into the extension or the existing request/answer renderer. Constructing the wrapper does not write or read the store.
Projection returns text, byte-bounded sections, per-record entries labelled inline, pointer or index-only, tier counts, and a structured index. Defaults are 20 KiB total: 8 KiB items, 8 KiB unresolved human messages in the selected session, 4 KiB index, with a shared 3 KiB pointer sub-budget. Headings and metadata count toward these UTF-8 byte limits. Text and metadata values are single-line JSON strings (including escaped Unicode line separators) before byte allocation; structured outputs retain the original values. Optional budgets can reduce these caps; the mandatory index needs at least 512 bytes and total must cover it (invalid_projection_budget otherwise). Inline selection prefers more-specific scopes, then recency; display order is stable, general-to-specific then id, within the prescribed sections. Proposed directives have a separate, non-binding heading.
Every scoped item (including retired items) and every selected human message is counted; resolved messages and retired items are index-only. Large indexes coarsen to scope totals, then overall totals; complete structured counts remain available, and memory_list scope=<..> cursor=<..> / recall ... describe the future tool paging seam, not tools registered by this slice. More than 50 active items in a scope produces a hygiene warning. Withheld messages use reason-bearing pointers without fabricated ranges when space permits, never invented text. Multi-gap message pointers identify and excerpt the first uncovered range, plus a count of additional gaps, rather than claiming a range across resolved text.
src/memory/spans.ts derives dispositions solely from accepted folded events: directive adds cover only their source spans, explicit classifications union coverage, and whitespace needs no classification. Any uncovered remainder repeats on every projection until resolved, independently of boundaries. Explicit whole: "none" dispositions retain their reasons in the index. Filtered message paging applies resolution before pagination; callers can still page or search resolved messages through the core.
Intent-memory origin gate (inert)
src/memory/origin.ts exports the pure classifyOrigin(input, context) gate. It is pure and does not write memory; the flag-gated journal hook (below) is its only caller. S3b must check enabled && journal before any store or journal access, supply trusted adapter facts, and skip writes when journal is false. Input text, tool arguments and model claims must never supply these facts.
The adapter supplies hasUI, the host's subagent bit, { sessionId, primarySessionId }, and firstInput (count every input, including injected inputs). Either child signal skips journaling, regardless of source/UI. Missing identity, host bit or input position cannot grant human provenance. originEvidence records decisions without copying prompt bodies.
For the first input, supply initialPrompt/relaunchPrompt as the exact assembled input, not merely an argv token or the contents of launchPrompt. pi combines @file text (including its file wrapper) and the positional continuation; bin/pi-session supplies both. Each value is string | null: null explicitly verifies that no such launch prompt exists; undefined leaves it unverified. Either unverified value makes the first input unattended (launch-unverified), even if the other value matches. Exact matches are launch traffic; non-exact input containing a known launch text after trimming and collapsing whitespace is unattended (launch-near-match). These values are not instructions to read arbitrary paths. Later identical text is not automatically launch traffic.
S3b must run the gate before every other input transform, using untransformed input for launch and synthetic comparisons, not just before skill/template expansion. pi's input runner lets earlier extensions replace text while leaving source="interactive" unchanged; inspecting already-transformed text cannot establish its original provenance.
Child exclusion runs first. The ordered RULES table then chooses its first match:
| Rule | Decision |
|---|---|
| Extension | injected; takes precedence over launch matches |
| Synthetic | injected for known synthetic text |
| Unattended | non-interactive, unknown source or no UI |
| Launch | first-input metadata verification, exact match or normalized near-match |
| Position | unattended when input position is unverified |
| Main | unattended unless main-session identity is verified |
| Human | verified main input after every exclusion |
Unknown sources always default to unattended. source="interactive" alone is insufficient: installed subagent runAgent/resumeAgent and structured retries call session.prompt(text) with no source option. source="rpc" is unattended even when the host exposes a UI bridge. Sender labels are descriptive only, never coordinator authority; forged orchestration headers are injected rather than human. Residual risk: unknown in-process senders calling session.prompt() without a source default to interactive and can classify as human when the other main/UI/launch checks pass. This gate cannot distinguish them from terminal input; adapters must label or exclude those senders.
src/memory/synthetic.ts centralizes anchored provider-continue, settle/idle recovery, handoff/structured retry, overflow-continue, task-notification and orchestration-header recognition. Add new user-role synthetic senders here with hostile cases. Custom job/question/subagent completion messages bypass input; future journal code must not reinterpret those as human input.
Offline origin matrix
CI runs test/memory-origin*.test.ts against its pinned pi peer. SDK tests use real input/queue/resource-expansion paths with a stub UI, and explicitly open the SDK run boundary for offline streaming queue tests. They do not test terminal rendering, real provider streams, or live worker delivery. Representative installed sender texts and source-less child calls are reproduced, not imported from machine-local plugins.
Run the same matrix plus actual installed CLI probes (print, @file plus continuation, RPC), without credentials or paid calls:
node eval/origin-matrix.mjs "$HOME/.local/share/pi-runtime/lib/node_modules/@earendil-works/pi-coding-agent"
| Path | Expected provenance |
|---|---|
| TUI typed / pasted input | human |
| Streaming steer / followUp | human |
| Interactive initial CLI argument / wrapper relaunch text | launch |
| Print/no-UI / RPC / unknown source | unattended |
Orchestration sendUserMessage / provider fallback / settle or retry text | injected |
| Child initial prompt / source-less structured retry | skip journal |
| Job notification / question answer / child completion custom message | no input, no journal call |
| Skill / prompt-template expansion | retain human provenance |
Intent-memory journal (memory.journal, off by default)
With the memory block absent, all memory features are off: no memory directory is created, the store module is never loaded, the tool list and prompt are unchanged. The block lives in context-budget.json. Stage 0 explicitly disables every boolean flag:
{ "memory": { "journal": false, "requests": false, "intent": false, "resume": false, "recall": false,
"scope": { "mode": "only", "names": [] }, "coordinators": [], "trustRpc": false, "retentionDays": 30 } }
The shipped defaults for memory.journal, memory.requests, memory.intent, memory.resume, memory.recall and memory.trustRpc are all false. memory.scope defaults to {"mode":"only","names":[]} (nobody), and memory.coordinators to [] (no trusted coordinators). memory.retentionDays defaults to 30 and must be an integer from 1 to 3650 (anything else is an invalid value and turns the whole block off). memory.answers and memory.answerPolicy also default to false when omitted; leave them omitted in stage 0, since explicit false is not a valid enum value. When requests are enabled, their effective behaviors are "final" and "carry"; opt into "all" or "defer" explicitly.
Fail closed. A missing block, a missing flag, an invalid value or a parse error means false; the reason is logged once as memory_config_invalid in the event log. scope.mode: "only" with empty names is nobody, names match the session name, and everyone must be spelled {"mode":"all"}. requests needs journal. The file is re-read on every input and at session start, so journal on/off applies without a restart. Tools are registered at load only when a tool-bearing flag (intent, recall) is true then; each call re-checks flags and answers memory disabled when off, so rollback is immediate, while enabling a tool for an already-running session needs a restart (registerMemoryTool).
Rollback (any stage). Set requests:false first: carrier injection and answer/boundary/closure writes stop on the next input, and request-enabled handoff bytes return to baseline. Then disable intent, resume, recall, and finally journal. requests:true with journal:false parses as requests:false with a logged reason. Keep the block; an empty scope.names list means nobody, never everyone. For code rollback, use the previous tag. Store files remain append-only and inert when disabled.
Journal. Each input that the origin gate accepts (human, launch, unattended, injected; child sessions skipped) is appended to <agentDir>/memory/journal/<sessionId>.jsonl (dirs 0700, files 0600, PI_MEMORY_HOME overrides). Bodies over 64 KiB keep head 2 KiB + tail 1 KiB inline and the whole redacted body in blobs/. The hook never throws into pi: failures are logged as journal_error (message only, never prompt text) and swallowed. The first input is human only when argv, TTY and launcher indicators verify that no initial/relaunch prompt exists; otherwise it remains unattended (launch-unverified). Later typed input is human.
Requests and answers (memory.requests, needs memory.journal; memory.answers: "final" default or "all"). A human prompt, or a non-relaunch launch prompt, opens a request. Every assistant message is captured (redacted) at message_end, before any boundary effect, into answers/<sessionId>.jsonl; a final stop answer durably closes the requests that were open when it started (request_close, system actor). Handoff, backstop, idle, overflow and manual compaction and aborts append a boundary event naming the open requests (inline up to 32 ids, else a content-addressed blob). Write failures degrade loudly (memory_degraded event) and never block pi; the request stays open. Launch facts are verified narrowly from argv/TTY and the authoritative bin/pi-session: positional or @file prompts, unknown flags, piped stdin, and unknown PI_SESSION_/PI_RELAUNCH_ markers are unverified. A prompt-free argv on a TTY lets plain pi journal its first typed input as human. pi-session exports the narrow PI_SESSION_PROMPT_FREE=1 fact only for its first prompt-free TTY invocation; successors explicitly clear it. That fact permits only the wrapper's known markers, never unknown markers or an actual launch/relaunch prompt.
Reset delivery (memory.requests). Handoffs carry the oldest open requests before volatile state, with journal id pointers/counts when text does not fit, and the last redacted answer (about 4 KiB head plus 1.5 KiB tail, with an answer-file pointer). This separate block is capped at 12 KiB (4 KiB in emergency summaries); the narrative retains its existing cap. A same-run last answer asks for a short recap because the user's screen may no longer show it. The block replaces the older user-message excerpt and ends with an instruction to answer the open requests, not merely execute the handoff. Each request/answer item is quoted inside a fresh, per-render nonce fence. Harness-written handoff/backstop/emergency summaries retain their block. Plan deviation (Option A): native manual/automatic compaction is untouched: pi 1.2.0's context event (extension types ContextEvent, before every LLM call) appends a fresh, non-persisted message after a recorded reset. Only open request IDs and the last-answer ID captured by the latest reset are eligible; prompts/answers already visible after that cutoff are not re-injected, and unresolved cutoff membership is not guessed. Harness-written summaries already embed the block and get no duplicate carrier. This projection reads only the redacted durable store; native model routing, authentication, headers, environment, retry policy and summaries remain native. It covers native overflow and the package's mechanical overflow fallback in observe, guard-off and enforce modes without overriding summaries, interpreting marker text, or calling sendMessage. Eligible open tasks project on each request; a same-run answer's recap hint is acknowledged only after successful assistant completion (stop, toolUse or length), not on projection, error or abort. Acknowledgement is process/session-local: restart or rebind may recap again. Contract §10.4 deviation: journal and answer files remain durable, but this continuity block has no separately persisted extension message or TUI rendering; Option A supplies it ephemerally to the provider only. All of this is absent when requests are disabled, out of scope, in subagents or in sessions with no active tools.
TUI live-check status: package in-place (retain-none) commit — pending trial; native streaming overflow — pending trial. In the prior b43b712 manual retained-tail /compact trial, the pre-boundary answer stayed visible and the next response recapped it. That is not a keep/drop observation for either pending origin, nor a live verification of the new request-time projection. Runtime integration tests verify provider context, not terminal rendering.
memory.answerPolicy accepts "carry" (the default behavior) or "defer". Carry leaves answer-settle handoff enforcement unchanged. Defer lets a durable final answer settle below the hard ceiling without an extra handoff/steer turn; a required handoff is requested at the start of the next human turn. Hard-ceiling and provider-failure recovery remain enforced. Invalid policies fail the entire memory block closed, as before.
Answer records are strictly below 8 KiB including JSON escaping and CRC metadata; larger redacted bodies are written atomically to verified blobs before the referencing record. Model metadata is redacted too; degradation logs use fixed codes, not exception text. The 50 MiB session cap includes the answer log and distinct referenced body/id-set blobs: once reached, every persistence path drops new interims (including boundary flushes), while finals remain durable. RequestsHook.health().interimsDropped reports drops. Explicit agent abandonment requires a later human journal source; readSessionState().agentAbandonments lists these indexed events and the fold exposes requests:abandoned:agent counts. Unresolved id-set blobs retain counts and never guess membership.
Redaction (src/memory/redact.ts). Pass 1 is <agentDir>/lib/secret-mask.ts scan() when present (loaded with a dynamic import). Pass 2 always runs a built-in set (GitHub tokens, AWS keys, sk-/sk_live_, Slack, JWT, Bearer, PEM blocks, URL credentials, NAME_(SECRET|TOKEN|PASSWORD|KEY)=value, long hex/base64 runs on key-like lines) and is the only pass when the module is absent. A scanner that throws, returns an unrecognised shape or skipped, a module that is present but unusable, or a body over 2 MiB makes the entry withheld (text: null, withheld: "redactor_failed" | "too_large", hash of the empty string). Raw text is never stored or hashed. Pass 2 is intentionally broad and may over-redact.
The origin gate runs inside the extension's input handler, so it sees the text after any extension that registered earlier; it cannot see the untransformed input.
Intent-memory tools (memory.intent, off by default)
memory.intent: true registers memory_add, memory_retire, memory_classify and memory_list for an in-scope main session. Set memory.journal: true to capture source messages for citation. No intent tools or commands register when disabled or in subagents; enabling after load requires a restart. Disabling live makes every registered intent tool return memory disabled. Defaults are unchanged.
Directive additions cite a journal id and exact character span. Rule version 1 refuses automatic eligibility for the whole message if it contains any run of three or more backticks or tildes anywhere, or an HTML <pre/<code prefix (case-insensitive). Additional per-span checks allow only human spans of at most 600 characters outside inline code, blockquotes (including nested/list and lazy-continuation forms), indented code, JSON/log-looking regions and the middle of a paste over 4 KiB (only the first/last 1 KiB can qualify). HTML <blockquote>/<q> contents conservatively remain quoted through the rest of the message. Log detection conservatively checks five neighboring lines for timestamps, stack frames, JSON keys/braces or lines with two key=value fields; at least half looking structured makes the span ineligible. Other readable human or unattended/launch spans stay proposed, not binding; injected messages cannot become user directives. Orders cite injected messages but always remain proposed until a human confirms them through /memory confirm <id> in the TUI. memory.coordinators is parsed but reserved until an authenticated transport exists; sender labels never grant authority. memory.trustRpc is also reserved and does not affect origin classification or authority. The store rechecks provenance, quotes and authority on fold; model-supplied actor/origin/authority fields are ignored. Quotes must match the source slice exactly, including Unicode whitespace; stored text comes from that slice. Quotes exceeding the item-size cap are refused rather than truncated: cite a shorter exact span. After a human retires or rejects an item, overlapping spans from that same journal entry remain proposed on automatic re-addition. Command-generated journal entries are not automatic directive sources except for the complete /directive text; rejection journals only the command and item id.
Journal retention. Per-session journal files (<memory home>/journal/<sessionId>.jsonl) whose modification time is older than memory.retentionDays (default 30) are deleted, at most once a day in a bounded pass at session start (200 ms, 5000 files, resuming alphabetically; stamp <memory home>/.journal-prune), and on demand with /memory purge (no time cap, same 5000-file cap, reports capped). Nothing runs unless memory.journal is on for the session; with the block absent or journal off nothing is created or touched.
Items and requests live in events.jsonl, but every event is re-validated on fold against the journal entries it cites, so retention follows two rules. Evidence pins files: an expired file is a candidate only if no event in events.jsonl of any kind or item state (add, confirm, retire, reject, withdraw, supersede, request close, command sources) cites a message id it contains. Retired, rejected and withdrawn items therefore keep their source files; that is deliberate, because deleting them would change the fold (a retired item could come back, or a human withdrawal stop blocking an overlapping agent directive). Verification fold: before anything is deleted the projection is folded twice in memory, with the full journal and with the candidate files hidden, and every item and event result must be identical; on any difference or error nothing is deleted and the pass reports kept all: verification mismatch. The events are re-read and each file is re-checked (size, mtime) immediately before it is deleted. Also kept: the current session's file, and (only when memory.requests is on) any session with an open request. Anything not provably dead is kept: unreadable or oversized (over 8 MiB) files, a failing fold, a corrupt events.jsonl, a file that changed while being examined. Only regular files named <sessionId>.jsonl directly in the journal directory are candidates; other names, directories and symlinks are never touched.
Caveats: items that are done, superseded, withdrawn or rejected lose their evidence once their journal ages out, so their add/retire events are rejected on fold (health().rejectedEvents can rise; /memory list simply omits them). Old unanswered requests pin their file while requests are on; close or abandon them. Answer records (answers/) and blobs are not pruned yet. Restored or copied journals with fresh mtimes are kept longer. A stray directory or symlink with a journal-style name in journal/ makes the store's fold fail, which keeps everything.
Human commands:
/directive <text>journals and records a session-scoped directive./memory confirm <id>activates a proposed order, or a proposed directive from a human source./memory reject <id>rejects only a proposed directive or order (never an active item)./memory list [id]reads items without raising authority;memory_listsupports filters and cursor paging./memory purge [--days N] [--dry-run]prunes aged journal files now (see Journal retention). No confirmation dialog; use--dry-runfirst to see what would go. It needsmemory.journalon for the session and acts on the whole memory home, not just this session's scope.
Directives, confirmation and rejection require an affirmative interactive TUI dialog showing the directive and source id, even if command text came from an extension. RPC/print modes, cancellation, a missing UI, exceptions and a 30-second timeout refuse without authorising anything. No model tool can confirm or reject. Fold trusts confirmation events in the local log file as authoritative. Its 0600 permissions protect against other operating-system users, not edits by the same user; the file does not provide cryptographic proof of a TUI confirmation. An unattended/launch source cannot be promoted by confirmation; use /directive to make a new, explicitly human-authorised instruction instead.
Resume packet (memory.resume, default false). At a handoff commit, append a separate reference-material section to the persisted compaction summary (or the handoff file for wrapper relaunch). It is built once, never per provider call; reloading the session reuses the same bytes. HEAD/dirty, claims and live jobs/subagents carry commit observation times, not restart-time guarantees. Unavailable facts—including unread inter-session messages, which the collectors do not expose—are unknown. For every non-subagent session with no matching named resumeChecks or PI_RESUME_CHECK command, the packet includes a deterministic memory resume check of at most 1 KiB: counts of visible active directives, unresolved chain messages and proposed items, the newest visible retirement (item id and time), and a memory_list pointer. Unread inter-session messages are unknown (no collector); no inter-session message collector is added. A configured command takes precedence and suppresses this built-in section. A missing memory store is not created; an unavailable store or insufficient packet space omits only this section. The existing resume-check injection is unchanged.
files_to_read excerpts must be absolute, regular text files without traversal or symlink escapes, contained by the current repository root, known repositories’ .ai-work, or the agent directory. Secret-ish names (.env*, *.pem, id_*, auth.json), binary/invalid UTF-8, fence runs, and files above the redactor’s 2 MiB scan cap are withheld with notes. Each accepted file records its name, mtime, SHA prefix and whether its mtime is newer than the handoff. Both redaction passes run before head/tail clipping, and private filesystem paths use recall’s masking. Metadata and excerpts are single-line encoded, never instructions. Encoded file sections are capped at 8 KiB each; the complete packet is capped at 24 KiB, including up to 3 KiB of facts, and further reduced or omitted to preserve the existing 52 KiB handoff limit. With the flag off, handoff bytes and resume checks are unchanged.
Recall (memory.recall, default false). recall({query, scope, limit:1..20, origin:"human"|"any"}) searches literal, case-insensitive history, including pre-compaction transcript entries. Query needs at least 3 characters; defaults are session, 10 hits, and human. Human means verified journal provenance: old transcript user messages lack that evidence and are labelled unattended (known injections retain their sender label), available with origin:"any" alongside assistant/tool output. Session reads only its own journal/transcript. The intermediate scope in the tool schema searches session ids in the chainIdentity handoff chain, not a shared session name; without prior chain identity it is session-only. The all scope spans every repo's journal and transcripts under the configured memory home and the agent/current session directories, including child transcripts; it is not restricted to the current repo. Outside-root symlinks are not followed. Every hit is redacted with both journal passes, including the external scanner when installed, before matching the query against the redacted text; masked secrets cannot be queried by prefix. Absolute filesystem paths are replaced with [REDACTED:path], including in metadata; a redaction failure withholds that hit. Excerpts and metadata are single-line encoded historical data, never instructions. Output is capped at 16 KiB, snippets at 2 KiB per field; reads stream with bounded lines and skip files over 200 MiB with a note. Each call scans at most 256 files (including blobs), reads at most 32 MiB total, and visits at most 4096 directory entries; caps add a short note. Disallowed session headers stop that file immediately, and cancellation stops further reads and traversal. Recall never writes memory. Tools register only if enabled at extension load and after main-session binding; enabling later needs a restart, while disabling returns memory disabled immediately. No recall tool is registered in child sessions.
At mandatory handoff, intent-enabled main sessions may make at most 12 recovery calls per window across these four tools and recall. Those calls preserve stored/pending handoffs and do not consume .ai-work grace; call 13 blocks and instructs context_handoff. Other tools retain the existing handoff policy. The budget resets after compaction; non-idle recovery steering reminds the agent to classify unresolved messages before handing off. Unavailable or degraded handoff paths retain their prior behavior without a memory recovery limit.
With memory.intent on, normal handoffs and mechanical emergency summaries place harness-rendered intent immediately after the goal. If memory.requests is also on, its request/answer delivery block comes first. Intent has a separate 20 KiB budget (including a <=4 KiB index); requests plus intent stay within 32 KiB and do not consume the existing 52 KiB narrative budget. Full, pointer-only and index-only tiers preserve bounded output. Unclassified human-message spans replace legacy “since previous handoff” replay and repeat across compactions/relaunches until classified. Proven directives and coordinator orders receive distinct headers; proposed items are explicitly non-binding. The compatible model user_constraints field is labelled Agent-reported constraints (not verified against user messages) with a lint warning.
With memory.intent enabled, decided pi-questions items are also read from <PI_QUESTIONS_HOME || agentDir/user-questions>/items/Q-<n>/r########.json (latest revision only), without importing or writing to that package. Under User decisions (question store), each decision is single-line encoded as Q-<n> <title> -> <option text> ("<user words>"), bounded to about 300 UTF-8 bytes; the question body is never included. These use the same inline/pointer/index-only budgets as other memory items; agent decisions retain Agent decisions. Stored memory takes precedence on duplicate source type and source.ref. A recorded repository retains repo scope: a matching Owner/Name or repository alias maps to the current canonical repository identity. For repo: null, the recorded concurrent-worker grouping id on asker selects orch:<groupId>, otherwise asker.sessionId selects that session. Without either, the question is not rendered into handoffs; it remains available in the question store itself (user_questions), not through memory_list or recall. Question items are never global; project and cc do not grant visibility. Other repositories and unrelated worker groups/sessions are excluded from selection and counted under other scopes; a missing repo field is an unknown shape, not global. The tolerant reader counts ignored, malformed, unknown and limited items, reads at most 128 revision files of 64 KiB each in descending numeric Q-number order, caps each directory enumeration at 4096 entries, and ignores symlinks (without falling back to stale revisions). Turning intent off performs no question-store reads.
Pi-questions also records null when git fails, so repo-less questions rely on asker provenance rather than becoming global. Without an origin, a bare repository basename can collide with another repository's name.
When ctx.hasUI is explicitly false, the bounded last-answer block and its source pointer remain, but screen-visibility wording and the recap instruction are omitted. Missing or unknown UI availability keeps the existing wording.
The harness selects global *, the current repository's normalised origin URL and absolute root, and every session in the handoff chain. Task items are selected individually by source journal entries belonging to that chain, never by a shared task key. The concurrent-worker grouping scope uses orch:<PI_ORCH_ID> when that launcher environment variable is nonempty, never a session name. Otherwise adds use chain:<laneRoot>. The server atomically saves the inherited root (or the session's own id) in each committed/backstopped handoff's JSON sidecar, including wrapper relaunches. Inheritance trusts only compaction/state handoff paths or the last continue from … line of the first user message; earlier launch-prompt lines are ignored. Both handoff and sidecar must resolve inside the server-selected .ai-work/handoffs directory, without symlink escape, and metadata must parse cleanly; otherwise the session uses its own id. Fallback visibility includes the persisted root and ids from trusted ancestry only. memory_add resolves grouping keys server-side and ignores caller-supplied grouping keys. Items belonging to another group cannot be listed, retired, classified, authorised or superseded by id; lists fill visible pages before returning. Global and repository items remain shared across names and chains. Other items are counted in the index and remain pageable with memory_list. memory_add normalises matching current-repository aliases to the origin URL and reports the selected scope keys; it still accepts unrelated keys. Default SSH/HTTPS ports do not change origin identity. If projection fails, the degraded memory block includes bounded legacy userMessagesSince replay, encoded on one line so fallback text cannot forge binding headers. Turning memory.intent off preserves the legacy handoff layout and replay even if a store exists.
Related projects
- pi-setup: my full pi agent setup (rules, agents, extensions, installer) that ties these together
- pi-jobs: background shell jobs and watches that wake the agent when they finish
- pi-recover:
/recoverpicks up unfinished subagents, workflows and jobs after a crash or usage limit - pi-orch (experimental): repo-owner orchestration with an order bus and batched candidate PRs
License
MIT, see LICENSE.