Plan: a helper in its own git worktree, committing there under one checkout per session

Closes: #477. Branch: feat/helper-worktree. Status: Done (2026-10-26) — implemented as planned, with the errata below

Design

The decision

Build a small workspace provider in pi-modes, on pi-subagents' WorkspaceProvider seam (node_modules/@gotgenes/pi-subagents/src/lifecycle/workspace.ts), rather than adopt @gotgenes/pi-subagents-worktrees 0.3.3, the author’s own provider on the same seam (named in pi-subagents' README, lines 278-279, which also records that the core’s isolation: "worktree" spawn flag was removed). The alternatives weighed:

Option For Against

Adopt @gotgenes/pi-subagents-worktrees

Written by pi-subagents' author on the seam it was made for; 748 lines, tested; handles the uncertain-teardown case well (never deletes a worktree whose state is unknown; lists preserved worktrees and unmerged branches at session start).

Its rescue commit retries with --no-verify when a hook rejects (its README, "Behavior": "If a commit hook rejects that commit, it is retried once with --no-verify`"; read 2026-10-26 from the package’s repository, not in this workspace), a hook bypass the agency forbids outright. Its commit message is `pi-agent: <description>, which the commit guard would refuse. Both are made by the package, outside pi-workflow’s guard, so nothing of ours would catch them. The worktree is detached at HEAD, so a helper cannot commit on a {type}/<desc> branch as the workflow expects. The worktree is torn down when the helper completes, which pi-subagents then refuses to resume ("workspace-disposed").

Build our own provider (chosen)

~150 lines of git plumbing, most of it borrowed in shape from the package above. The helper commits as any session does: its own pi-modes and pi-workflow load in the child session (pi-subagents runs the installed extensions in a child), so the commit guard, the reflection pause and the branch rule read the worktree. No commit is ever made by the package. The worktree lives on a real branch from the start.

Our code to maintain. The cases the package handles (preserved worktrees, unmerged branches) become ours, in a smaller form: list them at session start, delete nothing.

Document the patch-carry workflow only

No code.

Leaves canopy’s pattern clumsy, and an uncommitted worktree easy to lose (its words).

No ADR: one provider in one package, reversible by deleting it. A pi-subagents configuration (not ours) enables it, as the author’s package does, so a repository that wants the author’s package instead installs that and leaves ours unconfigured. Only one provider may register (subagent-manager.ts:249); ours registers only when configured, so the two never collide by default.

What a helper in a worktree is

The helper’s session runs with cwd = the worktree (create-subagent-session.ts:280-296 takes the provider’s cwd as effectiveCwd). In that session:

  • pi-modes and pi-workflow load as they do in any child, so git commit there goes through the commit guard (branch rule, message format, no --no-verify) and the reflection pause, reading that checkout’s index and HEAD. The #462 rule holds: one checkout per agent session, and this helper’s session is in the worktree.

  • yield works unchanged: the child’s session file stays under the parent’s session directory (deriveSubagentSessionDir derives from the parent’s file, not the cwd), where pi-modes collects sidecars (yield-tool.ts, sidecarSearchDirs).

  • The helper’s tools are its agent file’s; a helper without bash cannot commit, and nothing here grants it.

The provider never commits, stages, pushes or deletes. It creates a worktree on a branch, hands the path to pi-subagents, and at dispose decides only whether the worktree may be removed.

The lifecycle

Moment What happens

Opt-in

worktreeAgents in ~/.pi/agent/gadhs-pi-modes.json, a list of agent types ("worktreeAgents": ["general-purpose"]). Nothing registers without it. A project may not widen it: the modes overlay is the human’s file (#468), and a repository’s .pi must not put helpers into worktrees the human did not ask for.

Prepare (WorkspaceProvider.prepare, before the child session exists)

For a listed agentType only; others return undefined and run in the parent cwd. prepare receives { agentId, agentType, baseCwd } and nothing else (workspace.ts:16-20), so the branch is named from those: helper/<type>-<id8>, the agent type lowercased and <id8> the first 8 characters of the agent id (unique per spawn; the spawn’s description is not available here and is not used). Requires a git checkout with a HEAD at baseCwd, else the run fails with git’s reason rather than running unisolated. Created from the session’s HEAD: git worktree add -b helper/<type>-<id8> <path> HEAD. The path is $TMPDIR/gadhs-helper-<type>-<id8> (no slash: a flat name the session-start scan can glob), never under the main checkout, where a nested worktree confuses tooling and git status. The branch is the helper’s: its first commit lands there.

Running

pi-subagents' own prompt header tells the child its working directory and branch (buildPromptHeader, session/prompts.ts:149-158: Working directory: <cwd>, Branch: <branch>). Nothing more from us. Its result contract is unchanged.

Dispose (Workspace.dispose, when the helper completes, errors or is stopped)

git -C <path> status --porcelain and git rev-list HEAD..<branch>: no commits and no changes → git worktree remove <path> and git branch -d <branch>, addendum "ran in a worktree, left nothing". Commits or changes → the worktree is KEPT, addendum names the branch and path: "its work is on branch <branch>, worktree <path> (N commits, M uncommitted files); merge or open an MR from there; git worktree remove when done". Removal of any worktree with content is the human’s, never the package’s. A dispose whose git calls fail leaves everything in place and says so.

Continuing after a pause (operator decision, 2026-10-26)

pi-subagents disposes the workspace on every completion except one: a helper that ends its turn with a question for the parent (ask_parent) keeps both its session and its workspace, and a resume re-enters them (subagent.ts:698-706, completeResume). A disposed workspace is never resumed into (subagent.ts:268, agent-tool.ts:326). So the two-phase pattern is: the helper ends phase one with a question ("Draft is on branch helper/x; say build when the machine is free"), and the lead resumes it with the answer. The documented recipe says exactly this, and the worktree recipe’s example task tells the helper to do it. The held session lasts unconsumedSessionRetentionMinutes (720 by default; a pending question is never "consumed", subagent-manager.ts:127-133), so the pause may be long. A helper that simply completes is one run per spawn: the worktree and branch are kept, the addendum names them, and a new helper continues on the branch (its own worktree is created from HEAD, so its task says git checkout <branch> first). Nothing here is a mechanism of ours; it is the seam’s shape, documented.

Session start

Worktrees registered with this repository (git worktree list --porcelain) whose path matches $TMPDIR/gadhs-helper-, and helper/ branches not merged into HEAD (git branch --list 'helper/*' --no-merged HEAD), are named in one notice, so kept work is not forgotten. Nothing is deleted.

Registration, once, by the top-level session

pi-subagents runs every extension’s factory again for each in-process child and sends the child session_shutdown (session-wiring.ts:122-131, the bridge’s lesson, #228). A child’s pi-modes must not register a second provider (pi-subagents throws on a second, subagent-manager.ts:249-253) nor unregister the parent’s on its shutdown. So registration follows the bridge’s pattern exactly: a globalThis slot keyed by a symbol; the first instance to find it empty registers through getSubagentsService().registerWorkspaceProvider(…​) (the service adapter exposes it, service/service-adapter.ts:126-128; pi-modes' local type for the service, subagent-wiring.ts:122-124, widens from { listAgents } to add it) and keeps the disposer; an instance that finds the slot taken does nothing; shutdown unregisters only the disposer this instance holds. A child’s session_start therefore sees the parent’s registration and leaves it. A test runs two instances against one fake service and asserts one registration and one unregistration, by the owner.

Risks

Risk Mode Mitigation

The provider deletes work

Fail-closed

Removal only when status --porcelain is empty AND rev-list HEAD..<branch> is empty; any git error keeps everything. Tests (integration, against a temporary repository): a worktree with an uncommitted file survives dispose; one with a commit survives, branch included; an untouched one is removed with its branch.

A helper commits without the guard

Silent

Contract test: a child session created with pi’s real createAgentSession on the faux provider (the pattern of test/drop.test.ts and test/yield-reminder.test.ts), its cwd the worktree, runs git commit -m "bad subject" through the bash tool and is refused by the commit guard with the worktree’s HEAD read (the branch rule) and its index as the diff.

A child instance registers a second provider, or unregisters the parent’s

Fail-closed (pi-subagents throws on a second registration)

The global-slot registration above; the two-instance test pins one registration and one unregistration by the owner.

The author’s package is also installed and registers first

Fail-closed (ours cannot register)

Ours catches the throw into one session-start warning naming the conflict; helpers run under the other provider, as configured there.

A kept worktree is forgotten

Silent

The addendum at dispose and the session-start notice; a test pins the notice for a kept worktree and an unmerged helper/* branch, and its absence when there are none.

worktree add fails (no HEAD, an index lock)

Fail-closed

The run fails with git’s message; nothing runs unisolated.

Scope

In

  • packages/pi-modes/helper-worktree.ts: the provider, the branch name, the dispose decision, the session-start scan, the once-only registration slot. ≤ 200 lines.

  • packages/pi-modes/subagent-wiring.ts: the service type widened with registerWorkspaceProvider; registration on session_start once the service is published (it is published by pi-subagents' factory, which loads before ours: 25-agents.ts loads pi-subagents first, #438); the owner’s disposer called on shutdown.

  • packages/pi-modes/config.ts: ModesConfig.worktreeAgents?: string[], validated as a list of non-empty strings; refused by name otherwise, as other fields are.

  • Tests: unit (branch name, the dispose decision table over status × rev-list × git-error, config validation, the two-instance registration); integration against a temporary git repository (prepare creates the branch and path; dispose across the four states; the session-start scan); the commit-guard contract test above.

  • Docs: a section under "The delegation gate" in docs/modules/ROOT/pages/modes.adoc; a cookbook recipe "Run a helper in its own worktree" in docs/modules/ROOT/pages/tuning.adoc showing the two-phase pattern (the helper ends phase one with a question; the lead resumes it); the CHANGELOG entry.

Out

  • Merging, pushing or opening an MR from the helper’s branch: the lead’s or the human’s workflow.

  • Deleting a worktree or branch with content: never by the package; the notice names them.

  • A mechanism to hold a workspace past a plain completion: the seam’s pending-question hold is the route (decided 2026-10-26), documented as the recipe; asking upstream for a hold option was considered and not chosen for now.

  • A per-spawn opt-in: pi-subagents removed its isolation spawn flag (README "Migrating"); the opt-in is per agent type, as upstream’s is.

  • Windows: the worktree path and git calls are the same; the commit guard’s Windows behaviour is #447’s and #450’s, unchanged.

Delivery

One branch, one MR, Closes #477. The plan file is committed first (reviewed at exit_plan_mode). Tests ship with the code; validate green before push; the docs and the CHANGELOG entry on the same branch.

Erratum (2026-10-26): pi-subagents publishes its service in its own factory, and registration happens at session_start, after every factory has run, so the load order does not matter (the plan’s "`25-agents.ts` loads pi-subagents first" was wrong: it loads pi-agents).

Erratum (2026-10-26): the service is reached from helper-worktree.ts itself, by its own import, not by widening the type in subagent-wiring.ts, which stays unchanged.

Erratum (2026-10-26): the commit-guard contract test drives the pre-review "commit elsewhere" and --no-verify refusals, not a bad subject: the format check runs after the reflection review, which would need a reviewer model. The property is the same (the worktree is the session’s repository), and it lives in pi-workflow’s tests (test/worktree-session.test.ts), since pi-modes' tests do not import pi-workflow.

Edit this page · latest