Skip to content

Adopt a terminal Claude on an SSH host: transition script, launch, dropped-link recovery, fakerelay, docs #589

Closed

Description

@barelyworkingcode

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: true when its registry tests pass, the host probe found claude, the host has detach_sessions absent or true, and the host project allows the claude-code template.
  • The probe marks a Claude row host_unsupported on a host whose probe did not find claude, on a host with detach_sessions: false, or in a host project with no claude-code template.
  • POST /api/sessions/adopt on an adoptable host row answers 201, and the session runs claude --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 changed when the pid's start time differs from the row's before the first signal.
  • The door or the script answers 409 busy and sends no signal when the session is not idle, unless the request sets interrupt.
  • With interrupt, the script sends SIGINT, then SIGTERM and SIGKILL as needed, and checks the start time before each signal.
  • After an adopt with interrupt on a busy session, relay sends the recovery message, as for a local adopt.
  • Relay writes the session_adopt intent, the session_interrupt intent (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_lost and 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 model never answers model_unknown.
  • The session_adopt and session_interrupt rows of a host adopt carry host_id, and each intent gets exactly one completion.
  • The adopted session lists with its host, headless: true, and no unsandboxed field.
  • 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_lost refusal 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 with host_id, dormant record, /launch with adopt_host, outcomes, host_link_lost).
  • Resume: a record with adopt_pending resumes through adopt_host with no_signal.
  • Script: internal/sshhost/adopt.go, the detached transition around the existing start step.
  • relay-sessions: adopt_host on /launch; resume_conversation on 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_lost knob.
  • 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 ps seam, the prooftest case, the two journeys.
  • Break and restore: make the script's lifetime comparison always match, confirm TestAdoptHostChanged goes 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

  1. Gate (cmd/relay/outside_session_ops.go). GateAdoption keeps main's signature GateAdoption(s *Session, onHost, inProject bool, agent string). The probe passes onHost = h != nil && !hostAdopts(settings, h, project), where
    // 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
    The probe script, probe.go and the row shape do not change.
  2. Door (cmd/relay/session_adopt.go, cmd/relay/session_adopt_host.go). adoptableRow lets a host key through when the row is adoptable. adoptOutside hands a host row to
    func (a *adoptOps) adoptHost(ctx context.Context, req AdoptRequest, obs outsidesessions.Observation, hostID string, st *adoptState) (*AdoptResult, *AdoptRefusal)
    Order: audit ready and host ready (as main); the in-flight lock (as main); a fresh hostAdopts and the row's project (hosted, on that host); the managed list (ManagedClaudeIdentities); the tail read (outsideRun with outsideRangeScript(obs.Transcript, -1, 256 KiB); no answer: 502 unavailable); the verdict (busy when the row state is not idle or adopt.ReadTail(tail).OpenTool != nil; busy without interrupt: 409 busy); the turn-boundary read (interface 4; only when the adopt does not interrupt; it reads and writes nothing); the model (body model, else ReadTail(tail).ModelFamily, else empty; never model_unknown, no broker step); AuthorizeLaunch (the host project's claude launch, as for any host session); the session_adopt intent; the session_interrupt intent when it interrupts (the request sets interrupt and the verdict is busy; only then does the script get interrupt: true); the dormant record; /launch. Nothing reaches the host before the intents and the record are durable. A failed record write answers 502 unavailable, completes the intent as error, and starts nothing.
    Audit args add "host_id" to main's keys on every row of a host adopt. The door writes the completion itself, once, for every outcome.
  3. Ledger (internal/sessions/ledger/ledger.go):
    type 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"`
    The record is result.Ledger with State dormant and AdoptPending set, written with Put before /launch. A successful launch writes it live with AdoptPending nil. commitLaunch and session_launch.go do not change.
  4. 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"`
    • checkResumeConversation accepts resume_conversation on a host claude launch, fresh or resume: true, only with adopt_host set, on a Unix host with detach on. adopt_host on any other launch is 400 invalid_spec. Local launches keep main's rule.
    • session.CreateSpec.AdoptHost passes it to provider.ClaudeConfig.AdoptHost.
    • Manager.resolveSessionForCreate: a Resume with AdoptHost set and no saved session builds a new session (seeded with resume_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 on main. Then, with AdoptHost set, it runs sshhost.AdoptStartIn or AdoptStartInPane in place of RunnerStartIn or RunnerStartInPane, with the same argv and env.
    • Errors, written by writeErr through sessionLaunchStatus: 409 adopt_busy, 409 adopt_changed, 502 adopt_stop_failed, 502 adopt_launch_failed, 502 adopt_link_lost, 502 adopt_setup_failed. server.go does not change.
    • func TurnWindow(tail []byte, whole bool, procStart time.Time) (from time.Time, known bool) in internal/sessions/adopt/adopt_claude.go: an exported wrapper of lastTurnBoundary, known false when the tail is not whole and holds no prompt. No behaviour change. procStart is the row's since. When TurnWindow is 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, until TurnWindow is known or the read reaches the file's start. The door sends child_test "all" when it is still not known (a failed or short read, or the bound; fail closed), "none" when from is zero, else "window" with from and ReadTail(tail).LastRecord.
  5. 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. RunnerRemove already deletes them with the session. latest() reads only g*, so they never count as a generation.
    • The SSH command ($0 is relay-adopt) writes adopt.sh, starts it detached (setsid, else set -m, HUP ignored, as launch_plain), prints each adopt.state line as @@RELAY_ADOPT@@ <line>, and exits after the terminal line. The detached script's $0 is relay-adopt-run.
    • adopt.state lines: any signal INT|TERM|KILL <unix ms>, then exactly one terminal line: ok <generation>, refused busy, refused changed, failed stop_failed or failed launch_failed.
    • Order inside the script: (1) the lifetime of the pid, computed exactly as the probe computes it (/proc on Linux; else TZ=UTC LC_ALL=C ps -o lstart= -p <pid>, squeezed to single spaces), calling ps by name; (2) the pid gone: go to the start. With no_signal: the pid alive with the pinned lifetime answers refused changed, and anything else goes to the start. Without it: a different lifetime answers refused changed; (3) the registry ~/.claude/sessions/<pid>.json (not a symlink, at most 64 KiB) names the conversation, else refused 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 first txt entry of lsof -a -p <pid> -d txt -Fn; never ps -o comm=, which reads caffeinate because 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 without interrupt: refused busy; (5) the ladder: SIGINT when interrupt, 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: agentStartHead plus launch_plain or pane_launch plus agentStartWait, byte for byte the existing start, then ok <generation>. A start failure: failed launch_failed.
    • agentrun.go and pane.go do not change: adopt.go uses their constants in the same package.
  6. Outcomes in the door:
    relay-sessions answers Record Completion Door answers
    201 live, adopt_pending cleared ok, interrupted 201, then the recovery message when it interrupted
    adopt_busy, adopt_changed removed error, the code 409 busy, changed
    adopt_stop_failed removed error 502 stop_failed (main's message)
    adopt_setup_failed removed error 502 unavailable
    any other code (relay-sessions refused before a script ran) removed error 502 unavailable
    adopt_launch_failed dormant, adopt_pending kept error 502 launch_failed (main's message)
    adopt_link_lost (also: another adopt script runs for the session), or the call fails dormant, adopt_pending kept error host_link_lost 502 host_link_lost
  7. Resume (cmd/relay/session_routes.go: one branch; the body in session_adopt_host.go). resumeSessionInner hands a record with AdoptPending to func (d sessionRouteDeps) resumeAdoptPending(ctx context.Context, ev *logging.Event, caller LaunchCaller, rec ledger.Record) resumeOutcome. It authorizes as any resume (AuthorizeLaunch, Resume: true), refuses 409 managed when another session holds the conversation, then launches with resume: true, resume_conversation and adopt_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 with adopt_pending cleared. adopt_changed: the record is removed and the answer is 409 changed, "the terminal session still runs; adopt it again". Any other failure: 502 launch_failed, the record stays. Audit: main's session_resume rows.
  8. fakerelay (fakerelay/internal/world/validate.go, fakerelay/internal/sessions/adopt.go): a host row may be adoptable: true; a host row that is not adoptable still derives host_unsupported. An adoptable host row is adopted into its host project with the host on the session, no unsandboxed, and model = body model, else adopt.model_family, else empty, with no model_unknown. adopt.refuse: "host_link_lost" answers 502 host_link_lost with the wire message and keeps the row.

File ownership

Dev (23 files):

  • cmd/relay/outside_session_ops.go: hostAdopts and the gate call only
  • cmd/relay/session_adopt.go: adoptableRow, the hand-off to adoptHost, the host model rule
  • cmd/relay/session_adopt_host.go (new)
  • cmd/relay/session_routes.go: the one resume branch
  • internal/sessions/adopt/adopt_claude.go: export TurnWindow only
  • internal/sshhost/adopt.go (new)
  • internal/sessions/ledger/ledger.go
  • internal/sessions/hostapi/types.go
  • internal/sessions/hostapi/dispatch.go
  • internal/sessions/session/manager.go: the spec field, its pass-through and the resume fallback
  • internal/sessions/provider/claude.go: the config field
  • internal/sessions/provider/claude_detached.go
  • fakerelay/internal/world/validate.go
  • fakerelay/internal/sessions/adopt.go
  • docs/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 fresh relay-agent session)
  • docs/ssh-hosts.md: "Detached sessions": the adopt files and adopt_host
  • docs/audit-log.md: host_id on session_adopt and session_interrupt; no signals on a host adopt
  • docs/FEATURES.md: the new row G1.55; TM3f.1 claim and refs; TM3f.2 refs
  • docs/THREAT-MODEL.md: one note in 3f
  • docs/routes.md: one line, 502 host_link_lost
  • docs/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 2
  • docs/session-host.md: only the resume_conversation sentence, 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 the host_unsupported table, whose host moves to detach_sessions: false. The PR names it as an approved behaviour change.
  • e2e/harness/sshstub.go: the one seam: a ps wrapper first on the stub host's PATH that reports a shifted lstart for a pid named in <root>/.fakessh/lie/<pid>, and SSHLieStart(pid int)
  • fakerelay/prooftest/adopt_test.go: one host case for interface 8
  • cmd/devboxverify/journey_adopt_host.go (new): the two journeys
  • cmd/devboxverify/journey_adopt.go: the two adoptJourneys table entries only (main.go already concatenates adoptJourneys)
  • 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 by outsideId (the row with the host's hostId, never its console twin) with no model; tmux ls lists relay-agent-<id>; a Chief of Staff send answers 202 and the reply lands in the same transcript; relay drop-in opens Claude, a send answers dropped_in; the terminal closes and the session is headless again; a second Chief of Staff send answers 202; the session_adopt rows carry host_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 the signal TERM line of the host's adopt.state, it kills the adopt's ssh client (a process named ssh, child of relay-sessions, whose arguments hold relay-adopt; never the relay-adopt-run script). PASS: the adopt answers 502 host_link_lost; after the adopt.state terminal line, relay session resume answers 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 revision that 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.state line, read through the stub root by a file watch.
  • A drop: SSHDown returns after the stub's commands got SIGTERM; the adopt's HTTP answer follows. The return: SSHUp, then the adopt.state terminal 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-adopt does. Everything else waits on adopt.state lines, 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

  1. added
    enhancement
    task
    on Oct 22, 2026
  2. barelyworkingcode commented on Oct 22, 2026

    @barelyworkingcode
    OwnerAuthor

    Coordinator approval: inherits the approved epic's listed batches, 2026-10-22

  3. barelyworkingcode commented on Oct 23, 2026

    @barelyworkingcode
    OwnerAuthor

    Contract amendment: (2026-10-22, planner; stack-run findings, commits b225a0f and 4cd5240)

    1. Interface 1 and criteria 1 and 2: hostAdopts also requires a host probe with OK set and a ClaudePath. Otherwise the row reads host_unsupported.
    2. Interface 4: when the 256 KiB tail holds no prompt and the adopt does not interrupt, the door reads the transcript backwards below the tail, 1 MiB per read, 8 MiB in all.
    3. Interface 4: the door sends child_test "all" only when that read fails, reads short, or reaches the bound without a prompt.
    4. Interface 5 step 4: the script finds the turn helper by its executable (/proc/<pid>/exe, else the first lsof txt entry), never by ps -o comm=.
    5. Interface 5 step 4: a child whose executable the script cannot read counts as a child, not as the turn helper.
    6. Interface 6: adopt_setup_failed, and any relay-sessions refusal without an adopt_ code, remove the record and answer 502 unavailable.
    7. Interface 6: a second adopt script for the same session reads as adopt_link_lost, and the dormant record stays.
      Ownership, budget and tests do not change.
  4. barelyworkingcode commented on Oct 23, 2026

    @barelyworkingcode
    OwnerAuthor

    Merged into epic/588-host-adopt by #597.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementtask

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions