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.

  • stat returns undefined for a missing path rather than throwing ENOENT: nearly every caller today pairs existsSync with statSync, and a remote round trip for each is the cost to avoid. Other errors (EACCES, ENOTDIR) throw a WorkspaceError with a code field.

  • env is 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.

  • exec and spawn take argv, not a shell string. The shell is a caller’s choice (["bash", "-lc", cmd]), and pi’s BashOperations adapter in phase 2 is where that choice is made once.

  • resolve carries the anchor mapping. Locally it is path.resolve(root, p). Remotely (phase 2) a path under the local anchor maps under the remote root, so callers that resolve against ctx.cwd keep working unchanged; a path the model gives as the remote’s absolute path passes through.

  • readCapped(path, cap) exists with exactly workspace-read.ts readCapped’s contract (`undefined at 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.ts reads with the same helper and its own cap.

  • No watch, no copy, no symlink. 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:

  • realpath is fs.promises.realpath, the JavaScript resolution, which is what realpathSync gives authorize.ts (lines 139, 171, 212, 224) and workspace-read.ts (lines 51 and 52) today; the contract suite and the property test pin it to realpathSync, so containment semantics do not shift when those callers move.

  • readdir with withFileTypes, kinds from the dirent.

  • glob is fs.promises.glob (Node 22, within engines >=22.19.0), with exclude from ignore and the result cut at limit.

  • exec wraps spawn: stdio piped, chunks forwarded to onStdout/onStderr and collected up to maxBytes, timeoutMs kills with SIGKILL after SIGTERM and sets timedOut, signal aborts the same way. code and signal are the child’s.

  • spawn returns the Process: on POSIX detached: true so kill can signal the group, as monitor-process.ts does; on Windows kill runs taskkill /pid /T /F, moved from monitor-process.ts where 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): () ⇒ void sets 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): Workspace returns the published workspace when cwd is under its anchor or its root, else localWorkspace(cwd). A helper in a local worktree beside a remote session is thereby local, correctly, until phase 4 gives helpers remote worktrees.

  • currentWorkspace(): Workspace | undefined for 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 writeFile and readFile, including a 3 MiB file and an empty one; mode is honoured (0o600 read back by stat);

  • readCapped returns the whole file when it is shorter than cap, and undefined when it is exactly cap bytes or longer;

  • mkdir recursive creates ancestors; non-recursive into a missing parent throws with code ENOENT;

  • stat kinds for a file, a directory, a symlink (followed) and a FIFO (other); lstat reports the symlink; a missing path gives undefined; a file as a directory component throws ENOTDIR;

  • realpath through a symlink chain equals the target; a missing path gives undefined; resolve of a relative path, of a path under anchor, and of an absolute host path;

  • readdir names and kinds, sorted by the test, not the implementation;

  • rm recursive and force on a missing path; rename across directories;

  • glob matches, honours ignore, and stops at limit;

  • exec: exit code 0 and 3, stdout and stderr kept apart and streamed in order, stdin delivered, cwd honoured (pwd), an added env value visible and the host’s PATH still present, timeoutMs sets timedOut with code null, an aborted signal ends it within a second, output past maxBytes sets truncated, and a program that does not exist resolves with code null, signal null and the error in stderr rather than throwing or hanging;

  • spawn: a pid, exited resolves with the code, kill ends a sleeping process and its child (the group);

  • git: git rev-parse --show-toplevel in 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) throws WorkspaceError with the code; callers that catch today keep catching (fail-closed, loud).

  • exec on a program that does not exist resolves with code null and the spawn error’s message in stderr and signal null, so a guard that runs git where there is none sees a failure, never a hang (fail-closed).

  • A publishWorkspace while one is published throws at the publisher (fail-closed, loud); the slot is never silently replaced.

  • The glob limit is a cap, not a page: results past it are dropped and the caller is told nothing more than limit results, 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-workspace 0.1.0, files *.ts, exports . and ./contract, engines as pi-bash, no dependencies but fast-check and vitest dev), 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 against localWorkspace), test/realpath.property.test.ts, test/slot.test.ts (publish, withdraw, double publish throws, workspaceFor by 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 of stat, the env merge order, the timeout kill, the maxBytes cut, the anchor mapping in resolve, 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/pi loader or dependency (the library has no extension). No SSH code (phase 2). No watch, copy or symlink methods. A Windows spawn group semantics beyond taskkill.

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.

Edit this page · latest