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
toolslist (auto, manual, yolo) starts a session withunlistedTools(pi.getAllTools())(packages/pi-modes/mode-controller.ts, exported, synchronous): every registered tool whose exposure isdirectormodel-only, minus pi’spowershelloff Windows, minustool_searchwhile no deferred tool is registered.onSessionStart(s, ctx)(private, async) stores it ins.unlistedTools.applyTools(s, mode)(private) sets a listed mode’smode.tools, and on leaving a listed mode puts back the set the session had before it. -
pi-modes registers
yieldin every session (packages/pi-modes/subagent-wiring.ts), and itsexecuteYieldanswersYIELD_NO_PARENTunless the system prompt carries pi-subagents'<active_agent name="…"/>tag (activeAgentName(systemPrompt)inpackages/pi-modes/yield-tool.ts, exported, synchronous). A helper session binds the same extensions, so pi-modes'onSessionStartruns 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’ssystemPromptOverridebeforebindExtensionsfiressession_start. pi-subagents passes the agent’stools: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, andyieldis among them for every packaged agent. -
exit_plan_moderefuses outside the mode whose id isplan(exitPlanModeinpackages/pi-modes/plan-tools.ts). The shipped plan mode lists it intools(packages/pi-modes/modes.json), pinned by "plan mode can always ask to leave" inpackages/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_restorestarts again the monitors the restart notice named. The notice is sent at session start bytellLost(pi, branch)and the tool readstoldLost(records);lostMonitors(records)andbranchRecords(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)callsregisterMsgTools(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.setActiveToolsignores names that are not registered (pidocs/extensions.md), so plan’s list may keep naming them. -
A grant reaches the session that holds the link:
BoxSpaces.grantcallschanged(), which isLink.spacesChanged()(packages/pi-remote/spaces.ts,packages/pi-remote/link.ts). pi-remote already tells the agent messaging facts asMSG_NOTICE_TYPEmessages that start no turn (tellRelabelledinpackages/pi-remote/index.ts). -
packages/pi-guidance/guidance/global.mdis 14,249 bytes and reaches every main session and every appending helper. Two of its bullets under# GitLab and plansare 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’ssystemPromptinmodes.jsonis thegadhs-modesection of every plan-mode turn;plan-mode.test.tspins 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 (addsToolsWithoutCheckpointinnode_modules/pi-web-access/tool-activation.tsneeds asupportsMidConvoToolChanges-style flag, andpackages/pi-vertexsets none), so plan’s list is what switches the loader back on. Where pi-web-access did select its loader, its ownbefore_agent_starthandler 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(pidocs/session-format.md), andtools/consumer-sim.mjsalready reads those rows for its helper probe (helperProbeSystemRows).
Decisions for the operator to confirm at approval
-
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.
-
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. -
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.
-
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_modein every case,yieldwhenfacts.helperis false, andmonitor_restorewhenfacts.monitorsToRestoreis false. The three names are constants at the file top. -
unlistedTools(tools, platform = process.platform, withheld: ReadonlySet<string> = new Set())drops the names inwithheldafter its present filters. Its other behaviour is unchanged. -
A private
toolFacts(ctx: Pick<ExtensionContext, "getSystemPrompt" | "sessionManager">): ToolFactsreadshelperasactiveAgentName(ctx.getSystemPrompt()) !== undefinedandmonitorsToRestoreaslostMonitors(records).length > 0 || toldLost(records).length > 0, withrecords = branchRecords(ctx.sessionManager.getBranch()). Reading both lists makes the answer the same before and aftertellLostappends itstoldrecord, whichever session-start handler runs first (T5 covers both record shapes). -
onSessionStartcomputess.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 declaredmonitor_restorein 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.tsgains, 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 inloadSubscriptions(state.agentDir)is non-empty, orloadRevoked(state.agentDir)has a key. All three loaders read a missing file as empty;loadSpaceslogspi_remote.spaces_unreadablefor a broken one and returns none. -
RemoteDeps(the private type inindex.ts) gainsusesMessaging?: () ⇒ boolean, defaulting to() ⇒ messagingInUse(state), beside its other injectable facts. -
createRemoteregisters the five tools whenusesMessaging()is true. Otherwise it registers none and setsstate.onSpacesChanged = toolsWaitNotice(state, usesMessaging). -
RemoteState(state.ts) gainsonSpacesChanged?: () ⇒ void.LinkDeps(link.ts) gainsonSpaces?(): void, called as the last line ofLink.spacesChanged(). Wherelifecycle.tsbuilds the link’s deps it passesonSpaces: () ⇒ state.onSpacesChanged?.(). -
toolsWaitNotice(state, uses)(private,index.ts) returns a function that does nothing untiluses()is true, then once sends{ customType: MSG_NOTICE_TYPE, content: MSG_TOOLS_WAIT, display: true }with{ triggerTurn: false }.MSG_TOOLS_WAITis: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-controlcommand, 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’ssystemPromptbetween "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 usecountwhenever 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 themeanwhileparameter 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; teststest/mode-controller.test.ts,test/plan-mode.test.ts. The fake contexts that reachmodes.onSessionStartgaingetSystemPrompt: () ⇒ "": those intest/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.tsandtest/context-budget-boundary.test.ts, and any other the suite then names by agetSystemPrompt is not a functionfailure. -
packages/pi-remote:index.ts,msg-tools.ts,link.ts,lifecycle.ts,state.ts; teststest/extension.test.ts,test/units.test.ts,test/surface-contract.test.ts. Inextension.test.ts,loaded()passesusesMessaging: () ⇒ trueunless called with the new optionrealMessagingCheck: true, so its existing messaging cases keep their tools;surface-contract.test.tspassesusesMessaging: () ⇒ 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 ofWEB_TOOLS,web_enableincluded. 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 keepsyield; a session with monitors to restore keepsmonitor_restore. -
T2
unlistedToolsleaves 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_restoreandenter_plan_moderegistered activatesreadandenter_plan_mode. -
T4 the case that would catch a helper losing its result channel: a start whose system prompt carries
<active_agent name="Explore"/>activatesyield. -
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_modehas 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 noweb_enableand hasweb_search,fetch_content,get_search_contentandsource_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 ofWEB_TOOLS). The listing half asserts that plan’s list holdsWEB_TOOLSwithoutweb_enable(expect.arrayContainingof the four) and does not containweb_enable, and that the Explore and Research lists hold all ofWEB_TOOLSas 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 logspi_remote.spaces_unreadable. -
T10
test/extension.test.ts, withrealMessagingCheck: an agent dir that has not used messaging registers/remote-controland no tool namedmsg_*; one holding a space registers the five. -
T11 contract:
test/surface-contract.test.tsstill matchestest/fixtures/surface.jsonbyte for byte. -
T12 the notice: in a session that registered no messaging tools, a grant over the link sends one
gadhs-msg-noticewhose content isMSG_TOOLS_WAITand 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".
helperProbeSystemRowsalso returns each row’stoolsAddednames. The spawning session’s rows declareread(the control) and none ofyield,exit_plan_mode,monitor_restore,msg_channels,msg_handle,msg_post,msg_read,msg_subscribe; the Explore rows declareyield.
D5 changes descriptions and no behaviour; the package suites run unchanged over it.
Risks
-
A helper loses
yieldand 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_restorein 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.adocsays 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 statusshowsspaces: 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
systemPromptdrops the moved text. Silent. Mitigation:modes.adocsays 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_enableleaves 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_moderesult text. -
A
/treemove onto a branch whose restart notice is unanswered, in a session that started with nothing to restore:monitor_restorestays undeclared there, and the notice’s other route (monitor) still works. Filed as #1044.
Delivery
-
One MR on
refactor/trim-injected-context,Closes #1043. This plan is committed first asdocs/modules/ROOT/pages/plans/context-trim.adocwith itsdocs/modules/ROOT/nav.adocline. -
Docs, each page canonical for its surface:
modes.adoc(thetoolsrow: the three withheld tools and when each is declared; plan’s prompt carries the plan conventions),tools.adoc(monitors:monitor_restoreis declared when the session has monitors to restore),helpers.adoc(yieldis 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). -
CHANGELOG.adoc== Unreleased, Changed: one entry naming the four changes and #1043. -
Before queuing:
node tools/task.mjs check, thennode tools/task.mjs validateandnode tools/consumer-sim.mjsin full, as a job. -
Queue on the merge train. After the merge: Status to Done, and one line on #1043 with the merge SHA and the measured sizes.