Plan: an SSH project’s sessions and memory live on the remote host
Closes: #915 (and #877, by this plan’s first MR). Relates to: #914 (folded in), #876, #524, #750. Branch: feat/ssh-remote-home. Status: Done (2026-11-24) — sessions and memory live on the host; Windows rows and a real /ssh round trip panther to luchs on #915 (note 4316797188)
Context
Ruled by the operator (2026-11-22, 2026-11-24): the remote host is the home of an SSH project’s sessions and memory; two writers are settled by forking the later one; a client fetches all of the box’s sessions, in the background.
What the code does today, by reading:
-
pi’s
SessionManager(pi 1.5.2,dist/core/session-manager.js) writes a session synchronously to a local file and gives an extension no storage hook. It files a directory’s sessions under<agentDir>/sessions/--<cwd, separators as →--/(getDefaultSessionDirPath, not exported).switchSessiontakes the session’s cwd from the file’s header and refuses one that does not exist on this machine (assertSessionCwdExists).pi -ctakes the newest.jsonlby mtime that opens with a session header (findMostRecentSession). A file is created once the session holds a user or assistant message (_persist) and then grows by appended lines; pi rewrites one in place only to convert a header below version 3. -
/ssh(pi-ssh/commands.ts,open) probes the remote, then continueslastConversation(anchor, sessionDir)(pi-ssh/anchor.ts), which callsSessionManager.listand so reads every session file of the anchor whole: 3.2 s for 328 MiB on panther (#877). -
Memory (
pi-modes/memory.ts,memory-wiring.ts) is one local store,<agentDir>/gadhs-memory.json, keyed by a.gitwalk ofctx.cwdandos.hostname(). In an SSH sessionctx.cwdis the anchor, which holds no.git, and pi-ssh publishes the workspace after pi-modes' session start (#914). -
The wire (
pi-ssh/protocol.ts,helper.mjs) has no append, no ranged read and no digest; itsHellonames the remote’shome, not its pi directory or host name.
Design
The shape
The remote holds the session files, where a pi running on the box files that directory’s sessions. This machine keeps a working copy of each in the anchor’s session directory, which is what pi opens and /resume lists. The two copies of a session are the same bytes after the first line. The first line, the header, differs in cwd (the remote root there, the anchor here: each pi needs a cwd that exists on its own machine) and in parentSession when that names a file of the session directory (the same name in the other directory). A header is written when a copy is created; after that both copies grow by the same appended bytes. A body line that names the anchor stays as written.
The anchor, remote.json, the mirror, trust, left.json, plan drafts, approvals and diagnostics stay on this machine, unchanged.
The transition needs no step of its own: a session this machine holds and the remote does not is sent (below), with one notice. Nothing is set aside, since the copy here stays the working copy and /resume lists each session once.
Three workspace operations and two host facts (pi-workspace, pi-ssh)
Workspace (pi-workspace/types.ts) gains three required members, implemented in local.ts, in ssh-workspace.ts and as helper operations of the same names in helper.mjs:
-
appendFile(path: string, data: Uint8Array, options?: { at?: number; mode?: number }): Promise<number>appends and resolves to the file’s new size, creating a missing file withmode. Withat, it appends only when the file is exactlyatbytes long (a missing file is 0); otherwise it throwsWorkspaceErrorwith codeECONFLICTand the message<path> is <n> bytes, not <at>. The helper checks and writes synchronously on one descriptor, so two clients of one daemon cannot interleave. -
readRange(path: string, from: number, length: number): Promise<Uint8Array>: at mostlengthbytes fromfrom; fewer at the file’s end. -
digest(path: string, from?: number, length?: number): Promise<string>: the SHA-256, in hex, of that range (default: the whole file).
Erratum (2026-11-24): appendFile writes through an append-mode descriptor, never at a position. pi-win found that the positional write overwrote another process’s appends, each writer told its append had landed (#915, note 4316000630). With append mode, an append from another process between the size check and the write lands before these bytes, and the next append at the returned size is refused. The tests are pi-ssh/test/append-race.test.ts and pi-workspace/test/append-race.test.ts.
Erratum (2026-11-24): a fourth required member, utimes(path: string, mtimeMs: number): Promise<void>, is a helper operation of the same name. Every copy this machine sends or fetches is given its source’s mtime once in step, the remote’s push included. Without it, the box’s pi -c, which takes the newest file, would continue whichever session was sent last. Contract case: utimes.
and one optional member, absent on a local workspace as clientPath is: hostPi?(): Promise<{ agentDir: string; hostname: string }>, pi’s agent directory on the host and the host’s name, as a pi running there computes them. The helper’s Hello gains agentDir (PI_CODING_AGENT_DIR when set, a leading ~/ put under the home; else <home>/.pi/agent) and hostname (os.hostname()); HostFacts carries both; hostPi is defined in ssh-workspace.ts’s `onHost, so a view made by at() has it. PROTOCOL_VERSION becomes 4 in protocol.ts and helper.mjs. readRange and digest join IDEMPOTENT in connection.ts; appendFile does not. Test fakes written as object literals are cast (as unknown as Workspace) and the rest spread localWorkspace, so none needs the new members.
The session to continue, found as pi -c finds it (#877)
anchor.ts loses lastConversation. In its place, both exported:
-
messageAmong(lines: AsyncIterable<string>): Promise<{ cwd: string } | undefined>: the first line that parses must be a session header (else undefined); it resolves to the header’scwdat the first later line whosetypeis"message", asking for no line after it; undefined when the lines end first. -
latestConversation(dir: string, cwd: string): Promise<Conversation | undefined>:dir’s `.jsonlfiles by mtime, newest first; the first whosemessageAmong(over the file’s lines, read as a stream) answers with acwdthat resolves tocwd;modifiedis its mtime. A file that cannot be read is passed over.
commands.ts (open, newerElsewhere) calls latestConversation(sessionDir, anchor), sessionDir being deps.sessionDir or, absent, SessionManager.create(anchor).getSessionDir(). The cost is the lines before each file’s first message, not the files.
The record and the decision (new: pi-ssh/sync-record.ts, pi-ssh/session-sync.ts)
<anchor>/sessions.json: { "version": 1, "sessions": { "<name>.jsonl": { "local": <bytes>, "remote": <bytes>, "mark": "<hex>", "forked"?: { "as": "<name>.jsonl", "at": <bytes> } } } }. local and remote are the sizes at which the copies were last in step; mark is the SHA-256 of the last min(4096, body length) body bytes at that point; forked is set between the two steps of a fork. The file is read again before each change, written beside and renamed into place. Missing, not JSON, or another version: an empty record.
The remote directory is <hostPi().agentDir>/sessions/--<slug>--, the slug made from ws.realpath(root) by pi’s rule (leading separator dropped; /, \ and : to -), and the remote header’s cwd is that same resolved path. Directories are made with mode 0700 and files with 0600: a transcript holds whatever the session saw.
decide(entry, local, remote) is pure; local and remote are the sizes now, undefined when a copy is absent:
| State | Action |
|---|---|
remote only, no entry |
|
remote only, an entry |
|
local only, no entry |
|
local only, an entry |
|
both, |
|
both, an entry, sizes as recorded |
|
both, local longer, remote as recorded |
|
both, remote longer, local as recorded |
|
both, an entry, any other sizes |
|
both, no entry |
|
compare: when the shorter body’s digest equals the same range of the longer one, the entry is written at the shorter and decide runs again; else fork. A tail is sent or fetched only after the side that grew still shows the recorded mark just before the recorded size; a side that does not was rewritten, and is a fork.
How each action moves bytes:
-
Pieces are whole lines up to
PIECE_BYTES(1 MiB), or one line when it alone is longer; one piece is in flight at a time. -
pushwrites the header (rewritten) and body to<name>.jsonl.parton the remote and renames it when complete, so the box’s pi never lists half a file.fetchcollects the remote’s bytes in a local<name>.jsonl.partand, complete, writes the.jsonlwith the rewritten header and sets its mtime to the remote’s. A.parton either side is continued when its digest equals the same range of its source, else started again. -
forkhas two steps. First:SessionManager.forkFrom(file, anchor, sessionDir)makes a new session from this machine’s version, its mtime set to the old file’s, andforkedis recorded (a local fileforkFromrefuses is renamed<name>.jsonl.divergedinstead). Second,replace: the remote’s version is fetched whole over the old name and the entry is written in step. The new session has no entry, so it is pushed as any local-only session is. -
A fetched file whose header
versionis above pi’sCURRENT_SESSION_VERSIONis not fetched; one notice counts them. -
Helpers' transcripts (the directory named as the session file without
.jsonl) are sent as they are, when the remote has none of that name or a shorter one; they are not fetched and their headers are not rewritten, since pi opens none of them as a session.
Erratum (2026-11-24): the module layout differs from the plan. The record and decide are in sync-record.ts; the byte moves both directions share are in session-copy.ts; the actions and settle are in session-sync.ts; bringUpToDate is in session-open.ts; SessionSync is in session-live.ts.
Erratum (2026-11-24): both sides' listings keep only sessions whose header names that side’s own cwd. This machine’s folder can hold other projects' sessions (pi’s PI_CODING_AGENT_SESSION_DIR), and the host’s another directory’s, because pi spells /srv-app and /srv/app alike. Copies that both grew past their entry are compared beyond it before a fork, so an append whose reply was lost counts once, whether met at the conflict or at the next settle. A helper’s transcripts are sent with every push of their session, not only its first: helpers run during the session. While the open session’s fork waits for the switch, the session is not a candidate to continue. Its fork’s file is entered when nothing newer is.
Opening: /ssh (commands.ts)
open awaits ctx.waitForIdle() first. Inside probe, on its connection, after the mirror and unless --new, bringUpToDate(ws, anchor, sessionDir, openFile) (session-sync.ts; openFile is the session this pi has open):
-
Lists both directories (remote: one
readdir, then thestat`s sent together) and runs `decidefor every name. -
Does every fork’s first step, and warns:
pi-ssh: <file> was continued both here and on <destination>. The remote’s version keeps the session; this machine’s is now <new file>, which /resume lists.ForopenFilethis step is done last, in the same tick as the call toctx.switchSession. -
Orders the candidates newest first: a remote version by the remote’s mtime, a local-only or forked-off session by its own. The first that holds a message is the session
/sshcontinues. When it needs afetch, afetch-tailor areplace, that is done now, the status line readingssh <label>: fetching your last session, <a> of <b> MiB. AreplaceofopenFileis not done; the next candidate is taken. -
Leaves every push, and every other fetch, to the background.
So only a fetch of the session being continued holds /ssh. openFile is appended to by this step at most (a fetched tail, which the switch then reloads) and is not replaced while open. newerElsewhere (#876) runs after it, unchanged apart from latestConversation.
A failure of bringUpToDate (the remote’s pi directory cannot be written, a full disk, a dropped link) does not stop /ssh: it continues latestConversation of the local copies and says pi-ssh: sessions are not kept on <destination> this session: <reason>. They stay on this machine and are sent at the next /ssh.
While the session runs (session.ts, extension.ts)
SessionDeps gains sessions?: { shutdownWaitMs?: number } (the session directory and the live file come from ctx.sessionManager): present, the instance that owns the remote keeps its session files in step, through a SessionSync (session-sync.ts) that SshSession.sync() returns; absent (tests of other things), and for a helper’s instance, there is none. piSsh passes sessions: {}.
-
At
session_start, aftersession.start:sync.begin(ctx.sessionManager, ctx.ui). When the remote’s copy of the live file is longer than recorded and the local one is not:pi-ssh: <destination> has a newer copy of this session; /ssh <place> picks it up. What you add here before that is kept as a new session.Then the background queue runs every other name bydecide,replacefirst, then newest first. It pushes the live file and otherwise leaves it alone. The first time sessions with no entry are pushed:pi-ssh: <n> session(s) kept only on this machine are now on <destination> (<dir>). -
On
turn_end,agent_endandsession_shutdown:sync.push()sends what the live file holds past its entry withappendFile(remote, piece, { at: entry.remote, mode: 0o600 }). One push runs at a time; a second trigger sends what is left when the first ends. The handlers do not await it, exceptsession_shutdown, which waits at mostSHUTDOWN_PUSH_WAIT_MS(5 s) before the connection closes. -
ECONFLICT: when the remote is exactly the piece longer anddigest(remote, entry.remote)equals the piece’s, the push had landed before a dropped link lost its reply, and it counts. Any other conflict stops pushes for this session (kept in memory) and sayspi-ssh: this session was continued on <destination> since it was opened here. What you add stays on this machine; the next /ssh <place> files it as a new session beside that one. -
Any other failure changes no entry; the next trigger and the next
/sshtry again.
/ssh status gains one line: ` sessions: <remote dir>, in step`, or , <n> KiB not yet sent, or , not kept there: <reason>.
sshBlock (prompt.ts): the line about pi’s own files becomes Plan drafts stay on this machine under <agentDir>; write those by their absolute path. Sessions and memory are kept on the remote host, under its own pi directory.
Memory (pi-modes)
memory.ts exports repoKeyOf(identity: string): string, the hash computeScopeKeys makes today, and uses it. New memory-remote.ts: remoteScope(ws: Workspace): Promise<{ keys: ScopeKeys; path: string; archivePath: string }> for a workspace with hostPi. The repo key is repoKeyOf of git config --local --get remote.origin.url in the root, else of path: and ws.realpath of git rev-parse --path-format=absolute --git-common-dir; outside a repository there is none. The machine key is hostPi().hostname. The store is <hostPi().agentDir>/gadhs-memory.json, its archive beside it: the files and keys the box’s own pi uses, so both see the same notes. A machine note in an SSH session is the remote host’s.
memory-wiring.ts: file access goes through a MemoryFiles seam (read, replace by write-beside-and-rename, append), one over node:fs and one over a workspace (readFile; writeFile and rename, keeping the store’s mode, 0600 when it creates it; appendFile). The handlers take the session’s cwd and become async: rememberCommand, memoryCommand, runMemoryCommand, pickMemory, memoryCandidates, memoryCompletions, rememberTool, forgetTool, memoryPromptBlock; MemoryWiring.systemPromptBlock(cwd, ui) returns a promise, awaited in session-wiring.ts onBeforeAgentStart, whose context type gains ui. ready asks workspaceFor(cwd): a local workspace is today’s path; a remote one’s scope is computed once per workspace label, and its first use expires old proposals as session start does locally. memoryCompletions, which pi calls with no context, uses the scope last resolved. A version-1 store on the remote is not converted from here: memory: <label>'s store is from an older release; start pi there once to convert it. A remote read that fails, or does not answer within MEMORY_REMOTE_WAIT_MS (5 s), gives no block and, once per workspace until it answers again, memory: <label> did not answer; no notes this turn. Cost: one round trip a turn.
Notes filed on this machine under the same origin are not copied to the box: each machine’s store is its own.
Scope
Four MRs on main, in this order, each passing validate.
-
#877 (
fix/ssh-latest-conversation,Closes #877):anchor.ts,commands.ts;test/anchor.test.ts(thelastConversationcase);test/session.test.ts(the #876 cases share one session directory between two anchors and date conversations by message time:converseAtalso sets the file’s mtime); `ssh.adoc’s #877 limitation. -
The operations and the wire:
pi-workspace/types.ts,local.ts,contract.ts;pi-ssh/helper.mjs,protocol.ts,connection.ts,ssh-workspace.ts; theprotocol: 3literals inpi-ssh/test/connection.test.ts,fake-helper.ts,protocol.test.tsandsession.test.ts;public-surface.adoc(PROTOCOL_VERSION = 4);packages.adoc(the new members). -
Sessions: new
pi-ssh/sync-record.ts,session-sync.ts,test/session-sync.test.ts;commands.ts,session.ts,extension.ts,prompt.ts;test/session.test.ts(itspipeConnectgives the remote a scratchPI_CODING_AGENT_DIRthroughpipeTransportWith, so/sshin a test writes under no real home; the prompt and status cases);test/tools.test.ts(the eventspiSshsubscribes to gainagent_endandturn_end). -
Memory (
Closes #915): newpi-modes/memory-remote.ts,test/memory-remote.test.ts(overtest/ssh-under-test.ts’s `remoteUnderTest);memory.ts,memory-wiring.ts,session-wiring.ts;test/memory-wiring.test.ts(its 69 calls of the handlers gainawaitand a cwd),test/session-wiring.test.ts(its memory fake returns a promise); the docs and the release note.
Risks
| Risk | Mode | Mitigation |
|---|---|---|
Two writers interleave in one remote file |
fail-closed |
Every push names the size it expects; a mismatch writes nothing, and the helper’s check and write are one synchronous step. A pi on the box writing in that same instant leaves both writers' whole lines, and the next push conflicts. Contract test of |
A retried append lands twice after a dropped link |
fail-closed |
|
A session added to on both sides loses one side |
fail-closed |
|
A copy rewritten in place is read as one that grew |
fail-closed |
The |
The remote’s pi directory cannot be written, or the link is down |
fail-open |
Sessions work from this machine as today, one warning says why, |
Transcripts, which hold what a session saw, land on a shared host |
silent |
Files 0600 and directories 0700; |
|
silent |
|
A box with an older pi cannot read a newer client’s session; a newer box’s session is in a format this pi does not know |
silent / fail-closed |
The second is not fetched, and counted in a notice (test). The first is a documented limit: update pi on the box. |
A first connect moves hundreds of MiB (pi’s history here: 355 MiB) |
silent |
Background, one 1 MiB piece in flight, continued after a restart; only the continued session’s fetch is in the foreground, with its progress shown; |
Memory holds a turn on a slow link |
fail-open |
Five-second bound; no block and one notice. Test: a workspace that never answers. |
|
fail-closed |
No entry leads to |
Tests
-
Contract (
workspaceContract; local, the helper over pipes, the daemon,ssh localhost):appendFileplain; withatequal; withatunequal (ECONFLICT, the file unchanged); a missing file withat: 0andmode;readRangeanddigestwhole, ranged and past the end.protocol.test.tsholds the two protocol versions equal; a hello carriesagentDirandhostname, with and withoutPI_CODING_AGENT_DIR. -
Contract (
session-sync.test.ts, the pipe remote with a scratch pi directory):-
a session begun over
/sshand pushed is whatSessionManager.continueRecent(root, <remote dir>)opens: headercwdthe root, entries equal, a body line naming the anchor byte-equal; -
one begun there (
SessionManager.create(root, <remote dir>), messages appended) is the file/sshswitches to: headercwdthe anchor, entries equal; -
the remote directory’s name equals the one
SessionManager.create(root)uses, withPI_CODING_AGENT_DIRstubbed.
-
-
Regression (#877,
anchor.test.ts): over fixtures (a header-only file, one whose first message comes late, one that is no session, another anchor’s in the same directory, several by mtime)latestConversationnames the file thatSessionManager.list, kept tomessageCount > 0and ordered by file mtime, names;messageAmongover lines that throw when asked past the first message still answers. -
Two writers: both sides add to one session. Live: the conflict’s text, the remote file unchanged, no further
appendFile. At the next/ssh: the warning names both files, a new file holds this machine’s version, and after the next start the old name equals the remote’s. Typed inside that session: the open file’s bytes are unchanged whenswitchSessionis called. -
Concurrency: two clients append with the same
at: one succeeds, oneECONFLICT. Two triggers in one tick send each byte once. A remote whoseappendFilenever answers: theturn_endhandler has returned, and thesession_shutdownhandler returns once its wait has passed (the test sets the wait to 50 ms throughsessions.shutdownWaitMs) with the entry unchanged. -
Property (fast-check),
decide: total over arbitrary sizes and entries;push-tailonly with the remote as recorded and the local longer;fetch-tailonly with the local as recorded and the remote longer;nonefor a recorded pair only at the recorded sizes. -
Failure: a remote home that refuses writes (the warning, the session usable, no entry); a link dropped mid-push (the next trigger sends the rest); a lost reply (counted by digest, no duplicate); a whole-file push stopped after its first piece (the remote directory holds
<name>.jsonl.partand no<name>.jsonl, andSessionManager.list(root, <remote dir>)is empty), then continued after a restart; a newer-format file not fetched; a rewritten file forked; a deleted record compared. -
Migration: an anchor with three local sessions, one with a helper’s transcript, and no record: after one start all are on the remote, header
cwdrewritten, body digests equal, modes 0600, one notice; a second start callsappendFilezero times. A newest session that is local only:/sshswitches with noappendFilebefore the switch. -
Ownership: an instance that reuses its parent’s workspace has no
SessionSync. -
Memory (
memory-remote.test.ts): a remote checkout’s repo key equalscomputeScopeKeysof a local clone of the same origin; a note written through the SSH workspace is listed by a localMemoryStateover the remote’s agent directory, and the reverse; a workspace published after session start gets its pool at the next turn; a version-1 remote store is left byte-equal, with its notice; a workspace that never answers gives no block and one notice.memory-wiring.test.tspasses with no changed expectation: a local session is as before. -
Windows: pi-win runs pi-workspace, pi-ssh and pi-modes on panther, main against each branch, and one real
/sshfrom panther to luchs: continue there withpi -c, come back. -
Measured after the first MR:
/sshinto panther’s 328 MiB anchor, before and after; the prediction filed first.
Delivery
-
Canonical page:
ssh.adoc. A new section, "Sessions and memory live on the remote"; "What runs where" moves sessions and memory to the remote’s column; the paragraph "Sessions stay on this machine" and the limitation "Plan drafts, memory and sessions are local" are rewritten (plan drafts stay); the #877 limitation goes; the first-connect cost, the file modes and thePI_CODING_AGENT_DIRcase are stated.tuning.adoc(Memory): what an SSH session reads and writes.security.adoc: transcripts and notes on the remote host. -
CHANGELOG
== Unreleased: Fixed for #877; Changed for sessions and memory, saying that the first/sshafter the update sends this machine’s sessions to the remote and fetches the remote’s. -
The plan is committed to
docs/modules/ROOT/pages/plans/ssh-remote-home.adocon approval and listed innav.adoc. -
Each MR’s merge SHA is noted on its issue. Released as a minor after the fourth: pi-workspace, pi-ssh and pi-modes change, and their dependents move with them.