Plan: jobs on a remote workspace - a job’s process lives on the remote, in a session of its own

Closes: #671. Branch: feat/remote-jobs. Status: Done (2026-11-01) — a job in a remote session runs on the remote and lives there; the eight remote cases pass on luchs

TL;DR

A job (#577) is a process pi starts, records under the agent dir, and finds again by pid and start time in any later session, so it outlives the session and pi. executeJob refuses a remote workspace at its first line (job-tools.ts REMOTE_REFUSAL): the registry reads and writes local files, signals local pids, and spawns a local shell. pivot’s seat works only over SSH, so it never gets a job’s tracking, and its workaround is the pre-#577 one (feedback round, #671).

The plan moves what is host-bound behind a JobHost seam with two implementations, local and remote (over the Workspace the monitors already use for their remote path, #492), and keeps one rule: a job’s files and process live on the host that runs it. A remote job’s record is on the remote, under ~/.pi-ssh/jobs/, where every later session on that remote, from any client machine, lists it. Nothing of it is mirrored locally. That is the opposite of a monitor, whose records stay here while its command runs there, and it is why a job can outlive the client while a monitor cannot.

The seam’s cost is that every host operation is asynchronous (every Workspace member is), so the registry and everything that reads it become asynchronous too. That change is listed caller by caller below; it is most of the diff.

Design

What is host-bound today, and where it goes

In job-registry.ts Local today Remote

The state dir

<agentDir>/gadhs-pi-jobs (JOBS_DIR)

<remote home>/.pi-ssh/jobs, made 0700 with ws.mkdir. .pi-ssh is the daemon’s own directory, already private to the user (ssh.adoc, "A dropped link"). The home is ws.home().

Id claim (claimId: exclusive create of <id>.json, openSync(path, "wx"))

local

ws.exec("sh", ["-c", 'set -C && : > "$1"', "sh", path]): the shell’s noclobber is the same exclusive create. Exit 0 claims; a non-zero exit means another pi took the number, and the next is tried, as locally.

The script, log and exit file

writeFileSync, 0600

ws.writeFile(path, text, { mode: 0o600 }), the same jobScript text. The script’s paths are the remote’s; quoted() already emits forward slashes. The record’s atomic write (writeEntry: a .tmp then renameSync) becomes ws.writeFile then ws.rename.

The spawn (spawnJob → spawnInShell, outlivesPi: true)

a detached local child

ws.exec("bash", ["-lc", "setsid nohup bash <script> >/dev/null 2>&1 </dev/null & echo $!"], { cwd }). The launcher prints the job’s pid and exits at once; the job is in a session of its own. A non-zero exit, or no pid on stdout, is a JobStartError carrying the launcher’s stderr, and the claimed record, script and log are removed (ws.rm), as the local start removes its files on failure.

The pid’s start time (rememberedStart → processStartMs; Linux reads /proc/<pid>/stat)

local reads

ws.readFile("/proc/stat") and /proc/<pid>/stat, through the exported startTicks parser (process-start.ts). When /proc/stat is not there (macOS, BSD), ws.exec("ps", ["-o", "lstart=", "-p", pid]) through the exported psAnswer. Both parsers exist; only the reads move behind the seam. No memo: a remote look is already a round trip, and REMEMBER_START_MS exists for Windows' slow query.

Alive and group checks (pidAlive, groupLeft: process.kill(-pid, 0))

local signals

ws.exec("kill", ["-0", "--", "-<pid>"]): exit 0 means a member lives; exit 1 with stderr matching "Operation not permitted" means one lives that is not ours (EPERM, as locally); any other exit 1 means none. One round trip per look.

Stop (signalJob: SIGTERM, SIGKILL after graceMs)

local signals to the group

ws.exec("kill", ["-TERM", "--", "-<pid>"]), then -KILL. The group is the job’s own session, which setsid gave it.

Listing and pruning (idNumbers: readdirSync; pruned: rmSync of each file)

local

ws.readdir(dir) and ws.rm(path, { force: true }).

The exit file’s time (exitTime: statSync(…​).mtimeMs)

local

ws.stat(exitFile)?.mtimeMs.

The watch (job-watch.ts: statSync, readSync at an offset, each JOB_POLL_MS)

local reads

ws.stat for the size and ws.exec("tail", ["-c", "+<offset+1>", log]) for what the log gained, capped at MAX_READ_BYTES as the local read is (from = max(offset, size - MAX_READ_BYTES): a job that wrote more since the last look skips to the latest of it, locally and remotely alike). Every JOB_POLL_MS for a job with a match; every JOB_END_POLL_MS = 5 s for one without, where only its end is wanted (see Costs).

Why the launcher is setsid nohup … & through exec, not ws.spawn: the helper spawns every child detached: true in its own group and its shutdown() SIGKILLs each child’s group when the daemon ends: at pi’s goodbye, at /reload, or ten idle minutes after the last client (helper.mjs shutdown, DAEMON_IDLE_MS; ssh.adoc, "A dropped link"). A job must survive all three. setsid puts it in a new session the helper never tracked; the exec that launched it returns as soon as echo $! prints, and the helper has nothing to kill. The idle shutdown then ends nothing of the job’s.

The seam

JobHost, a new interface in job-registry.ts, with these asynchronous operations: claim(id), write(path, text, mode), rename(from, to), read(path), readdir(), rm(path), stat(path) (size and mtime), launch(spec, files) (the pid), startOf(pid), alive(pid), groupLeft(pid), signal(pid, signal), label (local, or the workspace label). Two implementations:

  • localJobHost(dir, options) in job-registry.ts: today’s code, each operation wrapped as a resolved promise. options carries what JobRegistryOptions carries today for tests (alive, startedAt, now stays on the registry).

  • remoteJobHost(ws, dir) in a new packages/pi-modes/remote-jobs.ts: each operation one or two ws calls, as the table says.

JobRegistry is constructed from a host only: new JobRegistry(host, options). The dir constructor goes; its callers pass localJobHost(dir): job-tools.ts registerJobTools, hub-wiring.ts (through job-tools), and the tests job-registry.test.ts, job-tools.test.ts, job-sessions.test.ts and job-cleanup.ts. No alias is kept.

JobEntry gains one optional field, host?: string: the workspace label for a remote job, absent locally. The job tool’s text and the hub’s Monitors & Jobs tab show it (job j3 started on user@host …). The record’s paths are already the host’s own.

Erratum (2026-11-01): JobHost’s operations are grouped one level up (`claimId, ids, readEntry, writeEntry, exitCode, exitTime, remove, launch, sameProcess, groupLeft, signal, size, readRange), so the local host is today’s synchronous helpers unchanged, the four-process claimId test included, and a remote host spends fewer round trips.

Erratum (2026-11-01): a remote job’s id is r<n>, not j<n>. A remote session’s hub lists this box’s jobs and the remote’s together, and both hosts number from 1, so the letter makes an id name one host.

Erratum (2026-11-01): the hub reads its jobs once, as it opens (hub-wiring.ts awaits list() before showHub), rather than keeping a snapshot the watcher refreshes.

Synchronous today, asynchronous after

Every Workspace member is asynchronous, so a registry over a host is too. Each of these changes signature, and each caller follows:

Today After Callers that change

JobRegistry.list(): JobEntry[], get(id), settled(id), markReported(id), running(entry), groupLeft(entry)

each returns a Promise

job-tools.ts (registerJobStopAndList, adoptJobs, the session_shutdown quit notice: the handler is already async); job-watch.ts; hub-wiring.ts.

JobWatcher.poll() and its newLines (synchronous file reads each tick)

async poll(): one tick awaits its looks, and the next tick is scheduled when the previous settles (setTimeout after the await, not setInterval), so a slow link never stacks looks. newLines reads through host.stat and host.read.

job-watch.ts only; its deps gain the host (the entry’s registry).

neverStarted(entry, now, exists) (a synchronous exists)

unchanged: it is Windows-local only (startMarker is set only by scriptGroup, Windows' file transport), and a remote is POSIX, so it is never asked of a remote entry. The watcher calls it only when entry.startMarker !== undefined.

none.

HubSources.jobs(): JobEntry[] and sources.tail(path, n) (hub-pane.ts runItems, monitorView; hub-wiring.ts jobs: () ⇒ deps.jobs.list())

The hub keeps a synchronous view: hub-wiring.ts holds a JobEntry[] snapshot that the watcher’s changed callback refreshes (it already fires on every start and end for the status line), and jobs() returns the snapshot. A remote job’s tail cannot be synchronous, so jobRow’s latest line and `jobDetail’s tail show `(on user@host) for a remote entry instead of lines; the watcher’s matched lines and its end still reach the session as messages. Local jobs keep their live tail.

hub-wiring.ts, hub-pane.ts (latest, jobDetail for a remote entry), hub-views.ts untouched (it has no jobs code).

JobWatcher’s look that throws (`readRange, writeEntry) ends poll() for every watched job

one job’s failed look is caught per job and that job is tried again next tick, so a dropped link (every remote call rejects) blinds the watch without ending it. Today only sizeOf is guarded; the plan guards the look as a whole.

job-watch.ts.

Where a session’s jobs come from

Today registerJobTools builds one registry over the agent dir and, at session_start, adopts the project’s jobs from it. With remote jobs:

  • A local session is unchanged: one registry over localJobHost.

  • A remote session (workspaceFor(ctx.cwd).isRemote) builds a second registry over remoteJobHost(ws, <home>/.pi-ssh/jobs) for its workspace and adopts that host’s jobs whose project is the remote root: watched if running, told once if ended (job-records.ts startNotice, with the host named). The local registry is not consulted for them (a remote session’s project is a remote path, so none matches anyway).

  • job in a remote session starts on the remote host. job_list lists the session’s workspace’s jobs. job_stop finds the id on that host. The tool deps gain registryFor(cwd): the remote registry when the cwd’s workspace is remote, the local one otherwise.

A remote session on a second client machine finds the same jobs: the records are on the remote. That is the property pivot asked for.

The command’s judge and shell

executeJob judges the command with judgeCommand as now; a remote session’s judge already reads the remote checkout’s facts (#492). The shell is the remote’s bash -lc, as the monitor’s remote path uses (monitor-process.ts remoteShell), so a job runs where it was judged to run (#451). pi’s session markers and the environment the monitor’s remote action gets are the environment the job gets, and nothing else of this machine’s.

A job needs the link only to be looked at. While the link is down each look rejects, the watch catches it per job and tries again next tick, and the reconnect brings the next look back. Nothing is told twice: the end is marked reported on the remote record by the session that told it. A pi that gives up reconnecting loses its watch, not the job; the next session on that remote adopts it.

Costs

Each look is one or two round trips (a stat; a tail when the size grew; a kill -0 when the exit file is absent). On a LAN that is tens of milliseconds per look (ssh.adoc, "What each operation costs"). A job with a match is looked at every second, as locally; one without, every 5 s. The session-start adoption is one readdir plus one read per record. Nothing polls when the session has no jobs on the remote.

Not in scope

  • A Windows remote (out of pi-ssh’s scope already).

  • The Windows-local start marker and MSYS group handling (startMarker, scriptGroup): a remote is POSIX, so `setsid’s session is the group.

  • Mirroring a remote job’s log to this machine, or a live tail of it in the hub.

  • A job started locally and watched from a remote session, or the reverse.

  • Running a job’s command through the helper’s own spawn with a "keep it" flag: that changes pi-ssh’s shutdown contract for every spawned child, and the daemon’s idle shutdown would still have to except it. The setsid launcher needs no helper change.

Tests

Where: packages/pi-modes/test/. The remote cases use the real pi-ssh helper over pipes (ssh-under-test.ts, as remote-helpers.test.ts does), so every operation takes the remote route while the files are on this machine for the test to read. They skip visibly on Windows (describe.skipIf(process.platform === "win32")), as remote-helpers.test.ts does: the helper needs a POSIX host.

  • (contract) remote-jobs.test.ts: a job started in a remote session runs to its end; its record, log and exit file are under the remote home’s .pi-ssh/jobs, 0600, and nothing appears under the local agent dir. Its exit code is recorded. A job that writes more than MAX_READ_BYTES between looks is skipped ahead, as the local watch does, and its last lines and end still arrive.

  • (contract) the job outlives the daemon: after the job starts, close() the remote (the goodbye that ends the helper and SIGKILLs its children), then open a new connection to the same root and home; the job’s pid is alive, and a new remoteJobHost on the new connection lists it running and later exited. This is the property the setsid launcher exists for. Mutation: launched through ws.spawn instead, the job dies with the helper and the case fails.

  • (contract) a launcher that fails (a bash that is not on the remote’s PATH, through the test’s own PATH) throws JobStartError with the remote’s stderr, and leaves no record, script or log on the remote.

  • (concurrency) two registries over the same remote dir claim ids at once: 2 × 25 start`s in parallel take 50 distinct ids with no gap, as job-registry.test.ts’s four-process local case does. The `set -C create is the exclusive step.

  • (concurrency) two registries settle one job’s end at once: both read the exit file, both write exited with the same code, and exactly one markReported wins; a third read shows one record, ended once, reported once.

  • (contract) a second registry over the same remote dir, as a second client machine, lists the job, watches it from the log’s end, and is the one to tell its end when the first has stopped watching; the end is told once.

  • (contract) job_stop ends the job’s whole session: a job that starts two background sleeps leaves none alive after the stop, judged by kill -0 of each pid on the remote.

  • (contract) a dropped link mid-job (drop()): the watch’s next look rejects, is caught, and the other watched job’s look still runs; the link comes back and the job’s later lines and its end arrive once.

  • (unit) remoteJobHost.startOf with a fake ws: /proc present reads through startTicks; /proc/stat ENOENT and ps answering reads through psAnswer; neither answers gives undefined (cannot say), and sameProcess then judges by the pid alone, as locally.

  • (unit) JobWatcher with a fake host whose stat rejects once: the tick completes, the other job’s look ran, and the next tick is scheduled after the previous settled (no overlap under a slow host).

  • (regression) job-registry.test.ts: every existing local case passes against new JobRegistry(localJobHost(dir), …) with await where a read became asynchronous; the assertions are unchanged.

  • (contract) job-tools.test.ts: REMOTE_REFUSAL is gone; a remote workspace’s executeJob starts on the remote host and its answer names the host; job_list in a remote session lists that host’s jobs and no local one; hub-pane’s `jobRow shows (on user@host) for a remote entry.

Gate: node tools/task.mjs validate on luchs (the remote cases run there) and on panther (they skip visibly; the local cases run).

Docs

  • modes.adoc, the jobs section: a job in a remote session runs on the remote, where its record lives, and what that means (outlives the client, found by any session on that remote, not mirrored here, no live tail in the hub); the remote refusal line is removed.

  • ssh.adoc, "Helpers, monitors, count and images": a Jobs bullet beside Monitors, with the contrast (a monitor’s records stay here; a job’s live there), and the Limitations bullet "Monitors' records stay on this machine" gains "a job’s are on the remote". "A dropped link" gains one sentence: a job is not the daemon’s child, so the daemon’s end does not end it.

  • CHANGELOG.adoc == Unreleased === Added, naming #671 and pivot.

  • This plan’s durable copy under docs/modules/ROOT/pages/plans/ and its nav entry.

Scope

  • In: packages/pi-modes/job-registry.ts (the JobHost seam, localJobHost, the host-only constructor, asynchronous reads), new remote-jobs.ts (remoteJobHost), job-tools.ts (the remote path replaces the refusal; registryFor; adoption per host), job-watch.ts (asynchronous looks through the host, caught per job, no overlap; the 5 s look for a job with no match), job-records.ts (startNotice names the host), hub-wiring.ts (the jobs snapshot), hub-pane.ts (a remote entry’s row and detail), the tests above, ssh-under-test.ts if a case needs a PATH of its own, the two doc pages, CHANGELOG, the plan copy and nav.

  • Out: pi-ssh’s helper and protocol (no change); process-start.ts (its parsers are reused as exported; no change); hub-views.ts (no jobs code); the Windows-local job path; pi-remote.

  • Bump: pi-modes minor (a tool gains a capability it refused, and the registry’s signatures change).

  • Check: task.mjs validate on both boxes. The eval is not touched (no judge change).

  • Close: an MR with Closes #671; a note to pivot on pi-feedback with the job call that replaces its setsid nohup pattern.

Risks

Risk Failure mode Mitigation

The daemon’s idle shutdown or a /reload kills the job after all

Fail-closed, loud: the job ends and its end is recorded as lost; the property it exists for is false

The launcher is setsid, outside the helper’s groups; the "outlives the daemon" contract test closes the connection and checks the pid, and its mutation (launch through ws.spawn) must fail.

setsid or nohup missing on the remote

Fail-closed: the job cannot start

Both are POSIX/util-linux and present on every Linux and macOS; the launcher’s failure is a JobStartError with the remote’s stderr, nothing is recorded (its contract test), and the agent is told to use a monitor there.

Pid reuse on the remote between sessions

Fail-open: a later session takes a stranger’s process for the job, and job_stop would signal it

The same guard as locally: sameProcess by pid and start time, read from the remote’s /proc (or ps), the #561 fix applied over the seam; its unit test covers both reads and the cannot-say case.

The watch’s round trips load a slow link, or stack when the link is slower than the poll

Silent: a session with several remote jobs spends its link on looks

One stat per look, a read only when the size grew; 5 s looks for a job with no match; the next tick is scheduled only after the previous settled (its unit test); the costs section’s numbers are in the docs.

Two client machines settle or claim at once

Fail-open for a claim (two jobs under one id would overwrite each other’s record); silent for a settle (one ended write clobbers an identical one)

The claim is an exclusive create (set -C) with its concurrency test; the settle writes the same fact from the same exit file, and reported is set by the one that told it, with its concurrency test. Same design as two local pi processes today (#577).

A remote job is invisible when the link is down

Silent: job_list in the client shows nothing of it until the link is back

job_list says so ("the remote cannot be asked; its jobs run on") rather than listing none, as the hub’s row says (on user@host).

Edit this page · latest