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

fix: detect agent CLI fallback signals outside serialized transcript writes (#2384)

Adam Eivyc4db7550f05e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 97620dc070..db6a0905cf 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -51,6 +51,8 @@
## Fixed
+- **[issue-2384] A usage-limit fallback signal now stops a direct-CLI CoS agent immediately even when an earlier transcript write is stalled, and the persisted transcript can no longer be reordered.** The direct-CLI spawn path (`spawnDirectly` in `server/services/agentCliSpawning.js`) let each stdout/stderr `data` event run its transcript-mutating body (`outputBuffer` append + `output.txt` write + batched live-tail push) as an independent async handler, so two chunks' interleaved `await`s could persist output out of order, and a blocked state/file write on an earlier chunk could sit in front of a later chunk that carried the `Now using extra usage` fallback marker. Fallback detection now runs **synchronously** in the raw listener — before any transcript work is enqueued — so the provider is killed the instant the signal arrives regardless of a stalled write, while the transcript body is serialized onto a single per-agent tail promise (mirroring `shell.js`'s `hookQueue` and `pipeline/issues.js`'s `issueWriteTail`) that the close/error/terminate paths drain before finalizing. A regression test blocks an earlier write, emits the fallback signal on a later chunk, and asserts termination stays immediate and final output stays ordered.
+
- **CoS agents (notably codex) now open their PR as the gh account that matches the repo owner, not gh's mutable active user.** PortOS's own `createPR` pins `GH_TOKEN` to the logged-in gh account whose login matches the repo owner (avoiding the multi-account "must be a collaborator" failure), but a spawned agent running its *own* `gh pr create` — a codex/Claude/CLI CoS agent finishing `/do:pr` — never received that pinning. TUI agents fared worst: `shell.js`'s `buildSafeEnv` strips `GH_TOKEN` from the inherited env entirely, so their `gh` fell back to whatever `hosts.yml` active user happened to be set. A new best-effort `resolveForgeTokenEnv(dir)` (in `server/services/git.js`) resolves just the owner-matched `GH_TOKEN` overlay and is injected into all three agent-spawn env paths — direct CLI (`spawnDirectly`), TUI shell session (`spawnTuiAgent`), and the CoS runner (`spawnViaRunner`). It's provider-agnostic (no codex special-case), returns `{}` when no owner-matched account exists (so single-account installs and GitLab repos are untouched), and is spread before `provider.envVars` so an explicit provider `GH_TOKEN` override still wins.
- **Codex CoS agents no longer die `paste-not-rendered` while codex boots its MCP servers.** Codex boots any MCP servers configured in the user's global `~/.codex/config.toml` on every headless spawn — including heavyweight interactive ones like `playwright` (fetched via `npx`) or a `node_repl` with `startup_timeout_sec = 120`. That boot can run for tens of seconds up to ~2 minutes, during which codex swallows pastes, renders no `[Pasted Content N chars]` commit marker, and shows only the *tail* of a long paste in its input viewport (never the verified prefix) — so PortOS's paste-verify retry could not confirm delivery and killed the agent after only 3 short attempts (~19s), long before the boot finished (real incident 2026-07-10: `agent-c5a26b40` / `agent-3f4ae3b1`, both on gpt-5.6-sol; the same prompt succeeded days earlier when no MCP servers were configured and codex was ready in <10s). The spawner now detects codex's MCP-boot banner (`Booting MCP server` / `Starting MCP servers`) and extends the paste-retry budget from the fixed 3 attempts to a time budget (150s, covering `node_repl`'s 120s startup plus an `npx` cold download while staying under the idle-reap window), so a slow boot completes and the paste finally lands. If the boot genuinely never finishes, the failure now names the MCP-boot cause and points at the codex config instead of a misleading "still initializing" message. Non-codex TUIs and codex installs without MCP servers are unchanged.
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index c9970dd349..8f8f1614f2 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -524,7 +524,33 @@ export async function spawnDirectly({
// stdout/stderr could land after the terminal record. (The close handler
// still drains too; flush() is idempotent.)
const cliAgentEntry = activeAgents.get(agentId);
- if (cliAgentEntry) cliAgentEntry.flushOutput = () => outputBatcher.flush();
+ // Drain the serialized write chain (defined just below) before flushing the
+ // batcher so any enqueued-but-unrun stdout/stderr push lands first.
+ if (cliAgentEntry) cliAgentEntry.flushOutput = async () => {
+ await drainTranscriptWrites();
+ await outputBatcher.flush();
+ };
+
+ // Serialize the transcript-mutating body of every stdout/stderr `data` event
+ // onto a single per-agent tail promise. Both handlers mutate the same shared
+ // `outputBuffer`/`rawStreamBuffer` and write the same `output.txt`, so their
+ // interleaved awaits (e.g. one chunk's `writeFile` yielding while the next
+ // chunk appends) would otherwise reorder the transcript (#2384). Fallback
+ // detection stays OUTSIDE this chain — it runs synchronously in the raw
+ // listener before the enqueue, so a blocked earlier write can never delay
+ // killing the provider on a usage-limit signal. The close/error handlers
+ // `await drainTranscriptWrites()` before finalize so the tail lands first.
+ // Mirrors shell.js `hookQueue` and pipeline/issues.js `issueWriteTail`.
+ let transcriptWriteTail = Promise.resolve();
+ const enqueueTranscriptWrite = (fn) => {
+ transcriptWriteTail = transcriptWriteTail.then(fn).catch((err) => {
+ // Runs in a child-process callback — a rejection here would escape as an
+ // unhandled rejection and crash Node. output.txt is best-effort; log+swallow.
+ console.error(`❌ agentCli transcript write failed for ${agentId}: ${err.message}`);
+ });
+ return transcriptWriteTail;
+ };
+ const drainTranscriptWrites = () => transcriptWriteTail;
const stopForImmediateFallbackSignal = (text) => {
if (immediateFallbackAnalysis || claudeProcess.killed) return;
@@ -554,53 +580,62 @@ export async function spawnDirectly({
}
}, 3000);
- claudeProcess.stdout.on('data', async (data) => {
+ claudeProcess.stdout.on('data', (data) => {
try {
const text = data.toString();
+ // Detect fallback signals SYNCHRONOUSLY, before enqueuing any transcript
+ // mutation — a blocked earlier write must never delay killing the provider
+ // on a usage-limit signal (#2384).
stopForImmediateFallbackSignal(text);
+ // Serialize the transcript body so two `data` events can't interleave their
+ // awaits and reorder output.txt / the batched live tail.
+ enqueueTranscriptWrite(async () => {
+ if (!hasStartedWorking) {
+ hasStartedWorking = true;
+ await updateAgent(agentId, { metadata: { phase: 'working' } });
+ emitLog('info', `Agent ${agentId} working...`, { agentId, phase: 'working' });
+ }
- if (!hasStartedWorking) {
- hasStartedWorking = true;
- await updateAgent(agentId, { metadata: { phase: 'working' } });
- emitLog('info', `Agent ${agentId} working...`, { agentId, phase: 'working' });
- }
-
- if (streamParser) {
- // Parse stream-json and emit extracted text lines (cap buffer at 512KB for error analysis)
- rawStreamBuffer += text;
- if (rawStreamBuffer.length > 512 * 1024) {
- rawStreamBuffer = rawStreamBuffer.slice(-512 * 1024);
+ if (streamParser) {
+ // Parse stream-json and emit extracted text lines (cap buffer at 512KB for error analysis)
+ rawStreamBuffer += text;
+ if (rawStreamBuffer.length > 512 * 1024) {
+ rawStreamBuffer = rawStreamBuffer.slice(-512 * 1024);
+ }
+ const lines = streamParser.processChunk(text);
+ for (const line of lines) outputBuffer += line + '\n';
+ outputBatcher.push(lines);
+ await writeFile(outputFile, outputBuffer).catch(() => {});
+ } else {
+ // Non-stream providers: emit raw stdout as before
+ outputBuffer += text;
+ await writeFile(outputFile, outputBuffer).catch(() => {});
+ outputBatcher.push(text);
}
- const lines = streamParser.processChunk(text);
- for (const line of lines) outputBuffer += line + '\n';
- outputBatcher.push(lines);
- await writeFile(outputFile, outputBuffer).catch(() => {});
- } else {
- // Non-stream providers: emit raw stdout as before
- outputBuffer += text;
- await writeFile(outputFile, outputBuffer).catch(() => {});
- outputBatcher.push(text);
- }
+ });
} catch (err) {
console.error(`❌ agentCli stdout handler failed: ${err.message}`);
}
});
- claudeProcess.stderr.on('data', async (data) => {
+ claudeProcess.stderr.on('data', (data) => {
try {
const text = data.toString();
+ // Synchronous fallback detection before the serialized write (see stdout).
stopForImmediateFallbackSignal(`[stderr] ${text}`);
- // Codex stderr: show thinking + tool names, skip config dump and command output
- if (codexStderrFormatter) {
- const lines = codexStderrFormatter.processChunk(text);
- for (const line of lines) outputBuffer += line + '\n';
- outputBatcher.push(lines);
+ enqueueTranscriptWrite(async () => {
+ // Codex stderr: show thinking + tool names, skip config dump and command output
+ if (codexStderrFormatter) {
+ const lines = codexStderrFormatter.processChunk(text);
+ for (const line of lines) outputBuffer += line + '\n';
+ outputBatcher.push(lines);
+ await writeFile(outputFile, outputBuffer).catch(() => {});
+ return;
+ }
+ outputBuffer += `[stderr] ${text}`;
await writeFile(outputFile, outputBuffer).catch(() => {});
- return;
- }
- outputBuffer += `[stderr] ${text}`;
- await writeFile(outputFile, outputBuffer).catch(() => {});
- outputBatcher.push(`[stderr] ${text}`);
+ outputBatcher.push(`[stderr] ${text}`);
+ });
} catch (err) {
console.error(`❌ agentCli stderr handler failed: ${err.message}`);
}
@@ -632,6 +667,9 @@ export async function spawnDirectly({
}
cosEvents.emit('agent:error', { agentId, error: err.message });
+ // Drain queued transcript writes before flushing the batcher + recording
+ // the run so outputBuffer reflects everything that streamed (#2384).
+ await drainTranscriptWrites();
await outputBatcher.flush();
await completeAgent(agentId, { success: false, error: err.message });
await completeAgentRun(runId, outputBuffer, 1, 0, { message: err.message, category: 'spawn-error' });
@@ -678,6 +716,12 @@ export async function spawnDirectly({
const finalSuccess = terminatedByUser ? false : (success && !immediateFallbackAnalysis);
const finalError = terminatedByUser ? 'Agent terminated by user' : null;
+ // Drain any queued transcript writes before reading/appending outputBuffer
+ // for finalization — a still-pending stdout/stderr write would otherwise
+ // land after the terminal record or clobber the final output.txt (#2384).
+ // No new `data` events fire after 'close', so a single drain is sufficient.
+ await drainTranscriptWrites();
+
// Flush remaining stream parser data (persists the tail of the transcript
// before any early-return, so a paused agent's output.txt is complete for
// the resume modal).
diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.js
index 28f5315a5d..be5b2004ea 100644
--- a/server/services/agentCliSpawning.test.js
+++ b/server/services/agentCliSpawning.test.js
@@ -76,6 +76,7 @@ vi.mock('fs', () => ({ existsSync: vi.fn().mockReturnValue(false) }));
// spawn wiring uses whatever prepareCliSpawn returns.
vi.mock('../lib/bufferedSpawn.js', () => ({
prepareCliSpawn: vi.fn((command, args) => ({ command, args })),
+ killProcessTree: vi.fn(),
}));
// Mock child_process.spawn to return a controllable fake process
@@ -90,7 +91,7 @@ vi.mock('child_process', () => ({
import { buildCliSpawnConfig, createStreamJsonParser, spawnDirectly } from './agentCliSpawning.js';
import { spawn } from 'child_process';
-import { prepareCliSpawn } from '../lib/bufferedSpawn.js';
+import { prepareCliSpawn, killProcessTree } from '../lib/bufferedSpawn.js';
// Helper: feed the parser a sequence of stream-json lines
function runStream(parser, events) {
@@ -451,6 +452,58 @@ describe('stream error containment', () => {
expect(logged).toBe(true);
});
+ it('detects a fallback signal and terminates immediately even while an earlier transcript write is blocked, keeping output ordered (#2384)', async () => {
+ killProcessTree.mockClear();
+
+ // Block the FIRST chunk's serialized transcript body at its phase-working
+ // updateAgent await (the pid updateAgent at spawn time carries no
+ // metadata.phase, so it resolves normally and lets spawn finish).
+ let releaseFirstWrite;
+ const firstWriteGate = new Promise((r) => { releaseFirstWrite = r; });
+ cosAgentsMocks.updateAgent.mockImplementation((id, patch) => {
+ if (patch?.metadata?.phase === 'working') return firstWriteGate;
+ return Promise.resolve(undefined);
+ });
+
+ // Non-stream provider so outputBuffer is raw text and ordering is trivial to assert.
+ const args = {
+ ...minimalArgs,
+ cliConfig: { command: 'claude', args: [], stdinMode: 'prompt', streamFormat: 'text' },
+ };
+
+ const spawnPromise = spawnDirectly(args);
+ // Yield so spawnDirectly's awaits resolve and the stdout listener registers.
+ await new Promise((r) => setTimeout(r, 10));
+
+ // Chunk 1: ordinary output → its serialized write body blocks on the gate.
+ fakeProcess.stdout.emit('data', Buffer.from('first output line\n'));
+ await new Promise((r) => setTimeout(r, 10));
+
+ // Chunk 2: a usage-limit fallback signal arrives WHILE chunk 1 is blocked.
+ // The synchronous detector must fire the kill without waiting for the gate.
+ fakeProcess.stdout.emit('data', Buffer.from('Now using extra usage\n'));
+
+ // Assert: termination was immediate — killProcessTree fired synchronously in
+ // the data listener, before the blocked first write could settle.
+ expect(killProcessTree).toHaveBeenCalledTimes(1);
+ expect(killProcessTree.mock.calls[0][1]).toBe('SIGTERM');
+ fakeProcess.killed = true;
+
+ // Release the gate, let the serialized chain drain, then close.
+ releaseFirstWrite();
+ await new Promise((r) => setTimeout(r, 20));
+ fakeProcess.emit('close', 143);
+ await spawnPromise.catch(() => {});
+
+ // Assert: the two chunks landed in emission order (serialized, not reordered
+ // by the blocked first write racing the second).
+ const allLines = cosAgentsMocks.appendAgentOutputLines.mock.calls.flatMap((c) => c[1]);
+ const firstIdx = allLines.findIndex((l) => l.includes('first output line'));
+ const usageIdx = allLines.findIndex((l) => l.includes('Now using extra usage'));
+ expect(firstIdx).toBeGreaterThanOrEqual(0);
+ expect(usageIdx).toBeGreaterThan(firstIdx);
+ });
+
it('routes the CLI command through prepareCliSpawn and spawns its resolved+wrapped result (#2243)', async () => {
// The reported bug: on Windows a bare `opencode`/`claude` .cmd shim can't be
// spawned directly under shell:false → ENOENT (-4058) → startup-failure.