Plan: trim the context every session is sent

Closes: #1043. Relates to: #953, #904, #629. Branch: refactor/trim-injected-context. Status: Done (2026-12-04) — state-specific tool withholding, messaging-in-use gating, plan-prompt split, and tool-description dedup (#1043)

Context

What the tree says, by reading:

  • A mode with no tools list (auto, manual, yolo) starts a session with unlistedTools(pi.getAllTools()) (packages/pi-modes/mode-controller.ts, exported, synchronous): every registered tool whose exposure is direct or model-only, minus pi’s powershell off Windows, minus tool_search while no deferred tool is registered. onSessionStart(s, ctx) (private, async) stores it in s.unlistedTools. applyTools(s, mode) (private) sets a listed mode’s mode.tools, and on leaving a listed mode puts back the set the session had before it.

  • pi-modes registers yield in every session (packages/pi-modes/subagent-wiring.ts), and its executeYield answers YIELD_NO_PARENT unless the system prompt carries pi-subagents' <active_agent name="…​"/> tag (activeAgentName(systemPrompt) in packages/pi-modes/yield-tool.ts, exported, synchronous). A helper session binds the same extensions, so pi-modes' onSessionStart runs there too. pi-subagents builds the tag into the helper’s prompt in both prompt modes (node_modules/@gotgenes/pi-subagents/src/session/prompts.ts) and installs that prompt as the loader’s systemPromptOverride before bindExtensions fires session_start. pi-subagents passes the agent’s tools: as the session’s allowlist (node_modules/@gotgenes/pi-subagents/src/lifecycle/create-subagent-session.ts), and pi registers in that session the tools the allowlist names. So a helper’s active tools are today the unlisted set of what its allowlist registered, and yield is among them for every packaged agent.

  • exit_plan_mode refuses outside the mode whose id is plan (exitPlanMode in packages/pi-modes/plan-tools.ts). The shipped plan mode lists it in tools (packages/pi-modes/modes.json), pinned by "plan mode can always ask to leave" in packages/pi-modes/test/plan-mode.test.ts. An overlay merges a mode as {…​existing, …​incoming} (mergeModesConfig), so it can replace the list but not remove it.

  • monitor_restore starts again the monitors the restart notice named. The notice is sent at session start by tellLost(pi, branch) and the tool reads toldLost(records); lostMonitors(records) and branchRecords(entries) are beside them (packages/pi-modes/monitor-records.ts, all exported, synchronous). A session with neither lost nor told monitors gets "no monitor a restart ended is waiting to be restored".

  • pi-remote registers five msg_* tools at load, whatever the box holds: createRemote(pi, deps) calls registerMsgTools(pi, state, selfBox) (packages/pi-remote/index.ts, packages/pi-remote/msg-tools.ts). Without a space each refuses ("this box holds no space: the operator grants one from the phone"). pi.setActiveTools ignores names that are not registered (pi docs/extensions.md), so plan’s list may keep naming them.

  • A grant reaches the session that holds the link: BoxSpaces.grant calls changed(), which is Link.spacesChanged() (packages/pi-remote/spaces.ts, packages/pi-remote/link.ts). pi-remote already tells the agent messaging facts as MSG_NOTICE_TYPE messages that start no turn (tellRelabelled in packages/pi-remote/index.ts).

  • packages/pi-guidance/guidance/global.md is 14,249 bytes and reaches every main session and every appending helper. Two of its bullets under # GitLab and plans are for an agent authoring a plan: "A plan carries, before anyone reviews it" (lines 79-88, 681 bytes) and "Plan review is bounded" (lines 89-108, 1,445 bytes). The plan mode’s systemPrompt in modes.json is the gadhs-mode section of every plan-mode turn; plan-mode.test.ts pins that it ends with the four pre-exit checks.

  • Plan’s list names web_enable. pi-web-access switches its loader off in a session it starts with the web tools on, which is every model pi-vertex registers (addsToolsWithoutCheckpoint in node_modules/pi-web-access/tool-activation.ts needs a supportsMidConvoToolChanges-style flag, and packages/pi-vertex sets none), so plan’s list is what switches the loader back on. Where pi-web-access did select its loader, its own before_agent_start handler adds it back when it is missing (same file, lines 161-168).

  • The first system row of a session’s transcript records every declared tool as toolsAdded (pi docs/session-format.md), and tools/consumer-sim.mjs already reads those rows for its helper probe (helperProbeSystemRows).

Decisions for the operator to confirm at approval

  1. The static "outside signal" guidelines stay. The issue lists them as duplicates of the stamp each event carries. They are about 150 characters, and a standing rule beside the per-event stamp is defence in depth against an event read as an instruction.

  2. Messaging tools follow use, not only a held space. They register when the agent dir holds a space, a subscription or a revoked space’s record. A box whose space was revoked keeps them, since msg_subscribe { restore: true } is how its subscriptions come back.

  3. A first grant does not add tools to a running session. They register at the next session start, and the session holding the link is told so once. Registering mid-session was rejected: a tool registered while a listed mode is active is dropped when the mode controller puts back its earlier set.

  4. No worker-scoped guidance for helpers here. It is not in #1043, and it changes what a committing helper is told.

Design

D1. Three tools are withheld from sessions that have no use for them (packages/pi-modes/mode-controller.ts)

  • New exported type and function:

    export interface ToolFacts {
    	/** A helper session: its prompt carries pi-subagents' <active_agent> tag. */
    	helper: boolean;
    	/** The branch holds monitors a restart ended that no restore has started again. */
    	monitorsToRestore: boolean;
    }
    export function withheldTools(facts: ToolFacts): ReadonlySet<string>;

    It returns exit_plan_mode in every case, yield when facts.helper is false, and monitor_restore when facts.monitorsToRestore is false. The three names are constants at the file top.

  • unlistedTools(tools, platform = process.platform, withheld: ReadonlySet<string> = new Set()) drops the names in withheld after its present filters. Its other behaviour is unchanged.

  • A private toolFacts(ctx: Pick<ExtensionContext, "getSystemPrompt" | "sessionManager">): ToolFacts reads helper as activeAgentName(ctx.getSystemPrompt()) !== undefined and monitorsToRestore as lostMonitors(records).length > 0 || toldLost(records).length > 0, with records = branchRecords(ctx.sessionManager.getBranch()). Reading both lists makes the answer the same before and after tellLost appends its told record, whichever session-start handler runs first (T5 covers both record shapes).

  • onSessionStart computes s.unlistedTools = unlistedTools(s.pi.getAllTools(), process.platform, withheldTools(toolFacts(ctx))).

  • Nothing else changes. Entering plan mode sets plan’s list, which names exit_plan_mode; leaving it puts back the earlier set, which does not. A restart is a session start, so a session that is told of lost monitors is declared monitor_restore in the same start.

D2. Plan’s list drops web_enable (packages/pi-modes/modes.json)

Erratum (2026-12-04): Dropped D2/T8b; widenedCapability in packages/pi-modes/subagent-gate.ts requires plan.tools to remain a superset of Explore and Research’s profiles (both of which list `web_enable), and NON_CAPABILITY_TOOLS stays closed to yield.

Remove "web_enable" from the plan mode’s tools. The four web tools stay listed, so plan mode has them whatever pi-web-access chose. The Explore and Research profiles keep web_enable: a helper’s allowlist decides what is registered for it.

D3. Messaging tools register where messaging is in use (packages/pi-remote)

  • msg-tools.ts gains, exported and synchronous:

    /** Whether this agent dir has used messaging: it holds a space, a subscription, or a revoked space's record. */
    export function messagingInUse(state: Pick<RemoteState, "agentDir" | "wire" | "log">): boolean;

    True when loadSpaces(state.agentDir, state.wire, state.log) is non-empty, or any list in loadSubscriptions(state.agentDir) is non-empty, or loadRevoked(state.agentDir) has a key. All three loaders read a missing file as empty; loadSpaces logs pi_remote.spaces_unreadable for a broken one and returns none.

  • RemoteDeps (the private type in index.ts) gains usesMessaging?: () ⇒ boolean, defaulting to () ⇒ messagingInUse(state), beside its other injectable facts.

  • createRemote registers the five tools when usesMessaging() is true. Otherwise it registers none and sets state.onSpacesChanged = toolsWaitNotice(state, usesMessaging).

  • RemoteState (state.ts) gains onSpacesChanged?: () ⇒ void. LinkDeps (link.ts) gains onSpaces?(): void, called as the last line of Link.spacesChanged(). Where lifecycle.ts builds the link’s deps it passes onSpaces: () ⇒ state.onSpacesChanged?.().

  • toolsWaitNotice(state, uses) (private, index.ts) returns a function that does nothing until uses() is true, then once sends { customType: MSG_NOTICE_TYPE, content: MSG_TOOLS_WAIT, display: true } with { triggerTurn: false }. MSG_TOOLS_WAIT is: This box now holds a messaging space, but this session started without one and has no msg_* tools. They register when a session starts: ask the human to run /reload, or start a new session.

  • The /remote-control command, the hooks and the bus events are registered as before.

D4. Two plan-only bullets move to plan mode’s prompt

  • Delete the two bullets named in Context from global.md. The bullets on issues, plan shape and Status, the freeze and erratum rule, and naming evidence stay.

  • In modes.json, insert both bullets' text into the plan mode’s systemPrompt between "propose them in the plan instead." and "Before each exit_plan_mode": each bullet word for word, its list dash dropped and its lines joined by single spaces, the two separated by a space.

  • packages/pi-guidance/payload.ts: the header’s (guidance/global.md, ~60 lines) becomes (guidance/global.md; payload.test.ts pins its size).

D5. Sentences a tool states twice are stated once

Each description below drops words that its own guideline or parameter description repeats. New text in full:

  • count (command-wiring.ts) description: Count regex matches in a file or directory tree, deterministically. Returns exact totals and a per-file breakdown, 20 files at a time: when more follow, the result says the offset that continues it. Snippet: Count regex matches in files (exact totals). Its guideline keeps the rule to use count whenever a number is the answer.

  • ask (command-wiring.ts) description: Ask the human a question and wait for their answer. Offer options when you can enumerate them; omit them for an open question. Its first guideline keeps when to ask.

  • enter_plan_mode (plan-tools.ts) description: Switch yourself into plan mode: investigate and design, change nothing. Its guideline keeps "large, ambiguous, or risky".

  • exit_plan_mode (plan-tools.ts) description: Ask the human to approve the plan and leave plan mode. Its first guideline keeps "agree the approach in conversation FIRST".

  • remember (memory-wiring.ts) description: Propose a memory for this project (scope repo) or this machine (scope box). Each pool holds ten notes, proposals included; a proposal into a full pool is refused. Proposals are unconfirmed until the human promotes them. Its guideline keeps what belongs in memory and what does not.

  • queue_question (question-wiring.ts) description: Put a question to the human without stopping: it waits in their /pending queue with its context, options and your recommendation, and their answer arrives later as a message. Its second guideline and the meanwhile parameter keep proceed and park.

No parameter schema changes, so no test/fixtures/surface.json record changes.

What it saves

Estimated from the source text, per request prefix: yield 0.5K characters, exit_plan_mode 1.8K, monitor_restore 0.4K, the five messaging tools 5.1K, global.md 2.1K, D5 0.7K. That is about 10.6K characters (about 2.6K tokens) for a seat that has not used messaging and about 5.5K for one that has. Plan mode is unchanged in size by D4 and loses web_enable (0.6K). The MR states the measured figures.

Scope

  • packages/pi-modes: mode-controller.ts, modes.json, command-wiring.ts, plan-tools.ts, memory-wiring.ts, question-wiring.ts; tests test/mode-controller.test.ts, test/plan-mode.test.ts. The fake contexts that reach modes.onSessionStart gain getSystemPrompt: () ⇒ "": those in test/mode-controller.test.ts, test/session-wiring.test.ts, test/wiring.test.ts, test/model-roles.test.ts, test/monitor-tools.test.ts, test/shell-timeout.test.ts and test/context-budget-boundary.test.ts, and any other the suite then names by a getSystemPrompt is not a function failure.

  • packages/pi-remote: index.ts, msg-tools.ts, link.ts, lifecycle.ts, state.ts; tests test/extension.test.ts, test/units.test.ts, test/surface-contract.test.ts. In extension.test.ts, loaded() passes usesMessaging: () ⇒ true unless called with the new option realMessagingCheck: true, so its existing messaging cases keep their tools; surface-contract.test.ts passes usesMessaging: () ⇒ true.

  • packages/pi-guidance: guidance/global.md, payload.ts, test/payload.test.ts.

  • packages/pi/test/web-tools.test.ts: its case "every mode with rules allows each web tool, and plan mode and the Explore and Research helpers list it" today requires every listing to hold all of WEB_TOOLS, web_enable included. It changes as T8b says.

  • tools/consumer-sim.mjs.

  • Docs and CHANGELOG.adoc, under Delivery.

Tests

Regression and unit, packages/pi-modes/test/mode-controller.test.ts:

  • T1 withheldTools: a main session with nothing to restore withholds all three; a helper keeps yield; a session with monitors to restore keeps monitor_restore.

  • T2 unlistedTools leaves out the withheld names and keeps every other declared tool, in order.

  • T3 a main session’s start with read, yield, exit_plan_mode, monitor_restore and enter_plan_mode registered activates read and enter_plan_mode.

  • T4 the case that would catch a helper losing its result channel: a start whose system prompt carries <active_agent name="Explore"/> activates yield.

  • T5 a branch with a monitor started and not ended activates monitor_restore; so does one whose loss was told and not restored; a branch whose told monitors were restored does not.

  • T6 a round trip through a listed mode that names exit_plan_mode has it while there and not after.

Guidance and prompt:

  • T7 packages/pi-guidance/test/payload.test.ts: packagedGlobalGuidance() is at most 12,400 characters, holds neither "A plan carries, before anyone reviews it" nor "Plan review is bounded", and still holds "Plans freeze at implementation start" and "Status is ONE header value".

  • T8 packages/pi-modes/test/plan-mode.test.ts: the shipped plan prompt holds "A plan carries, before anyone reviews it", "Plan review is bounded: at most two rounds on six fixed questions" and "there is no round three", all before "Before each exit_plan_mode"; the shipped plan list has no web_enable and has web_search, fetch_content, get_search_content and source_check. The existing four-checks case is unchanged.

  • T8b packages/pi/test/web-tools.test.ts, the listing case: the rules half is unchanged (every ruled mode allows each of WEB_TOOLS). The listing half asserts that plan’s list holds WEB_TOOLS without web_enable (expect.arrayContaining of the four) and does not contain web_enable, and that the Explore and Research lists hold all of WEB_TOOLS as before.

pi-remote:

  • T9 test/units.test.ts, messagingInUse: false for an empty agent dir; true with a granted space, with only a subscription, with only a revoked record; false with an unparseable spaces file, which logs pi_remote.spaces_unreadable.

  • T10 test/extension.test.ts, with realMessagingCheck: an agent dir that has not used messaging registers /remote-control and no tool named msg_*; one holding a space registers the five.

  • T11 contract: test/surface-contract.test.ts still matches test/fixtures/surface.json byte for byte.

  • T12 the notice: in a session that registered no messaging tools, a grant over the link sends one gadhs-msg-notice whose content is MSG_TOOLS_WAIT and starts no turn; a second grant sends none; a session that registered the tools sends none.

The real stack, tools/consumer-sim.mjs:

  • T13 a live row after the helper probe, "a session is declared no tool of a state it is not in, and a helper keeps yield". helperProbeSystemRows also returns each row’s toolsAdded names. The spawning session’s rows declare read (the control) and none of yield, exit_plan_mode, monitor_restore, msg_channels, msg_handle, msg_post, msg_read, msg_subscribe; the Explore rows declare yield.

D5 changes descriptions and no behaviour; the package suites run unchanged over it.

Risks

  • A helper loses yield and returns prose where a checked result was due. Silent. Mitigation: T4 pins the helper case and T13 reads it from a real helper’s transcript.

  • The lost-monitors notice names monitor_restore in a session not declared it. Silent. Mitigation: the notice and the declaration read the same records in the same session start; T5 pins each record shape.

  • Plan mode without exit_plan_mode. Fail-closed: the agent stays in plan mode and the human can still switch. Reachable through an operator’s own replacement list, as today; the shipped list is pinned by "plan mode can always ask to leave".

  • A box’s first space arrives mid-session. Fail-closed: no messaging tool until the next session start. Visible in the session holding the link (T12); silent in the box’s other running sessions, where a later wake still shows the message’s preview. Mitigation: remote.adoc says tools register at session start.

  • The spaces file is unreadable at load. Fail-closed: no messaging tools, logged as pi_remote.spaces_unreadable, and /remote-control status shows spaces: none. T9 pins it.

  • Helpers and non-plan sessions no longer read the plan-authoring bullets. Silent. Mitigation: a plan is authored in plan mode, whose prompt carries them (T8), and `exit_plan_mode’s mechanical check refuses a draft without the items before any reviewer runs.

  • An overlay that replaces plan’s systemPrompt drops the moved text. Silent. Mitigation: modes.adoc says the shipped prompt carries the plan conventions; the mechanical check and both reviewers apply them whatever the prompt says.

  • A removed sentence was the one a model acted on. Silent. Mitigation: each sentence D5 removes is repeated by the same tool’s guideline or parameter description, listed per tool.

  • web_enable leaves plan’s list in a session where pi-web-access selected it. Silent: one extra tool change at the next turn start, when pi-web-access adds its loader back. Nothing is lost; the web tools stay listed.

Out of scope

  • The judge rubrics and reviewer prompts (#953), and the agent files: measured by the battery, untouched.

  • Whether Vertex Claude accepts mid-conversation tool changes (its own investigation issue).

  • Messaging tool text for seats that use messaging, and the enter_plan_mode result text.

  • A /tree move onto a branch whose restart notice is unanswered, in a session that started with nothing to restore: monitor_restore stays undeclared there, and the notice’s other route (monitor) still works. Filed as #1044.

Delivery

  1. One MR on refactor/trim-injected-context, Closes #1043. This plan is committed first as docs/modules/ROOT/pages/plans/context-trim.adoc with its docs/modules/ROOT/nav.adoc line.

  2. Docs, each page canonical for its surface: modes.adoc (the tools row: the three withheld tools and when each is declared; plan’s prompt carries the plan conventions), tools.adoc (monitors: monitor_restore is declared when the session has monitors to restore), helpers.adoc (yield is declared to helper sessions), remote.adoc ("The tools": when the five register, and the notice), plan-mode.adoc (the author is told the plan conventions and review rounds by plan mode’s prompt).

  3. CHANGELOG.adoc == Unreleased, Changed: one entry naming the four changes and #1043.

  4. Before queuing: node tools/task.mjs check, then node tools/task.mjs validate and node tools/consumer-sim.mjs in full, as a job.

  5. Queue on the merge train. After the merge: Status to Done, and one line on #1043 with the merge SHA and the measured sizes.

Edit this page · latest