Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

name the fault when node-pty cannot fork, instead of retrying it forever

[._.]/ Adam Eivya77fc1610e40
diff --git a/AGENTS.md b/AGENTS.md
index ad210b143d..ab0923c348 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -102,6 +102,8 @@ The server is always user-facing on `:5555` (HTTP or HTTPS). The client runs on
**Ports.** PortOS uses 5553–5561 (system PostgreSQL on 5432, Docker PostgreSQL on 5561). When HTTPS is on, the loopback-only HTTP mirror on `:5553` is what local curl/scripts should hit to skip the cert warning. Define ports in the top-level `PORTS` object in `ecosystem.config.cjs` (canonical re-export at `server/lib/ports.js`). Full guide and diagram: `docs/PORTS.md`.
+**Never run `npm ci` or `npm install` from inside a CoS worktree (`data/cos/worktrees/*`).** A fresh `git worktree` has no `node_modules`, so agents symlink the primary checkout’s `node_modules`, `client/node_modules` and `server/node_modules` into the worktree to make `vitest` runnable. npm does not treat that symlink as a boundary: it empties the **target** — the primary checkout’s real `node_modules` — then replaces the symlink with a fresh real directory in the worktree and installs there. The primary is left with an EMPTY `node_modules`, and removing the worktree does nothing to restore it. This is not a slow-burn annoyance, it takes the whole CoS fleet down at once: `portos-cos` keeps running on its already-loaded node-pty binding, but node-pty execs its `spawn-helper` binary from disk on EVERY spawn, so every agent spawn then fails with the opaque `posix_spawn failed: No such file or directory` until someone reinstalls. If a worktree is missing dependencies, symlink them from the primary checkout and call the workspace binaries directly (`server/node_modules/.bin/vitest run <files>`) — never install. Recovery is `npm install --prefix server` (and `client`) in the PRIMARY checkout, then `pm2 restart portos-cos`. The runner names this fault instead of retrying it — see `server/lib/ptySpawnDiagnostics.js`.
+
**Backup excludes.** `DEFAULT_EXCLUDES` in `server/services/backup.js` is **rsync filter syntax — every path must be anchored with a leading `/`.** An unanchored pattern matches at any depth and silently drops unrelated user data; that is a data-loss bug, not a style nit. See `docs/BACKUP.md` for the failure mode, the `overridable` tiers, and `computeEffectiveExcludes()`.
### Per-directory conventions
diff --git a/server/cos-runner/index.js b/server/cos-runner/index.js
index 3e0b52a127..5c1b7cc31a 100644
--- a/server/cos-runner/index.js
+++ b/server/cos-runner/index.js
@@ -23,6 +23,7 @@ import { prepareCliPrompt } from '../lib/cliProviderArgs.js';
import { commandExists } from '../lib/commandExists.js';
import { adoptNpmGlobalBinDir } from '../lib/npmGlobalBin.js';
import { findCommandOnPath } from '../lib/processEnv.js';
+import { diagnosePtySpawnFailure, probePtyRuntime, PTY_WORKSPACE_MISSING_PREFIX } from '../lib/ptySpawnDiagnostics.js';
import { createCodexStderrFormatter } from '../lib/codexCliOutput.js';
import { isKnownCliStderrNoise } from '../lib/cliStderrNoise.js';
import { createStreamingAnsiStripper } from '../lib/ansiStrip.js';
@@ -206,6 +207,15 @@ app.post('/spawn-tui', async (req, res) => {
}
const cwd = workspacePath && typeof workspacePath === 'string' ? workspacePath : ROOT_DIR;
+ // Ahead of the executable checks below, because both of them run the child IN
+ // this directory: a worktree reaped before the spawn makes the `--version`
+ // probe fail too, and the runner would then blame the provider CLI and tell a
+ // human to reinstall a binary that is sitting right there on PATH.
+ if (!existsSync(cwd)) {
+ return res.status(422).json({
+ error: `${PTY_WORKSPACE_MISSING_PREFIX} the workspace for this spawn does not exist. Its worktree was probably removed before the agent launched.`
+ });
+ }
const childEnv = buildCliChildEnv({ before: envVars, provider: providerAuth, cwd });
// node-pty reports a missing executable as an immediate exit with no data.
// Check the exact child PATH first so the caller gets a usable configuration
@@ -235,13 +245,30 @@ app.post('/spawn-tui', async (req, res) => {
// Use the same safe wrapper for the actual PTY launch. In particular, this
// preserves the shared escaping contract for paths/args passed to cmd.exe.
const { command: ptyCommand, args: ptyArgs } = prepareCliSpawn(executable, args, childEnv);
- const tuiProcess = pty.spawn(ptyCommand, ptyArgs, {
- name: 'xterm-256color',
- cols,
- rows,
- cwd,
- env: childEnv,
- });
+ // Both checks above cleared the executable, so a throw here is about the PTY
+ // layer or the workspace — not the command. node-pty collapses those into one
+ // opaque `posix_spawn failed: No such file or directory`, which read as a
+ // transient runner refusal and sent the whole fleet into a retry storm. Name
+ // the actual fault instead, and let the caller block on the unrecoverable ones.
+ let tuiProcess;
+ try {
+ tuiProcess = pty.spawn(ptyCommand, ptyArgs, {
+ name: 'xterm-256color',
+ cols,
+ rows,
+ cwd,
+ env: childEnv,
+ });
+ } catch (err) {
+ const { retryable, message } = diagnosePtySpawnFailure(err, {
+ cwd,
+ probeCwd: ROOT_DIR,
+ runtimeProbe: (probeCwd) => probePtyRuntime(pty, probeCwd),
+ });
+ if (retryable) throw err;
+ console.error(`❌ PTY spawn failed for ${agentId}: ${message}`);
+ return res.status(422).json({ error: message });
+ }
const startedAt = Date.now();
const agent = {
kind: 'tui',
diff --git a/server/lib/README.md b/server/lib/README.md
index 2ded4ea349..ffb1b6571d 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -357,6 +357,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `processEnv.js` | `stripDebugMallocEnv(env)` / `safeChildProcessEnv(extra)` — drop macOS `Malloc*` debug env vars before spawning a child. `safeChildProcessOptions(options)` adds that sanitized environment plus `windowsHide: true`, preventing detached PM2 subprocesses from opening transient Windows console UI; `buildSafeCliBaseEnv(env, provider)` allowlists runtime/delivery essentials and only the selected CLI's ambient provider auth before an AI CLI inherits the server environment. Route Node→Python and other background CLI spawns through the process helpers. Also `whichFirst(name)` — first-hit `which`/`where` PATH probe (safe options, 5s timeout) returning the absolute binary path or `null`; `whichFirstSync(name)` provides the same contract without the await; `findCommandOnPath(name, { env, cwd })` resolves an executable from the exact child environment without needing `which` itself on that PATH. `adoptPathDirs(dirs)` appends the ones that exist and are not already there to THIS process's `process.env.PATH` (case-insensitively on Windows), which fixes this process AND every child, since the env builders above derive from `process.env` — the only fix that reaches a CLI launched by BARE NAME through node-pty. Shared by `npmGlobalBin.js` and `services/llamaServerManager.js`'s winget-shim adoption. |
| `branchUpstreamGuard.js` | `enforceSafeBranchUpstream(repo, branch)` / `readBranchUpstream` / `isSafeBranchUpstream` — the agent-branch upstream invariant (#4172): a branch handed to a CoS agent tracks either NOTHING or its OWN ref, never `refs/heads/main`. `git worktree add -b <b> <path> origin/main` does not leave the branch untracked — `branch.autoSetupMerge` records `merge=refs/heads/main` — and `/do:pr` derives its push destination from that config (`git push <remote> HEAD:<merge>`), so the agent's work lands straight on the default branch with no PR. Prevention is `--no-track` at the `worktreeManager.js` creation sites; this is the backstop that also REPAIRS branches created before the fix (drops the bogus upstream, logs it) and throws only if the repair doesn't take. Fails CLOSED: `readBranchUpstream` returns `null` for could-not-read (distinct from `''` = genuinely unset), and an unverifiable upstream is refused rather than waved through — `worktreeManager.js` undoes the `worktree add` on refusal so the throw can't strand a tree. Pairs with `primaryCheckoutGuard.js`, which catches the other way agent work reaches `main`. |
| `primaryCheckoutGuard.js` | `capturePrimaryCheckoutState(path)` / `detectPrimaryCheckoutDrift(baseline, {agentBranch})` + `PRIMARY_CHECKOUT_MUTATED_REASON`/`_CATEGORY` — the branch-jack detector (#3680): stamps the PRIMARY checkout's branch + HEAD onto a worktree agent's metadata at spawn (`agentLifecycle.js`) and re-reads it in the shared finalize path (`agentFinalization.js`), so a worktree-isolated agent that commits to the primary is recorded as a FAILURE naming the drifted branch, the commit count, and the `git reset --hard` recovery — instead of a silent "completed". Detect-and-report only: the reset discards commits, so it stays a human decision. Non-throwing (runs outside the request lifecycle); an unreadable checkout reports no drift rather than inventing one. |
+| `ptySpawnDiagnostics.js` | `diagnosePtySpawnFailure(err, {cwd, probeCwd, runtimeProbe})` + `probePtyRuntime(pty, cwd)` and the `PTY_UNAVAILABLE_PREFIX` / `PTY_WORKSPACE_MISSING_PREFIX` markers — turns node-pty's one opaque `posix_spawn failed: No such file or directory` into a named fault. The executable is already cleared upstream (PATH resolve + `--version` probe), so a throw is either a `cwd` that vanished (cheap `existsSync`) or a PTY layer that cannot fork AT ALL — proven by re-launching a known-good command in a known-good directory. Both are non-retryable, and `agentTuiSpawning.js` matches the prefixes to block the task with the repair instead of retrying it as a transient `spawn-rejected`. The motivating outage: an `npm ci` inside a CoS worktree emptied the primary checkout's `server/node_modules` through a symlink, deleting the `spawn-helper` binary node-pty execs on every fork, while the already-loaded binding left the runner process itself looking healthy. |
| `pythonSetup.js` | Python venv / runner setup helpers. |
| `vttTranscript.js` | WebVTT/SRT → readable prose. `vttToPlainText(vtt)` (paragraph-joined transcript), `vttToLines(vtt)` (cleaned caption lines), `cleanCaptionLine(line)`. Collapses YouTube auto-captions' rolling repetition and strips inline `<c>`/timestamp markup. Used by the brain YouTube ingest. |
| `youtubeIngestFormat.js` | Pure data transformations for the brain's YouTube ingest (#6015): `parseVideoMetadata(json)` (yt-dlp `--dump-single-json` → the stored metadata shape, incl. the `subtitles`-vs-`automatic_captions` manual-caption signal), `buildIngestNote({meta,url,transcript,tags,agentPrompt,capturedAt})` (the Obsidian note, whose YAML frontmatter the user's own vault queries key on — every interpolated scalar goes through `yamlString`), `buildAgentTaskContext(...)` (the CoS follow-up prompt, including the untrusted-transcript boundary notice), `resolveObsidianPointer({written,vaultId,notePath,prior})` (keeps the prior note pointer when an ATTEMPTED mirror failed, so an evicted note can't be orphaned — #3706), plus `sanitizeFilename`, `formatDuration` (seconds → `h:mm:ss`) and `yamlString`. No fs/db/childProcess/SSE imports; orchestration and storage stay in `services/youtubeIngest.js`. Surfaced through the barrel as a NAMESPACE export (`youtubeIngestFormat.*`) because `formatDuration` collides with `fileCore.js` and `sanitizeFilename` with `mimeTypes.js`. |
diff --git a/server/lib/index.js b/server/lib/index.js
index b01d60dd67..d4940f38ec 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -342,6 +342,7 @@ export * from './npmGlobalBin.js';
export * from './openFolder.js';
export * from './processEnv.js';
export * from './primaryCheckoutGuard.js';
+export * from './ptySpawnDiagnostics.js';
export * from './pythonSetup.js';
export * from './vttTranscript.js';
export * as youtubeIngestFormat from './youtubeIngestFormat.js';
diff --git a/server/lib/ptySpawnDiagnostics.js b/server/lib/ptySpawnDiagnostics.js
new file mode 100644
index 0000000000..f9825abc6b
--- /dev/null
+++ b/server/lib/ptySpawnDiagnostics.js
@@ -0,0 +1,118 @@
+/**
+ * Turn a raw node-pty spawn failure into a diagnosis a human can act on.
+ *
+ * node-pty reports every POSIX launch failure as the same opaque string —
+ * `posix_spawn failed: No such file or directory` — with no indication of WHICH
+ * file was missing. Three very different faults collapse into it:
+ *
+ * 1. the target executable is gone (already ruled out upstream: the CoS runner
+ * resolves it on the child PATH and runs a `--version` capability probe
+ * before it ever opens a PTY);
+ * 2. the `cwd` no longer exists — a worktree reaped out from under a spawn;
+ * 3. **node-pty's own runtime is broken** — on macOS/Linux `pty.fork()` execs a
+ * sibling `spawn-helper` binary that is read from disk on EVERY spawn, so an
+ * emptied `server/node_modules` breaks all future spawns while the already
+ * loaded binding keeps the runner process itself alive and healthy-looking.
+ *
+ * (3) is the one that cost a day: `npm ci` run inside a CoS worktree whose
+ * `server/node_modules` was symlinked at the primary checkout empties the
+ * SYMLINK TARGET and then installs into a fresh real directory in the worktree —
+ * see the "Agent worktrees" rule in the root `AGENTS.md`. The primary checkout is
+ * left with an empty `server/node_modules`, `spawn-helper` is gone, and every
+ * subsequent agent spawn fails identically forever. Classified as a generic
+ * `spawn-rejected` it looks transient, so the fleet retried it: every task type
+ * burned MAX_TASK_RETRIES, blocked itself, and filed a meta-investigation task
+ * that failed the same way.
+ *
+ * The probe is what separates (3) from the rest: re-launch a trivially-known-good
+ * command in a known-good directory. If THAT fails too, nothing is wrong with the
+ * caller's request — the PTY layer itself is unusable.
+ */
+
+import { existsSync } from 'fs';
+
+/**
+ * Message prefix marking a broken PTY runtime. `agentTuiSpawning.js` matches it
+ * to classify the run as actionable-and-blocked instead of retrying, the same way
+ * it already special-cases `Command executable unavailable:`. Changing this string
+ * means changing that matcher.
+ */
+export const PTY_UNAVAILABLE_PREFIX = 'CoS Runner PTY unavailable:';
+
+/** Message prefix for a spawn whose working directory vanished before launch. */
+export const PTY_WORKSPACE_MISSING_PREFIX = 'CoS Runner workspace missing:';
+
+/**
+ * A command guaranteed to exist on the host, used only to prove the PTY layer can
+ * still fork at all. Never runs long enough to matter: the probe kills it.
+ */
+const PROBE_COMMAND = process.platform === 'win32' ? 'cmd.exe' : '/bin/echo';
+const PROBE_ARGS = process.platform === 'win32' ? ['/c', 'exit'] : ['portos-pty-probe'];
+
+/**
+ * Can node-pty still fork? Spawns {@link PROBE_COMMAND} in `probeCwd` and kills it
+ * immediately — we care only whether the constructor threw.
+ *
+ * @param {object} pty - the node-pty module (injected so this stays testable)
+ * @param {string} probeCwd - a directory known to exist (the runner's own root)
+ * @returns {boolean} true when the PTY layer is usable
+ */
+export function probePtyRuntime(pty, probeCwd) {
+ // Outside the Express request lifecycle and deliberately best-effort: a probe
+ // that itself explodes must not mask the original failure we are explaining.
+ try {
+ const probe = pty.spawn(PROBE_COMMAND, PROBE_ARGS, {
+ name: 'xterm-256color',
+ cols: 80,
+ rows: 24,
+ cwd: probeCwd,
+ env: process.env,
+ });
+ try {
+ probe.kill();
+ } catch {
+ // Already exited — `echo` is fast enough to beat the kill. Still a success.
+ }
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Explain a `pty.spawn` throw.
+ *
+ * Order matters: the workspace check is a cheap `existsSync` on the exact path the
+ * caller asked for, and a missing worktree is a per-request fault that says nothing
+ * about the runtime. Only once that is ruled out do we spend a probe fork asking
+ * whether the PTY layer is broken for everyone.
+ *
+ * @param {Error} err - what `pty.spawn` threw
+ * @param {object} options
+ * @param {string} options.cwd - the working directory the spawn requested
+ * @param {string} options.probeCwd - a directory known to exist, for the probe
+ * @param {(probeCwd: string) => boolean} options.runtimeProbe - returns whether the
+ * PTY layer still works; injected so callers own the node-pty import
+ * @returns {{ retryable: boolean, message: string }} `retryable: false` marks a
+ * fault that will fail identically on every attempt, so the caller should block
+ * rather than burn retries.
+ */
+export function diagnosePtySpawnFailure(err, { cwd, probeCwd, runtimeProbe }) {
+ const raw = err?.message || String(err);
+
+ if (cwd && !existsSync(cwd)) {
+ return {
+ retryable: false,
+ message: `${PTY_WORKSPACE_MISSING_PREFIX} the working directory for this spawn no longer exists. It was probably removed (a reaped worktree) between the request and the launch. Original error: ${raw}`,
+ };
+ }
+
+ if (!runtimeProbe(probeCwd)) {
+ return {
+ retryable: false,
+ message: `${PTY_UNAVAILABLE_PREFIX} node-pty cannot fork any process, so this is not specific to the requested command. The usual cause is an emptied or partially installed \`server/node_modules\` — node-pty execs its \`spawn-helper\` binary from disk on every spawn. Repair it with \`npm install --prefix server\` and restart the runner (\`pm2 restart portos-cos\`). Original error: ${raw}`,
+ };
+ }
+
+ return { retryable: true, message: raw };
+}
diff --git a/server/lib/ptySpawnDiagnostics.test.js b/server/lib/ptySpawnDiagnostics.test.js
new file mode 100644
index 0000000000..95c2426dc1
--- /dev/null
+++ b/server/lib/ptySpawnDiagnostics.test.js
@@ -0,0 +1,116 @@
+import { describe, it, expect } from 'vitest';
+import { tmpdir } from 'os';
+import { mkdtempSync, rmSync } from 'fs';
+import { join } from 'path';
+import {
+ diagnosePtySpawnFailure,
+ probePtyRuntime,
+ PTY_UNAVAILABLE_PREFIX,
+ PTY_WORKSPACE_MISSING_PREFIX,
+} from './ptySpawnDiagnostics.js';
+
+// The exact string node-pty raises for every POSIX launch failure — the whole
+// reason this module exists. Nothing in it names which file was missing.
+const POSIX_SPAWN_ENOENT = new Error('posix_spawn failed: No such file or directory');
+
+const workingProbe = () => true;
+const brokenProbe = () => false;
+
+describe('diagnosePtySpawnFailure', () => {
+ it('blames the PTY runtime, not the request, when a known-good probe also fails', () => {
+ // The outage this module was written for: `server/node_modules` emptied out
+ // from under a live runner, so node-pty's `spawn-helper` is gone and every
+ // fork fails — while the requested cwd and command are both perfectly fine.
+ const { retryable, message } = diagnosePtySpawnFailure(POSIX_SPAWN_ENOENT, {
+ cwd: tmpdir(),
+ probeCwd: tmpdir(),
+ runtimeProbe: brokenProbe,
+ });
+
+ expect(retryable).toBe(false);
+ expect(message.startsWith(PTY_UNAVAILABLE_PREFIX)).toBe(true);
+ // The repair command is the payload — a diagnosis that omits it leaves the
+ // reader exactly where the raw node-pty string did.
+ expect(message).toContain('npm install --prefix server');
+ expect(message).toContain(POSIX_SPAWN_ENOENT.message);
+ });
+
+ it('blames the workspace when the requested cwd is gone, without spending a probe', () => {
+ const missing = join(tmpdir(), 'portos-pty-diagnostics-absent-dir');
+ let probed = false;
+
+ const { retryable, message } = diagnosePtySpawnFailure(POSIX_SPAWN_ENOENT, {
+ cwd: missing,
+ probeCwd: tmpdir(),
+ runtimeProbe: () => { probed = true; return true; },
+ });
+
+ expect(retryable).toBe(false);
+ expect(message.startsWith(PTY_WORKSPACE_MISSING_PREFIX)).toBe(true);
+ // A reaped worktree says nothing about the runtime; forking to ask would be
+ // a wasted process on the one path that already has its answer.
+ expect(probed).toBe(false);
+ });
+
+ it('stays retryable when the workspace exists and the PTY layer still forks', () => {
+ // Neither known fault applies, so the failure is specific to this request and
+ // may well be transient. Reporting it as unrecoverable would block a task
+ // that a plain retry fixes.
+ const err = new Error('resource temporarily unavailable');
+ const { retryable, message } = diagnosePtySpawnFailure(err, {
+ cwd: tmpdir(),
+ probeCwd: tmpdir(),
+ runtimeProbe: workingProbe,
+ });
+
+ expect(retryable).toBe(true);
+ expect(message).toBe('resource temporarily unavailable');
+ });
+
+ it('checks the cwd it was handed, not the probe directory', () => {
+ // Guards the argument-swap bug: probing a directory that always exists would
+ // make the workspace branch permanently unreachable.
+ const missing = join(tmpdir(), 'portos-pty-diagnostics-absent-dir-2');
+ const { message } = diagnosePtySpawnFailure(POSIX_SPAWN_ENOENT, {
+ cwd: missing,
+ probeCwd: missing,
+ runtimeProbe: brokenProbe,
+ });
+ expect(message.startsWith(PTY_WORKSPACE_MISSING_PREFIX)).toBe(true);
+ });
+});
+
+describe('probePtyRuntime', () => {
+ it('reports false when the pty module throws, and never lets the probe escape', () => {
+ const exploding = { spawn: () => { throw new Error('posix_spawn failed: No such file or directory'); } };
+ expect(() => probePtyRuntime(exploding, tmpdir())).not.toThrow();
+ expect(probePtyRuntime(exploding, tmpdir())).toBe(false);
+ });
+
+ it('reports true — and still cleans up — when the child exits before kill()', () => {
+ // `echo` regularly beats the kill, so a throwing kill() must not be read as a
+ // broken runtime.
+ const alreadyGone = { spawn: () => ({ kill: () => { throw new Error('process not found'); } }) };
+ expect(probePtyRuntime(alreadyGone, tmpdir())).toBe(true);
+ });
+
+ it('runs the probe in the directory it was given', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'portos-pty-probe-'));
+ try {
+ let seen = null;
+ const recording = { spawn: (_cmd, _args, opts) => { seen = opts.cwd; return { kill: () => {} }; } };
+ expect(probePtyRuntime(recording, dir)).toBe(true);
+ expect(seen).toBe(dir);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ it('actually forks against the real node-pty module', async () => {
+ // The one test that would have caught the live outage: it fails exactly when
+ // node-pty's on-disk artifacts are missing, which is what an emptied
+ // `server/node_modules` produces while the loaded binding still looks fine.
+ const pty = await import('node-pty');
+ expect(probePtyRuntime(pty, tmpdir())).toBe(true);
+ });
+});
diff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.js
index a4b402ea57..7d8736cfc2 100644
--- a/server/services/agentErrorAnalysis.js
+++ b/server/services/agentErrorAnalysis.js
@@ -1001,6 +1001,22 @@ export const COMPLETION_REASON_ANALYSES = {
message: 'Worktree agent mutated the primary checkout',
suggestedFix: 'The agent was given its own git worktree and committed to the primary checkout anyway, so the primary is carrying commits nothing reviewed. The same work is almost certainly on the agent\'s branch too. Inspect the primary with `git log --oneline origin/<branch>..<branch>` and, once the content is confirmed preserved, restore it with `git reset --hard origin/<branch>` — PortOS will not run that for you, because it discards commits.'
},
+ // The runner opened no PTY because its own PTY layer is unusable, or because
+ // the workspace it was pointed at disappeared. Unlike `spawn-rejected` below
+ // this is deliberately ACTIONABLE: both faults reproduce exactly on every
+ // retry, so blocking once with the repair command beats letting each task type
+ // burn MAX_TASK_RETRIES and file a meta-investigation that fails identically.
+ // Named after the observed outage: an `npm ci` inside a CoS worktree emptied
+ // the primary checkout's `server/node_modules` through a symlink, deleting the
+ // `spawn-helper` binary node-pty execs on every fork while the already-loaded
+ // binding kept the runner process itself looking healthy.
+ 'runner-pty-unavailable': {
+ category: 'spawn-error',
+ actionable: true,
+ escalation: 'Repair the runner host, then approve the retry: for a broken PTY layer run `npm install --prefix server` and `pm2 restart portos-cos`; for a missing workspace confirm the worktree was not reaped mid-spawn.',
+ message: 'The runner could not open a PTY',
+ suggestedFix: 'No agent process was created and no retry can change that — the runner\'s own diagnosis (carried in the completion error) names which half failed: node-pty unable to fork at all (usually an emptied or partially installed `server/node_modules`, since node-pty execs its `spawn-helper` from disk on every spawn), or a working directory that no longer exists.'
+ },
'spawn-rejected': {
category: 'spawn-error',
actionable: false,
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index ff7644e797..99336c7144 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -21,6 +21,7 @@ import { PATHS, watchForFile } from '../lib/fileUtils.js';
import { resolveAgentCliCwd } from '../lib/spawnCwd.js';
import { doneSentinelName, doneSentinelPath as resolveDoneSentinelPath, parseSentinelPayload } from '../lib/agentSentinel.js';
import { HOST_SHUTDOWN_REASON } from '../lib/hostShutdown.js';
+import { PTY_UNAVAILABLE_PREFIX, PTY_WORKSPACE_MISSING_PREFIX } from '../lib/ptySpawnDiagnostics.js';
import { finalizeAgentRunCommon, shouldAbandonAgentRun } from './agentRunFinalize.js';
import { SENTINEL_COMPLETION_MARKER } from '../lib/agentOutputMarkers.js';
import { prClaimWasVerified, leavesPrForHuman } from '../lib/prDisposition.js';
@@ -1579,9 +1580,17 @@ export async function spawnTuiAgent({
// A LOCAL direct PTY raises the SAME failure with the same prefix — see the
// pre-spawn resolve in createAgentTuiSession's restricted branch (#6159) —
// so the test is no longer gated on the runner.
+ //
+ // The runner's PTY-layer diagnoses get the same treatment for the same
+ // reason: a broken node-pty install or a workspace that vanished fails
+ // identically on every attempt, so retrying it as a transient rejection just
+ // burns MAX_TASK_RETRIES on every task in the fleet and buries the one line
+ // that names the repair (see lib/ptySpawnDiagnostics.js).
const reason = /^Command executable unavailable:/i.test(message)
? 'command-not-found'
- : useDurableRunner ? 'spawn-rejected' : 'spawn-error';
+ : message.startsWith(PTY_UNAVAILABLE_PREFIX) || message.startsWith(PTY_WORKSPACE_MISSING_PREFIX)
+ ? 'runner-pty-unavailable'
+ : useDurableRunner ? 'spawn-rejected' : 'spawn-error';
if (useDurableRunner) {
// A handoff that did not land (#4540), recorded like the CLI path's. A
// LOCAL PTY that won't open is a host problem, not a handoff, so it is