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: keep the idle reaper off agents waiting on backgrounded /do:pr reviewers

[._.]/ Adam Eivy080d5fad5ae7
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index ba0d72521c..ced6580f37 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -28,6 +28,8 @@
- A Layered Intelligence run that ends badly now says what actually went wrong. Its whole job is to return JSON that a deterministic step files as one tracker issue — its prompt *forbids* touching the repo — yet the idle reaper judged it by the same "is there a file change or a commit?" question it asks a coding agent, and reported `idle-no-changes`: "the agent did not modify files", on a task told not to modify files. The real miss was one question away and is now the one asked: the `.agent-done` payload never landed, so nothing was filed. Failures on this task type read `idle-no-deliverable` and point at the missing payload (a smaller model answering in the terminal instead of writing the file — see #3640), and a run that did write its payload just before the reaper is now correctly rescued rather than failed for a clean tree. Code-editing task types are unchanged.
+- A CoS agent waiting on a **backgrounded reviewer** is no longer reaped as dead. `/do:pr`'s self-review gate runs each reviewer (an Ollama per-file pass, a headless `codex` pass over the branch diff) as a background command and waits to be re-invoked when it finishes — and in that wait the model has nothing to do, so it returns to the prompt and the terminal goes *completely* silent. Idleness is measured by terminal output, so a correctly-working agent looked identical to a dead one and the three-minute default killed it. On 2026-08-09 that cost one task three consecutive attempts: the feature was written, committed and pushed all three times, the review never got to finish, and the PR was never opened — twice reported as "no pull request exists", once as the actively misleading "idled out with no file changes", on a branch that by then held three commits. The reaper now extends its patience to 15 minutes whenever the terminal reports background commands still in flight, matching the existing merge-queue and multi-reviewer-loop graces. Those two didn't cover this: they latch on the multi-reviewer *loop*'s banners, which only print when the review loop is enabled, and this run had it off — the reviewers came from the ordinary self-review gate, which prints no such banner. Keying on outstanding background work instead covers any long-running background command, and the maximum-runtime backstop still bounds a genuinely dead session. The stranded work from that incident is recovered in #3679; a second defect the same three attempts exposed — the agent also writing its commits into the primary checkout — is tracked in #3680.
+
- CoS agents whose deliverable is a **commit** are no longer scored as failures. The idle reaper's "did this agent do anything?" gate read only *uncommitted* changes, so a `/do:release` or `/do:pr` run that committed, pushed, and opened its PR — leaving a clean tree *because it succeeded* — was recorded as `idle-no-changes` and retried. Two consecutive release runs on 2026-08-08 each did their whole job (cut the release commit, opened the release PR, then repaired it against review findings) and were both reported failed, holding the release for two days. The gate now counts commits made inside the run window as evidence of work, alongside a dirty tree. The report-shaped half of the same problem (`/do:review`, `/do:scan`, `/do:plan-task`, `/do:replan`, whose deliverable lands outside the repo) is tracked in #3636, and the unsatisfiable `[task-<id>]` success criterion one layer up in #3637.
- **CoS now brings recent unrated completed runs back to you.** The feedback queue was durable but easy to miss once a completion notification disappeared. Tasks now surface an actionable reminder that opens the Agents tab directly in its shareable “Needs feedback” filter, so a quick rating can actually improve future routing and task quality.
diff --git a/server/lib/tuiHandshake.js b/server/lib/tuiHandshake.js
index 3a3f0b6a5a..22ec3bf07e 100644
--- a/server/lib/tuiHandshake.js
+++ b/server/lib/tuiHandshake.js
@@ -732,6 +732,98 @@ export function createReviewLoopTracker() {
};
}
+// Extended idle threshold applied while the wrapped TUI still has BACKGROUND
+// SHELL COMMANDS outstanding. Observed 2026-08-09 (task-mslczmtr, three
+// consecutive attempts): the agent finished the feature, committed, pushed,
+// then ran `/do:pr`, which backgrounds each self-review reviewer (an Ollama
+// per-file pass, a headless `codex` pass over the branch diff) and waits to be
+// re-invoked on completion. Between those completions the model has NOTHING to
+// do, so it returns to the `❯` prompt and the TUI goes completely silent — no
+// spinner, no repaint, no PTY output at all. `idle` is measured off
+// `lastOutputAt`, so that legitimate wait is indistinguishable from a dead
+// session and the 3-minute default reaped all three attempts mid-review. The
+// branch ended up with three commits pushed and NO PR, twice recorded as
+// `pr-missing` and once as the actively misleading `idle-no-changes`.
+//
+// This is deliberately NOT covered by REVIEW_LOOP_IDLE_TIMEOUT_MS above: that
+// tracker keys on the multi-reviewer LOOP's banners (`Review plan: [`,
+// `Review pass N/M`), which only print when `configReviewLoop` is on. This run
+// had `configReviewLoop: false` — the reviewers came from `/do:pr`'s ordinary
+// self-review gate, which prints no such banner (verified: zero marker hits
+// across all three transcripts). Keying on the outstanding-shell footer covers
+// that gap and generalizes to ANY long background command, which is the real
+// invariant — an agent with async work still in flight is waiting, not dead.
+// 15 minutes mirrors the two graces above.
+export const BACKGROUND_SHELL_IDLE_TIMEOUT_MS = 900000;
+
+// The rendered footer Claude Code shows while background commands are still in
+// flight: `✻ Baked for 20s · 2 shells still running`. Anchored on the
+// digit-plus-noun shape rather than the bare phrase "still running" for the
+// same reason the review-loop patterns are anchored (see above) — a bare
+// substring would latch on any agent narrating about a running process. The
+// `\s*` between the count and the noun is not cosmetic: the TUI repaints
+// DIFFERENTIALLY, so a redraw that rewrites only the changed cells can drop
+// the separating space and emit `1shell still running` (exactly what the
+// 2026-08-09 agent-839255ca transcript contains — its ONLY rendering of the
+// footer). Requiring a literal space there would have missed that run entirely.
+//
+// Verified collision-free against the tracked tree (`git grep -niE
+// '[0-9]+ shells? still running'` matches nothing outside this feature's own
+// files), and a false positive would only extend the bounded idle window.
+const BACKGROUND_SHELL_PATTERN = /\d+\s*shells?\s+still\s+running/i;
+
+// Rolling tail cap for createBackgroundShellTracker's cross-chunk buffer. The
+// marker itself is ~22 chars, so this leaves generous headroom for intervening
+// chrome without growing unbounded over a long session.
+const BACKGROUND_SHELL_TAIL_CAP = 512;
+
+/**
+ * True when a chunk of ANSI-stripped TUI output shows the wrapped agent still
+ * has background shell commands in flight. Callers MUST pass stripped output.
+ * Non-string / empty input yields false.
+ *
+ * @param {string} strippedText — ANSI-stripped output (a chunk or accumulator).
+ * @returns {boolean}
+ */
+export function isBackgroundShellSignal(strippedText) {
+ if (typeof strippedText !== 'string' || !strippedText) return false;
+ return BACKGROUND_SHELL_PATTERN.test(strippedText);
+}
+
+/**
+ * Latching tracker for "this agent has background shell commands outstanding".
+ * Feed it each ANSI-stripped post-submit chunk via `observe(text)`; it becomes
+ * `active` the first time the outstanding-shell footer appears and STAYS active
+ * thereafter.
+ *
+ * Latching (rather than clearing when the shells finish) is deliberate and
+ * matches createMergeQueueTracker / createReviewLoopTracker: the failure mode
+ * is a session that goes ENTIRELY silent while waiting, so there is no later
+ * output in which to observe the footer's disappearance — a recency window
+ * would age the flag out at exactly the moment the grace is needed. The cost of
+ * over-latching is bounded on both ends: the extended window is still finite,
+ * and `tuiMaxRuntimeMs` remains the hard backstop.
+ *
+ * Uses the same rolling tail buffer as createReviewLoopTracker so a marker
+ * split across two `onData` chunks still appears whole on the next observation.
+ *
+ * @returns {{ observe: (strippedText: string) => boolean, readonly active: boolean }}
+ */
+export function createBackgroundShellTracker() {
+ let active = false;
+ let tail = '';
+ return {
+ observe(strippedText) {
+ if (active) return true;
+ if (typeof strippedText !== 'string' || !strippedText) return active;
+ tail = (tail + strippedText).slice(-BACKGROUND_SHELL_TAIL_CAP);
+ if (isBackgroundShellSignal(tail)) active = true;
+ return active;
+ },
+ get active() { return active; },
+ };
+}
+
// ─── Codex MCP-server boot detection ──────────────────────────────────────
//
// Codex (unlike Claude Code) boots any MCP servers configured in the user's
diff --git a/server/lib/tuiHandshake.test.js b/server/lib/tuiHandshake.test.js
index 49698774a0..d621c21e57 100644
--- a/server/lib/tuiHandshake.test.js
+++ b/server/lib/tuiHandshake.test.js
@@ -18,6 +18,9 @@ import {
REVIEW_LOOP_IDLE_TIMEOUT_MS,
isReviewLoopSignal,
createReviewLoopTracker,
+ BACKGROUND_SHELL_IDLE_TIMEOUT_MS,
+ isBackgroundShellSignal,
+ createBackgroundShellTracker,
MCP_BOOT_PASTE_DEADLINE_MS,
MCP_BOOT_PASTE_RETRY_DELAY_MS,
isMcpBootSignal,
@@ -389,6 +392,66 @@ describe('tuiHandshake — review-loop idle suppression', () => {
});
});
+// Incident 2026-08-09, task-mslczmtr: three consecutive attempts were reaped
+// while `/do:pr`'s self-review gate waited on backgrounded reviewers (an Ollama
+// per-file pass, a headless codex pass). Between reviewer completions the model
+// sits at the prompt and the TUI emits NOTHING, so the 3-minute default fired
+// on a session that was working correctly. The branch ended with three commits
+// pushed and no PR. The review-loop tracker above did NOT cover it: that keys
+// on the multi-reviewer LOOP banners, which only print when configReviewLoop is
+// on — this run had it off (zero marker hits across all three transcripts).
+describe('tuiHandshake — background-shell idle grace (task-mslczmtr)', () => {
+ it('extends the idle timeout well past the default 3-minute window', () => {
+ expect(BACKGROUND_SHELL_IDLE_TIMEOUT_MS).toBe(900000);
+ expect(BACKGROUND_SHELL_IDLE_TIMEOUT_MS).toBeGreaterThan(DEFAULT_TUI_IDLE_TIMEOUT_MS);
+ });
+
+ it('isBackgroundShellSignal matches the outstanding-shell footer', () => {
+ expect(isBackgroundShellSignal('✻ Baked for 20s · 2 shells still running')).toBe(true);
+ expect(isBackgroundShellSignal('✻ Cooked for 2s · 1 shell still running')).toBe(true);
+ expect(isBackgroundShellSignal('SAUTÉED FOR 1M 8S · 3 SHELLS STILL RUNNING')).toBe(true);
+ });
+
+ // The TUI repaints DIFFERENTIALLY, so a redraw that rewrites only the changed
+ // cells can drop the space between the count and the noun. This exact string
+ // is the ONLY rendering of the footer in the agent-839255ca transcript — a
+ // pattern requiring a literal space would have missed that run entirely.
+ it('isBackgroundShellSignal tolerates the space dropped by a differential repaint', () => {
+ expect(isBackgroundShellSignal('✻ Baked for 34m 33s · 1shell still running')).toBe(true);
+ });
+
+ it('isBackgroundShellSignal ignores ordinary narration and non-strings', () => {
+ expect(isBackgroundShellSignal('the dev server is still running on :5555')).toBe(false);
+ expect(isBackgroundShellSignal('shells still running')).toBe(false);
+ expect(isBackgroundShellSignal('Ran 5 shell commands')).toBe(false);
+ expect(isBackgroundShellSignal('')).toBe(false);
+ expect(isBackgroundShellSignal(null)).toBe(false);
+ expect(isBackgroundShellSignal(undefined)).toBe(false);
+ });
+
+ it('createBackgroundShellTracker latches on first signal and stays active through silence', () => {
+ const tracker = createBackgroundShellTracker();
+ expect(tracker.active).toBe(false);
+ tracker.observe('implementing the fix, running the suite');
+ expect(tracker.active).toBe(false);
+ expect(tracker.observe('✻ Baked for 20s · 2 shells still running')).toBe(true);
+ expect(tracker.active).toBe(true);
+ // The silent reviewer wait is exactly when the grace is needed, so quiet
+ // chunks must not un-latch it.
+ tracker.observe('Standing by for the review to finish.');
+ tracker.observe('');
+ expect(tracker.active).toBe(true);
+ });
+
+ it('createBackgroundShellTracker latches on a marker split across two chunks', () => {
+ const tracker = createBackgroundShellTracker();
+ tracker.observe('✻ Baked for 20s · 2 shells');
+ expect(tracker.active).toBe(false);
+ expect(tracker.observe(' still running')).toBe(true);
+ expect(tracker.active).toBe(true);
+ });
+});
+
describe('tuiHandshake — codex MCP-boot paste patience (agent-c5a26b40)', () => {
it('deadline covers a node_repl startup_timeout_sec=120 plus margin, under the idle-reap window', () => {
// Long enough for the documented 120s node_repl startup + an npx cold
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index fa6ad4b598..a1c09d0158 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -41,6 +41,7 @@ import {
buildWrapUpProdMessage,
MERGE_QUEUE_IDLE_TIMEOUT_MS,
REVIEW_LOOP_IDLE_TIMEOUT_MS,
+ BACKGROUND_SHELL_IDLE_TIMEOUT_MS,
READY_POLL_INTERVAL_MS,
READY_IDLE_THRESHOLD_MS,
PASTE_MARKER_POLL_MS,
@@ -48,6 +49,7 @@ import {
createWorkActivityTracker,
createMergeQueueTracker,
createReviewLoopTracker,
+ createBackgroundShellTracker,
createMcpBootTracker,
MCP_BOOT_PASTE_DEADLINE_MS,
MCP_BOOT_PASTE_RETRY_DELAY_MS,
@@ -335,6 +337,16 @@ export async function spawnTuiAgent({
// isn't reaped as a false `idle-complete` success before it reaches the
// merge gate (issue observed on agent-61508f36, PR #2084).
const reviewLoop = createReviewLoopTracker();
+ // Latches once the TUI reports background shell commands still in flight.
+ // `/do:pr`'s self-review gate backgrounds each reviewer and waits to be
+ // re-invoked, and between completions the model returns to the prompt and the
+ // TUI emits NOTHING — a legitimate wait the default 3-minute window reaps as
+ // if the session were dead. The review-loop tracker above does not cover it:
+ // it keys on the multi-reviewer LOOP's banners, which only print when
+ // `configReviewLoop` is on (task-mslczmtr ran with it off and lost three
+ // consecutive attempts this way). See the BACKGROUND_SHELL_IDLE_TIMEOUT_MS
+ // declaration for the full incident.
+ const backgroundShell = createBackgroundShellTracker();
// Latches once codex prints its MCP-server boot banner during startup. A user
// with heavyweight interactive MCP servers in ~/.codex/config.toml (playwright
// via npx, a node_repl with startup_timeout_sec=120) makes codex spend tens of
@@ -789,6 +801,15 @@ export async function spawnTuiAgent({
emitLog('info', `TUI agent ${agentId} entered review loop — idle reaper extended to ${Math.round(REVIEW_LOOP_IDLE_TIMEOUT_MS / 60000)}min`, { agentId, phase: 'review-loop' });
await updateAgent(agentId, { metadata: { phase: 'review-loop' } });
}
+ // Detect outstanding background shell commands so the idle reaper can
+ // extend its grace across the fully-silent stretch while the agent waits
+ // to be re-invoked on their completion (see backgroundShell declaration).
+ // Deliberately does NOT set `metadata.phase` — unlike merge-queue and
+ // review-loop, "has background work" is not a phase of the run, and
+ // overwriting the phase here would clobber a more specific one.
+ if (promptSubmittedAt && stripped && !backgroundShell.active && backgroundShell.observe(stripped)) {
+ emitLog('info', `TUI agent ${agentId} has background shells outstanding — idle reaper extended to ${Math.round(BACKGROUND_SHELL_IDLE_TIMEOUT_MS / 60000)}min`, { agentId });
+ }
lastOutputAt = now;
if (firstOutputAt === null) firstOutputAt = lastOutputAt;
@@ -1357,7 +1378,9 @@ export async function spawnTuiAgent({
? Math.max(tuiConfig.idleTimeoutMs, MERGE_QUEUE_IDLE_TIMEOUT_MS)
: reviewLoop.active
? Math.max(tuiConfig.idleTimeoutMs, REVIEW_LOOP_IDLE_TIMEOUT_MS)
- : tuiConfig.idleTimeoutMs;
+ : backgroundShell.active
+ ? Math.max(tuiConfig.idleTimeoutMs, BACKGROUND_SHELL_IDLE_TIMEOUT_MS)
+ : tuiConfig.idleTimeoutMs;
// Once within the LEAD window of the (possibly extended) reap deadline, keep
// a reachability reading fresh (throttled, non-blocking) so the gate below
// can read it synchronously and won't reap an agent that's only silent