Plan: Remote execution phase 2c — /ssh, the anchor, the safeguards, the loader
Closes: #498 (phase 2c). Relates to: #488 (meta plan: plans/remote-execution.adoc), #490 (2b), #496 (2a), #491 (phase 3), #492 (phase 4). Branch: feat/pi-ssh-session. Status: Done (2026-10-26) — implemented as planned, with the errata below; the live check follows the program’s release at the operator’s direction
Design
What this phase is for
Phases 1 to 2b built the seam, the SSH workspace and pi’s tools on it; nothing loads them for a user. This phase is the session: how a remote project becomes the thing pi is working on, how pi knows it, and what is refused until phases 3 and 4 catch up. The bar is the meta plan’s, functions identically, with the limitations named below rather than discovered.
The anchor, and why a session switches into it
pi keys sessions, trust, AGENTS.md and .pi/ discovery by the local cwd (meta plan, "The local anchor"). A remote project gets a local directory of its own: <agentDir>/remotes/<host>/<slug>/ (getAgentDir() from pi; host is the destination without user@; slug is the remote path with / as -, plus six hex characters of SHA-256 over destination:root, so /srv/app and /srv-app never share one). It holds:
-
remote.json:{ "version": 1, "destination": "dev@box", "root": "/srv/app", "created": "<ISO>" }, parsed at the boundary into a typed shape; a malformed file is reported and the session stays local. -
AGENTS.md,.pi/gadhs-guidance.mdand the language marker files, mirrored from the remote (below).
pi only ever changes a session’s working directory by replacing the session (AgentSessionRuntime.switchSession, dist/core/agent-session-runtime.js:128-144), and the replacement’s cwd is the session file’s header (SessionManager.open, session-manager.js:1326-1347: cwd is read from the file; with no file it is process.cwd()). pi writes no session file until a conversation exists (_persist, session-manager.js:794-813). So /ssh writes one itself: SessionManager.create(anchor) (exported from pi’s root) supplies pi’s session directory for the anchor and the file name; /ssh writes its header (getHeader(), the documented session format) as the file’s one line, then ctx.switchSession(file). A contract test opens such a file with SessionManager.open and asserts getCwd() is the anchor. The switch replaces the extension runtime and fires session_start in the anchor (pi’s lifecycle, docs/extensions.md "Session startup and replacement"), which is the one entry point below. pi "/ssh dev@box:/srv/app" runs the command as the first prompt, so there is no launcher binary; the meta plan’s pi-ssh launcher and --ssh flag are dropped (erratum below).
/ssh: commands.ts
/ssh <destination>:<path> parses the destination and the absolute remote path (a relative path is refused with the form), probes first: connect and the hello, then stat of the root (a missing or non-directory root is refused with "no such directory on dev@box: /srv/app"). A probe that fails reports the connection’s reason (2a’s refusals: ssh, host key, no node, old node, protocol) in the current session and switches nothing. On success the probe connection is closed, the anchor and remote.json are written, the session file is written, and ctx.switchSession runs. /ssh with no argument, and /ssh status: destination, root, anchor, connected or not, the remote’s node and platform; in a local session, "this session is local". /ssh reconnect: closes the live connection and re-establishes it, reporting the result. For these the RemoteWorkspace gains close(): Promise<void> and connected(): boolean (ssh-workspace.ts; the lazy live promise already reconnects on the next call).
Session start in an anchor: session.ts
session_start: if <cwd>/remote.json is absent, nothing (a local session). Otherwise:
-
If
currentWorkspace()is already a remote workspace whoseanchoris this cwd’s real path, reuse it and own nothing: this is a helper session (pi-subagents re-instantiates extensions per helper in the same process; meta plan, "Helpers"). Ownership is the extension instance’s closure: only the instance that published holds the withdrawal, so a helper’ssession_shutdowncloses nothing of its parent’s. -
Else build
sshWorkspace({ destination, root, anchor, connect }),publishWorkspaceit, keep the withdrawal, and callhost()eagerly so a failure is a notification now ("cannot reach dev@box: <reason>; tools will retry per call") rather than the first tool’s error. The tools fail closed per call until the link is back (2a). -
Mirror (below), set the status line
ssh dev@box:/srv/app(ctx.ui.setStatus("ssh", …)), and recordssh.sessionin diagnostics: destination, root, anchor,reused,connected.
session_shutdown (idempotent): the owner withdraws and closes; a reuser does nothing. /new in the anchor therefore closes and reconnects once, which is acceptable.
project_trust (an extension loaded from the personal layer may answer it; docs/extensions.md:50): when event.cwd is an anchor, ask with the remote’s name, "Trust dev@box:/srv/app? Its AGENTS.md and .pi/gadhs-guidance.md will steer agents here", and answer { trusted: "yes" | "no", remember: true }; with no UI, "undecided" leaves pi’s own flow. Trusting the anchor is trusting that remote project, and the prompt says so instead of naming a directory under ~/.pi.
The mirror: mirror.ts
Three reads of the local cwd feed the system prompt (meta plan, "The one abstraction"): pi’s own AGENTS.md discovery, readProjectGuidance(cwd) and detectLanguages(cwd) (packages/pi-guidance/payload.ts:66-77, markers in the cwd and its first-level directories). At every session start the mirror writes, from the remote through the workspace:
-
AGENTS.md: the remote root’s, preceded by its ancestors' up to the remote repository’s top (git rev-parse --show-toplevelon the remote; none outside a repository), concatenated top-down, each under an HTML comment naming its source. The anchor’s own ancestors are~/.pi/agent/remotes/…, so pi’s walk upward finds only the global~/.pi/agent/AGENTS.md, as it does locally. -
.pi/gadhs-guidance.mdwhen the remote has one; removed from the anchor when it does not. -
The language markers: for each name in
LANGUAGE_MARKERS(newly exported from@gadhs/pi-guidance;pi-sshtakes pi-guidance as a peer dependency, as pi-modes does) present at the remote root or in one of its first-level directories, an empty file at the same relative place ({}for a.jsonname, so nothing that parses it chokes). Stale markers are removed. Phase 4 pointsdetectLanguagesat the workspace and drops this.
The mirror copies nothing else: project extensions, skills and prompts on the remote are not loaded (meta plan, "Honest limitations"). A test gives the remote tree .pi/extensions/x.ts, .pi/skills/, .pi/prompts/ and an .env.local, and asserts the anchor’s exact listing afterwards.
The system prompt and the status line
pi renders the working directory as <cwd>\n<path>\n</cwd> (system-prompt.js:110,118), and pi-modes (loaded first) returns a replaced systemPrompt, after which pi treats the text as forced (extensions/runner.js:1147-1149), so a later systemPromptOptions.cwd edit would be ignored. pi-ssh’s `before_agent_start therefore rewrites the rendered text: the <cwd> block whose path is the anchor becomes the remote root, followed by a <gadhs-ssh> block: the workspace is /srv/app on dev@box over SSH; paths in tool calls and results are the remote’s; pi’s own files under <agentDir> are local. When no <cwd> block names the anchor, the <gadhs-ssh> block is still appended, the rest is unchanged, and ssh.prompt.unmatched is recorded. A sentinel test reads pi’s system-prompt.js for the wrapper literal, so a pi release that changes it fails a test rather than a session.
Containment resolves real locations on the remote: authorize.ts
(#492’s containment, pulled forward; the operator chose this on 2026-10-26 over the meta plan’s judge detour.) In a session whose cwd is the anchor, the local checks answer wrong in both directions: isPlainWorkspaceRead (authorize.ts:129-144) calls realpathSync on <anchor>/src/x.ts, which does not exist locally, so every remote read would go to the judge; realLocation (authorize.ts:156-176) finds nothing to resolve under the anchor and calls a write inside, allowing it without the judge, while the write acts where src may be a link out of the tree. A judge detour would not see the link either.
So AuthorizeDeps gains workspace?: Workspace, supplied by decideAtGate (judge-wiring.ts:987-1012) as workspaceFor(cwd); pi-modes takes @gadhs/pi-workspace as a dependency (ADR-006: "pi-modes and pi-workflow depend on it by name"). When it is absent or local, every path below is today’s synchronous code, so the existing suites are unchanged. When it is remote, a new remote-containment.ts answers the three sites through the workspace, where the symlinks are:
-
remoteRealLocation(ws, path):ws.realpathof the deepest existing prefix (the remote’srealpath(3)resolves every link in every component and steps..from real locations, which is whatrealLocationreproduces segment by segment), plus the missing tail with its..stepped; a missing component thatws.lstatreports as a link is dangling and yields undefined. One round trip for an existing path, one more per missing level. -
remoteInside(ws, path):isInside(real, rootReal, posix),rootRealbeingws.realpath(ws.root)cached per workspace object. -
Write stage (
workspaceWriteAllow): targetws.resolve(toolPath(path)), thenremoteInside; the credential-shaped rule stays. Read stage (isPlainWorkspaceRead): the same, and the path must exist (ws.realpathdefined), as locally an absent path is not plain. Redirect targets (writesAtHome):remoteInside, or inside the remote’s/tmpreal location. The three callers andruleAllowbecomeasync;authorizeAskalready is.
Security (contract) tests against a fake remote workspace with a programmable realpath/lstat: a link inside the remote tree pointing out makes a write and a read go to the judge; link/.. is the target’s parent; a dangling link is not inside; an in-tree path is allowed deterministically; a credential-shaped name still goes to the judge; an absent read target goes to the judge. Regression: the same cases through sshWorkspace over pipes against a real scratch tree with real symlinks, so the fake is held to the helper.
The commit refusal: commit-pause.ts
Until phase 3, the commit guard reads a local .git that an anchor does not have, so a commit over SSH would pass unreviewed (meta plan, "Guards blind"). pauseBashCommand (commit-pause.ts:636-648) gains remoteWorkspaceRefusal first in its early chain: workspaceFor(ctx.cwd).isRemote refuses with "commit guard: not yet guarded over SSH (phase 3, #491); commit from a local checkout", recorded as git_guard.remote_workspace. pi-workflow takes @gadhs/pi-workspace as a dependency for this one read. Security (contract): with a remote workspace published for ctx.cwd, git commit -m x through bash is blocked with that reason; git status is not; locally nothing changes.
pi’s own files stay local: extension.ts
2b sends every write, edit and read to the remote. A plan draft is a local file under <agentDir>/plans/ that pi-modes reads back at exit_plan_mode; written on the remote it would never be found. The switched tools gain one rule before the remote: an absolute path under getAgentDir() that is not under the anchor goes to pi’s local tool. The anchor itself still maps to the remote root (2a’s resolve), so read AGENTS.md reads the remote’s. The <gadhs-ssh> prompt block says so. Test: with a remote published, write <agentDir>/plans/x.adoc lands locally and write <anchor>/x and write src/x land on the remote.
The judge’s facts, the loader, the switch-off
askFacts (session-facts.ts:200, called from judge-wiring.ts) names the workspace as ws.label plus (over SSH; local anchor <anchor>) when workspaceFor(cwd) is remote, so the judge’s trusted header does not call a remote session local; a unit test pins both labels. @gadhs/pi-ssh’s `index.ts gains export { default } from "./extension.ts", so packages/pi/loaders/11-ssh.ts re-exports by bare specifier like every other GADHS loader (distribution.test.ts:78-121: a subpath target is counted as vendored and must exist under node_modules, which ours would fail). pi.extensions lists it after 10-modes.ts; the order assertions hold (prefixes sorted, modes first, remote last). GADHS_PI_SSH=off makes the factory register nothing, as GADHS_PI_TUI_PATCH=off does for the lone-escape patch (lone-escape.ts:25).
Fail modes
-
The probe fails:
/sshreports the reason and switches nothing (fail-closed, loud). -
Session start cannot connect: the workspace is published, the user is told, each tool fails with the connection’s error until the link is back; no local fallback (fail-closed, loud).
-
The link drops mid-session: each call fails with the loss until the next call reconnects (2a; fail-closed, loud); the status line shows
ssh dev@box: disconnectedfrom the connection’sonLost, back to the name on the next successful call. -
A malformed
remote.json: reported, the session is local, the status line says nothing (fail-closed, loud: nothing is published, so no remote write can happen by accident). -
The slot already holds a workspace for a different anchor (a stale publication;
publishWorkspacethrows,slot.ts:19-24): reported, the session is local (fail-closed, loud)./sshfrom one anchor to another does not hit this: the old session’s shutdown withdraws before the new one’s start publishes, which a test with two instances in that order pins. -
The mirror fails (an unreadable remote
AGENTS.md): the anchor keeps the previous mirror, the user is told, the session proceeds (fail-open on freshness, loud). -
The
<cwd>block is not found: the cwd text is unchanged,ssh.prompt.unmatchedrecorded, the<gadhs-ssh>block still tells the model where it is (fail-open on the cwd text, loud in diagnostics). -
A worktree-isolated helper is spawned in an anchor:
createHelperWorktreethrows, as in any non-repository ("rather than running unisolated",helper-worktree.ts:91-94); the spawn fails with git’s message (fail-closed, loud); documented; phase 4 gives helpers remote worktrees.
Limitations this phase documents
Key or agent authentication only (BatchMode=yes; a password prompt cannot reach pi’s terminal). Helpers that need a worktree do not run yet. No commit over SSH until phase 3; glab, git push and anything the remote runs use the remote’s credentials. The remote project’s extensions, skills and prompts are not loaded. Every operation is a round trip; containment adds one or two per write ask. Plan drafts, memory and sessions are local, so /ssh to another host from the same local pi shares none of the remote’s state.
Scope
In
-
packages/pi-ssh/:anchor.ts(the path,remote.json, the slug),session.ts,mirror.ts,commands.ts,prompt.ts,diag.ts(thegadhs:diagnosticsslot with a shape guard, pi-workflow’s bridge pattern),extension.ts(wiring, the local-agent-dir rule,GADHS_PI_SSH),ssh-workspace.ts(close,connected),index.ts(the default export),package.json(peer@gadhs/pi-guidance), README. -
packages/pi-guidance/payload.tsandindex.ts: exportLANGUAGE_MARKERS. -
packages/pi-modes/:authorize.ts, newremote-containment.ts,judge-wiring.ts(workspaceindecideAtGate),session-facts.ts(the facts label),package.json(@gadhs/pi-workspace). -
packages/pi-workflow/:commit-pause.ts,package.json(@gadhs/pi-workspace). -
packages/pi/:loaders/11-ssh.ts,package.json(pi.extensions, dependency@gadhs/pi-ssh),test/distribution.test.tsif its fixtures name the list. -
Tests, each named for its property, by category. Contract: the session file written by
/sshopens withSessionManager.opento the anchor’s cwd; the prompt<cwd>sentinel against pi’s source. Property: 10k distinctdestination:rootpairs give distinct anchors. Unit:remote.jsonparsing refuses each malformed shape (missing key, wrong type, relative root, other version); the slug; the prompt rewrite with and without a match;project_trustwording and the three decisions;GADHS_PI_SSH=offregisters nothing; the facts label. Integration (against a scratch remote over pipes): session start reuse-vs-own and shutdown ownership (two extension instances, one slot;/sshanchor-to-anchor order; the stale-slot refusal); the mirror (ancestor concatenation, guidance added and removed, markers added and removed, the exact anchor listing; the marker set equals pi-guidance’s by import);/sshprobe refusals (unreachable, missing root, relative path) and the switch (a fakectx.switchSessionreceiving the written file). Security (contract): containment, the commit refusal, the local agent dir, as stated in their sections. Regression: containment’s cases throughsshWorkspaceagainst real symlinks; the existing pi-modes and pi-workflow suites unchanged. Coverage thresholds of pi-ssh, pi-modes, pi-workflow hold or rise. -
Mutation check: the anchor-under-agentDir rule,
remoteInside’s root comparison, the dangling-link branch, the commit refusal’s `isRemoteread, the reuse-vs-own branch, the<cwd>match; each killed before the MR. -
Live verification against a real host, recorded on the MR:
pi "/ssh user@host:/path"from this box, a read, an edit, a grep,!git status, the status line,/ssh status, a refused commit, and/diagshowingssh.session. -
Docs:
docs/modules/ROOT/pages/ssh.adoc("pi over SSH"), the canonical page for the surface this phase turns on: how to start, what is local and what is remote, the anchor, trust, the limitations above verbatim; phase 6 adds the cookbook and the measured costs.packages.adoc’s pi-ssh row; `modes.adoc’s containment paragraph gains the remote case; `nav.adoc;CHANGELOG.adocAdded(pi-ssh, pi) andChanged(pi-modes containment, pi-workflow refusal). -
Meta plan errata:
/sshplusctx.switchSessionreplaces thepi-sshlauncher and--sshflag; containment moved from phase 4 to 2c;ssh.adocstarts in 2c. ADR-006 gains one line: the anchor is entered by a session switch, not a launcher. -
Delivery: one MR,
Closes #498,Relates to #488; then the release that turns remote execution on (pi-ssh 0.2.0, pi-modes, pi-workflow, pi-guidance, pi-workspace as changed,@gadhs/pi); the merge SHA on #488; phase 3 (#491) next.
Out
Port forwarding, the daemonised helper and the Windows client check (phase 5). The commit path over SSH (phase 3). Remote worktrees for helpers, count, generate_image, monitors, session facts' git reads and detectLanguages on the workspace (phase 4, re-scoped). A --ssh CLI flag. A Windows remote. Password authentication.
Named but not supplied to the cold reviewer: CHANGELOG.adoc, docs/modules/ROOT/nav.adoc, docs/modules/ROOT/pages/packages.adoc, docs/modules/ROOT/pages/modes.adoc, docs/modules/ROOT/pages/adrs/adr-006-remote-execution.adoc, packages/pi-ssh/{connection,ops,remote-search}.ts, packages/pi-workspace/{types,local}.ts, packages/pi-modes/{helper-worktree,diagnostics,lone-escape}.ts, packages/pi-guidance/index.ts, packages/pi-ssh/index.ts, and pi’s dist/core/{agent-session-runtime,session-manager,system-prompt}.js, dist/core/extensions/runner.js and docs/extensions.md (untracked node_modules; line numbers are pi 1.1.0’s, the repository’s pinned copy).
Erratum (2026-10-26): pi reads AGENTS.md when it creates a session, before any session_start, so /ssh writes the mirror during its probe, before the switch; session start refreshes it for the next session and says when AGENTS.md changed (/reload). A helper’s session, which reuses its parent’s workspace, does not mirror.
Erratum (2026-10-26): the mirror follows pi’s own discovery (resource-loader.js), not "up to the repository’s top": every directory from / down to the root, the first of AGENTS.override.md, AGENTS.md, AGENTS.MD, CLAUDE.md, CLAUDE.MD that is a file, its BOM stripped, found in one remote shell call. No git rev-parse.
Erratum (2026-10-26): no project_trust handler. pi asks for trust only when a project has .pi/settings.json, .pi/mcp.json, .pi/extensions or .agents/skills (trust-manager.js), none of which the mirror writes, so an anchor is trusted exactly as a local checkout with the same files is, and the handler would never run.
Erratum (2026-10-26): the slug’s hash is twelve hex characters, not six, so the 10k-sample property test holds for pairs that sanitise alike.
Erratum (2026-10-26): a tool call or ! in an anchor with no remote published (the start could not publish, or a helper outlived its parent) refuses with the reason instead of acting on the anchor’s files.
Erratum (2026-10-26): authorizeAsk reads an ask’s path under the anchor, or a relative one, as the remote path it stands for before any rule sees it: the anchor lives under ~/.pi/agent, where the shipped /.pi/ write rule asks, so every remote write went to the judge (found by the contract test).
Erratum (2026-10-26): containment places a path on the remote without collapsing .. (placeOnRemote); the workspace’s resolve normalises lexically, which judged out/../x inside while a shell’s redirect wrote through the link (found by the regression test over a real helper).
Erratum (2026-10-26): the judge’s facts in a remote session also leave the origin unclaimed and call a push’s destination a network host, since the anchor has no repository to read.
Erratum (2026-10-26): the status line is refreshed after each tool call from connected(), not from the connection’s onLost; the workspace’s onLost now clears only its own attempt, so a closed connection’s late loss cannot orphan its successor.
Erratum (2026-10-26): a wrapped connection error keeps its class name in the session-start and reconnect notices; that is 2a’s asWorkspaceError, filed as #500 and fixed before the release.