Repository navigation
Description
Child of #588. Read the parent's Contract first: it holds the wire, the re-cut, the merge order and the joint close task. Branch off epic/588-host-adopt, cut from main after #585 merged.
User story
As the owner, I want relay to adopt a terminal Claude on an SSH host and keep it running there, so that I can drive it like a local adopted session.
Acceptance criteria
- The probe marks a live Claude row on a Unix host
adoptable: truewhen its registry tests pass, the host probe foundclaude, the host hasdetach_sessionsabsent ortrue, and the host project allows theclaude-codetemplate. - The probe marks a Claude row
host_unsupportedon a host whose probe did not findclaude, on a host withdetach_sessions: false, or in a host project with noclaude-codetemplate. POST /api/sessions/adopton an adoptable host row answers 201, and the session runsclaude --resume <conversation id>on the host in the row's folder.- On a host with tmux 3.0 or later the session runs in the tmux session
relay-agent-<session id>. Without it, the session runs under the plain runner. - One SSH command starts the transition script detached on the host. Relay sends no signal over SSH itself.
- The script sends no signal and answers 409
changedwhen the pid's start time differs from the row's before the first signal. - The door or the script answers 409
busyand sends no signal when the session is not idle, unless the request setsinterrupt. - With
interrupt, the script sends SIGINT, then SIGTERM and SIGKILL as needed, and checks the start time before each signal. - After an adopt with
interrupton a busy session, relay sends the recovery message, as for a local adopt. - Relay writes the
session_adoptintent, thesession_interruptintent (when it interrupts) and the session's dormant ledger record before the SSH command starts. - When the SSH command ends with no result, relay answers 502
host_link_lostand keeps the dormant record. - A resume of that record attaches the agent the script started, or starts
claude --resume <conversation id>on the host when none runs. - A resume answers 409
changed, starts nothing and removes the record while the outside process still runs with its pinned start time. - A host adopt with no
modelnever answersmodel_unknown. - The
session_adoptandsession_interruptrows of a host adopt carryhost_id, and each intent gets exactly one completion. - The adopted session lists with its host,
headless: true, and nounsandboxedfield. - A Chief of Staff send to the session answers 202. Drop in opens Claude on the same conversation on the host, and a send while it holds the session answers 409
dropped_in. - fakerelay serves an adoptable host row, the host adopt answer and the
host_link_lostrefusal as relay does.
What I'd notice
An Adopt button on a terminal Claude row on an SSH host (through eve). After adopt, relay session list --json shows the session with its host, and tmux ls on the host lists relay-agent-<id>.
Tasks
- Gate: the probe's caller passes the host test into
GateAdoption; the door re-checks it. - Door: the host branch of
adoptOutside(tail read, verdict, model rule, intents withhost_id, dormant record,/launchwithadopt_host, outcomes,host_link_lost). - Resume: a record with
adopt_pendingresumes throughadopt_hostwithno_signal. - Script:
internal/sshhost/adopt.go, the detached transition around the existing start step. - relay-sessions:
adopt_hoston/launch;resume_conversationon a host claude launch only with it; the provider's transition start; the manager's fallback for a missing saved session. - fakerelay: an adoptable host row, the host adopt answer, the
host_link_lostknob. - Docs: the files in the ownership list, in the line budgets it gives.
- Tests (test writer, from the criteria and this contract): the four e2e cases, the
psseam, the prooftest case, the two journeys. - Break and restore: make the script's lifetime comparison always match, confirm
TestAdoptHostChangedgoes red, restore byte for byte. - Review on the default model: the diff touches a threat-model promise (3f).
Contract
Re-cut 2026-10-22 (see #588, "Re-cut"). Every file this child may touch is listed below. No ownership amendment is planned; a file not listed is a question for the planner first.
Interfaces
- Gate (
cmd/relay/outside_session_ops.go).GateAdoptionkeepsmain's signatureGateAdoption(s *Session, onHost, inProject bool, agent string). The probe passesonHost = h != nil && !hostAdopts(settings, h, project), whereThe probe script,// hostAdopts: not Windows, the host probe found claude (Probe.OK and ClaudePath set), // detach_sessions nil or true, and the project allows claude-code. func hostAdopts(settings *config.Settings, h *config.Host, p *config.Project) bool
probe.goand the row shape do not change. - Door (
cmd/relay/session_adopt.go,cmd/relay/session_adopt_host.go).adoptableRowlets a host key through when the row is adoptable.adoptOutsidehands a host row toOrder: audit ready and host ready (asfunc (a *adoptOps) adoptHost(ctx context.Context, req AdoptRequest, obs outsidesessions.Observation, hostID string, st *adoptState) (*AdoptResult, *AdoptRefusal)
main); the in-flight lock (asmain); a freshhostAdoptsand the row's project (hosted, on that host); the managed list (ManagedClaudeIdentities); the tail read (outsideRunwithoutsideRangeScript(obs.Transcript, -1, 256 KiB); no answer:502 unavailable); the verdict (busy when the row state is notidleoradopt.ReadTail(tail).OpenTool != nil; busy withoutinterrupt:409 busy); the turn-boundary read (interface 4; only when the adopt does not interrupt; it reads and writes nothing); the model (bodymodel, elseReadTail(tail).ModelFamily, else empty; nevermodel_unknown, no broker step);AuthorizeLaunch(the host project's claude launch, as for any host session); thesession_adoptintent; thesession_interruptintent when it interrupts (the request setsinterruptand the verdict is busy; only then does the script getinterrupt: true); the dormant record;/launch. Nothing reaches the host before the intents and the record are durable. A failed record write answers502 unavailable, completes the intent aserror, and starts nothing.
Audit args add"host_id"tomain's keys on every row of a host adopt. The door writes the completion itself, once, for every outcome. - Ledger (
internal/sessions/ledger/ledger.go):The record istype AdoptPending struct { ConversationID string `json:"conversation_id"` PID int `json:"pid"` Lifetime string `json:"lifetime"` // the row's lifetime string, compared byte for byte } // Record.AdoptPending *AdoptPending `json:"adopt_pending,omitempty"`
result.LedgerwithStatedormant andAdoptPendingset, written withPutbefore/launch. A successful launch writes it live withAdoptPendingnil.commitLaunchandsession_launch.godo not change. - relay-sessions wire (
internal/sessions/hostapi/types.go,dispatch.go;session/manager.go;provider/claude.go,claude_detached.go):type AdoptHostSpec struct { PID int `json:"pid"` Lifetime string `json:"lifetime"` Interrupt bool `json:"interrupt,omitempty"` // send SIGINT first TranscriptSize int64 `json:"transcript_size"` // bytes the tail read saw ChildTest string `json:"child_test"` // "none", "window" or "all" WindowFromMs int64 `json:"window_from_ms,omitempty"` // "window": the last turn's first assistant record WindowToMs int64 `json:"window_to_ms,omitempty"` // "window": the newest transcript record NoSignal bool `json:"no_signal,omitempty"` // a resume: a live pinned pid answers changed } // LaunchRequest.AdoptHost *AdoptHostSpec `json:"adopt_host,omitempty"`
checkResumeConversationacceptsresume_conversationon a hostclaudelaunch, fresh orresume: true, only withadopt_hostset, on a Unix host with detach on.adopt_hoston any other launch is400 invalid_spec. Local launches keepmain's rule.session.CreateSpec.AdoptHostpasses it toprovider.ClaudeConfig.AdoptHost.Manager.resolveSessionForCreate: aResumewithAdoptHostset and no saved session builds a new session (seeded withresume_conversation) instead of failing. Nothing else changes there.ClaudeProvider.startDetached: the existing run-state check (Resume || AttachOnly) runs first and attaches a live run, as onmain. Then, withAdoptHostset, it runssshhost.AdoptStartInorAdoptStartInPanein place ofRunnerStartInorRunnerStartInPane, with the same argv and env.- Errors, written by
writeErrthroughsessionLaunchStatus:409 adopt_busy,409 adopt_changed,502 adopt_stop_failed,502 adopt_launch_failed,502 adopt_link_lost,502 adopt_setup_failed.server.godoes not change. func TurnWindow(tail []byte, whole bool, procStart time.Time) (from time.Time, known bool)ininternal/sessions/adopt/adopt_claude.go: an exported wrapper oflastTurnBoundary,knownfalse when the tail is not whole and holds no prompt. No behaviour change.procStartis the row'ssince. WhenTurnWindowis not known and the adopt does not interrupt, the door reads the transcript backwards over SSH below the tail's start (outsideRangeScript), 1 MiB per read and 8 MiB in all, untilTurnWindowis known or the read reaches the file's start. The door sendschild_test"all"when it is still not known (a failed or short read, or the bound; fail closed),"none"whenfromis zero, else"window"withfromandReadTail(tail).LastRecord.
- Host script (
internal/sshhost/adopt.go, new):func AdoptStartIn(hostOS, dir string, d RunDir, argv []string, env map[string]string, p runnerfiles.Patterns, pins AdoptPins) string func AdoptStartInPane(hostOS, dir string, d RunDir, argv []string, env map[string]string, p runnerfiles.Patterns, tmuxPath, pane string, pins AdoptPins) string type AdoptPins struct { PID int; Lifetime, ConversationID, ChildTest string; Interrupt, NoSignal bool; TranscriptSize, WindowFromMs, WindowToMs int64 } type AdoptOutcome struct { Result, Code, Generation string } // Result: "ok", "refused", "failed" func ParseAdoptResult(out string) (AdoptOutcome, error) // a stream with no terminal line is ErrAdoptLinkLost var ErrAdoptLinkLost = errors.New("sshhost: the adopt result did not arrive")
- Files on the host, beside the session's run folders:
~/.relay/agents/<session id>/adopt.sh,adopt.state,adopt.log.RunnerRemovealready deletes them with the session.latest()reads onlyg*, so they never count as a generation. - The SSH command (
$0isrelay-adopt) writesadopt.sh, starts it detached (setsid, elseset -m, HUP ignored, aslaunch_plain), prints eachadopt.stateline as@@RELAY_ADOPT@@ <line>, and exits after the terminal line. The detached script's$0isrelay-adopt-run. adopt.statelines: anysignal INT|TERM|KILL <unix ms>, then exactly one terminal line:ok <generation>,refused busy,refused changed,failed stop_failedorfailed launch_failed.- Order inside the script: (1) the lifetime of the pid, computed exactly as the probe computes it (
/procon Linux; elseTZ=UTC LC_ALL=C ps -o lstart= -p <pid>, squeezed to single spaces), callingpsby name; (2) the pid gone: go to the start. Withno_signal: the pid alive with the pinned lifetime answersrefused changed, and anything else goes to the start. Without it: a different lifetime answersrefused changed; (3) the registry~/.claude/sessions/<pid>.json(not a symlink, at most 64 KiB) names the conversation, elserefused changed; (4) the idle test: the registry status is not one the probe reads as running or asking, the transcript size equals the pin, and the child test passes. Child test"window": no child of the pid but the turn helper (the child whose executable is/usr/bin/caffeinate:readlink /proc/<pid>/exe, else the firsttxtentry oflsof -a -p <pid> -d txt -Fn; neverps -o comm=, which readscaffeinatebecause Claude starts it by name; an executable that cannot be read counts as a child, not the helper) started inside [window_from_ms,window_to_ms], compared in seconds, the boundary second counting as inside;"all": no child but the turn helper;"none": no test. Not idle withoutinterrupt:refused busy; (5) the ladder: SIGINT wheninterrupt, then SIGTERM, then SIGKILL, each after a lifetime check, with the local ladder's waits. A mismatch or a gone pid after a signal ends the ladder and goes to the start. Alive after the SIGKILL wait:failed stop_failed; (6) the start:agentStartHeadpluslaunch_plainorpane_launchplusagentStartWait, byte for byte the existing start, thenok <generation>. A start failure:failed launch_failed. agentrun.goandpane.godo not change:adopt.gouses their constants in the same package.
- Files on the host, beside the session's run folders:
- Outcomes in the door:
relay-sessions answers Record Completion Door answers 201 live, adopt_pendingclearedok, interrupted201, then the recovery message when it interrupted adopt_busy,adopt_changedremoved error, the code 409 busy,changedadopt_stop_failedremoved error 502 stop_failed(main's message)adopt_setup_failedremoved error 502 unavailableany other code (relay-sessions refused before a script ran) removed error 502 unavailableadopt_launch_faileddormant, adopt_pendingkepterror 502 launch_failed(main's message)adopt_link_lost(also: another adopt script runs for the session), or the call failsdormant, adopt_pendingkepterror host_link_lost502 host_link_lost - Resume (
cmd/relay/session_routes.go: one branch; the body insession_adopt_host.go).resumeSessionInnerhands a record withAdoptPendingtofunc (d sessionRouteDeps) resumeAdoptPending(ctx context.Context, ev *logging.Event, caller LaunchCaller, rec ledger.Record) resumeOutcome. It authorizes as any resume (AuthorizeLaunch,Resume: true), refuses409 managedwhen another session holds the conversation, then launches withresume: true,resume_conversationandadopt_host(no_signal: true, the pinned pid and lifetime). A live run of the session is attached by the provider's existing run-state check before any script runs. 200: the record goes live withadopt_pendingcleared.adopt_changed: the record is removed and the answer is409 changed, "the terminal session still runs; adopt it again". Any other failure:502 launch_failed, the record stays. Audit:main'ssession_resumerows. - fakerelay (
fakerelay/internal/world/validate.go,fakerelay/internal/sessions/adopt.go): a host row may beadoptable: true; a host row that is not adoptable still deriveshost_unsupported. An adoptable host row is adopted into its host project with the host on the session, nounsandboxed, and model = bodymodel, elseadopt.model_family, else empty, with nomodel_unknown.adopt.refuse: "host_link_lost"answers502 host_link_lostwith the wire message and keeps the row.
File ownership
Dev (23 files):
cmd/relay/outside_session_ops.go:hostAdoptsand the gate call onlycmd/relay/session_adopt.go:adoptableRow, the hand-off toadoptHost, the host model rulecmd/relay/session_adopt_host.go(new)cmd/relay/session_routes.go: the one resume branchinternal/sessions/adopt/adopt_claude.go: exportTurnWindowonlyinternal/sshhost/adopt.go(new)internal/sessions/ledger/ledger.gointernal/sessions/hostapi/types.gointernal/sessions/hostapi/dispatch.gointernal/sessions/session/manager.go: the spec field, its pass-through and the resume fallbackinternal/sessions/provider/claude.go: the config fieldinternal/sessions/provider/claude_detached.gofakerelay/internal/world/validate.gofakerelay/internal/sessions/adopt.godocs/outside-sessions.md: hosts in "Adopting a session"; drop "Sessions on SSH hosts are not adopted"docs/session-adoption.md: a "Sessions on SSH hosts" section: the script, the dropped link, the pane note (a terminal Claude that ran in a tmux pane ends, and adopt starts a freshrelay-agentsession)docs/ssh-hosts.md: "Detached sessions": the adopt files andadopt_hostdocs/audit-log.md:host_idonsession_adoptandsession_interrupt; nosignalson a host adoptdocs/FEATURES.md: the new rowG1.55;TM3f.1claim and refs;TM3f.2refsdocs/THREAT-MODEL.md: one note in 3fdocs/routes.md: one line,502 host_link_lostdocs/fakerelay.md: only the three rows that would read false (adopt refusal step 3,adoptable,adopt.refuse), per Epic: adopt an outside Claude session on an SSH host #588 open question 2docs/session-host.md: only theresume_conversationsentence, per Epic: adopt an outside Claude session on an SSH host #588 open question 2
Not touched: probe.go, agentrun.go, pane.go, hostapi/server.go, session_launch.go, docs/events.md, docs/cli.md, fakerelay/internal/sessions/register.go, fakerelay/internal/sessions/session.go.
Test writer (7 files):
e2e/features/g1_outside_adopt_host_test.go(new)e2e/features/g1_outside_adopt_test.go: only the host row case at thehost_unsupportedtable, whose host moves todetach_sessions: false. The PR names it as an approved behaviour change.e2e/harness/sshstub.go: the one seam: apswrapper first on the stub host'sPATHthat reports a shiftedlstartfor a pid named in<root>/.fakessh/lie/<pid>, andSSHLieStart(pid int)fakerelay/prooftest/adopt_test.go: one host case for interface 8cmd/devboxverify/journey_adopt_host.go(new): the two journeyscmd/devboxverify/journey_adopt.go: the twoadoptJourneystable entries only (main.goalready concatenatesadoptJourneys)cmd/devboxverify/README.md: their entries
docs/FEATURES.md row G1.55 "Adopt an outside Claude session on an SSH host". Claim: the criteria above in one paragraph. Simple door: Eve > Chief of Staff > Agents rail > Adopt. Power door: POST /api/sessions/adopt with outsideId; hosts[].detach_sessions: false turns it off for a host. Doors: http:POST /api/sessions/adopt http:POST /api/sessions/{id}/resume cli:relay session resume cli:relay drop-in. Gate: none. Proof: audit:session_adopt=ok#host_id event:session.adopt=ok#session_id code:http:POST /api/sessions/adopt#502. Test: the four e2e names below, journey:session-adopt-host, journey:session-adopt-host-drop. TM3f.1 adds "a Claude session on a Unix SSH host in its host project" and G1.55; TM3f.2 adds G1.55. G1.50 does not change. The run report lists the TM3f.1 edit as a threat-claim change.
Paths
As in the parent. This child adds no CLI verb, flag or setting.
Acceptance mapping and test surface
| Criterion | Test (e2e unless named) |
|---|---|
Row adoptable; host_unsupported on detach_sessions: false |
TestAdoptHostSuccess; g1_outside_adopt_test.go host case |
201, --resume in the row folder, pane or plain, one SSH adopt command and no kill in the fakessh call log, no model_unknown (no body model), host and no unsandboxed in the list, audit host_id with one completion |
TestAdoptHostSuccess |
| Busy refused, nothing sent | TestAdoptHostBusy (registry status busy; fakeoutside prints no signal line) |
| Start-time mismatch sends nothing | TestAdoptHostChanged (SSHLieStart after the row lists; fakeoutside prints no signal line; no record) |
Dropped link: host_link_lost, dormant record, Resume attaches the started agent |
TestAdoptHostLinkDrop (fakeoutside --ignore TERM) |
Chief of Staff send, drop-in, dropped_in |
journey session-adopt-host |
| Interrupt and the recovery message | the devbox pass in #590 |
| A resume refused beside a live outside process | review only: it needs a drop before the script starts, which needs a hold seam the owner cut. The reviewer checks interface 5 step (2) and interface 7. |
| fakerelay | fakerelay/prooftest/adopt_test.go host case |
Journeys (api phase; host, project and template written into settings.json as session-detached-host does; NOTRUN off a stack). Each starts its outside Claude in a named tmux session on the default server and ends only that session at cleanup; never kill-server.
session-adopt-host: an interactive Claude started outside relay in tmux on the loopback host, in the host project's folder; adopted byoutsideId(the row with the host'shostId, never its console twin) with nomodel;tmux lslistsrelay-agent-<id>; a Chief of Staff send answers 202 and the reply lands in the same transcript;relay drop-inopens Claude, a send answersdropped_in; the terminal closes and the session is headless again; a second Chief of Staff send answers 202; thesession_adoptrows carryhost_id.session-adopt-host-drop: as above until the adopt; the journey stops the outside Claude with SIGSTOP, so the SIGTERM wait runs its full bound. On thesignal TERMline of the host'sadopt.state, it kills the adopt'ssshclient (a process namedssh, child of relay-sessions, whose arguments holdrelay-adopt; never therelay-adopt-runscript). PASS: the adopt answers 502host_link_lost; after theadopt.stateterminal line,relay session resumeanswers 200 and a send replies in the same transcript. FAIL: the outside process is gone and no session record exists.
Waits:
- e2e boot: the test bundle's ready signal.
- The outside row: the inventory snapshot
revisionthat lists it. - A signal reaching the outside process: fakeoutside's
signal <name>line. Its exit: the fake's exit watch (PIDGone). - A script step: its
adopt.stateline, read through the stub root by a file watch. - A drop:
SSHDownreturns after the stub's commands got SIGTERM; the adopt's HTTP answer follows. The return:SSHUp, then theadopt.stateterminal line, then the resume's HTTP answer. - Adopt, resume, send, drop-in: the HTTP answer or the CLI's exit. Audit intents are durable before the answer.
- Journeys: the outside Claude's reply is model output with no signal, so a bounded transcript read, as
session-adoptdoes. Everything else waits onadopt.statelines, HTTP answers, CLI exits and the snapshot revision.
Budget
Dev: 23 files; about 800 to 900 changed Go lines (the two new files about 500 of them), about 50 fakerelay lines, 150 to 200 doc lines. Tests and journeys: 7 files, 900 to 1,100 lines. Past either figure, stop and ask the planner.
Amendment 1 (2026-10-22): hostAdopts and criteria 1 and 2 require a host probe that found claude. The door reads the transcript backwards below the tail (1 MiB per read, 8 MiB in all) to find the turn boundary. The script finds the turn helper by its executable, not its ps name. The outcome table adds adopt_setup_failed and other relay-sessions refusals (record removed, 502 unavailable). Ownership does not change.
Activity
barelyworkingcode commentedon Oct 22, 2026
Coordinator approval: inherits the approved epic's listed batches, 2026-10-22
barelyworkingcode commentedon Oct 23, 2026
Contract amendment: (2026-10-22, planner; stack-run findings, commits b225a0f and 4cd5240)
hostAdoptsalso requires a host probe withOKset and aClaudePath. Otherwise the row readshost_unsupported.child_test"all"only when that read fails, reads short, or reaches the bound without a prompt./proc/<pid>/exe, else the firstlsoftxtentry), never byps -o comm=.adopt_setup_failed, and any relay-sessions refusal without anadopt_code, remove the record and answer 502unavailable.adopt_link_lost, and the dormant record stays.Ownership, budget and tests do not change.
barelyworkingcode commentedon Oct 23, 2026
Merged into epic/588-host-adopt by #597.