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). switchSession takes the session’s cwd from the file’s header and refuses one that does not exist on this machine (assertSessionCwdExists). pi -c takes the newest .jsonl by 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 continues lastConversation(anchor, sessionDir) (pi-ssh/anchor.ts), which calls SessionManager.list and 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 .git walk of ctx.cwd and os.hostname(). In an SSH session ctx.cwd is 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; its Hello names the remote’s home, 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 with mode. With at, it appends only when the file is exactly at bytes long (a missing file is 0); otherwise it throws WorkspaceError with code ECONFLICT and 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 most length bytes from from; 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’s cwd at the first later line whose type is "message", asking for no line after it; undefined when the lines end first.

  • latestConversation(dir: string, cwd: string): Promise<Conversation | undefined>: dir’s `.jsonl files by mtime, newest first; the first whose messageAmong (over the file’s lines, read as a stream) answers with a cwd that resolves to cwd; modified is 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

fetch: the whole file

remote only, an entry

none: deleted here; it stays on the remote

local only, no entry

push when it holds a message (messageAmong), else none

local only, an entry

none: deleted on the remote; the copy here stays

both, forked, local equal to forked.at

replace: the fork’s second step

both, an entry, sizes as recorded

none

both, local longer, remote as recorded

push-tail

both, remote longer, local as recorded

fetch-tail

both, an entry, any other sizes

fork

both, no entry

compare

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.

  • push writes the header (rewritten) and body to <name>.jsonl.part on the remote and renames it when complete, so the box’s pi never lists half a file. fetch collects the remote’s bytes in a local <name>.jsonl.part and, complete, writes the .jsonl with the rewritten header and sets its mtime to the remote’s. A .part on either side is continued when its digest equals the same range of its source, else started again.

  • fork has 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, and forked is recorded (a local file forkFrom refuses is renamed <name>.jsonl.diverged instead). 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 version is above pi’s CURRENT_SESSION_VERSION is 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):

  1. Lists both directories (remote: one readdir, then the stat`s sent together) and runs `decide for every name.

  2. 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. For openFile this step is done last, in the same tick as the call to ctx.switchSession.

  3. 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 /ssh continues. When it needs a fetch, a fetch-tail or a replace, that is done now, the status line reading ssh <label>: fetching your last session, <a> of <b> MiB. A replace of openFile is not done; the next candidate is taken.

  4. 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, after session.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 by decide, replace first, 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_end and session_shutdown: sync.push() sends what the live file holds past its entry with appendFile(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, except session_shutdown, which waits at most SHUTDOWN_PUSH_WAIT_MS (5 s) before the connection closes.

  • ECONFLICT: when the remote is exactly the piece longer and digest(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 says pi-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 /ssh try 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.

Not in this plan

  • A storage hook upstream in pi. This design needs none.

  • Sessions of a subdirectory of the root: pi files those under another directory on the box.

  • A command that deletes a session on both sides.

Scope

Four MRs on main, in this order, each passing validate.

  1. #877 (fix/ssh-latest-conversation, Closes #877): anchor.ts, commands.ts; test/anchor.test.ts (the lastConversation case); test/session.test.ts (the #876 cases share one session directory between two anchors and date conversations by message time: converseAt also sets the file’s mtime); `ssh.adoc’s #877 limitation.

  2. The operations and the wire: pi-workspace/types.ts, local.ts, contract.ts; pi-ssh/helper.mjs, protocol.ts, connection.ts, ssh-workspace.ts; the protocol: 3 literals in pi-ssh/test/connection.test.ts, fake-helper.ts, protocol.test.ts and session.test.ts; public-surface.adoc (PROTOCOL_VERSION = 4); packages.adoc (the new members).

  3. 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 (its pipeConnect gives the remote a scratch PI_CODING_AGENT_DIR through pipeTransportWith, so /ssh in a test writes under no real home; the prompt and status cases); test/tools.test.ts (the events piSsh subscribes to gain agent_end and turn_end).

  4. Memory (Closes #915): new pi-modes/memory-remote.ts, test/memory-remote.test.ts (over test/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 gain await and 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 appendFile; the two-clients test.

A retried append lands twice after a dropped link

fail-closed

appendFile is not in IDEMPOTENT; the conflict that follows counts only on an equal digest. Test: a push whose reply is lost.

A session added to on both sides loses one side

fail-closed

fork keeps both as two sessions and says so; the open file is not replaced. Tests: two writers; /ssh typed in the forked session.

A copy rewritten in place is read as one that grew

fail-closed

The mark is checked before any tail moves; a mismatch is a fork. Test: a rewritten local file of greater size.

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, /ssh status shows it, the next /ssh sends them. Test: a read-only remote home.

Transcripts, which hold what a session saw, land on a shared host

silent

Files 0600 and directories 0700; ssh.adoc and security.adoc say what is written where. Test: the modes of what a push creates.

ssh’s non-interactive environment lacks a `PI_CODING_AGENT_DIR the box’s own shell sets, so the files land where its pi does not look

silent

/ssh status prints the remote directory; ssh.adoc names the case.

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; --new skips it.

Memory holds a turn on a slow link

fail-open

Five-second bound; no block and one notice. Test: a workspace that never answers.

sessions.json is lost, or two pi processes write it

fail-closed

No entry leads to compare, and from there to an entry or a fork. Test: the record deleted between two opens.

Tests

  • Contract (workspaceContract; local, the helper over pipes, the daemon, ssh localhost): appendFile plain; with at equal; with at unequal (ECONFLICT, the file unchanged); a missing file with at: 0 and mode; readRange and digest whole, ranged and past the end. protocol.test.ts holds the two protocol versions equal; a hello carries agentDir and hostname, with and without PI_CODING_AGENT_DIR.

  • Contract (session-sync.test.ts, the pipe remote with a scratch pi directory):

    • a session begun over /ssh and pushed is what SessionManager.continueRecent(root, <remote dir>) opens: header cwd the root, entries equal, a body line naming the anchor byte-equal;

    • one begun there (SessionManager.create(root, <remote dir>), messages appended) is the file /ssh switches to: header cwd the anchor, entries equal;

    • the remote directory’s name equals the one SessionManager.create(root) uses, with PI_CODING_AGENT_DIR stubbed.

  • 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) latestConversation names the file that SessionManager.list, kept to messageCount > 0 and ordered by file mtime, names; messageAmong over 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 when switchSession is called.

  • Concurrency: two clients append with the same at: one succeeds, one ECONFLICT. Two triggers in one tick send each byte once. A remote whose appendFile never answers: the turn_end handler has returned, and the session_shutdown handler returns once its wait has passed (the test sets the wait to 50 ms through sessions.shutdownWaitMs) with the entry unchanged.

  • Property (fast-check), decide: total over arbitrary sizes and entries; push-tail only with the remote as recorded and the local longer; fetch-tail only with the local as recorded and the remote longer; none for 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.part and no <name>.jsonl, and SessionManager.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 cwd rewritten, body digests equal, modes 0600, one notice; a second start calls appendFile zero times. A newest session that is local only: /ssh switches with no appendFile before 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 equals computeScopeKeys of a local clone of the same origin; a note written through the SSH workspace is listed by a local MemoryState over 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.ts passes 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 /ssh from panther to luchs: continue there with pi -c, come back.

  • Measured after the first MR: /ssh into 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 the PI_CODING_AGENT_DIR case 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 /ssh after 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.adoc on approval and listed in nav.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.

Edit this page · latest