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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
keep a reaped worktree retryable; only an unusable PTY layer blocks the task
[._.]/ Adam Eivy29a22a0bbaa7
diff --git a/server/cos-runner/index.js b/server/cos-runner/index.jsindex 5c1b7cc31a..e15fe979d3 100644--- a/server/cos-runner/index.js+++ b/server/cos-runner/index.js@@ -260,12 +260,14 @@ app.post('/spawn-tui', async (req, res) => {env: childEnv,});} catch (err) {- const { retryable, message } = diagnosePtySpawnFailure(err, {+ const { diagnosed, message } = diagnosePtySpawnFailure(err, {cwd,probeCwd: ROOT_DIR,runtimeProbe: (probeCwd) => probePtyRuntime(pty, probeCwd),});- if (retryable) throw err;+ // Neither known fault: let the original bubble to the error middleware exactly+ // as it did before, rather than dressing an unknown cause in a confident 422.+ if (!diagnosed) throw err;console.error(`❌ PTY spawn failed for ${agentId}: ${message}`);return res.status(422).json({ error: message });}diff --git a/server/lib/README.md b/server/lib/README.mdindex ffb1b6571d..3a308b8e58 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -357,7 +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. |+| `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-forking a known-good command in a known-good directory; `diagnosed: false` means neither matched, and the caller re-throws rather than inventing a cause. **Retry policy is the caller’s and the two faults differ:** `agentTuiSpawning.js` matches only the PTY-layer prefix, mapping it to the actionable `runner-pty-unavailable` so the task blocks once with the repair, while a reaped workspace falls through to the retrying `spawn-rejected` because the next attempt provisions a fresh worktree. 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/ptySpawnDiagnostics.js b/server/lib/ptySpawnDiagnostics.jsindex f9825abc6b..c4b95f550f 100644--- a/server/lib/ptySpawnDiagnostics.js+++ b/server/lib/ptySpawnDiagnostics.js@@ -17,7 +17,8 @@* (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+ * see the "Never run `npm ci` … from inside a CoS worktree" rule in the root+ * `AGENTS.md`, which exists to prevent this. 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@@ -39,7 +40,15 @@ import { existsSync } from 'fs';*/export const PTY_UNAVAILABLE_PREFIX = 'CoS Runner PTY unavailable:';-/** Message prefix for a spawn whose working directory vanished before launch. */+/**+ * Message prefix for a spawn whose working directory vanished before launch.+ *+ * Deliberately NOT matched by `agentTuiSpawning.js`: unlike a broken PTY layer this+ * is transient — each retry provisions a fresh worktree at a fresh path — so it+ * falls through to the retrying `spawn-rejected`. Naming it separately is what+ * keeps the two from being collapsed back together; a genuinely misconfigured cwd+ * still surfaces by failing every attempt and blocking on MAX_TASK_RETRIES.+ */export const PTY_WORKSPACE_MISSING_PREFIX = 'CoS Runner workspace missing:';/**@@ -58,8 +67,10 @@ const PROBE_ARGS = process.platform === 'win32' ? ['/c', 'exit'] : ['portos-pty-* @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.+ // Catching here is the point of the function, not an escape from the no-try/catch+ // rule: "did this throw?" IS the answer being computed. It also runs while the+ // caller is already handling a failure, so a probe that explodes on its own must+ // not replace the original error with its own.try {const probe = pty.spawn(PROBE_COMMAND, PROBE_ARGS, {name: 'xterm-256color',@@ -93,26 +104,29 @@ export function probePtyRuntime(pty, probeCwd) {* @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.+ * @returns {{ diagnosed: boolean, message: string }} `diagnosed: false` means the+ * failure matched neither known fault, so the caller should let the original error+ * bubble rather than dress an unknown cause in a confident explanation. Whether a+ * named fault is worth RETRYING is the caller's policy, not this function's — the+ * two differ: a reaped worktree clears on the next attempt (which provisions a+ * fresh one), while a broken PTY layer reproduces forever.*/export function diagnosePtySpawnFailure(err, { cwd, probeCwd, runtimeProbe }) {const raw = err?.message || String(err);if (cwd && !existsSync(cwd)) {return {- retryable: false,+ diagnosed: true,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,+ diagnosed: true,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 };+ return { diagnosed: false, message: raw };}diff --git a/server/lib/ptySpawnDiagnostics.test.js b/server/lib/ptySpawnDiagnostics.test.jsindex 95c2426dc1..ad7d7f44ad 100644--- a/server/lib/ptySpawnDiagnostics.test.js+++ b/server/lib/ptySpawnDiagnostics.test.js@@ -21,13 +21,13 @@ describe('diagnosePtySpawnFailure', () => {// 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, {+ const { diagnosed, message } = diagnosePtySpawnFailure(POSIX_SPAWN_ENOENT, {cwd: tmpdir(),probeCwd: tmpdir(),runtimeProbe: brokenProbe,});- expect(retryable).toBe(false);+ expect(diagnosed).toBe(true);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.@@ -39,31 +39,30 @@ describe('diagnosePtySpawnFailure', () => {const missing = join(tmpdir(), 'portos-pty-diagnostics-absent-dir');let probed = false;- const { retryable, message } = diagnosePtySpawnFailure(POSIX_SPAWN_ENOENT, {+ const { diagnosed, message } = diagnosePtySpawnFailure(POSIX_SPAWN_ENOENT, {cwd: missing,probeCwd: tmpdir(),runtimeProbe: () => { probed = true; return true; },});- expect(retryable).toBe(false);+ expect(diagnosed).toBe(true);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.+ it('declines to diagnose when the workspace exists and the PTY layer still forks', () => {+ // Neither known fault applies. Returning a confident explanation here would be+ // worse than saying nothing — the caller re-throws the original instead.const err = new Error('resource temporarily unavailable');- const { retryable, message } = diagnosePtySpawnFailure(err, {+ const { diagnosed, message } = diagnosePtySpawnFailure(err, {cwd: tmpdir(),probeCwd: tmpdir(),runtimeProbe: workingProbe,});- expect(retryable).toBe(true);+ expect(diagnosed).toBe(false);expect(message).toBe('resource temporarily unavailable');});diff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.jsindex 7d8736cfc2..750f4e2c5c 100644--- a/server/services/agentErrorAnalysis.js+++ b/server/services/agentErrorAnalysis.js@@ -1001,21 +1001,24 @@ 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.+ // The runner's PTY layer itself cannot fork — proven, not guessed: the runner+ // re-launched a known-good command in a known-good directory and that failed+ // too, so nothing about the requested command or workspace is at fault.+ //+ // Deliberately ACTIONABLE, unlike its `spawn-rejected` sibling below: this+ // reproduces on every attempt for every task, so blocking once with the repair+ // beats letting each task type burn MAX_TASK_RETRIES and file a+ // meta-investigation that fails the same way. Named after the observed outage —+ // an `npm ci` run 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 perfectly 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.',+ escalation: 'Repair the runner host, then approve the retry: run `npm install --prefix server` in the PRIMARY checkout and `pm2 restart portos-cos`. Every agent spawn fails until this is fixed, so expect other tasks to be blocked on it too.',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.'+ suggestedFix: 'No agent process was created and no retry can change that: node-pty could not fork even a known-good command, so the PTY layer is unusable for every task. The usual cause is an emptied or partially installed `server/node_modules` — node-pty execs its `spawn-helper` binary from disk on every spawn, and an `npm ci` run inside a CoS worktree deletes it through the symlinked `node_modules`. Reinstall in the primary checkout and restart the runner.'},'spawn-rejected': {category: 'spawn-error',diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 99336c7144..6f589ba811 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -21,7 +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 { PTY_UNAVAILABLE_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';@@ -1581,14 +1581,21 @@ export async function spawnTuiAgent({// 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).+ // An unusable PTY LAYER joins that actionable set for the same reason: it+ // reproduces on every attempt, so retrying it as a transient rejection burns+ // MAX_TASK_RETRIES on every task in the fleet and buries the one line naming+ // the repair (see lib/ptySpawnDiagnostics.js).+ //+ // The runner's OTHER named fault — a workspace that vanished — deliberately+ // does NOT join it. Each retry provisions a fresh worktree at a fresh path, so+ // a reaped one is exactly the transient case `spawn-rejected` exists for;+ // blocking on it would park work a retry fixes. A cwd that is missing because+ // it is misconfigured (a managed app whose directory is gone) still surfaces —+ // it fails identically every attempt and blocks on MAX_TASK_RETRIES carrying+ // the runner's message, which is that reason's documented behavior.const reason = /^Command executable unavailable:/i.test(message)? 'command-not-found'- : message.startsWith(PTY_UNAVAILABLE_PREFIX) || message.startsWith(PTY_WORKSPACE_MISSING_PREFIX)+ : message.startsWith(PTY_UNAVAILABLE_PREFIX)? 'runner-pty-unavailable': useDurableRunner ? 'spawn-rejected' : 'spawn-error';if (useDurableRunner) {diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex be72ebd431..01b3d09250 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -2631,6 +2631,47 @@ describe('spawnTuiAgent runtime', () => {);});+ // The runner's two PTY diagnoses split on RETRY POLICY, and the split is the+ // whole point of naming them separately. A PTY layer that cannot fork is+ // broken for every task until a human reinstalls, so it must block once+ // instead of retry-storming the fleet; a reaped worktree is cleared by the+ // very next attempt, which provisions a fresh one, so it must NOT block.+ // Collapsing them (an earlier revision matched both prefixes) parks work a+ // retry would have fixed.+ it('blocks on an unusable PTY layer as runner-pty-unavailable', async () => {+ vi.mocked(spawnTuiSessionViaRunner).mockRejectedValueOnce(+ new Error('CoS Runner PTY unavailable: node-pty cannot fork any process, so this is not specific to the requested command. Repair it with `npm install --prefix server`.'),+ );++ await expect(runSpawn({ useDurableRunner: true })).resolves.toBeNull();++ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'agent-1',+ success: false,+ completionReason: 'runner-pty-unavailable',+ error: expect.stringContaining('npm install --prefix server'),+ })+ );+ });++ it('leaves a reaped workspace retryable as spawn-rejected', async () => {+ vi.mocked(spawnTuiSessionViaRunner).mockRejectedValueOnce(+ new Error('CoS Runner workspace missing: the workspace for this spawn does not exist. Its worktree was probably removed before the agent launched.'),+ );++ await expect(runSpawn({ useDurableRunner: true })).resolves.toBeNull();++ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'agent-1',+ success: false,+ completionReason: 'spawn-rejected',+ error: expect.stringContaining('worktree was probably removed'),+ })+ );+ });+// The ledger has to carry the outcome it actually knows (#4615). A runner// that ANSWERED with a refusal and a transport failure that answered// nothing are different facts, and a diagnostic that reads the second as