Plan: Remote execution phase 1 — @gadhs/pi-workspace, the seam
Closes: #489. Relates to: #488 (meta plan: plans/remote-execution.adoc). Branch: feat/pi-workspace. Status: Done (2026-10-26) — implemented as planned, with the errata below
Design
What this phase is for
The meta plan names about twenty files in pi-modes and pi-workflow that touch the workspace through node:fs and child_process today (git-guard.ts, review-context.ts, authorize.ts, count-tool.ts, monitor-process.ts and the rest). Phases 3 and 4 move them onto one interface so that phase 2’s SSH implementation makes them act on the remote. This phase defines that interface, implements it locally, and pins its semantics with a suite the SSH implementation will run too. The interface is the hard-to-reverse part, so it is reviewed alone, before any consumer.
The shape follows ADR-004’s amendment: a library package like @gadhs/pi-bash (packages/pi-bash/package.json: no extension, no loader, exports of source .ts, a regular dependency of its consumers). ADR-006 records it, with the extension package phase 2 adds.
The interface, from what the callers do
Every call the twenty files make today was listed (the survey is on #489). They need: read a file (whole, and the first N bytes as workspace-read.ts does with openSync/readSync), write a file with a mode, make directories, stat and lstat for kind and size, realpath where the symlinks are, list a directory with kinds (count-tool.ts uses withFileTypes), remove and rename, glob (pi’s FindOperations.glob), run a program with streamed output and an exit code (git, rg, a monitor’s command), and a long-lived process with a pid and a kill (monitor-process.ts). Paths are absolute on the host that holds the workspace.
// packages/pi-workspace/types.ts
export type EntryKind = "file" | "dir" | "symlink" | "other";
export interface EntryStat { kind: EntryKind; size: number; mtimeMs: number; mode: number }
export interface Entry { name: string; kind: EntryKind }
export interface ExecOptions {
cwd: string;
/** Added to the host's own environment; never a replacement for it, so a local secret cannot be sent as a whole env. */
env?: Readonly<Record<string, string>>;
stdin?: string | Uint8Array;
signal?: AbortSignal;
timeoutMs?: number;
/** Output past this many bytes is dropped and `truncated` set; default 16 MiB. */
maxBytes?: number;
onStdout?: (chunk: Uint8Array) => void;
onStderr?: (chunk: Uint8Array) => void;
}
export interface ExecResult { code: number | null; signal: string | null; stdout: string; stderr: string; timedOut: boolean; truncated: boolean }
export interface Process {
readonly pid: number;
readonly exited: Promise<{ code: number | null; signal: string | null }>;
kill(signal?: "SIGTERM" | "SIGKILL" | "SIGINT"): void;
}
export interface Workspace {
/** `local`, or `user@host:/path` (phase 2). */
readonly label: string;
readonly isRemote: boolean;
/** The workspace directory on its own host. Locally pi's cwd; remotely the remote path. */
readonly root: string;
/** pi's cwd on the local machine: the same as `root` locally, the anchor remotely. */
readonly anchor: string;
/** A caller's path as the host's absolute path: relative against `root`; under `anchor`, mapped under `root`; already under `root`, as is. */
resolve(path: string): string;
readFile(path: string): Promise<Uint8Array>;
/** The file decoded, or undefined when it is `cap` bytes or more: `workspace-read.ts` readCapped's rule, since a truncated claim is worse than none. Reads at most `cap` bytes on the host. */
readCapped(path: string, cap: number): Promise<string | undefined>;
writeFile(path: string, data: Uint8Array | string, options?: { mode?: number }): Promise<void>;
mkdir(path: string, options?: { recursive?: boolean; mode?: number }): Promise<void>;
/** undefined when the path does not exist; every other failure throws. */
stat(path: string): Promise<EntryStat | undefined>;
lstat(path: string): Promise<EntryStat | undefined>;
/** The path with every symlink resolved on the host, or undefined when it does not exist. */
realpath(path: string): Promise<string | undefined>;
readdir(path: string): Promise<Entry[]>;
rm(path: string, options?: { recursive?: boolean; force?: boolean }): Promise<void>;
rename(from: string, to: string): Promise<void>;
glob(pattern: string, cwd: string, options: { ignore: string[]; limit: number }): Promise<string[]>;
exec(file: string, args: readonly string[], options: ExecOptions): Promise<ExecResult>;
spawn(file: string, args: readonly string[], options: Omit<ExecOptions, "maxBytes" | "timeoutMs" | "signal">): Promise<Process>;
/** `exec("git", args, { cwd })` with a 20 s default timeout: the guards' most common call. */
git(args: readonly string[], cwd: string, options?: Partial<ExecOptions>): Promise<ExecResult>;
}
Decisions in that shape, each one line:
-
Async throughout. The SSH implementation cannot be synchronous, and every caller already runs inside an async hook (meta plan). The sync-to-async moves are phases 3 and 4’s work, not this phase’s.
-
statreturnsundefinedfor a missing path rather than throwingENOENT: nearly every caller today pairsexistsSyncwithstatSync, and a remote round trip for each is the cost to avoid. Other errors (EACCES,ENOTDIR) throw aWorkspaceErrorwith acodefield. -
envis additions only. The meta plan’s security rule: the remote command gets its own login environment plus an allowlist, never the local environment. The interface makes a whole-environment replacement impossible to express, so a future caller cannot leak one by accident. -
execandspawntake argv, not a shell string. The shell is a caller’s choice (["bash", "-lc", cmd]), and pi’sBashOperationsadapter in phase 2 is where that choice is made once. -
resolvecarries the anchor mapping. Locally it ispath.resolve(root, p). Remotely (phase 2) a path under the local anchor maps under the remote root, so callers that resolve againstctx.cwdkeep working unchanged; a path the model gives as the remote’s absolute path passes through. -
readCapped(path, cap)exists with exactlyworkspace-read.tsreadCapped’s contract (`undefinedat or over the cap, never a truncated text; a bounded read, not a stat-then-read), because a remote implementation must enforce the cap on the host rather than fetch the whole file;review-context.tsreads with the same helper and its own cap. -
No
watch, nocopy, nosymlink. No caller needs them; a phase that does adds them with its plan.
The local implementation: local.ts
localWorkspace(root: string): Workspace over node:fs/promises and node:child_process:
-
realpathisfs.promises.realpath, the JavaScript resolution, which is whatrealpathSyncgivesauthorize.ts(lines 139, 171, 212, 224) andworkspace-read.ts(lines 51 and 52) today; the contract suite and the property test pin it torealpathSync, so containment semantics do not shift when those callers move. -
readdirwithwithFileTypes, kinds from the dirent. -
globisfs.promises.glob(Node 22, withinengines>=22.19.0), withexcludefromignoreand the result cut atlimit. -
execwrapsspawn:stdiopiped, chunks forwarded toonStdout/onStderrand collected up tomaxBytes,timeoutMskills withSIGKILLafterSIGTERMand setstimedOut,signalaborts the same way.codeandsignalare the child’s. -
spawnreturns theProcess: on POSIXdetached: truesokillcan signal the group, asmonitor-process.tsdoes; on Windowskillrunstaskkill /pid /T /F, moved frommonitor-process.tswhere it lives today (phase 4 deletes the copy there). -
Environment:
{ …process.env, …options.env }.
The slot: slot.ts
WORKSPACE_KEY = Symbol.for("gadhs:workspace"), after runtime-bridge.ts’s `BRIDGE_KEY (packages/pi-workflow/runtime-bridge.ts), because pi-subagents gives each helper session a fresh extension instance in the same process, and globalThis is what they share.
-
publishWorkspace(ws: Workspace): () ⇒ voidsets the slot and returns the withdrawal; a second publish while one is live throws (two remotes in one process is not a state this design has). -
workspaceFor(cwd: string): Workspacereturns the published workspace whencwdis under itsanchoror itsroot, elselocalWorkspace(cwd). A helper in a local worktree beside a remote session is thereby local, correctly, until phase 4 gives helpers remote worktrees. -
currentWorkspace(): Workspace | undefinedfor the status line and diagnostics.
The contract suite: contract.ts
Exported as @gadhs/pi-workspace/contract: workspaceContract(name, make: () ⇒ Promise<{ ws: Workspace; dispose(): Promise<void> }>) registers a describe block. It is the definition of the interface’s semantics, run here against the local implementation and in phase 2 against the SSH one. It asserts, each as its own case with the value the behaviour produces:
-
bytes round-trip through
writeFileandreadFile, including a 3 MiB file and an empty one;modeis honoured (0o600read back bystat); -
readCappedreturns the whole file when it is shorter thancap, andundefinedwhen it is exactlycapbytes or longer; -
mkdirrecursive creates ancestors; non-recursive into a missing parent throws with codeENOENT; -
statkinds for a file, a directory, a symlink (followed) and a FIFO (other);lstatreports the symlink; a missing path givesundefined; a file as a directory component throwsENOTDIR; -
realpaththrough a symlink chain equals the target; a missing path givesundefined;resolveof a relative path, of a path underanchor, and of an absolute host path; -
readdirnames and kinds, sorted by the test, not the implementation; -
rmrecursive andforceon a missing path;renameacross directories; -
globmatches, honoursignore, and stops atlimit; -
exec: exit code 0 and 3, stdout and stderr kept apart and streamed in order,stdindelivered,cwdhonoured (pwd), an addedenvvalue visible and the host’sPATHstill present,timeoutMssetstimedOutwithcodenull, an abortedsignalends it within a second, output pastmaxBytessetstruncated, and a program that does not exist resolves withcodenull,signalnull and the error instderrrather than throwing or hanging; -
spawn: apid,exitedresolves with the code,killends a sleeping process and its child (the group); -
git:git rev-parse --show-toplevelin a scratch repository returns the root, and a non-repository returns a non-zero code without throwing.
Infrastructure the suite needs (git, a POSIX shell for the group test) is detected and the case skipped visibly with it.skipIf, never passed empty.
Property test
With fast-check: for arbitrary trees of directories, files and symlinks under a scratch root (depth to 4, names from a safe alphabet, links to earlier entries), localWorkspace(root).realpath(p) equals realpathSync(p) for every path in the tree and undefined exactly for paths that do not exist; and resolve is idempotent and always returns an absolute path under root for a relative input.
Fail modes
-
A host error other than "missing" (
EACCES,EISDIR,ENOTDIR,EMFILE) throwsWorkspaceErrorwith thecode; callers that catch today keep catching (fail-closed, loud). -
execon a program that does not exist resolves withcodenull and the spawn error’s message instderrandsignalnull, so a guard that runsgitwhere there is none sees a failure, never a hang (fail-closed). -
A
publishWorkspacewhile one is published throws at the publisher (fail-closed, loud); the slot is never silently replaced. -
The
globlimit is a cap, not a page: results past it are dropped and the caller is told nothing more thanlimitresults, as pi’s own find tool behaves (silent by design, documented on the method).
ADR-006
docs/modules/ROOT/pages/adrs/adr-006-remote-execution.adoc, Accepted, deciders @bitskrieg: the three shapes and three connections from the meta plan with the sources, the chosen shape, the Node 20 requirement, the two packages (library @gadhs/pi-workspace now, extension @gadhs/pi-ssh in phase 2) as the amendment to ADR-004’s ceiling by its own criteria, and the Workspace interface as the seam every workspace-touching file will depend on. It gets a row in adrs/index.adoc’s table after 005 (the nav lists only the index, so no nav change), a bullet in `architecture.adoc’s "Key decisions" list after ADR-005 (line 240), and the package a row in `packages.adoc’s table beside `@gadhs/pi-bash (line 93).
Scope
In
-
packages/pi-workspace/:package.json(@gadhs/pi-workspace0.1.0,files*.ts,exports.and./contract,enginesas pi-bash, no dependencies butfast-checkandvitestdev),tsconfig.json,vitest.config.ts(coverage thresholds set at the measured level of the pass, rounded down, per the pi-bash comment),README.md,LICENSE,index.ts,types.ts,local.ts,slot.ts,contract.ts. -
test/local.test.ts(runs the contract suite againstlocalWorkspace),test/realpath.property.test.ts,test/slot.test.ts(publish, withdraw, double publish throws,workspaceForby anchor, by root, and local fallback). -
The ADR and its index row; the architecture page: a "Key decisions" bullet, and one paragraph in its bridge section ("The bridge between pi-modes and pi-workflow", line 143) naming the workspace slot beside the bridge; the packages page row;
CHANGELOG.adoc== Unreleased=== Added, one entry. -
Named but not supplied to the cold reviewer (the budget is twelve files):
packages/pi-workflow/{git-guard,review-context}.ts(cited only as callers to be moved in phase 3),CHANGELOG.adoc,docs/modules/ROOT/nav.adoc,docs/modules/ROOT/pages/packages.adoc,docs/modules/ROOT/pages/architecture.adoc. -
Tests by category: contract (the suite), property (realpath, resolve), unit (the slot). Mutation check: the
undefined-on-missing branch ofstat, theenvmerge order, the timeout kill, themaxBytescut, the anchor mapping inresolve, the double-publish throw; each killed before the MR. -
Delivery: one MR,
Closes #489,Relates to #488; the merge SHA on both issues. Released with phase 2 (meta plan), so no release in this phase.
Out
-
Any consumer: no file in pi-modes or pi-workflow changes (phases 3 and 4). No
@gadhs/piloader or dependency (the library has no extension). No SSH code (phase 2). Nowatch,copyorsymlinkmethods. A Windowsspawngroup semantics beyondtaskkill.
Erratum (2026-10-26): the contract suite gained four cases the coverage pass showed were undefined. They cover a program that ignores SIGTERM, which is still ended on a timeout by SIGKILL after a 2 s grace; an already-aborted signal; a symlink loop, which throws ELOOP rather than reading as missing; and spawn with stdin and output callbacks.
Erratum (2026-10-26): realpath treats ENOTDIR as missing as well as ENOENT (a path through a file does not exist), as existsSync does for the callers that pair it with realpathSync; stat still throws ENOTDIR.
Erratum (2026-10-26): a second publish throws WorkspaceSlotError, a distinct class, so it cannot be mistaken for a host failure. contract.ts imports vitest, so the package declares vitest an optional peer dependency, and contract.ts is left out of coverage because it is test code.