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
fix: remove CoS TUI idle timeout
Adam Eivy1cdb8971d00b
diff --git a/.changelog/next/fixed-agent-64f9d496.md b/.changelog/next/fixed-agent-64f9d496.mdnew file mode 100644index 0000000000..57b3eb3e2b--- /dev/null+++ b/.changelog/next/fixed-agent-64f9d496.md@@ -0,0 +1 @@+- CoS TUI agents no longer finalize or fail solely because provider output is idle; retain the wall-clock max-runtime backstop.diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsxindex 939f8b40b1..fe48703feb 100644--- a/client/src/pages/AIProviders.jsx+++ b/client/src/pages/AIProviders.jsx@@ -635,7 +635,7 @@ export default function AIProviders() {)}{isTuiProvider(provider) && (<p className="text-xs break-words">- TUI: paste delay <span className="text-gray-300">{provider.tuiPromptDelayMs || 2500}ms</span>, idle complete <span className="text-gray-300">{provider.tuiIdleTimeoutMs || 180000}ms</span>+ TUI: paste delay <span className="text-gray-300">{provider.tuiPromptDelayMs || 2500}ms</span>, completion by sentinel, process exit, or runtime ceiling</p>)}{provider.fallbackProvider && (@@ -811,8 +811,7 @@ function ProviderForm({ provider, onClose, onSave, allProviders = [], runnerAlloenvVars: provider?.envVars || {},secretEnvVars: provider?.secretEnvVars || [],headlessArgs: provider?.headlessArgs?.join(' ') || '',- tuiPromptDelayMs: provider?.tuiPromptDelayMs || 2500,- tuiIdleTimeoutMs: provider?.tuiIdleTimeoutMs || 180000+ tuiPromptDelayMs: provider?.tuiPromptDelayMs || 2500});const [newEnvKey, setNewEnvKey] = useState('');@@ -890,16 +889,11 @@ function ProviderForm({ provider, onClose, onSave, allProviders = [], runnerAlloe.preventDefault();const tuiPromptDelay = parseInt(formData.tuiPromptDelayMs, 10);- const tuiIdleTimeout = parseInt(formData.tuiIdleTimeoutMs, 10);- // Three cases for the timeout field on submit:- // 1. valid integer within bounds → send the parsed number- // 2. blank/whitespace → omit so the server keeps the current value- // (Number('') is 0, which would 400 against the min-1000 rule)- // 3. non-empty but invalid (e.g. '1e3', '500', 'abc') → send the- // RAW STRING. Number() would accept '1e3' as 1000, silently- // saving an exponent form the client/runner reject as invalid;- // the server's digit-only preprocess will leave the string- // alone and z.number() will produce a clear validation error.+ // Blank input is omitted so the server keeps the current value. Non-empty+ // invalid input (e.g. '1e3', '500', 'abc') is sent as the raw string so+ // Number() cannot silently save an exponent form the client/runner reject;+ // the server's digit-only preprocess leaves it alone and z.number() produces+ // a clear validation error.const parsedTimeout = parseTimeoutMs(formData.timeout);const timeoutInput = String(formData.timeout ?? '').trim();const data = {@@ -934,11 +928,8 @@ function ProviderForm({ provider, onClose, onSave, allProviders = [], runnerAlloif (formData.type === 'tui') {if (Number.isFinite(tuiPromptDelay)) data.tuiPromptDelayMs = tuiPromptDelay;else delete data.tuiPromptDelayMs;- if (Number.isFinite(tuiIdleTimeout)) data.tuiIdleTimeoutMs = tuiIdleTimeout;- else delete data.tuiIdleTimeoutMs;} else {delete data.tuiPromptDelayMs;- delete data.tuiIdleTimeoutMs;}// Only send apiKey if user entered a new value (avoid overwriting existing key with empty string)@@ -1057,18 +1048,8 @@ function ProviderForm({ provider, onClose, onSave, allProviders = [], runnerAlloclassName="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"/></FormField>- <FormField label="Idle Complete (ms)">- <input- type="number"- min="10000"- max="1800000"- value={formData.tuiIdleTimeoutMs}- onChange={(e) => setFormData(prev => ({ ...prev, tuiIdleTimeoutMs: e.target.value }))}- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"- />- </FormField><p className="sm:col-span-2 text-xs text-gray-500">- TUI providers open an attachable shell session, paste the agent prompt, parse terminal output, and complete after the terminal is idle.+ TUI providers stay attached while the provider is silent; they finish on the completion sentinel, process exit, explicit failure, or the max-runtime ceiling.</p></div>)}diff --git a/data.reference/providers.json b/data.reference/providers.jsonindex bd1f4f7a38..bea2310a13 100644--- a/data.reference/providers.json+++ b/data.reference/providers.json@@ -98,8 +98,7 @@"timeout": 600000,"enabled": false,"envVars": {},- "tuiPromptDelayMs": 2500,- "tuiIdleTimeoutMs": 180000+ "tuiPromptDelayMs": 2500},"claude-code-tui": {"id": "claude-code-tui",@@ -115,8 +114,7 @@"timeout": 900000,"enabled": true,"envVars": {},- "tuiPromptDelayMs": 2500,- "tuiIdleTimeoutMs": 180000+ "tuiPromptDelayMs": 2500},"claude-code-tui-bedrock": {"id": "claude-code-tui-bedrock",@@ -133,8 +131,7 @@"enabled": false,"envVars": { "CLAUDE_CODE_USE_BEDROCK": "1", "AWS_BEARER_TOKEN_BEDROCK": "" },"secretEnvVars": ["AWS_BEARER_TOKEN_BEDROCK"],- "tuiPromptDelayMs": 2500,- "tuiIdleTimeoutMs": 180000+ "tuiPromptDelayMs": 2500},"claude-ollama-tui": {"id": "claude-ollama-tui",@@ -153,8 +150,7 @@"ANTHROPIC_SMALL_FAST_MODEL": "qwen2.5:7b"},"secretEnvVars": [],- "tuiPromptDelayMs": 2500,- "tuiIdleTimeoutMs": 180000+ "tuiPromptDelayMs": 2500},"opencode-ollama": {"id": "opencode-ollama",@@ -188,8 +184,7 @@"OPENCODE_CONFIG_CONTENT": "{\"permission\":\"allow\",\"provider\":{\"ollama\":{\"npm\":\"@ai-sdk/openai-compatible\",\"name\":\"Ollama (local)\",\"options\":{\"baseURL\":\"http://localhost:11434/v1\"}}}}"},"secretEnvVars": [],- "tuiPromptDelayMs": 2500,- "tuiIdleTimeoutMs": 180000+ "tuiPromptDelayMs": 2500},"opencode-mtplx": {"id": "opencode-mtplx",@@ -225,8 +220,7 @@"OPENCODE_CONFIG_CONTENT": "{\"permission\":\"allow\",\"provider\":{\"mtplx\":{\"npm\":\"@ai-sdk/openai-compatible\",\"name\":\"MTPLX (local MTP)\",\"options\":{\"baseURL\":\"http://127.0.0.1:8000/v1\"}}}}"},"secretEnvVars": [],- "tuiPromptDelayMs": 2500,- "tuiIdleTimeoutMs": 180000+ "tuiPromptDelayMs": 2500},"antigravity-tui": {"id": "antigravity-tui",@@ -242,8 +236,7 @@"timeout": 600000,"enabled": false,"envVars": {},- "tuiPromptDelayMs": 2500,- "tuiIdleTimeoutMs": 180000+ "tuiPromptDelayMs": 2500},"lmstudio": {"id": "lmstudio",@@ -364,8 +357,7 @@"enabled": false,"envVars": {},"secretEnvVars": [],- "tuiPromptDelayMs": 2500,- "tuiIdleTimeoutMs": 180000+ "tuiPromptDelayMs": 2500},"kimi-cli": {"id": "kimi-cli",@@ -400,8 +392,7 @@"enabled": false,"envVars": {},"secretEnvVars": [],- "tuiPromptDelayMs": 2500,- "tuiIdleTimeoutMs": 180000+ "tuiPromptDelayMs": 2500},"cursor-cli": {"id": "cursor-cli",@@ -434,8 +425,7 @@"enabled": false,"envVars": {},"secretEnvVars": [],- "tuiPromptDelayMs": 2500,- "tuiIdleTimeoutMs": 180000+ "tuiPromptDelayMs": 2500}}}diff --git a/server/lib/README.md b/server/lib/README.mdindex 0571d58235..96b2922340 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -221,7 +221,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `httpClient.js` | Fetch-based HTTP client factory (axios.create replacement). || `abortTimeout.js` | `withAbortTimeout(timeoutMs, fn)` — runs `fn(signal)` under an `AbortController` that aborts after `timeoutMs` and always clears the timer on settle. Generic lifecycle helper for callers that need the insecure-agent `peerFetch` (so can't use `fetchWithTimeout`) or one signal across parallel fetches. || `fetchWithTimeout.js` | `fetch` wrapper with AbortController timeout. |-| `connectivity.js` | `isMachineOnline({timeoutMs?, hosts?})` — internet-reachability probe: bare TCP `connect` to public anycast resolvers on :443 (no DNS, no HTTP), resolves `true` on the first connect and `false` only after all fail; never rejects. Used by the CoS TUI idle reaper (`agentTuiSpawning.js`) so a dropped connection isn't mistaken for a hung/finished agent. |+| `connectivity.js` | `isMachineOnline({timeoutMs?, hosts?})` — internet-reachability probe: bare TCP `connect` to public anycast resolvers on :443 (no DNS, no HTTP), resolves `true` on the first connect and `false` only after all fail; never rejects. Reuse when a caller needs a best-effort local reachability signal. || `safeUrlFetch.js` | SSRF-guarded public-URL fetch: `isPublicHttpUrlSafe`/`assertPublicHttpUrl` (scheme + blocked-host-literal via `catalogValidation.isBlockedIngestHost` + DNS-resolve), exported strict `isPrivateAddress`, plus `fetchPublicText`/`fetchPublicBinary` (timeout, redirect revalidation, size cap) and `buildPinnedLookup`/`buildPinnedDispatcher` (the connect-time IP pin that closes the DNS-rebinding TOCTOU). Reuse instead of copying the SSRF guard for any "fetch this remote thing the user pointed us at" flow. || `pinterestFeed.js` | Pure Pinterest board RSS helpers: `normalizePinterestFeedUrl(input)` (board URL or `.rss` → `{ feedUrl, boardUrl }`, host-gated) + `parsePinterestRss(xml)` (per-pin `pinUrl`/`imageUrl`/title/description, 736x size upgrade). Feeds the mood-board Pinterest importer. || `requestAbort.js` | `abortSignalFromResponse(res)` — AbortSignal that fires only when an Express client disconnects *before the response finishes* (keyed off `res` close + `writableEnded`). Plus `anyAbortSignal(signals)` — combine several signals into one (native `AbortSignal.any` with a Node-18 fallback). |@@ -358,7 +358,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `prDisposition.js` | `resolvePrCompletion(metadata)` resolves the explicit `review-then-merge` / `merge-on-green` / `leave-open` policy, with legacy `reviewLoop` fallback; `leavesPrForHuman(task)` + `PR_STAYS_OPEN_TASK_TYPES` keep JIRA hand-offs open. Shared by the agent prompt builder and `agentWorktreeCleanup` so both halves agree. `resolvePrCreation({taskOpenPR, agentOwnsPr, prClaimVerified})` → a `PR_CREATION` tri-state (`never` / `if-missing` / `always`) naming who opens the change request for a completing worktree agent, so the runner, TUI, and direct-CLI completion paths cannot drift into double-firing `gh pr create`. || `shellQuote.js` | `shellQuote(value)` — POSIX single-quote escaping for values interpolated into shell command strings (display command lines, copy-paste blocks in agent prompts). Bare-safe tokens pass through; everything else is single-quoted. Canonical escaper — don't hand-roll. || `sidecarProcess.js` | `runSidecarProcess({bin,args,env,signal,onStage,onProcess})` + `parseSidecarResult(stdout)` — the shared Python-sidecar STAGE:/RESULT: wire-protocol runner (spawn, tail-capped stdout/stderr, per-STAGE-line callback, abort/SIGTERM → `canceled`, non-zero exit → stderr-tail reason). Used by `pipeline/musicGen.js` (all music backends) and `audioMidiTranscription.js` (MuScriptor). |-| `slashdoCatalog.js` | The single catalog of which bundled slashdo workflows PortOS offers as a one-click agent run — `SLASHDO_WORKFLOWS` (`{command, label, description, icon, templateName, templatePrompt?, settings, appTypes, configurable?}`), `getSlashdoWorkflow()` (the allowlist gate for `POST /api/cos/tasks/slashdo`), `SLASHDO_COMMAND_NAMES`, `slashdoWorkflowsForApp(isSwiftApp)`, `SLASHDO_APP_TYPES`, and the two run-shape postures `WORKFLOW_OWNS_ITS_OWN_GIT` (commit-shaped) / `WORKFLOW_REPORTS_NO_CODE` (report-shaped — carries `worktreeChangesExpected: false` so the TUI idle reaper does not score a filed-issue/printed-report run as `idle-no-changes`). Backs the Agent Operations buttons, the CoS quick templates (`taskTemplates.js`), and the route allowlist, replacing two catalogs that had drifted. Mirrored in `client/src/lib/slashdoCatalog.js` (button styling only), pinned by `slashdoCatalog.test.js`. |+| `slashdoCatalog.js` | The single catalog of which bundled slashdo workflows PortOS offers as a one-click agent run — `SLASHDO_WORKFLOWS` (`{command, label, description, icon, templateName, templatePrompt?, settings, appTypes, configurable?}`), `getSlashdoWorkflow()` (the allowlist gate for `POST /api/cos/tasks/slashdo`), `SLASHDO_COMMAND_NAMES`, `slashdoWorkflowsForApp(isSwiftApp)`, `SLASHDO_APP_TYPES`, and the two run-shape postures `WORKFLOW_OWNS_ITS_OWN_GIT` (commit-shaped) / `WORKFLOW_REPORTS_NO_CODE` (report-shaped — carries `worktreeChangesExpected: false` so a filed-issue/printed-report run retains its non-code deliverable posture). Backs the Agent Operations buttons, the CoS quick templates (`taskTemplates.js`), and the route allowlist, replacing two catalogs that had drifted. Mirrored in `client/src/lib/slashdoCatalog.js` (button styling only), pinned by `slashdoCatalog.test.js`. || `slashdoInvocation.js` | Resolves how a bundled slashdo workflow is invoked on a given host CLI. `resolveSlashdoInvocation({command, args, providerId, providerCommand, leanMode})` → `{command, args, style, invocation, skillName}` for the three shapes slashdo's installer produces (`slash-namespaced` `/do:x` for Claude Code, `slash-flat` `/do-x` for OpenCode, `skill` — an Agent Skill selected by name — for codex/grok/antigravity and any unidentified provider). Plus `buildSlashdoSection(resolved, body, {bodyPath, reviewWith})` (pure renderer; the caller loads the body via `loadSlashdoFile`. Over `SLASHDO_INLINE_BUDGET_CHARS` (24,000) with a `bodyPath` it emits a filesystem pointer instead of the text — #3110), `unreachableReviewerIncludes({reviewers, usernames})` → the reviewer-variant lib includes a run can never reach (the `skipIncludes` set for `loadSlashdoFile`; defaults to pruning NOTHING for an unresolved/unrecognized reviewer set, since an over-pruned prompt is worse than a fat one), `SLASHDO_REVIEWER_INCLUDES`/`SLASHDO_REVIEWER_INCLUDE_NAMES`, `slashdoSkillName`, `isValidSlashdoCommand` (the one definition of the safe bare-command shape, also gating the Zod schemas), `agentOwnsPrWorkflow({providerType, leanMode})` — a strictly WEAKER question than typing a slash command: any local `cli`/`tui` harness that is not a lean `--bare` session drives its own commit → push → PR → review → merge (#3733), with `resolveOwnsPrWorkflow({persisted, …})` reading the value stamped on a completed agent record and falling back to the slash-command gate for pre-#3733 records; `oversizedBodyPointer(bodyPath, body)` (the shared "it is on disk, go read it" line); and `canTypeSlashCommands()` — the single predicate behind `agentPromptBuilder.js`'s completion-workflow gates (can this session TYPE `/do:pr` / `/simplify`?), which reads `resolveSlashdoStyle`'s `assumeClaudeWhenUnknown` posture because the spawners resolve a blank command to `claude`. Provider is only known at spawn time, so a task persists the BARE command name — never a rendered `/do:x` string. || `slashdoLoader.js` | Loads bundled slashdo command/lib markdown (`lib/slashdo/` submodule) and resolves it the way slashdo's own per-environment installer would, since PortOS inlines these bodies into CoS-agent prompts WITHOUT running that installer. `loadSlashdoFile(cmd, {stripFrontmatter, skipIncludes})` / `loadSlashdoLib(name, {teams})` resolve the `` !`cat ~/.claude/lib/…` `` includes + `if:teams` conditionals, with `skipIncludes` pruning lib includes the run can never reach (each leaves a one-line "not applicable" marker — #3110); `writeResolvedSlashdoBody(cmd, body, {skipIncludes})` → absolute path, writing the already-loaded body under `PATHS.slashdoResolved` (`data/cos/slashdo-resolved/`, gitignored derived cache) at most once per (command, body) per process, so a file-tool host can be handed a path instead of a 250KB paste. Split out of `fileUtils.js` (a generic file-utilities module) as its own feature module — pairs with `slashdoInvocation.js`, which resolves how a workflow is TYPED per host CLI rather than how its body is loaded. || `singleFlight.js` | `createSingleFlight()` → `run(key, fn)` — keyed in-flight coalescer: concurrent calls for the same key share one `fn()` execution and result; the slot auto-clears on settle. Minimal by design (no TTL/result cache layered on top, doesn't reject concurrent callers). Used by `promptRunner.js`'s fallback mark-and-pick. |diff --git a/server/lib/aiToolkit/defaults/providers.sample.json b/server/lib/aiToolkit/defaults/providers.sample.jsonindex 3e3f03f210..4f1dc10fbf 100644--- a/server/lib/aiToolkit/defaults/providers.sample.json+++ b/server/lib/aiToolkit/defaults/providers.sample.json@@ -74,8 +74,7 @@"ANTHROPIC_SMALL_FAST_MODEL": "qwen2.5:7b"},"secretEnvVars": [],- "tuiPromptDelayMs": 2500,- "tuiIdleTimeoutMs": 180000+ "tuiPromptDelayMs": 2500},"opencode-ollama": {"id": "opencode-ollama",@@ -109,8 +108,7 @@"OPENCODE_CONFIG_CONTENT": "{\"permission\":\"allow\",\"provider\":{\"ollama\":{\"npm\":\"@ai-sdk/openai-compatible\",\"name\":\"Ollama (local)\",\"options\":{\"baseURL\":\"http://localhost:11434/v1\"}}}}"},"secretEnvVars": [],- "tuiPromptDelayMs": 2500,- "tuiIdleTimeoutMs": 180000+ "tuiPromptDelayMs": 2500},"opencode-mtplx": {"id": "opencode-mtplx",@@ -146,8 +144,7 @@"OPENCODE_CONFIG_CONTENT": "{\"permission\":\"allow\",\"provider\":{\"mtplx\":{\"npm\":\"@ai-sdk/openai-compatible\",\"name\":\"MTPLX (local MTP)\",\"options\":{\"baseURL\":\"http://127.0.0.1:8000/v1\"}}}}"},"secretEnvVars": [],- "tuiPromptDelayMs": 2500,- "tuiIdleTimeoutMs": 180000+ "tuiPromptDelayMs": 2500},"codex": {"id": "codex",@@ -182,8 +179,7 @@"enabled": false,"envVars": {},"secretEnvVars": [],- "tuiPromptDelayMs": 2500,- "tuiIdleTimeoutMs": 180000+ "tuiPromptDelayMs": 2500},"claude-code-tui": {"id": "claude-code-tui",@@ -200,8 +196,7 @@"enabled": true,"envVars": {},"secretEnvVars": [],- "tuiPromptDelayMs": 2500,- "tuiIdleTimeoutMs": 180000+ "tuiPromptDelayMs": 2500},"claude-code-tui-bedrock": {"id": "claude-code-tui-bedrock",@@ -218,8 +213,7 @@"enabled": false,"envVars": { "CLAUDE_CODE_USE_BEDROCK": "1", "AWS_BEARER_TOKEN_BEDROCK": "" },"secretEnvVars": ["AWS_BEARER_TOKEN_BEDROCK"],- "tuiPromptDelayMs": 2500,- "tuiIdleTimeoutMs": 180000+ "tuiPromptDelayMs": 2500},"antigravity-tui": {"id": "antigravity-tui",@@ -237,8 +231,7 @@"enabled": false,"envVars": {},"secretEnvVars": [],- "tuiPromptDelayMs": 2500,- "tuiIdleTimeoutMs": 180000+ "tuiPromptDelayMs": 2500},"antigravity-cli": {"id": "antigravity-cli",@@ -380,8 +373,7 @@"enabled": false,"envVars": {},"secretEnvVars": [],- "tuiPromptDelayMs": 2500,- "tuiIdleTimeoutMs": 180000+ "tuiPromptDelayMs": 2500},"kimi-cli": {"id": "kimi-cli",@@ -416,8 +408,7 @@"enabled": false,"envVars": {},"secretEnvVars": [],- "tuiPromptDelayMs": 2500,- "tuiIdleTimeoutMs": 180000+ "tuiPromptDelayMs": 2500},"cursor-cli": {"id": "cursor-cli",@@ -450,8 +441,7 @@"enabled": false,"envVars": {},"secretEnvVars": [],- "tuiPromptDelayMs": 2500,- "tuiIdleTimeoutMs": 180000+ "tuiPromptDelayMs": 2500}}}diff --git a/server/lib/aiToolkit/errorDetection.js b/server/lib/aiToolkit/errorDetection.jsindex 1aac87eb0f..ed15dc8a62 100644--- a/server/lib/aiToolkit/errorDetection.js+++ b/server/lib/aiToolkit/errorDetection.js@@ -190,8 +190,8 @@ const IMMEDIATE_FALLBACK_SIGNALS = [{// Antigravity leaves its composer visible while Google verifies account// eligibility, so a CoS agent can appear ready, accept a paste, then do no- // work until the idle reaper eventually kills it. This exact two-line banner- // is provider chrome (not a generic auth word an agent may print), so it is+ // work until the provider-signal grace window fails over. This exact two-line+ // banner is provider chrome (not a generic auth word an agent may print), so it is// safe to act on and let the task select a fallback.//// NOT actionable: the account is fine and nothing in PortOS config is wrong@@ -233,9 +233,8 @@ const IMMEDIATE_FALLBACK_SIGNALS = [// asks for, and fails over only once those retries are exhausted.//// Why 120s: with retries every 20s that is five real attempts rather than- // one dead wait, and it still sits under the 180s default TUI idle timeout —- // a genuinely stuck provider fails over sooner than the idle reaper would- // have caught it, which is the whole point of an immediate signal.+ // one dead wait. The signal has its own bounded fail-over window, which is+ // the whole point of an immediate provider signal.graceMs: 120000,pattern: /We're finishing verifying your account eligibility\.\s*This usually takes a moment\. Please try again shortly\./i,// The banner sentence is distinctive, but it is not chrome-ONLY: it matchesdiff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.jsindex 975bdd4908..a54c0748c2 100644--- a/server/lib/aiToolkit/providers.js+++ b/server/lib/aiToolkit/providers.js@@ -566,10 +566,8 @@ export function createProviderService(config = {}) {secretEnvVars: providerData.secretEnvVars || [],headlessArgs: providerData.headlessArgs || [],tuiPromptDelayMs: providerData.tuiPromptDelayMs || 2500,- tuiIdleTimeoutMs: providerData.tuiIdleTimeoutMs || 180000,- // Absolute wall-clock ceiling for long-running TUI agents (3h). The idle- // reaper can't bound a busy-but-stuck agent whose working counter keeps- // repainting; the consumer (agentTuiSpawning) enforces this backstop.+ // Absolute wall-clock ceiling for long-running TUI agents (3h). The+ // consumer (agentTuiSpawning) enforces this backstop.tuiMaxRuntimeMs: providerData.tuiMaxRuntimeMs || 10800000};diff --git a/server/lib/aiToolkit/providers.test.js b/server/lib/aiToolkit/providers.test.jsindex 0d8a266bbd..682d316449 100644--- a/server/lib/aiToolkit/providers.test.js+++ b/server/lib/aiToolkit/providers.test.js@@ -144,7 +144,6 @@ describe('Provider Service', () => {secretEnvVars: ['OPENAI_API_KEY', 'ANTHROPIC_API_KEY'],headlessArgs: ['--quiet', '--no-color'],tuiPromptDelayMs: 5000,- tuiIdleTimeoutMs: 120000,};const created = await providerService.createProvider(seed);diff --git a/server/lib/aiToolkit/validation.js b/server/lib/aiToolkit/validation.jsindex 8001343692..0aa0440d39 100644--- a/server/lib/aiToolkit/validation.js+++ b/server/lib/aiToolkit/validation.js@@ -109,10 +109,8 @@ export const providerSchema = z.object({secretEnvVars: z.array(z.string()).optional(),headlessArgs: z.array(z.string()).optional(),tuiPromptDelayMs: z.number().int().min(250).max(60000).optional(),- tuiIdleTimeoutMs: z.number().int().min(10000).max(1800000).optional(),- // Absolute wall-clock ceiling for a long-running TUI agent (idle-reap can't- // bound a busy-but-stuck agent — see DEFAULT_TUI_MAX_RUNTIME_MS). Min 1min,- // max 12h to cover the longest legitimate multi-hour orchestration.+ // Absolute wall-clock ceiling for a long-running TUI agent. Min 1min, max 12h+ // to cover the longest legitimate multi-hour orchestration.tuiMaxRuntimeMs: z.number().int().min(60000).max(43200000).optional()});diff --git a/server/lib/connectivity.js b/server/lib/connectivity.jsindex 880566a839..0ffc3c3aab 100644--- a/server/lib/connectivity.js+++ b/server/lib/connectivity.js@@ -1,9 +1,8 @@/*** Internet-reachability probe.*- * A liveness signal answering "does this machine currently have internet?" —- * used by the CoS TUI idle reaper so a dropped connection doesn't get mistaken- * for a hung or finished agent (a silenced TUI looks identical either way).+ * A liveness signal answering "does this machine currently have internet?" for+ * callers that need to distinguish a local outage from an unreachable service.** This is deliberately a bare TCP *connect* to well-known anycast endpoints on* :443 — NOT a DNS lookup (we dial IPs directly, so a broken resolver can't read@@ -14,9 +13,8 @@* Assumes normal outbound egress (the single-user private-machine model PortOS* targets). In a locked-down, proxy-only network where both anycast IPs are* blocked, a machine with working internet would read as offline — the caller- * (the TUI idle reaper) treats that as "defer the reap", which its independent- * max-runtime backstop still bounds, so the failure mode is a delayed reap, not- * a wedged agent.+ * callers should treat that as an indeterminate reachability result rather than+ * a definitive statement about the remote service.*/import net from 'net';diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.jsindex 093736dd57..e002d87fbd 100644--- a/server/lib/cosValidation.js+++ b/server/lib/cosValidation.js@@ -999,8 +999,8 @@ export const createCosTaskSchema = z.object({),// The slashdo catalog's deliverable posture (#3636): whether this run is// EXPECTED to leave commits in its worktree. A report-shaped workflow- // (`/do:review`) carries `false` so the TUI idle reaper doesn't score its- // correctly-clean tree as `idle-no-changes`. Carried onto the task by+ // (`/do:review`) carries `false` so downstream bookkeeping does not treat its+ // correctly-clean tree as missing code work. Carried onto the task by// `cosTaskStore.js` only on a strict boolean — absent means "no opinion".worktreeChangesExpected: z.preprocess(v => v === 'true' ? true : v === 'false' ? false : v,@@ -1186,8 +1186,8 @@ export const createCosJobSchema = z.object({openPR: z.boolean().optional(),prCompletion: z.enum(PR_COMPLETION_VALUES).optional(),simplify: z.boolean().optional(),- // Absent = true (a clean worktree at idle-out is a failure). `false` opts the- // job out of the TUI idle-complete worktree-changes gate — see+ // Absent = true for code-shaped work. `false` marks a report-shaped job whose+ // deliverable is intentionally outside the worktree — see// ALLOWED_TASK_METADATA_KEYS below and agentTuiSpawning.js (#3102).worktreeChangesExpected: z.boolean().optional(),}).optional(),@@ -1367,11 +1367,10 @@ const ALLOWED_TASK_METADATA_KEYS = [// agent can't land code. See agentWorktreeCleanup.js.'discardWorktree',// Whether a successful run is EXPECTED to leave file changes in the worktree- // (#3102). Default (absent) = true: the TUI idle-complete gate fails a run that- // idled out on a clean tree. `false` opts a task type out of that gate — e.g. a- // reference-watch run against a GitHub/GitLab/JIRA work tracker files its- // proposals as issues and, per the prompt, edits no application code, so a- // clean worktree is the SUCCESS shape. See agentTuiSpawning.js.+ // (#3102). Default (absent) = true for code-shaped work. `false` marks a task+ // type whose deliverable is outside the repo — e.g. a reference-watch run+ // against a GitHub/GitLab/JIRA work tracker files its proposals as issues and,+ // per the prompt, edits no application code, so a clean worktree is expected.'worktreeChangesExpected'];diff --git a/server/lib/opencodeConfig.js b/server/lib/opencodeConfig.jsindex 525698bc7f..c6ba6483fb 100644--- a/server/lib/opencodeConfig.js+++ b/server/lib/opencodeConfig.js@@ -11,10 +11,10 @@** The shipped `OPENCODE_CONFIG_CONTENT` declared the Ollama provider but omitted* that models map, so OpenCode (>=1.17) rejected every `--model ollama/<id>` as- * "Model ollama/… is not valid" — the pasted prompt sat in the input box, the- * agent produced zero output, and the idle reaper marked it complete (issue- * -2190). This module builds the config dynamically at spawn time, declaring the- * provider's configured models (+ the model being run) under+ * "Model ollama/… is not valid" — the pasted prompt sat in the input box and+ * the agent produced zero output (issue -2190). This module builds the config+ * dynamically at spawn time, declaring the provider's configured models (+ the+ * model being run) under* `provider.<local-backend>.models` with bare ids.*/diff --git a/server/lib/slashdoCatalog.js b/server/lib/slashdoCatalog.jsindex 623c868215..fa83abf792 100644--- a/server/lib/slashdoCatalog.js+++ b/server/lib/slashdoCatalog.js@@ -33,16 +33,15 @@* absent-vs-empty rule) — it does NOT mean false.** The two postures below differ ONLY in `worktreeChangesExpected`, which declares- * the workflow's DELIVERABLE (#3636). The TUI idle reaper fails a run as- * `idle-no-changes` when the worktree is clean and no commit landed during the- * run (`worktreeHasWorkEvidence`), so a workflow whose output never touches the- * repo has to opt out — the reaper cannot see a filed issue or a printed report.+ * the workflow's DELIVERABLE (#3636). The metadata remains useful to downstream+ * task bookkeeping: a workflow whose output never touches the repo must not be+ * mistaken for a code-editing run merely because its worktree stays clean.*//*** Commit-shaped workflows: `next` / `better` / `better-swift` / `depfree` /- * `release` / `push` land a commit (usually behind their own PR), so the- * reaper's evidence probe covers them and the clean-tree gate stays armed.+ * `release` / `push` land a commit (usually behind their own PR), so their+ * deliverable posture expects repository changes.*/export const WORKFLOW_OWNS_ITS_OWN_GIT = Object.freeze({useWorktree: false, openPR: false, simplify: false, worktreeChangesExpected: true,diff --git a/server/lib/tuiHandshake.js b/server/lib/tuiHandshake.jsindex bc597c0254..3f1417ed85 100644--- a/server/lib/tuiHandshake.js+++ b/server/lib/tuiHandshake.js@@ -29,7 +29,7 @@ export const PASTE_DEADLINE_MS = 10000;// How long to wait for claude's POSITIVE input-ready footer (createInputReadyTracker)// before giving up and surfacing a startup failure. Generous because a cold// claude start can spend many seconds on banner + MCP-server + model init-// (still well under the 180s idle timeout). Used only on the input-ready-gated+// (well within the normal startup budget). Used only on the input-ready-gated// path; the non-claude providers use PASTE_DEADLINE_MS.export const TUI_INPUT_READY_DEADLINE_MS = 45000;@@ -393,111 +393,10 @@ export function createInputReadyTracker({ readyTextPattern = null, directLaunch};}-// "The model is actively processing a submitted prompt" signal. A TUI repaints-// its banner/status line continuously even with an UNSUBMITTED prompt sitting in-// the input box, so "any PTY output after the paste" cannot distinguish real-// work from chrome churn — that conflation is what finalized a never-submitted-// agent as `success: idle-complete` (issue #1229).-//-// We key on the TUI's elapsed-time WORKING COUNTER — `(1s · …` (Claude Code) /-// `(57s • …` (Codex) — which renders only while a request is in flight and-// INCREMENTS as the model works. This is the most model-agnostic signal (present-// in both providers, absent on the stuck screen) AND the only one that's-// echo-proof. The prompt is echoed into the input box BEFORE submission (and-// `promptSentAt` is set when the paste starts, before Enter), so word-matching-// `thinking`/`esc to interrupt` — or even a bare `(5s)` — could be tripped by a-// task description that merely contains those tokens (both flagged in review of-// #1229). Two defenses make the counter immune to the echo:-// 1. We require the counter's trailing bullet separator (`· ` / `• `, U+00B7 /-// U+2022) — `(\d+s` alone matches log lines and durations in prose, but-// `(\d+s ·` is the TUI's specific status-line format and effectively never-// appears in a pasted prompt. (The bullet survives ANSI stripping intact —-// verified in real transcripts: `(1s · thinking…`.)-// 2. We require ≥ MIN_WORK_COUNTER_SAMPLES DISTINCT second-counts — the live-// counter passes through many values; a static echoed literal is just one.-// There is one residual echo vector even with the bullet requirement: a task-// that asks the agent to ANALYZE A TUI TRANSCRIPT can paste content that itself-// contains two distinct bulleted counters (`(1s · …` and `(2s · …`), and the-// whole prompt is echoed at paste time — before Enter is known to have submitted-// (flagged in review of #1229). The defining difference is TIMING: the live-// counter is rendered ONE value at a time as wall-clock seconds pass, whereas an-// echoed transcript's counters all arrive together in the paste render. So the-// tracker activates only once it has seen ≥ MIN_WORK_COUNTER_SAMPLES distinct-// values whose observations SPAN ≥ MIN_WORK_COUNTER_SPAN_MS of real time — a-// span a single paste-render burst can't fake. `observe()` therefore takes the-// current timestamp.-// Verified against real transcripts: the working run cycled through many counter-// values across its runtime; the two confirmed stuck runs (`agent-92ed2c56`,-// `agent-30a3ab56`) had none. Heuristic by nature, so it gates only the FALLBACK-// idle-complete path on the long-running agent path — the authoritative success-// signal remains the `.agent-done` sentinel. (The one-shot runner is deliberately-// NOT gated: its idle-complete legitimately captures inline output that may carry-// no counter, and its authoritative path is the response file.)-export const WORK_COUNTER_PATTERN = /\(\s*(\d+)\s*s\s*[·•]/g;-export const MIN_WORK_COUNTER_SAMPLES = 2;-export const MIN_WORK_COUNTER_SPAN_MS = 750;--/**- * Extract every elapsed-second value from the TUI working counter in- * `strippedText` (e.g. `(1s · …` → 1, `(57s • …` → 57). Matches only the TUI's- * bullet-suffixed status-line counter, not a bare `(5s)` in prose. Callers MUST- * pass ANSI-stripped output. Returns an array (possibly empty); non-string input- * yields `[]`.- *- * @param {string} strippedText — ANSI-stripped output (a chunk or accumulator).- * @returns {number[]}- */-export function extractWorkCounterSeconds(strippedText) {- if (typeof strippedText !== 'string' || !strippedText) return [];- const out = [];- // Fresh matcher state per call — a module-level /g regex carries lastIndex- // across calls and would skip matches on the next invocation.- const re = new RegExp(WORK_COUNTER_PATTERN.source, 'g');- let m;- while ((m = re.exec(strippedText)) !== null) out.push(Number(m[1]));- return out;-}-/**- * Stateful tracker for the "model is actively working" signal. Feed it each- * ANSI-stripped post-paste chunk via `observe(strippedText, nowMs)`; it becomes- * (and stays) `active` once it has seen ≥ MIN_WORK_COUNTER_SAMPLES DISTINCT- * bulleted elapsed-second counter values whose observations span ≥- * MIN_WORK_COUNTER_SPAN_MS of wall-clock time — i.e. the live counter actually- * ticked across real seconds, which neither a static echoed prompt nor an echoed- * transcript's counters (all rendered in one paste burst) can fake. Used by the- * long-running agent path; lives here so the echo-proof logic is unit-testable.- *- * @returns {{ observe: (strippedText: string, nowMs: number) => boolean, readonly active: boolean }}- */-export function createWorkActivityTracker() {- const seconds = new Set();- let firstSeenAt = null; // wall-clock ms when the FIRST distinct counter appeared- let active = false;- return {- observe(strippedText, nowMs) {- if (active) return true;- for (const s of extractWorkCounterSeconds(strippedText)) {- if (seconds.has(s)) continue;- seconds.add(s);- if (firstSeenAt === null) {- firstSeenAt = nowMs;- } else if (- seconds.size >= MIN_WORK_COUNTER_SAMPLES &&- typeof nowMs === 'number' && typeof firstSeenAt === 'number' &&- nowMs - firstSeenAt >= MIN_WORK_COUNTER_SPAN_MS- ) {- // A later distinct value, far enough after the first — the live counter- // advanced across wall-clock time. A one-shot paste-render burst can't.- active = true;- return true;- }- }- return active;- },- get active() { return active; },- };-}+// Claude Code and Codex render a bulleted elapsed counter while a model request+// is in flight; agy uses its own `Generating…` indicator.+export const WORK_COUNTER_PATTERN = /\(\s*(\d+)\s*s\s*[·•]/g;// Chrome a TUI paints only while a model request is actually IN FLIGHT. agy// renders an animated `Generating…` for exactly as long as the request runs;@@ -512,8 +411,8 @@ export function createWorkActivityTracker() {// receipt: parked on the eligibility banner, a `/usage` scrape opened the palette// in its session, the palette footer read as "the provider recovered", and the// gate latched — which disarms BOTH the re-submission and the fail-over, so the-// run sat at the banner until the 180s idle reaper finalized it as a bogus-// `idle-no-changes`. That is the failure this whole mechanism exists to prevent,+// run sat at the banner until an old silent-session fallback finalized it as a+// bogus success. That is the failure this whole mechanism exists to prevent,// and no local feature separates the two footers.//// Dropping it costs nothing measurable: across every agy transcript on disk, each@@ -524,8 +423,7 @@ export const GENERATION_ACTIVITY_PATTERN =new RegExp(`Generating\\s*[.·•…]|${WORK_COUNTER_PATTERN.source}`, 'i');// Carry-over kept across chunks so in-flight chrome split by a PTY chunk boundary-// (`Generat` + `ing…`) still matches. The sibling trackers below each learned-// this the hard way — see createReviewLoopTracker's docblock.+// (`Generat` + `ing…`) still matches.//// Only needs to span the longest pattern alternative, because `observe` tests the// FULL `carry + chunk` window and trims only afterwards (see below) — the cap@@ -538,8 +436,8 @@ const GENERATION_ACTIVITY_CARRY_CAP = 64;* `active` once any in-flight chrome appears, and returns true on the call that* flipped it (so a caller can react to the transition).*- * Unlike `createWorkActivityTracker` this does not try to be echo-proof by- * construction — the gate that owns it handles the one case where the prompt can+ * This does not try to be echo-proof by construction — the gate that owns it+ * handles the one case where the prompt can* re-enter the stream (a re-submission; see SELF_CLEARING_RESUBMIT_ECHO_MS).** It is NOT, however, a "match anything that looks alive" pattern, which is how@@ -547,7 +445,7 @@ const GENERATION_ACTIVITY_CARRY_CAP = 64;* The cost asymmetry runs the other way now that the grace window re-submits: a* false "still stuck" merely re-asks a provider that was about to answer, while a* false "recovered" latches, disarming the retry AND the fail-over and leaving- * the run to idle-reap into a reported success it never earned. Only chrome that+ * the run to complete as a reported success it never earned. Only chrome that* a TUI paints EXCLUSIVELY while a request is in flight belongs here.** @returns {{ observe: (strippedText: string) => boolean, readonly active: boolean }}@@ -599,7 +497,7 @@ export const SELF_CLEARING_RESUBMIT_INTERVAL_MS = 20000;// phase), `takeResubmit` refuses, and that attempt is silently forfeited for a// whole interval. Polling faster than the cadence leaves the gate the single// authority on timing — the same shape the agent path gets for free by folding-// the question into its existing 5s idle poll.+// the question into its existing 5s provider-signal poll.export const SELF_CLEARING_RESUBMIT_POLL_MS = 5000;// How long after a re-submission the gate ignores output when deciding whether@@ -610,7 +508,7 @@ export const SELF_CLEARING_RESUBMIT_POLL_MS = 5000;// `Generating…` (a task about this very failure mode does) echoes straight into// the tracker and latches a bogus recovery — strictly worse than the expiry it// replaced, because a recovered gate neither retries nor fails over, leaving the-// run to idle-reap into a false success. 3s covers the paste and its spaced+// run to remain latched as a false recovery. 3s covers the paste and its spaced// submit-Enters (~1.4s).//// Applied to every re-submission rather than only to prompts whose text could@@ -632,16 +530,15 @@ export const SELF_CLEARING_RESUBMIT_ECHO_MS = 3000;* banner rejected the submission), disarm the moment the provider is* demonstrably generating again, and hand back a verdict at the deadline. Each* consumer keeps only its own timing mechanism — `agentTuiSpawning` folds the- * deadline and the retry cadence into its existing 5s idle poll, while+ * deadline and the retry cadence into its existing 5s provider-signal timer, while* `tuiPromptRunner` needs its own timers because its idle watcher is created* lazily on the first post-prompt chunk and may not exist yet when the banner* paints.** Usage per chunk: `gate.observe(stripped, now)` then, on a match,- * `gate.arm(analysis, now)`. `gate.armed` is the idle-suppression- * predicate — a session waiting out a handshake is silent by design, and letting- * an idle reaper finalize it would report a bogus success that scrapes the- * banner as the answer. `gate.takeResubmit(Date.now())` returns the 1-based+ * `gate.arm(analysis, now)`. `gate.armed` tells the provider-signal timer that+ * the handshake is still active; a session waiting out a handshake is silent by+ * design. `gate.takeResubmit(Date.now())` returns the 1-based* attempt number when it is time to re-send the prompt (0 otherwise), and* `gate.takeExpired(Date.now())` returns the analysis to fail over with, or null* while still waiting / after a recovery.@@ -664,7 +561,7 @@ export function createSelfClearingSignalGate() {// the exact bug the grace window exists to prevent (and it would now re-paste// the prompt into a working session on the way there). A genuine second banner// is therefore ignored rather than re-waited; the provider has demonstrably- // worked once, and the idle reaper remains the backstop if it truly wedges.+ // worked once, and the caller's normal failure/runtime handling remains in charge.let recovered = false;return {get armed() { return armed !== null; },@@ -738,7 +635,7 @@ export function createSelfClearingSignalGate() {// A SINGLE Enter after a large bracketed paste is unreliable: the TUI can still// be processing/reflowing the multi-line paste when the `\r` arrives and// swallow it, leaving the whole prompt sitting unsent in the input box. The-// agent then idles out and is falsely finalized as success — observed as the+// old fallback could then falsely finalize the run as success — observed as the// "the prompt was typed but I had to hit Enter myself" bug. (The marker fast// path above now fires again once matched against stripped output — see// detectPasteMarker — but the marker only renders for large multi-line pastes;@@ -784,26 +681,14 @@ export function scheduleSubmitEnters(write, isFinalized) {}// Defaults the consumer applies when the provider config doesn't pin-// per-provider values (provider.tuiPromptDelayMs / .tuiIdleTimeoutMs).+// per-provider prompt timing values (provider.tuiPromptDelayMs).export const DEFAULT_TUI_PROMPT_DELAY_MS = 2500;-export const DEFAULT_TUI_IDLE_TIMEOUT_MS = 180000;// Absolute wall-clock ceiling for a long-running TUI agent, applied from prompt-// submission. This is the honest backstop the idle reaper CAN'T be: the reaper-// resets on every PTY chunk, but Claude Code repaints its `(Ns · …)` working-// counter ~1×/sec while ANY tool/API call is in flight — INCLUDING one stuck-// retrying a stalled Bedrock/network operation. A "busy-but-stuck" agent keeps-// `lastOutputAt` advancing forever, so idle-reap never fires and the run has NO-// ceiling at all (real incident 2026-07-06: agent-b1c56083 churned the counter-// for 98min on a `/do:next --swarm` claim-issue task before Claude Code's OWN-// internal "Operation timed out" finally stopped it — had the CLI not self--// terminated, the agent would have run unbounded, holding a lane, blocking the-// app's cooldown, and leaking a shell session). The one-shot runner already has-// this backstop (tuiPromptRunner.js `hardTimeoutTimer`); the agent path omitted-// it. 3h sits comfortably above the longest legitimate single run observed-// (swarm claim-issue orchestrations routinely take 40–98min, and the merge-queue-// / review-loop idle windows are 15min each) while bounding a genuinely-stuck-// agent. Provider-configurable via `tuiMaxRuntimeMs`.+// submission. CoS agents intentionally have no output-idle completion/reap: a+// slow provider may be silent while it works. This ceiling is the remaining+// automatic backstop for a genuinely wedged provider/CLI and is configurable via+// `tuiMaxRuntimeMs`.export const DEFAULT_TUI_MAX_RUNTIME_MS = 3 * 60 * 60 * 1000;// Grace window opened when the max-runtime ceiling fires, BEFORE the agent is@@ -853,348 +738,6 @@ export function buildWrapUpProdMessage(graceMs, sentinelName) {].join('\n');}-// Extended idle threshold applied ONLY while a `/do:next --swarm` orchestrator-// is in its Phase C serialized merge queue (issue #2074). Merging PRs one at a-// time makes each subsequent PR rebase onto the new `main` and re-run required-// CI — several minutes of *silent* TUI output per PR (`gh pr checks --watch`-// shows a static "pending" screen with no repaint). That quiet window routinely-// blows past the 3-minute default and the runner reaps the still-working-// orchestrator as `idle-complete`, leaving PRs merged-but-uncleaned or unmerged-// while `state.json` records `status: completed`. 15 minutes comfortably covers-// one CI run's silent gap while still bounding a genuinely-dead orchestrator's-// reap (see MERGE_QUEUE_IDLE_TIMEOUT reap path in agentTuiSpawning.js).-export const MERGE_QUEUE_IDLE_TIMEOUT_MS = 900000;--// Distinctive markers the swarm orchestrator's TUI prints once it enters the-// Phase C merge queue. Detection is deliberately conservative: a false POSITIVE-// only *extends* the idle window (bounded, low-cost), and a false NEGATIVE just-// preserves the pre-#2074 behavior (no regression) — so this is nothing like the-// fragile completion-detection regexes we avoid for FINALIZING a run. Matched-// against ANSI-stripped output. Kept lower-cased for case-insensitive testing.-const MERGE_QUEUE_MARKERS = [- 'merge queue',- 'serialized merge',- 'phase c',- 'gh pr merge',- 'gh pr checks',- '--delete-branch',-];--/**- * True when a chunk of ANSI-stripped TUI output shows the swarm orchestrator has- * entered its Phase C serialized merge queue. 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 isMergeQueueSignal(strippedText) {- if (typeof strippedText !== 'string' || !strippedText) return false;- const lower = strippedText.toLowerCase();- return MERGE_QUEUE_MARKERS.some((marker) => lower.includes(marker));-}--/**- * Latching tracker for "this agent is in a serialized merge queue" (issue- * #2074). Feed it each ANSI-stripped post-submit chunk via `observe(text)`; it- * becomes `active` the first time a merge-queue marker appears and STAYS active- * thereafter. Latching (not a sliding window) is deliberate: the whole failure- * mode is a *silent* CI wait — no markers print during the quiet gap — so a- * recency window would age the flag out exactly when the extended idle grace is- * needed. Once latched, the idle reaper uses MERGE_QUEUE_IDLE_TIMEOUT_MS instead- * of the 3-minute default. Lives here so the detection logic is unit-testable.- *- * @returns {{ observe: (strippedText: string) => boolean, readonly active: boolean }}- */-export function createMergeQueueTracker() {- let active = false;- return {- observe(strippedText) {- if (active) return true;- if (isMergeQueueSignal(strippedText)) active = true;- return active;- },- get active() { return active; },- };-}--// Extended idle threshold applied while a `/do:release`, `/do:pr`, or `/do:rpr`-// multi-reviewer loop is waiting on a slow external reviewer (a Copilot cloud-// review, a headless codex/agy/claude review pass, an Ollama pass, or an-// arbitrary @<login> human reviewer). Observed 2026-07-02 (agent-61508f36): the-// review loop correctly backgrounds the reviewer and polls for it rather than-// blocking — but the reviewer itself can go silent in the wrapped TUI for well-// over the 3-minute default while it works (e.g. codex reading a large diff),-// and the runner reaped the still-waiting release agent as `idle-complete` (a-// false SUCCESS) before it ever reached the merge gate, leaving the release PR-// open and unmerged. Mirrors the merge-queue grace (#2074) exactly: 15 minutes-// comfortably covers one reviewer's silent working stretch while still-// bounding a genuinely-dead agent's reap.-export const REVIEW_LOOP_IDLE_TIMEOUT_MS = 900000;--// Distinctive markers the multi-reviewer loop (do:release/do:pr/do:rpr) prints-// once it starts waiting on a reviewer pass. Detection is deliberately-// conservative, same rationale as MERGE_QUEUE_MARKERS above: a false POSITIVE-// only extends the (bounded) idle window, and a false NEGATIVE just preserves-// prior behavior. Matched against ANSI-stripped output.-//-// Both patterns are anchored to the literal RENDERED shape rather than a bare-// substring, because this repo bundles the slashdo docs that DESCRIBE these-// banners — `lib/slashdo/lib/multi-reviewer-loop.md` alone contains the word-// "multi-reviewer" dozens of times, the literal phrase "Review plan:" once-// (inside its own instruction text), AND a fully-rendered example of its own-// aggregate-report heading ("## Multi-Reviewer Summary", in the doc's sample-// output block) — so a THIRD marker keyed on that heading alone would latch-// on any agent reading/quoting that one doc file (codex review flagged this-// exact collision; verified via `grep -rn "multi-reviewer summary"-// lib/slashdo/` — it's the only bundled doc containing that literal string).-// This project's CLAUDE.md convention text is also "run a simplify/-// self-review pass before committing", whose substring "review pass" would-// otherwise latch on ANY CoS agent's ordinary narration — not just an actual-// do:release/do:pr/do:rpr run. Anchoring on the shape only the runtime output-// actually has (a rendered `[...]` agent list, or a digit/slash pass counter)-// — verified clean against every bundled slashdo doc — keeps the-// false-positive rate low without weakening true-positive detection: the-// review-plan banner alone is a complete, sufficient signal (it prints once,-// unconditionally, before ANY reviewer pass begins) and the tracker latches-// permanently once set, so the pass-banner pattern only needs to catch the-// (rare) case where the plan banner itself was missed.-const REVIEW_PLAN_PATTERN = /review plan:\s*\[/i;-const REVIEW_PASS_BANNER_PATTERN = /review pass\s+\d+\s*\/\s*\d+/i;--/**- * True when a chunk of ANSI-stripped TUI output shows the multi-reviewer loop- * (do:release/do:pr/do:rpr) has started a reviewer pass. 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 isReviewLoopSignal(strippedText) {- if (typeof strippedText !== 'string' || !strippedText) return false;- return REVIEW_PLAN_PATTERN.test(strippedText) || REVIEW_PASS_BANNER_PATTERN.test(strippedText);-}--// Rolling tail cap for createReviewLoopTracker's cross-chunk buffer (below).-// The banner text itself is well under 100 chars (e.g. "Review plan: [claude,-// codex] (mode: series, stop-mode: all)" is ~62), so this is generous-// headroom for intervening chrome without letting the buffer grow unbounded-// over a long-running session.-const REVIEW_LOOP_TAIL_CAP = 512;--/**- * Latching tracker for "this agent is waiting inside a multi-reviewer loop"- * (do:release/do:pr/do:rpr). Feed it each ANSI-stripped post-submit chunk via- * `observe(text)`; it becomes `active` the first time a review-loop marker- * appears and STAYS active thereafter (same latching rationale as- * createMergeQueueTracker — the failure mode is a silent external-reviewer- * wait, so a recency window would age the flag out exactly when the extended- * grace is needed). Once latched, the idle reaper uses- * REVIEW_LOOP_IDLE_TIMEOUT_MS instead of the 3-minute default.- *- * Keeps a small rolling buffer of the most recent REVIEW_LOOP_TAIL_CAP- * characters (codex review finding, iteration 2): a real TUI can deliver the- * one-shot `Review plan: [` / `Review pass N/M` banner split across two- * `onData` chunks — plausible during token-by-token streaming — so checking- * only the current chunk in isolation would miss it if the split lands- * mid-marker. Concatenating each new chunk onto the tail before testing means- * a marker split across a chunk boundary still appears whole on the very next- * observation.- *- * @returns {{ observe: (strippedText: string) => boolean, readonly active: boolean }}- */-export function createReviewLoopTracker() {- let active = false;- let tail = '';- return {- observe(strippedText) {- if (active) return true;- if (typeof strippedText !== 'string' || !strippedText) return active;- tail = (tail + strippedText).slice(-REVIEW_LOOP_TAIL_CAP);- if (isReviewLoopSignal(tail)) active = true;- return active;- },- get active() { return active; },- };-}--// 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; },- };-}--/**- * The idle reaper's verdict, as a pure function of the signals the spawner has- * already latched. Lives here (not inline in the interval body) so the branch- * matrix is unit-testable against the REAL implementation — `agentTuiSpawning`- * calls this and executes what it returns.- *- * Priority order, highest first:- * 1. `prFollowUpMerged` — a PR follow-up run (`reviewLoopFollowUp`) exists to- * land ONE pull request. Once that PR reads MERGED and the session has been- * silent for the BASE window, the deliverable is provably in hand and there- * is nothing left to wait for. This outranks everything below because those- * branches all measure proxies (silence, worktree churn, a merge-queue- * latch) for a question this one answers directly. Without it a merge- * follow-up that did its whole job in 60s was recorded as a FAILURE: its- * prompt QUOTES `gh pr checks` / `gh pr merge` / `--delete-branch`, so the- * TUI's echo of that prompt latches `mergeQueueActive` before any work runs,- * and the agent — which is told to "Exit", makes no commit, and on- * Antigravity often skips the sentinel — then idles into (4)/(5)'s- * needs-manual-finish verdict 15 minutes later, gets retried twice more, and- * lands in Blocked with a HIGH "PR left open" card naming an already-merged- * PR (task sys-rl-msr1j1a5, PR #3909, 2026-08-13).- * 2. A null base timeout (local-runtime model) → keep waiting indefinitely;- * `tuiMaxRuntimeMs` remains the separate wall-clock backstop.- * 3. Not yet at the (possibly extended) deadline → keep waiting.- * 4–5. The extended-grace reaps: a latched merge queue / multi-reviewer loop- * that blew even its 15-minute window is a needs-manual-finish FAILURE- * (#2074, PR #2084) — the run really did go dark mid-merge.- * 6. `idle-no-activity` (#1229) — provider renders a work counter and it never- * advanced: the prompt never submitted.- * 7. Otherwise the pre-existing permissive `idle-complete`, which the caller- * still gates on worktree evidence (#2191) before recording success.- *- * Note `backgroundShellActive` extends the deadline but carries NO verdict of- * its own — a background-shell wait that blows its window falls through to the- * ordinary (6)/(7) reasoning, unchanged.- *- * @param {Object} signals- * @param {number} signals.idle - ms since the last PTY output- * @param {number|null} signals.baseIdleTimeoutMs - the run's configured idle- * window, or null to disable idle reaping for a local-runtime model- * @param {boolean} [signals.mergeQueueActive]- * @param {boolean} [signals.reviewLoopActive]- * @param {boolean} [signals.backgroundShellActive]- * @param {boolean} [signals.prFollowUpMerged] - this is a PR follow-up AND its PR reads MERGED- * @param {boolean} [signals.workActive] - the work counter advanced post-submit- * @param {boolean} [signals.rendersCounter] - this provider renders a work counter at all- * @returns {{ action: 'wait'|'reap', effectiveIdleTimeoutMs: number, success?: boolean, reason?: string }}- */-export function decideIdleReap({- idle,- baseIdleTimeoutMs,- mergeQueueActive = false,- reviewLoopActive = false,- backgroundShellActive = false,- prFollowUpMerged = false,- workActive = false,- rendersCounter = false,-} = {}) {- const idleTimeoutDisabled = baseIdleTimeoutMs === null;- const effectiveIdleTimeoutMs = idleTimeoutDisabled- ? Infinity- : mergeQueueActive- ? Math.max(baseIdleTimeoutMs, MERGE_QUEUE_IDLE_TIMEOUT_MS)- : reviewLoopActive- ? Math.max(baseIdleTimeoutMs, REVIEW_LOOP_IDLE_TIMEOUT_MS)- : backgroundShellActive- ? Math.max(baseIdleTimeoutMs, BACKGROUND_SHELL_IDLE_TIMEOUT_MS)- : baseIdleTimeoutMs;- if (!idleTimeoutDisabled && prFollowUpMerged && idle >= baseIdleTimeoutMs) {- return { action: 'reap', success: true, reason: 'pr-follow-up-merged', effectiveIdleTimeoutMs };- }- if (idleTimeoutDisabled || idle < effectiveIdleTimeoutMs) {- return { action: 'wait', effectiveIdleTimeoutMs };- }- if (mergeQueueActive) {- return { action: 'reap', success: false, reason: 'merge-queue-idle-timeout', effectiveIdleTimeoutMs };- }- if (reviewLoopActive) {- return { action: 'reap', success: false, reason: 'review-loop-idle-timeout', effectiveIdleTimeoutMs };- }- if (!workActive && rendersCounter) {- return { action: 'reap', success: false, reason: 'idle-no-activity', effectiveIdleTimeoutMs };- }- return { action: 'reap', success: true, reason: 'idle-complete', effectiveIdleTimeoutMs };-}// ─── Codex MCP-server boot detection ──────────────────────────────────────//@@ -1223,8 +766,8 @@ export function decideIdleReap({// and a paste finally lands its marker, up to MCP_BOOT_PASTE_DEADLINE_MS. The// spawner (agentTuiSpawning.js) consumes `createMcpBootTracker` for exactly that.//-// Matched against ANSI-stripped output. Detection is deliberately conservative,-// same rationale as MERGE_QUEUE_MARKERS: a false POSITIVE only extends the+// Matched against ANSI-stripped output. Detection is deliberately conservative:+// a false POSITIVE only extends the// (bounded) retry window, and a false NEGATIVE just preserves the pre-fix 3-retry// behavior. The two phrases are anchored to codex's literal boot banners rather// than a bare "mcp server" substring so an agent whose prompt/output merely@@ -1233,9 +776,8 @@ const MCP_BOOT_MARKERS = ['booting mcp server', 'starting mcp servers'];// Covers a `node_repl` with the documented `startup_timeout_sec = 120` plus an// `npx`-fetched server's cold download and margin, while still bounding a-// genuinely-hung boot's failure. Kept under the 180s default idle-reap window so-// the boot-retry loop resolves (succeeds or fails cleanly) before the idle-// reaper can race it.+// genuinely-hung boot's failure. The deadline is independent of CoS agent+// runtime handling so a slow MCP boot gets its full retry budget.export const MCP_BOOT_PASTE_DEADLINE_MS = 150000;// Spacing between paste retries while codex is booting MCP servers. A swallowed// mid-boot paste renders nothing, so a re-paste every few seconds is a cheap@@ -1243,8 +785,8 @@ export const MCP_BOOT_PASTE_DEADLINE_MS = 150000;// marker-wait + verify window (~5.5s), so the effective cadence is ~10s.export const MCP_BOOT_PASTE_RETRY_DELAY_MS = 5000;-// Rolling tail cap for createMcpBootTracker's cross-chunk buffer, same rationale-// as REVIEW_LOOP_TAIL_CAP: a boot banner can split across two onData chunks+// Rolling tail cap for createMcpBootTracker's cross-chunk buffer: a boot banner+// can split across two onData chunks// during streaming, so concatenate onto a short tail before testing.const MCP_BOOT_TAIL_CAP = 256;@@ -1332,27 +874,6 @@ export const RAW_SPOOL_MAX_BYTES = 256 * 1024 * 1024;*/export { inferTuiCommand };-/**- * True when the given TUI command renders the elapsed working counter- * (`(Ns ·` / `(Ns •`) that `createWorkActivityTracker` keys on. Only Claude- * Code and Codex are known to render it; Antigravity/Gemini/other TUIs do not.- *- * The work-activity idle gate (issue #1229) must consult this before- * downgrading a sentinel-less idle-out to failure: on a provider that never- * renders the counter, absence of the signal proves nothing, so the original- * permissive idle-complete=success behavior must be preserved (otherwise every- * sentinel-less completion on those providers would falsely fail).- *- * @param {string} commandName — the spawned binary's basename (e.g. `claude`,- * `codex`, `agy`, `gemini`).- * @returns {boolean}- */-export function rendersWorkCounter(commandName) {- if (typeof commandName !== 'string') return false;- const lower = commandName.toLowerCase();- return lower.includes('claude') || lower.includes('codex');-}-/*** TUI posture-flag dispatch (approval/trust bypass per vendor). Defined in* providerVendors.js (the PROVIDER_VENDORS registry, #3618); re-exported here@@ -1389,7 +910,7 @@ export function buildTuiInvocation(provider, model) {/*** Returns true when the stripped chunk looks like a `command not found`* error for our spawned TUI binary. Used as an early-fail probe so a typo'd- * provider.command surfaces in seconds instead of after the idle timeout.+ * provider.command surfaces in seconds instead of after a completion timeout.*/export function detectMissingTuiBinary(strippedText, commandName) {const lower = strippedText.toLowerCase();diff --git a/server/lib/tuiHandshake.test.js b/server/lib/tuiHandshake.test.jsindex 895428d50f..0ba8531c95 100644--- a/server/lib/tuiHandshake.test.js+++ b/server/lib/tuiHandshake.test.js@@ -7,35 +7,19 @@ import {PASTE_MARKER_PATTERN,detectPasteMarker,countPasteMarkers,- WORK_COUNTER_PATTERN,- MIN_WORK_COUNTER_SAMPLES,- MIN_WORK_COUNTER_SPAN_MS,- extractWorkCounterSeconds,- createWorkActivityTracker,createGenerationActivityTracker,createSelfClearingSignalGate,SELF_CLEARING_RESUBMIT_INTERVAL_MS,SELF_CLEARING_RESUBMIT_ECHO_MS,- MERGE_QUEUE_IDLE_TIMEOUT_MS,- isMergeQueueSignal,- createMergeQueueTracker,- 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,createMcpBootTracker,- rendersWorkCounter,PASTE_TO_ENTER_MIN_DELAY_MS,PASTE_TO_ENTER_FALLBACK_MS,SUBMIT_ENTER_ATTEMPTS,SUBMIT_ENTER_SPACING_MS,DEFAULT_TUI_PROMPT_DELAY_MS,- DEFAULT_TUI_IDLE_TIMEOUT_MS,RAW_BUFFER_CAP,RAW_BUFFER_HEADROOM,OUTPUT_BUFFER_CAP,@@ -187,69 +171,6 @@ describe('tuiHandshake — paste timing constants', () => {expect(echoInStrippedBuffer > countPasteMarkers(strippedPrompt)).toBe(false);});- it('extractWorkCounterSeconds parses the TUI bullet-suffixed working counter', () => {- // Claude Code: `(1s · …`; Codex: `(57s • …`.- expect(extractWorkCounterSeconds('(1s · thinking with high effort)')).toEqual([1]);- expect(extractWorkCounterSeconds('(57s • esc to interrupt)')).toEqual([57]);- expect(extractWorkCounterSeconds('(0s · Churning…)')).toEqual([0]);- // Multiple bulleted counters in one buffer (e.g. an accumulated screen).- expect(extractWorkCounterSeconds('(1s · a (2s • b (3s · c')).toEqual([1, 2, 3]);- });-- it('extractWorkCounterSeconds ignores bare (Ns) durations in prose/logs (echo-proof)', () => {- // The #1229 review fix: a bare `(5s)` in a pasted prompt / log line must NOT- // count — only the TUI's bullet-suffixed status-line counter does. Without- // this, an echoed prompt containing duration literals could fake "work".- expect(extractWorkCounterSeconds('please respond within (5s) of receiving this')).toEqual([]);- expect(extractWorkCounterSeconds('[12:00:01] (3s) elapsed (4s) total')).toEqual([]);- expect(extractWorkCounterSeconds('● high · /effort')).toEqual([]);- expect(extractWorkCounterSeconds('')).toEqual([]);- expect(extractWorkCounterSeconds(null)).toEqual([]);- });-- it('extractWorkCounterSeconds is stateless across calls (no lastIndex carryover)', () => {- // A module-level /g regex would skip matches on the 2nd call; assert it doesn't.- expect(extractWorkCounterSeconds('(4s · x')).toEqual([4]);- expect(extractWorkCounterSeconds('(4s · x')).toEqual([4]);- });-- it('createWorkActivityTracker activates only when the counter ticks across real time (echo-proof)', () => {- const tracker = createWorkActivityTracker();- expect(tracker.active).toBe(false);- // Bare duration literals echoed from the prompt — no bullet → not the counter.- expect(tracker.observe('finish within (1s) and definitely under (2s)', 0)).toBe(false);- // A single bulleted counter value must NOT activate (one sample).- expect(tracker.observe('(5s · thinking)', 1000)).toBe(false);- expect(tracker.observe('(5s · thinking)', 1100)).toBe(false);- expect(tracker.active).toBe(false);- // A second DISTINCT bulleted value — and ≥750ms after the first — activates.- expect(tracker.observe('(6s · thinking)', 2000)).toBe(true);- expect(tracker.active).toBe(true);- // Stays active once tripped.- expect(tracker.observe('● high · /effort', 3000)).toBe(true);- });-- it('createWorkActivityTracker rejects an echoed transcript with two distinct counters arriving at once', () => {- // The #1229 round-3 review case: a task that pastes a TUI transcript can echo- // two distinct bulleted counters — but they all arrive in the same paste-render- // burst (same instant), so the time-span requirement keeps them from faking work.- const tracker = createWorkActivityTracker();- expect(tracker.observe('analyze this log: (1s · thinking) then (2s · thinking)', 5000)).toBe(false);- // Even repainted later as a whole (still the SAME two values, not new ones).- expect(tracker.observe('analyze this log: (1s · thinking) then (2s · thinking)', 9000)).toBe(false);- expect(tracker.active).toBe(false);- });-- it('createWorkActivityTracker stays inactive on pure stuck/idle chrome', () => {- const tracker = createWorkActivityTracker();- // The exact chrome from the #1229 false-success transcript (no counter).- tracker.observe('⏵⏵ bypass permissions on (shift+tab to cycle)', 0);- tracker.observe('● high · /effort', 1000);- tracker.observe('paste again to expand', 2000);- tracker.observe('Begin working on the task now.', 3000);- tracker.observe('Opus 4.8 │ agent-92ed2c56', 4000);- expect(tracker.active).toBe(false);- });// Verdict for agy's self-clearing eligibility banner: did the provider come// back? The chrome below is lifted from real transcripts — healthy agy runs@@ -508,41 +429,20 @@ describe('tuiHandshake — paste timing constants', () => {});// Cross-file invariant between the signal that sets the window and the gate- // that spends it. Too short and the window is back to being a pause in- // front of a fail-over; past the idle timeout and the reaper finalizes the- // deliberately-silent session first — as an `idle-complete` SUCCESS that- // scrapes the banner as the answer, since agy renders no work counter.- it("sizes agy's eligibility window for several retries, still inside the idle timeout", () => {+ // that spends it. The grace window must allow several retries before the+ // provider is classified as requiring fallback.+ it("sizes agy's eligibility window for several retries", () => {const signal = detectImmediateFallbackSignal("We're finishing verifying your account eligibility. This usually takes a moment. Please try again shortly.");expect(signal.graceMs).toBeGreaterThanOrEqual(3 * SELF_CLEARING_RESUBMIT_INTERVAL_MS);- expect(signal.graceMs).toBeLessThan(DEFAULT_TUI_IDLE_TIMEOUT_MS);+ expect(signal.graceMs).toBeGreaterThan(0);});});});- it('pins work-activity detection constants', () => {- expect(WORK_COUNTER_PATTERN).toBeInstanceOf(RegExp);- expect(MIN_WORK_COUNTER_SAMPLES).toBe(2);- expect(MIN_WORK_COUNTER_SPAN_MS).toBe(750);- });-- it('rendersWorkCounter is true only for the counter-rendering TUIs (Claude Code / Codex)', () => {- // The idle gate may downgrade to failure ONLY for providers that render the- // counter; others must keep the permissive idle-complete (codex P2 / #1229).- expect(rendersWorkCounter('claude')).toBe(true);- expect(rendersWorkCounter('codex')).toBe(true);- expect(rendersWorkCounter('/usr/local/bin/claude')).toBe(true);- expect(rendersWorkCounter('agy')).toBe(false);- expect(rendersWorkCounter('gemini')).toBe(false);- expect(rendersWorkCounter('')).toBe(false);- expect(rendersWorkCounter(null)).toBe(false);- });-it('pins provider-default constants', () => {expect(DEFAULT_TUI_PROMPT_DELAY_MS).toBe(2500);- expect(DEFAULT_TUI_IDLE_TIMEOUT_MS).toBe(180000);});it('pins buffer caps with headroom > cap (defensive growth allowance)', () => {@@ -561,187 +461,12 @@ describe('tuiHandshake — paste timing constants', () => {});});-// Issue #2074 — a swarm orchestrator in its Phase C serialized merge queue goes-// silent for minutes per PR (each rebases + re-runs CI). Detection latches so the-// idle reaper can extend its grace and not reap a still-working orchestrator.-describe('tuiHandshake — merge-queue idle suppression (#2074)', () => {- it('extends the idle timeout well past the default 3-minute window', () => {- expect(MERGE_QUEUE_IDLE_TIMEOUT_MS).toBe(900000);- expect(MERGE_QUEUE_IDLE_TIMEOUT_MS).toBeGreaterThan(DEFAULT_TUI_IDLE_TIMEOUT_MS);- });-- it('isMergeQueueSignal matches Phase C merge-queue chrome (case-insensitive)', () => {- expect(isMergeQueueSignal('### Swarm Phase C — Serialized merge queue')).toBe(true);- expect(isMergeQueueSignal('Running: gh pr checks 2071 --required --watch --fail-fast')).toBe(true);- expect(isMergeQueueSignal('gh pr merge 2071 --merge --delete-branch')).toBe(true);- expect(isMergeQueueSignal('PHASE C: serialized MERGE QUEUE begins')).toBe(true);- });-- it('isMergeQueueSignal ignores ordinary implementation/output chrome', () => {- expect(isMergeQueueSignal('Editing server/services/agentTuiSpawning.js')).toBe(false);- expect(isMergeQueueSignal('● high · (12s · running tests)')).toBe(false);- expect(isMergeQueueSignal('')).toBe(false);- expect(isMergeQueueSignal(null)).toBe(false);- expect(isMergeQueueSignal(undefined)).toBe(false);- });-- it('createMergeQueueTracker latches on first signal and stays active through silence', () => {- const tracker = createMergeQueueTracker();- expect(tracker.active).toBe(false);- tracker.observe('implementing the fix, running the suite');- expect(tracker.active).toBe(false);- // Enters Phase C — latches.- expect(tracker.observe('gh pr merge 2071 --merge --delete-branch')).toBe(true);- expect(tracker.active).toBe(true);- // Subsequent quiet CI-wait chunks (no marker) must NOT un-latch it — the- // whole point is that the silent gap is when the grace is needed.- tracker.observe('waiting...');- tracker.observe('');- expect(tracker.active).toBe(true);- });-});--// Observed 2026-07-02 (agent-61508f36) — a do:release run's multi-reviewer-// loop correctly backgrounded a slow codex review and polled for it rather-// than blocking, but the reviewer's silent working stretch exceeded the-// 3-minute default and the runner reaped the still-waiting release as a false-// `idle-complete` success before it reached the merge gate, leaving PR #2084-// open. Mirrors the merge-queue suppression above.-describe('tuiHandshake — review-loop idle suppression', () => {- it('extends the idle timeout well past the default 3-minute window', () => {- expect(REVIEW_LOOP_IDLE_TIMEOUT_MS).toBe(900000);- expect(REVIEW_LOOP_IDLE_TIMEOUT_MS).toBeGreaterThan(DEFAULT_TUI_IDLE_TIMEOUT_MS);- });-- it('isReviewLoopSignal matches multi-reviewer-loop chrome (case-insensitive)', () => {- expect(isReviewLoopSignal('Review plan: [claude, codex] (mode: series, stop-mode: all)')).toBe(true);- expect(isReviewLoopSignal('--- Review pass 1/2: codex ---')).toBe(true);- });-- it('isReviewLoopSignal ignores ordinary implementation/output chrome', () => {- expect(isReviewLoopSignal('Editing server/services/agentTuiSpawning.js')).toBe(false);- expect(isReviewLoopSignal('● high · (12s · running tests)')).toBe(false);- expect(isReviewLoopSignal('')).toBe(false);- expect(isReviewLoopSignal(null)).toBe(false);- expect(isReviewLoopSignal(undefined)).toBe(false);- });-- // Regression for false-positive latches found across three rounds of local- // review: bare substrings ('review pass', 'review loop', 'multi-reviewer',- // 'multi-reviewer summary') would match this project's own CLAUDE.md- // convention ("run a simplify/self-review pass before committing") and this- // repo's bundled slashdo docs — which say "review loop"/"multi-reviewer"- // dozens of times, include the literal instruction text "Review plan:- // {REVIEW_AGENTS}...", AND (codex review's finding) render a fully-formed- // example of their own "## Multi-Reviewer Summary" aggregate-report heading- // in a sample output block — latching the tracker for ANY CoS agent's- // ordinary narration or docs-editing, not just an actual do:release/do:pr/- // do:rpr run.- it('isReviewLoopSignal does NOT match ordinary self-review narration or doc prose', () => {- expect(isReviewLoopSignal('running the self-review pass before committing')).toBe(false);- expect(isReviewLoopSignal('## Local Agent Code Review Loop')).toBe(false);- expect(isReviewLoopSignal('You are a Copilot review loop agent.')).toBe(false);- expect(isReviewLoopSignal('the multi-reviewer wrapper dispatches each listed agent')).toBe(false);- expect(isReviewLoopSignal('Print the resolved plan before starting: `Review plan: {REVIEW_AGENTS} (mode: ...)`')).toBe(false);- expect(isReviewLoopSignal('## Multi-Reviewer Summary')).toBe(false);- });-- it('createReviewLoopTracker latches on first signal and stays active through silence', () => {- const tracker = createReviewLoopTracker();- expect(tracker.active).toBe(false);- tracker.observe('implementing the fix, running the suite');- expect(tracker.active).toBe(false);- // Enters the multi-reviewer loop — latches.- expect(tracker.observe('Review plan: [claude, codex] (mode: series, stop-mode: all)')).toBe(true);- expect(tracker.active).toBe(true);- // Subsequent quiet reviewer-wait chunks (no marker) must NOT un-latch it —- // the whole point is that the silent gap is when the grace is needed.- tracker.observe('waiting for codex...');- tracker.observe('');- expect(tracker.active).toBe(true);- });-- // Regression for codex review [P2] (iteration 2): a real TUI can deliver- // the banner split across two onData chunks (token-by-token streaming),- // so checking only the current chunk in isolation would miss it.- it('createReviewLoopTracker latches on a marker split across two chunks', () => {- const tracker = createReviewLoopTracker();- // Split right before the '[' that anchors the pattern — neither half- // alone contains "review plan: [".- tracker.observe('Now starting the review loop. Review plan:');- expect(tracker.active).toBe(false);- expect(tracker.observe(' [claude, codex] (mode: series, stop-mode: all)')).toBe(true);- expect(tracker.active).toBe(true);- });-});--// 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', () => {+ it('deadline covers a node_repl startup_timeout_sec=120 plus margin', () => {// Long enough for the documented 120s node_repl startup + an npx cold- // download, short enough to resolve before the 180s default idle reaper.+ // download, with a bounded retry window for a genuinely hung boot.expect(MCP_BOOT_PASTE_DEADLINE_MS).toBe(150000);expect(MCP_BOOT_PASTE_DEADLINE_MS).toBeGreaterThan(120000);- expect(MCP_BOOT_PASTE_DEADLINE_MS).toBeLessThan(DEFAULT_TUI_IDLE_TIMEOUT_MS);expect(MCP_BOOT_PASTE_RETRY_DELAY_MS).toBe(5000);});diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 0d71fb1045..c4f34454e9 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -417,10 +417,8 @@ export const providerSchema = z.object({envVars: z.record(z.string()).optional(),headlessArgs: z.array(z.string()).optional(),tuiPromptDelayMs: z.number().int().min(250).max(60000).optional(),- tuiIdleTimeoutMs: z.number().int().min(10000).max(1800000).optional(),// Absolute wall-clock ceiling for long-running TUI agents (mirrors the- // aiToolkit providerSchema; the idle reaper can't bound a busy-but-stuck agent- // — see DEFAULT_TUI_MAX_RUNTIME_MS in tuiHandshake.js). Min 1min, max 12h.+ // aiToolkit providerSchema). Min 1min, max 12h.tuiMaxRuntimeMs: z.number().int().min(60000).max(43200000).optional()});diff --git a/server/lib/validation.test.js b/server/lib/validation.test.jsindex a87c63c209..2418335f94 100644--- a/server/lib/validation.test.js+++ b/server/lib/validation.test.js@@ -575,7 +575,6 @@ describe('validation.js', () => {type: 'tui',command: 'codex',tuiPromptDelayMs: 2500,- tuiIdleTimeoutMs: 180000};const result = providerSchema.safeParse(provider);expect(result.success).toBe(true);diff --git a/server/lib/workTracker.js b/server/lib/workTracker.jsindex 884ebb20a4..b6bd8d8b82 100644--- a/server/lib/workTracker.js+++ b/server/lib/workTracker.js@@ -131,8 +131,8 @@ export function forgeCliForTracker(tracker) {* (on-commit) and `resolveReferenceWatchBlock` (the WEEKLY scheduled task) — to* stamp `worktreeChangesExpected` on the spawned task off the SAME resolved* value that picks the prompt's {trackerInstructions} block, so the flag can't- * drift from the instructions the agent actually got (see agentTuiSpawning.js's- * idle-complete gate, #3102/#3140).+ * drift from the instructions the agent actually got (see agentTuiSpawning.js,+ * #3102/#3140).* An unknown/absent tracker is treated as file-based, matching* formatTrackerInstructions' PLAN.md fallback.*/diff --git a/server/routes/cosTaskRoutes.js b/server/routes/cosTaskRoutes.jsindex 658374243b..ab51503e49 100644--- a/server/routes/cosTaskRoutes.js+++ b/server/routes/cosTaskRoutes.js@@ -171,8 +171,8 @@ router.post('/tasks/slashdo', asyncHandler(async (req, res) => {// PortOS-managed worktree gets one. `worktreeChangesExpected` declares the// workflow's deliverable: false for the report-shaped four (plan-task /// replan / review / scan), whose output is a filed issue or a printed report,- // so the TUI idle reaper doesn't score their clean tree `idle-no-changes`- // (#3636). `simplify` comes from the request (the run drawer's toggle), not+ // so downstream task bookkeeping does not score their clean tree as missing+ // code work (#3636). `simplify` comes from the request (the run drawer's toggle), not// the catalog.const { useWorktree, openPR, worktreeChangesExpected } = workflow.settings;let shape;diff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.jsindex 98ec99ec8e..8b2286e762 100644--- a/server/services/agentErrorAnalysis.js+++ b/server/services/agentErrorAnalysis.js@@ -617,7 +617,8 @@ const TUI_PLACEHOLDER_HINT_PATTERN = /^\s*[❯>]\s*Try\s+["'].*$/gm;* "lines". That defeated a line-only window entirely — the "last 200 lines" was* the WHOLE 17-minute session, so a keyword anywhere in it (in the pasted prompt,* or in a `grep -rn "maxTokens\|max_tokens"` the agent itself ran) classified the- * failure. That is exactly how an idle-reaper kill got labelled `context-length`.+ * failure. That is exactly how an earlier idle-reaper kill got labelled+ * `context-length`.** So: strip escape sequences, treat CR as a line break (repaints overwrite a* line rather than starting one), drop blanks, then bound by lines AND by@@ -657,14 +658,17 @@ function resolvePatternOrigin(errorDef, analysisOutput) {/*** Runner-resolved completion reasons → the failure they actually describe.*- * When the spawner's own finalize path already KNOWS why a run ended (the idle- * reaper fired, max runtime elapsed, the shell session never came up), that is a- * structural signal about the process — strictly better evidence than a regex+ * When the spawner's own finalize path already KNOWS why a run ended (a legacy+ * idle reaper fired, max runtime elapsed, or the shell session never came up),+ * that is a structural signal about the process — strictly better evidence than a regex* sweep over the transcript. Keyed by the `reason` each `finish()` call passes;* see `server/services/agentTuiSpawning.js`. Categories are deliberately reused* from ERROR_PATTERNS so downstream taxonomies (task-learning metrics,* layeredIntelligenceExecutionFailures) keep classifying them without a new token.*/+// Legacy idle-out reasons remain readable for archived agent records and retries;+// the current CoS TUI path completes by sentinel, process exit, explicit provider+// failure, or its wall-clock runtime ceiling.export const COMPLETION_REASON_ANALYSES = {'idle-no-changes': {category: 'no-changes',@@ -802,8 +806,8 @@ export const COMPLETION_REASON_ANALYSES = {/*** Screen signatures of a TUI parked on an interactive prompt — a multiple-choice* selector, an approval gate, a confirmation. A CoS agent is unattended, so- * nothing ever answers: the session repaints the prompt until the idle reaper- * kills it, and the run lands as a plain idle-out. That verdict is true but+ * nothing ever answers: older TUI handling repaints the prompt until its idle+ * fallback kills it, and the run lands as a plain idle-out. That verdict is true but* diagnostically useless — it sends the reader hunting for a stalled provider* request, and a retry re-runs the same command straight into the same gate.* (Observed cost: three identical `/do:plan-task` attempts, each parked on a@@ -837,8 +841,8 @@ export function endsAwaitingUserInput(analysisOutput) {}/**- * Idle-out reasons worth re-explaining as an unanswered prompt. All three are- * "the reaper killed it" verdicts, so when the tail shows a selector or approval+ * Legacy idle-out reasons worth re-explaining as an unanswered prompt. All three+ * are "the reaper killed it" verdicts, so when the tail shows a selector or approval* gate that IS the proximate cause — including for a programmatic-I/O run, whose* payload went unwritten precisely because it never got past the prompt.*/@@ -855,7 +859,7 @@ const AWAITING_INPUT_REFINABLE_REASONS = new Set(['idle-no-changes', 'idle-no-acconst STARTUP_GATE_REFINABLE_REASONS = new Set(['paste-not-rendered', 'tui-not-ready']);/**- * Re-word a run whose transcript ends on an unanswered prompt — an idle-out that+ * Re-word a run whose transcript ends on an unanswered prompt — a legacy idle-out that* stalled ON one, or a startup verdict where a dialog was up BEFORE the prompt* could land (the two groups get different prose; see the reason sets). The* original `category` is preserved — downstream taxonomies (auto-fix tiers,@@ -878,7 +882,7 @@ function refineIdleReasonAnalysis(def, completionReason, analysisOutput) {return {...def,message: 'Agent stalled on an interactive prompt with nobody to answer it',- suggestedFix: 'The transcript ends on an unanswered prompt (a choice selector or approval gate), so the agent never got past it and the idle reaper killed the run. Agents run unattended — re-running as-is will stall the same way. Invoke the command in its non-interactive form (e.g. `/do:plan-task --yes`) or reword the task so no approval is needed.'+ suggestedFix: 'The transcript ends on an unanswered prompt (a choice selector or approval gate), so the agent never got past it and the old idle fallback killed the run. Agents run unattended — re-running as-is will stall the same way. Invoke the command in its non-interactive form (e.g. `/do:plan-task --yes`) or reword the task so no approval is needed.'};}@@ -910,7 +914,7 @@ function structuralReasonAnalysis(def, completionReason, completionError) {* becomes the default classification, and only a STRUCTURED provider/runner* signal in the transcript (an `API Error: NNN` line, a Node error code) may* override it — a loose output-scan keyword match may not. Without that gate an- * idle-reaper kill was labelled `context-length` (actionable → task blocked ++ * an idle-reaper kill was labelled `context-length` (actionable → task blocked +* investigation filed) purely because the agent had run a grep for `max_tokens`* fifteen minutes earlier.*/diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex dca61a297f..59ae09c286 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -54,14 +54,14 @@ PortOS runs MANY apps under one shared pm2 daemon. To restart an app, use a SCOP// Also appended to every agent briefing. A CoS agent runs headless: the TUI has// no human attached, so an interactive selector or approval gate is a dead end —-// the session repaints it until the idle reaper kills the run and the work is+// the session can sit there until its wall-clock runtime ceiling and the work is// discarded. Nothing in the briefing used to SAY that, so a `/do:plan-task` run// (whose skill shows its drafted issue for approval before filing) parked on a// scope question for its whole life and was retried into the same gate three// times, filing nothing. The rule names the escape hatch too: slash commands// that gate on approval take a flag to skip it.export const UNATTENDED_RUN_RULE = `## ⚠️ Unattended Run (no human is present)-PortOS launched you autonomously. Nobody is watching this session and nothing can answer you — if you present an interactive choice (a multiple-choice question, an approval gate, a "which option?" selector, a confirmation), the session sits there until the idle reaper kills it and **your work is thrown away**.+PortOS launched you autonomously. Nobody is watching this session and nothing can answer you — if you present an interactive choice (a multiple-choice question, an approval gate, a "which option?" selector, a confirmation), the session can sit there until its runtime ceiling and **your work may be thrown away**.- **Never ask the user to choose or approve.** Make the call yourself, state the assumption in your summary, and proceed.- **Invoke commands and skills in their non-interactive form.** If one drafts something and gates on approval before acting, pass the flag that skips that gate (\`--yes\` for the slashdo commands that have one).- **Ambiguous task?** Pick the most reasonable reading, do the work, and note the alternatives you rejected in your completion summary.@@ -926,7 +926,7 @@ Only a successfully extracted \`.findings\` value is the review text; treat it l// Where the loop hands control back. A follow-up agent's whole task WAS the// loop, so it exits; an inline loop is one step of a larger completion// workflow that still owes the run its `.agent-done` sentinel — telling it to- // "exit" here is how a finished merge idles into a false timeout.+ // "exit" here leaves a finished merge without the sentinel that records it.const exitStep = inline? `6. ${inlineExitStep}`: `6. Exit. Do **not** run \`/do:push\` or open a new PR${leaveOpen ? '' : ' — the merge handles everything'}. The system will clean up your worktree on exit.`;@@ -1323,9 +1323,9 @@ export function buildProgrammaticOutputCompletionSection(sentinelPath) {** A TUI agent still needs a `.agent-done` sentinel to signal completion — the 2s* sentinel poll in `spawnTuiAgent` is the primary finalize path and the channel- * that ingests the run summary. Without it a read-only TUI run only finalizes via- * the idle reaper / shell-exit fallback, so the resolution summary is never- * captured cleanly (the bug this repairs). CLI/API read-only agents complete on+ * that ingests the run summary. Without it a read-only TUI run relies on shell+ * exit or the runtime ceiling, so the resolution summary is not captured+ * cleanly (the bug this repairs). CLI/API read-only agents complete on* process exit and never poll a sentinel, so they get the bare notice only.*/export function buildReadOnlyCompletionSection({ isTui = false, sentinelPath = null } = {}) {@@ -1346,7 +1346,7 @@ export function buildReadOnlyCompletionSection({ isTui = false, sentinelPath = n* nothing to commit or push, and telling the agent to run `/do:push` just makes it* load that skill for no reason (and can contradict the task prompt's own* "on a 200 your task is complete"). A TUI agent still writes a `.agent-done`- * sentinel so the 2s poll finalizes it promptly instead of waiting on the idle+ * sentinel so the 2s poll finalizes it promptly instead of waiting for a runtime* reaper.*/export function buildActionOutputCompletionSection({ isTui = false, sentinelPath = null } = {}) {@@ -2496,7 +2496,7 @@ function buildInlineReviewLoopSection({}) {// Where control goes after the merge. A TUI run still owes PortOS its// `.agent-done` sentinel — telling it to "exit" here is how a finished merge- // idles into a false timeout — while a CLI run signals completion by exiting.+ // can otherwise sit without recording completion — while a CLI run signals completion by exiting.const inlineExitStep = writesSentinel? 'Return to the **Completion Workflow** above and write the completion sentinel — the run is not done until you have. Do NOT open a second PR.': 'You are done — exit. Do NOT open a second PR or push anything further.';diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 469806fd59..be93fffe98 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -13,10 +13,9 @@ import * as shellService from './shell.js';import { emitLog } from './cosEvents.js';import { updateAgent } from './cosAgentLifecycle.js';import { createOutputSpooler } from './agentTuiSpawning/outputSpooler.js';-import { captureWorktreeDiff, worktreeHasWorkEvidence, resolveErrorAnalysis } from './agentTuiSpawning/finalizeHelpers.js';+import { captureWorktreeDiff, resolveErrorAnalysis } from './agentTuiSpawning/finalizeHelpers.js';import { finalizeAgent, releaseAgentLane } from './agentFinalization.js';-import { activeAgents, userTerminatedAgents, pausedAgents, isFalsyMeta, registerSpawnedAgent, unregisterSpawnedAgent } from './agentState.js';-import { isProgrammaticIoTaskType, resolveTaskHookType } from './taskTypeHooks.js';+import { activeAgents, userTerminatedAgents, pausedAgents, registerSpawnedAgent, unregisterSpawnedAgent } from './agentState.js';import { PATHS } from '../lib/fileUtils.js';import { doneSentinelName, doneSentinelPath as resolveDoneSentinelPath, parseSentinelPayload } from '../lib/agentSentinel.js';import { shouldAbandonForHostShutdown, HOST_SHUTDOWN_REASON } from '../lib/hostShutdown.js';@@ -32,34 +31,22 @@ import { shellQuote } from '../lib/shellQuote.js';import { isClaudeCommand, applyLeanClaudeArgs, providerSuppliesGithubToken } from '../lib/providerModels.js';import { createStreamingAnsiStripper, stripAnsi } from '../lib/ansiStrip.js';import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetection.js';-import { isMachineOnline } from '../lib/connectivity.js';import { isAntigravityCommand } from '../lib/antigravity.js';-import { detectForgeCli } from '../lib/gitForge.js';import {DEFAULT_TUI_PROMPT_DELAY_MS,- DEFAULT_TUI_IDLE_TIMEOUT_MS,DEFAULT_TUI_MAX_RUNTIME_MS,MAX_RUNTIME_WRAP_UP_GRACE_MS,buildWrapUpProdMessage,- MERGE_QUEUE_IDLE_TIMEOUT_MS,- REVIEW_LOOP_IDLE_TIMEOUT_MS,- BACKGROUND_SHELL_IDLE_TIMEOUT_MS,- decideIdleReap,READY_POLL_INTERVAL_MS,READY_IDLE_THRESHOLD_MS,PASTE_MARKER_POLL_MS,countPasteMarkers,- createWorkActivityTracker,createSelfClearingSignalGate,- createMergeQueueTracker,- createReviewLoopTracker,- createBackgroundShellTracker,createMcpBootTracker,MCP_BOOT_PASTE_DEADLINE_MS,MCP_BOOT_PASTE_RETRY_DELAY_MS,createInputReadyTracker,AGY_INPUT_READY_PATTERN,- rendersWorkCounter,PASTE_TO_ENTER_MIN_DELAY_MS,PASTE_TO_ENTER_FALLBACK_MS,scheduleSubmitEnters,@@ -83,48 +70,17 @@ import { execFile } from '../lib/childProcess.js';// Agent-specific timing/lifecycle constants (not shared with the one-shot// runner — agents stay alive much longer and write a sentinel file when done).-const DEFAULT_TUI_MIN_RUNTIME_MS = 15000;-// Grace window after the last input written to the session (human paste via-// the Shell page, or our own auto-paste) before the idle reaper is allowed to-// fire again. Covers a large bracketed paste sitting in a silent reflow/commit-// window with no PTY output yet — comfortably above the paste-to-enter-// handshake windows in tuiHandshake.js (PASTE_DEADLINE_MS=10s) without-// meaningfully weakening the idle-reap protection once input truly stops.-const PASTE_INPUT_GRACE_MS = 15000;--// Connectivity gate for the idle reaper. When the machine loses internet, a-// live TUI goes silent (it can't reach the model) in a way that's-// indistinguishable from a hung or finished agent to the idle timer — so an-// outage would reap an agent that's only blocked on the network. We keep a-// cheap reachability reading fresh only in the LEAD window right before the-// idle deadline and DEFER the reap while offline. `RECHECK_MS` throttles probes-// to at most one per interval; `LEAD_MS` is how far before the (possibly-// extended) reap deadline probing begins — so a healthy, chatty agent is never-// probed and a drifting one has a confirmed reading in hand at its reap tick,-// without probing for the whole window. This does NOT weaken the hung-agent-// safety net: a stuck agent on a healthy connection still reaps on schedule,-// and the max-runtime backstop still bounds an agent kept alive through a long-// outage.-const CONNECTIVITY_RECHECK_MS = 10000;-const CONNECTIVITY_PROBE_LEAD_MS = 20000;--// Throttle for the PR-follow-up deliverable check (see refreshFollowUpPrState).-// Far slacker than the connectivity probe because it shells out to `gh` over the-// network and the answer it is waiting for — "the PR flipped to MERGED" — only-// ever changes once per run. Polling starts only after the session has already-// been silent for its BASE idle window, so a busy follow-up never hits the forge.-const PR_STATE_RECHECK_MS = 30000;+const PROVIDER_SIGNAL_POLL_MS = 5000;// Output buffering/spooling (createOutputSpooler) and failure-analysis /-// worktree-inspection helpers (readFileTail, worktreeHasChanges, commitsSince,-// worktreeHasWorkEvidence, captureWorktreeDiff, resolveErrorAnalysis,+// worktree-inspection helpers (captureWorktreeDiff, resolveErrorAnalysis,// RAW_TAIL_ANALYSIS_BYTES) live in// ./agentTuiSpawning/ so spawnTuiAgent stays a thin orchestrator.// Sentinel-file polling. TUI agents write `.agent-done` in their workspace// when they've finished /simplify + /do:pr (or /do:push) — we poll for it// here so the agent gets cleanly finalized as soon as the work is done,-// without waiting on the much longer idle timeout fallback.+// without waiting for a runtime ceiling or a shell exit.// The filename is per agent instance — see doneSentinelName in ../lib/agentSentinel.js.const DONE_POLL_INTERVAL_MS = 2000;@@ -240,12 +196,6 @@ function shellHasLiveChild(shellPid) {});}-// Local-runtime models can spend many minutes between TUI output chunks while-// generating. Their separate max-runtime ceiling still bounds a genuinely stuck-// session, but silence must not be treated as completion or failure.-const isLocalModelProvider = (provider) =>- isOllamaBackedProvider(provider) || provider?.mtplxBacked === true;-export function buildTuiSpawnConfig(provider, model, { systemPromptFile = null, effort = null } = {}) {const command = provider?.command || inferTuiCommand(provider?.id);const baseArgs = applyCommandDefaults(command, [...(provider?.args || [])]);@@ -267,9 +217,6 @@ export function buildTuiSpawnConfig(provider, model, { systemPromptFile = null,args,commandLine: [command, ...args].map(shellQuote).join(' '),promptDelayMs: provider?.tuiPromptDelayMs || DEFAULT_TUI_PROMPT_DELAY_MS,- idleTimeoutMs: isLocalModelProvider(provider)- ? null- : provider?.tuiIdleTimeoutMs || DEFAULT_TUI_IDLE_TIMEOUT_MS,maxRuntimeMs: provider?.tuiMaxRuntimeMs || DEFAULT_TUI_MAX_RUNTIME_MS};}@@ -285,9 +232,9 @@ export function buildTuiSpawnConfig(provider, model, { systemPromptFile = null,//// `isFinalized`/`markPromptSent`/`markPromptSubmitted` are accessors into// spawnTuiAgent's own `finalized`/`promptSentAt`/`promptSubmittedAt` — those-// are read by handleData and the idle reaper well outside this cluster, so-// they stay owned by spawnTuiAgent and are threaded through rather than-// duplicated here. `finish`/`finishStartupFailure`/`appendLine`/+// are read by handleData and the provider-signal timer well outside this+// cluster, so they stay owned by spawnTuiAgent and are threaded through rather+// than duplicated here. `finish`/`finishStartupFailure`/`appendLine`/// `sentinelPresent` are likewise spawnTuiAgent's own closures, passed in// rather than re-implemented.function createPasteRetryController({@@ -331,9 +278,7 @@ function createPasteRetryController({let pasteVerifyTimer = null;let submitEnterTimer = null;// Absolute wall-clock backstop — armed once the prompt is SUBMITTED, cleared- // by cancel(). Unlike the idle reaper (which resets on every PTY repaint and- // so never fires for a busy-but-stuck agent whose working counter keeps- // ticking), this bounds the total run so a hung provider/CLI can't run+ // by cancel(). This bounds the total run so a hung provider/CLI can't run// unbounded. See DEFAULT_TUI_MAX_RUNTIME_MS for the incident.let maxRuntimeTimer = null;// Deadline for the wrap-up grace window the max-runtime ceiling opens instead of@@ -388,8 +333,8 @@ function createPasteRetryController({// Reap the run as a max-runtime failure. Shared by the wrap-up grace window's// expiry and its own "session already died" branch so both produce the same// record: uncommitted work captured for post-mortem, then a- // needs-manual-finish error (same recovery guidance as the merge-queue /- // review-loop idle-timeout paths — a stuck orchestrator may have left+ // needs-manual-finish error (the same recovery guidance as any stalled+ // orchestrator — it may have left// PRs/worktrees behind).const finishMaxRuntimeFailure = (detail, reason = 'max-runtime-timeout') => {captureWorktreeDiff(cwd, agentDir).catch(() => {});@@ -416,7 +361,7 @@ function createPasteRetryController({const startWrapUpGrace = () => {if (isFinalized() || wrapUpTimer) return;// A dead session can't be prodded — nothing will ever write the sentinel, so- // skip the grace window entirely rather than idling out the full 5min.+ // skip the grace window rather than waiting out the full 5min.if (!sessionId || !shellService.getSession(sessionId)) {finishMaxRuntimeFailure('the TUI session was already gone, so it could not be asked to wrap up;');return;@@ -453,7 +398,7 @@ function createPasteRetryController({// Let the sentinel path finalize it as the success it is.if (sentinelPresent()) return;finishMaxRuntimeFailure(- `it did not wrap up within ${graceMin}min of being asked, so the provider/CLI likely hung (a stalled request keeps the working counter repainting so the idle reaper never fires);`,+ `it did not wrap up within ${graceMin}min of being asked, so the provider/CLI likely hung (the wall-clock ceiling is the remaining backstop);`,'max-runtime-no-wrap-up',);} catch (err) {@@ -513,24 +458,22 @@ function createPasteRetryController({// prompt unsent (the "I had to hit Enter myself" bug). Tracked in// submitEnterTimer so cancel() can cancel pending retries if the agent ends.const submitEnter = () => {- // Mark submission so work-activity observation begins only now — after the- // Enter is written, past the prompt-echo window (issue #1229 review).+ // Record submission once the Enter is written, after the prompt-echo+ // window (issue #1229 review).markPromptSubmitted();submitEnterTimer = scheduleSubmitEnters(() => shellService.writeToSession(sessionId, '\r'),() => isFinalized());// Arm the absolute wall-clock backstop from submission (once — a paste- // retry re-enters submitEnter but must not stack timers). The idle reaper- // can't bound a busy-but-stuck agent because Claude Code's working counter- // keeps repainting through a stalled provider retry, resetting lastOutputAt- // forever; this timer is the honest ceiling regardless of PTY chatter.+ // retry re-enters submitEnter but must not stack timers). This timer is+ // the ceiling regardless of how much or how little PTY output arrives.if (!maxRuntimeTimer) {maxRuntimeTimer = setTimeout(() => {try {if (isFinalized()) return;// Salvage net: if the agent already wrote its .agent-done sentinel the- // run truly finished (the TUI just never idled/exited), so complete as+ // run truly finished (the TUI just never wrote the sentinel/exited), so complete as// success — mirrors the one-shot runner's response-file salvage. The// 2s doneSentinelTimer normally catches this first; this covers the// boundary where it lands right at the deadline.@@ -707,7 +650,6 @@ export async function spawnTuiAgent({isTruthyMetaFn,leanMode = false,useDurableRunner = false,- checkOnlineFn = isMachineOnline,}) {const outputFile = join(agentDir, 'output.txt');// Raw PTY bytes spool to disk continuously rather than accumulate in-memory.@@ -724,25 +666,19 @@ export async function spawnTuiAgent({// the sentinel watcher below) and then stops — it does NOT run `/quit` (that// is a UI command the agent can't invoke). The 2s poll is the primary// finalize path; finish() also ingests the sentinel directly so the summary- // is captured even if some other path (idle/exit) finalizes first. Computed+ // is captured even if some other path (shell exit/max-runtime) finalizes first. Computed// up front so both the watcher AND finish() can read it (see ingestDoneSentinel).// Resolved from the shared helper, so this is byte-identical to the path the// prompt told the agent to write (see resolveSentinelPath).const doneSentinelPath = resolveDoneSentinelPath(workspacePath, agentId);const promptPreview = prompt.replace(/\s+/g, ' ').slice(0, 100);const commandName = tuiConfig.command.split('/').pop();- // Derive this again at the enforcement point so a caller that supplied a- // stale/pre-built config cannot accidentally re-arm the idle reaper for a- // local model.- const idleTimeoutMs = isLocalModelProvider(provider) ? null : tuiConfig.idleTimeoutMs;-let finalized = false;let immediateFallbackAnalysis = null;const detectImmediateFallbackSignal = createImmediateFallbackSignalDetector();// Holds the wait-it-out window for a provider signal carrying a `graceMs`- // (agy's account-eligibility banner). The idle timer below both resolves its- // deadline, drives the re-submission cadence, and defers to `.armed` for idle- // suppression.+ // (agy's account-eligibility banner). The provider-signal timer below resolves+ // its deadline and drives the re-submission cadence.const selfClearingGate = createSelfClearingSignalGate();// Guards ingestDoneSentinel to a single read. finish() is its only caller and// is itself guarded by `finalized`, so this is defensive — it pins the@@ -750,43 +686,10 @@ export async function spawnTuiAgent({let sentinelIngested = false;let hasStartedWorking = false;let promptSentAt = null;- // When the submit-Enter is first written (NOT when the paste starts). Work-- // activity observation keys on this so the prompt ECHO — which renders during- // the paste→Enter window, before this is set — is never scanned for the working- // counter (issue #1229 review: a pasted transcript could otherwise echo counters- // that fake work before the prompt is actually submitted).+ // When the submit-Enter is first written (NOT when the paste starts). Provider+ // signal handling keys on this so a startup banner is not treated as a signal+ // from a submitted prompt.let promptSubmittedAt = null;- // Tracks evidence the model is actively processing the SUBMITTED prompt — the- // TUI's elapsed working counter advancing through ≥2 distinct values (see- // createWorkActivityTracker; echo-proof, unlike word-matching the prompt text).- // Distinct from `hasStartedWorking`, which flips on ANY post-spawn PTY output- // including pure banner/status-line chrome. `tracker.active` is what gates the- // fallback idle-complete path from finalizing a never-submitted prompt as- // success (issue #1229).- const workActivity = createWorkActivityTracker();- // Latches once the agent enters a `/do:next --swarm` Phase C serialized merge- // queue, whose per-PR CI re-runs produce minutes of silent output. While- // latched, the idle reaper uses the extended MERGE_QUEUE_IDLE_TIMEOUT_MS so a- // still-working orchestrator isn't reaped mid-merge (issue #2074).- const mergeQueue = createMergeQueueTracker();- // Latches once the agent enters a do:release/do:pr/do:rpr multi-reviewer- // loop, whose external reviewer passes (codex reading a large diff, a- // Copilot cloud review, a human @<login> review) can go silent in the TUI- // for well over the default idle window. While latched, the idle reaper- // uses the extended REVIEW_LOOP_IDLE_TIMEOUT_MS so a still-waiting release- // 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@@ -830,80 +733,6 @@ export async function spawnTuiAgent({let lastOutputAt = Date.now();let sessionId = null;- // Idle-reaper connectivity gate (see CONNECTIVITY_* constants). `online`- // starts optimistically true so the happy path reaps on schedule without- // waiting on a probe; it only ever flips to false once a probe confirms an- // outage, at which point the idle reaper defers. Probing is started by the- // idle timer only in the LEAD window before the reap deadline (not the whole- // idle window), so a confirmed reading is in hand at the reap tick and a busy- // agent is never probed.- const connectivity = { online: true, checking: false, lastCheckAt: 0, loggedOffline: false };- const refreshConnectivity = () => {- if (connectivity.checking) return;- if (Date.now() - connectivity.lastCheckAt < CONNECTIVITY_RECHECK_MS) return;- connectivity.checking = true;- connectivity.lastCheckAt = Date.now();- Promise.resolve()- .then(() => checkOnlineFn())- .then((online) => {- if (finalized) return;- // A probe that RESOLVES `false` is the only thing that flips us offline;- // any other resolved value maps to online. A probe that THROWS is- // swallowed by the `.catch` below and leaves the last reading untouched- // — a failed-to-run probe is never proof of an outage by itself.- const nowOnline = online !== false;- // Reconnect grace: on the offline→online transition, give the CLI a- // fresh idle window to notice the network is back and resume before the- // reaper can fire — otherwise we'd reap in the gap before it repaints.- if (nowOnline && connectivity.online === false) lastOutputAt = Date.now();- connectivity.online = nowOnline;- })- .catch(() => {})- .finally(() => { connectivity.checking = false; });- };-- // PR-follow-up deliverable gate. A follow-up run spawned by- // `spawnReviewLoopFollowUp` exists to land ONE pull request — it makes no- // commit, is told to "Exit" when the PR reads MERGED, and (on Antigravity,- // which routinely skips the sentinel) then just sits at its prompt. Every- // signal the idle reaper otherwise has is a proxy that gets this run WRONG:- // its prompt quotes `gh pr checks` / `gh pr merge` / `--delete-branch`, so the- // TUI's echo latches the merge-queue tracker before any work happens, and the- // finished run is reaped 15 minutes later as `merge-queue-idle-timeout` — a- // needs-manual-finish FAILURE naming a PR that is already merged, retried to- // `Max retries exceeded` and a HIGH orphaned-PR notification (sys-rl-msr1j1a5- // / PR #3909, 2026-08-13). So ask the forge the actual question instead.- //- // `merged` starts false and only a `known` MERGED answer flips it: a gh we- // could not run (firewalled, offline) is NOT evidence of anything and must- // leave the pre-existing verdicts untouched. GitHub only — `gh pr view`- // against a GitLab MR or an unresolved host answers nothing, so those follow-ups keep prior behavior.- const prFollowUpRef = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp)- && detectForgeCli(task.metadata?.reviewLoopPRHost) === 'gh'- ? (task.metadata?.reviewLoopPRUrl || task.metadata?.reviewLoopPRNumber || null)- : null;- const followUpPr = { merged: false, checking: false, lastCheckAt: 0 };- const refreshFollowUpPrState = () => {- if (!prFollowUpRef || followUpPr.merged || followUpPr.checking) return;- if (Date.now() - followUpPr.lastCheckAt < PR_STATE_RECHECK_MS) return;- followUpPr.checking = true;- followUpPr.lastCheckAt = Date.now();- // Dynamic import, matching agentFinalization's forge-lookup call site: it- // keeps `github.js` (and its settings/data-file dependencies) out of the- // module graph of every suite that mocks this spawner.- import('./github.js')- .then(({ getPullRequestState }) => getPullRequestState(prFollowUpRef, { cwd }))- .then((res) => {- if (finalized) return;- if (res?.status === 'known' && res.state === 'MERGED') {- followUpPr.merged = true;- emitLog('info', `TUI agent ${agentId} follow-up PR reads MERGED — finalizing on the deliverable rather than the idle window`, { agentId });- }- })- .catch(() => {})- .finally(() => { followUpPr.checking = false; });- };-// The paste-attempt / max-runtime / wrap-up-grace machinery (postPasteBuffer,// pasteEnterTimer, pasteVerifyTimer, submitEnterTimer, maxRuntimeTimer,// wrapUpTimer) lives in createPasteRetryController rather than this closure@@ -971,7 +800,7 @@ export async function spawnTuiAgent({*/const stopRunMachinery = () => {const agentData = activeAgents.get(agentId);- if (agentData?.idleTimer) clearInterval(agentData.idleTimer);+ if (agentData?.providerSignalTimer) clearInterval(agentData.providerSignalTimer);if (agentData?.promptTimer) clearInterval(agentData.promptTimer);if (agentData?.doneSentinelTimer) clearInterval(agentData.doneSentinelTimer);// Cancels the paste-attempt/max-runtime/wrap-up timers and releases the@@ -987,7 +816,7 @@ export async function spawnTuiAgent({const finish = async ({ success, exitCode = 0, error = null, reason = 'completed' }) => {if (finalized) return;// PortOS is going down. Whatever path got here — the PTY exiting under- // TreeKill, the idle reaper, a paste that failed because the shell died —+ // TreeKill, a provider-signal failure, a paste that failed because the shell died —// the cause is the host restart, not the agent, so there is no outcome to// record. Abandoning instead of finalizing is what keeps an interrupted run// from being written down as completed AND keeps its worktree (which@@ -1017,7 +846,7 @@ export async function spawnTuiAgent({// agent. The completion workflow writes the sentinel and stops; the 2s// doneSentinelTimer poll is what normally calls finish(). Reading it here// (not just in the poll) keeps the resolution captured even when a- // different path (idle-complete, shell-exit) finalizes first. Idempotent+ // different path (shell-exit, max-runtime) finalizes first. Idempotent// via `sentinelIngested`.await ingestDoneSentinel();@@ -1193,7 +1022,7 @@ export async function spawnTuiAgent({* agent named in it, and requeues the task as *interrupted* — resumable, and* without charging it orphan-retry budget.*- * Sets `finalized` so every other path (idle reaper, sentinel poll, paste+ * Sets `finalized` so every other path (provider-signal timer, sentinel poll, paste* retry) becomes a no-op for the rest of this process's life.*/const abandonForHostShutdown = async () => {@@ -1311,37 +1140,6 @@ export async function spawnTuiAgent({// still latches — the swallowed paste never sets promptSubmittedAt.if (isCodexSession && !promptSubmittedAt && stripped && !mcpBoot.active) mcpBoot.observe(stripped);const now = Date.now();- // Once the prompt is SUBMITTED (Enter sent — not merely pasted), watch for- // proof the model is actually working. Keying on promptSubmittedAt (not- // promptSentAt) excludes the prompt echo rendered during the paste→Enter- // window. The TUI repaints chrome continuously even with an unsent prompt,- // so we can't trust mere PTY activity — only the working counter advancing- // across wall-clock time confirms real work (a static echo's counters all- // arrive together and fail the time-span). Gates idle-complete (#1229).- if (promptSubmittedAt && stripped && !workActivity.active) workActivity.observe(stripped, now);- // Detect entry into the swarm Phase C merge queue so the idle reaper can- // extend its grace window across the silent per-PR CI waits (issue #2074).- // Latches once — observe only until active, then announce the transition.- if (promptSubmittedAt && stripped && !mergeQueue.active && mergeQueue.observe(stripped)) {- emitLog('info', `TUI agent ${agentId} entered merge queue — idle reaper extended to ${Math.round(MERGE_QUEUE_IDLE_TIMEOUT_MS / 60000)}min`, { agentId, phase: 'merge-queue' });- await updateAgent(agentId, { metadata: { phase: 'merge-queue' } });- }- // Detect entry into a do:release/do:pr/do:rpr multi-reviewer loop so the- // idle reaper can extend its grace across a slow reviewer's silent- // working stretch (see reviewLoop declaration above for the incident).- if (promptSubmittedAt && stripped && !reviewLoop.active && reviewLoop.observe(stripped)) {- 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;@@ -1545,8 +1343,8 @@ export async function spawnTuiAgent({// createPasteRetryController's own comment for why that cluster lives// outside this closure. `isFinalized`/`markPromptSent`/`markPromptSubmitted`// are accessors into THIS closure's `finalized`/`promptSentAt`/- // `promptSubmittedAt`, which handleData and the idle reaper below still read- // directly.+ // `promptSubmittedAt`, which handleData and the provider-signal timer below+ // still read directly.pasteController = createPasteRetryController({agentId,sessionId,@@ -1568,11 +1366,11 @@ export async function spawnTuiAgent({// Claude Code renders a startup banner and (in unfamiliar folders) a// folder-trust gate before its input box exists, and the old "saw output then- // went idle" heuristic fired during those lulls — pasting the prompt into the+ // went quiet" heuristic fired during those lulls — pasting the prompt into the// banner / trust menu / a returned shell. For claude we instead gate on its// POSITIVE input-ready footer (see createInputReadyTracker), auto-confirm the// trust gate, and NEVER blind-paste: if the prompt never appears we surface a- // failure. Other TUI providers keep the original idle heuristic + deadline.+ // failure. Other TUI providers keep the original startup readiness deadline.//// Antigravity (agy) gets the SAME positive gate (issue #2705), but agy alone// needs a second signal on top of paste mode: unlike claude it enables@@ -1588,7 +1386,7 @@ export async function spawnTuiAgent({// branch below is load-bearing, matching its "Yes, I trust this folder" option// via TUI_TRUST_PROMPT_PATTERN. If agy ever fails to signal ready, the// requireInputReady path fails fast with a surfaced startup error instead of- // silently idle-reaping.+ // silently failing at startup.const requireInputReady = isClaudeCommand(tuiConfig.command) || isAntigravityCommand(tuiConfig.command);// sendPrompt / finishStartupFailure are async and dispatched fire-and-forget// from the interval below. A setInterval callback can't await, and an@@ -1661,11 +1459,10 @@ export async function spawnTuiAgent({clearInterval(promptTimer);}, READY_POLL_INTERVAL_MS);- const idleTimer = setInterval(() => {+ // Provider-handshake retry timer. It is deliberately not an idle watchdog:+ // a CoS TUI may remain silent for as long as the provider needs.+ const providerSignalTimer = setInterval(() => {if (finalized) return;- // Resolve an expired grace window. Checked BEFORE the promptSentAt gate- // below: the banner can paint during startup too, and a run stalled there- // would otherwise hold the window forever.const expired = selfClearingGate.takeExpired(Date.now());if (expired) {// setInterval can't await, and an unhandled rejection here would crash the@@ -1674,229 +1471,8 @@ export async function spawnTuiAgent({emitLog('error', `TUI agent ${agentId} deferred fallback finish failed: ${err?.message || err}`, { agentId }));return;}- // A session waiting out a provider handshake is silent by definition — but it- // is NOT idle, and letting the reaper finalize it would be far worse than the- // premature kill this window replaced: with no `.agent-done` sentinel the- // idle path reports `idle-complete` SUCCESS for a run that never produced a- // token. Safely bounded — the window carries its own deadline, resolved just- // above, which fires strictly before any idle window it outlasts.- //- // The wait is ACTIVE: re-send the prompt on the gate's cadence, because the- // banner is the provider REJECTING this submission (see resubmitAfterSignal).- if (selfClearingGate.armed) {- resubmitAfterSignal();- return;- }- if (!promptSentAt) return;- // Don't reap a session that just received real input — a human pasting- // into the Shell page, or our own auto-paste. A big bracketed paste can- // sit in a silent reflow/commit window with no PTY output yet, which- // looks identical to "idle" to this timer otherwise (same class of bug- // as #2074/#2084, but for a live paste instead of a merge-queue/- // review-loop wait). Gated on INPUT RECENCY, not "is a socket attached" —- // a regular (non-external) Shell session keeps its socket bound after the- // viewer navigates away (only external one-shot runs get released via- // `shell:release-views`), so "attached" would permanently suppress- // idle-complete for any agent glanced at once in the Shell UI. Recency- // naturally expires once nobody is actually interacting.- if (sessionId) {- const lastInputAt = shellService.getLastInputAt(sessionId);- if (lastInputAt && Date.now() - lastInputAt < PASTE_INPUT_GRACE_MS) return;- }- const runtime = Date.now() - promptSentAt;- const idle = Date.now() - lastOutputAt;- if (runtime < DEFAULT_TUI_MIN_RUNTIME_MS) return;- // We track post-paste activity via lastOutputAt instead of parsed-line- // counts because per-line PTY capture is intentionally disabled for TUI- // agents — see handleData.- if (lastOutputAt <= promptSentAt) return;- // While the agent is in a swarm Phase C serialized merge queue, per-PR CI- // re-runs go silent for minutes at a time; extend the idle grace so a- // still-working orchestrator isn't reaped mid-merge (issue #2074). The- // extended window still bounds a genuinely-dead orchestrator's reap.- // Which verdict this tick warrants — the whole branch matrix, as a pure- // function so it can be unit-tested against the real implementation instead- // of a drifting inline copy. This body just executes what it returns.- const decision = decideIdleReap({- idle,- baseIdleTimeoutMs: idleTimeoutMs,- mergeQueueActive: mergeQueue.active,- reviewLoopActive: reviewLoop.active,- backgroundShellActive: backgroundShell.active,- prFollowUpMerged: followUpPr.merged,- workActive: workActivity.active,- rendersCounter: rendersWorkCounter(commandName),- });- const { effectiveIdleTimeoutMs } = decision;- // Past the BASE idle window a PR follow-up asks the forge whether its one- // deliverable already landed (throttled, non-blocking — the reading is read- // synchronously by the NEXT tick's decision). Keyed on the base window, not- // the extended one, precisely because the extended one is the bug: a merge- // follow-up latches the merge-queue grace off its own echoed prompt.- if (Number.isFinite(idleTimeoutMs) && idle >= idleTimeoutMs) refreshFollowUpPrState();- // 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- // because the machine lost internet. Gating on the effective deadline (not a- // fixed lead off the base window) keeps a long merge-queue/review-loop idle- // from probing for its whole 15-min window.- if (idle >= effectiveIdleTimeoutMs - CONNECTIVITY_PROBE_LEAD_MS) refreshConnectivity();- if (decision.action === 'reap') {- // The follow-up's PR is MERGED and the session has gone quiet: the- // deliverable is provably in hand, so finalize on it. Deliberately ahead- // of the offline defer below — that gate exists because silence is- // ambiguous, and this verdict does not rest on silence.- if (decision.reason === 'pr-follow-up-merged') {- finish({ success: true, exitCode: 0, reason: 'pr-follow-up-merged' }).catch(err => {- emitLog('error', `Failed to finalize TUI agent ${agentId}: ${err.message}`, { agentId });- });- return;- }- // An internet outage silences a live TUI exactly like a hung or finished- // agent looks to this timer. If a recent probe says we're offline, DEFER- // the reap — the agent is only blocked on the network and resumes when it- // returns. (The max-runtime backstop still bounds a very long outage.)- if (!connectivity.online) {- if (!connectivity.loggedOffline) {- emitLog('info', `📡 TUI agent ${agentId} idle past its window but the machine appears offline — deferring reap until connectivity returns`, { agentId });- connectivity.loggedOffline = true;- }- return;- }- connectivity.loggedOffline = false;- // Reaped AFTER the extended merge-queue grace elapsed: the orchestrator- // almost certainly died mid-merge with PRs opened/merged-but-uncleaned.- // Surface it as a needs-manual-finish FAILURE rather than the silent- // `status: completed` that hid the half-done merge queue (issue #2074).- if (decision.reason === 'merge-queue-idle-timeout') {- finish({- success: false,- exitCode: 1,- error: `TUI agent idled out after ${Math.round(effectiveIdleTimeoutMs / 60000)}min in the merge queue — it likely died mid-merge; check for open or merged-but-uncleaned PRs and finish them manually.`,- reason: 'merge-queue-idle-timeout',- }).catch(err => {- emitLog('error', `Failed to finalize TUI agent ${agentId}: ${err.message}`, { agentId });- });- return;- }- // Reaped AFTER the extended review-loop grace elapsed: a reviewer- // (copilot/codex/agy/claude/ollama/@<login>) likely hung, or the wait- // simply exceeded budget. Surface it as a needs-manual-finish FAILURE- // rather than the silent `status: completed` that let PR #2084 sit- // open+unmerged for hours while agent-61508f36 looked "done".- if (decision.reason === 'review-loop-idle-timeout') {- finish({- success: false,- exitCode: 1,- error: `TUI agent idled out after ${Math.round(effectiveIdleTimeoutMs / 60000)}min waiting inside the multi-reviewer loop — a reviewer may have hung or the wait exceeded budget; check the PR's review/merge state and finish manually.`,- reason: 'review-loop-idle-timeout',- }).catch(err => {- emitLog('error', `Failed to finalize TUI agent ${agentId}: ${err.message}`, { agentId });- });- return;- }- // Distinguish a real (sentinel-less) completion from a never-submitted- // prompt that just idled out. `lastOutputAt > promptSentAt` only proves- // the TUI repainted SOMETHING — banner/status chrome churns even with the- // prompt sitting unsent. The #1229 failure mode (prompt never submitted,- // zero work done) must be recorded as a FAILURE so the orchestrator doesn't- // treat a no-op run as done — but the work-counter signal exists ONLY on- // Claude Code / Codex. On a provider that never renders the counter- // (Antigravity/Gemini), its absence proves nothing, so we must preserve the- // original permissive idle-complete=success there (else every sentinel-less- // completion on those providers would falsely fail). So: downgrade to- // failure only when the provider DOES render the counter and we never saw- // it advance.- //- // Issue #2191 extension: even when workActivity.active is true, the model- // may have "worked" (made tool calls, printed output) without actually- // writing any files — e.g. rambled, made invalid tool calls, or hit an- // error. Check the worktree for evidence of actual changes: if the- // worktree is clean (no git status changes), mark as failed so the- // orchestrator doesn't treat a no-op as done. Capture the diff into the- // agent archive dir before cleanup so post-mortems can see what (if- // anything) was left behind.- if (decision.reason === 'idle-no-activity') {- // Capture any uncommitted changes for post-mortem analysis- captureWorktreeDiff(cwd, agentDir).catch(() => {});- finish({- success: false,- exitCode: 1,- error: 'TUI agent idled out with no sign of work — the prompt likely never submitted (no working indicator ever appeared after submit).',- reason: 'idle-no-activity',- }).catch(err => {- emitLog('error', `Failed to finalize TUI agent ${agentId}: ${err.message}`, { agentId });- });- } else {- // Gate idle-complete success on evidence of work in the worktree.- // An agent that shows activity counters but makes no file changes- // (rambled, invalid tool calls, hit an error) should fail, not succeed.- //- // "Evidence of work" is a dirty tree OR a commit made during the run,- // not a dirty tree alone — see worktreeHasWorkEvidence for why.- //- // ...UNLESS the task declares its work product isn't files (#3102).- // `worktreeChangesExpected: false` marks a task type whose deliverable- // lands OUTSIDE the repo — a reference-watch run against a GitHub/GitLab/- // JIRA work tracker files issues and, per its prompt, edits no application- // code, so a clean tree is the SUCCESS shape and this gate would fail a run- // that did its whole job. Absent/`true` keeps every code-editing task type- // on today's behavior; the `workActivity.active` signal above still- // distinguishes "prompt never submitted" → idle-no-activity either way.- const worktreeChangesExpected = !isFalsyMeta(task?.metadata?.worktreeChangesExpected);- // A PROGRAMMATIC-I/O run answers a DIFFERENT question, not a relaxed- // version of this one. Its deliverable is the structured `.agent-done`- // payload an output hook consumes — a layered-intelligence run reasons- // over the app's goals and returns JSON that a deterministic step files as- // one tracker issue — and its prompt FORBIDS touching the repo, so- // worktree evidence measures nothing about it. Asking anyway blamed the- // run for exactly the thing it was told not to do ("zero file changes"),- // while the honest question is right there: did the payload land?- // Usually it hasn't — the sentinel watcher below finalizes within- // DONE_POLL_INTERVAL_MS of `.agent-done` appearing, so a run that reached- // the reaper is normally one whose payload never materialized (the model- // printed its JSON into the TUI instead of writing the file, #3640).- // `sentinelPresent()` and not `false` because the two timers CAN land on- // the same tick, and this one is registered first: an agent that wrote its- // sentinel in the last idle window would otherwise be failed for a clean- // tree by the interval that happened to run before the watcher.- //- // Deliberately NOT folded into `worktreeChangesExpected`: exempting it- // from the gate would score that same run a PASS with no proposal filed,- // trading a misleading failure for a silent one.- const programmaticIo = isProgrammaticIoTaskType(resolveTaskHookType(task));- (async () => {- const delivered = programmaticIo- ? sentinelPresent()- : !worktreeChangesExpected || await worktreeHasWorkEvidence(cwd, startedAt);- // Capture any uncommitted changes for post-mortem analysis regardless- // of outcome — the diff is useful even on success for debugging, and is- // a no-op on a clean tree.- await captureWorktreeDiff(cwd, agentDir).catch(() => {});- if (!delivered) {- finish({- success: false,- exitCode: 1,- error: programmaticIo- ? 'TUI agent idled out without writing its .agent-done payload — this task type delivers structured output, not file changes, and nothing was left for the output hook to consume.'- : 'TUI agent idled out with zero uncommitted file changes and no new commits — the model may have processed but produced no work.',- reason: programmaticIo ? 'idle-no-deliverable' : 'idle-no-changes',- }).catch(err => {- emitLog('error', `Failed to finalize TUI agent ${agentId}: ${err.message}`, { agentId });- });- } else {- finish({ success: true, exitCode: 0, reason: 'idle-complete' }).catch(err => {- emitLog('error', `Failed to finalize TUI agent ${agentId}: ${err.message}`, { agentId });- });- }- })().catch(err => {- emitLog('error', `TUI agent ${agentId} idle-complete check failed: ${err.message}`, { agentId });- // Fall back to success if the check itself failed (don't block on git)- finish({ success: true, exitCode: 0, reason: 'idle-complete' }).catch(() => {});- });- }- }- }, 5000);+ if (selfClearingGate.armed) resubmitAfterSignal();+ }, PROVIDER_SIGNAL_POLL_MS);// Sentinel-file watcher. The agent's prompt instructs it to write// .agent-done in the workspace after running /simplify + /do:pr and then@@ -1905,8 +1481,8 @@ export async function spawnTuiAgent({// INTERVAL_MS of the sentinel appearing, and finish()'s own cleanup kills// the still-running TUI session. The actual sentinel READ happens in finish()// (via ingestDoneSentinel) so the resolution is captured no matter which path- // finalizes. Idle-complete is the fallback for a non-complying agent that- // never writes the sentinel.+ // finalizes. A normal shell exit, explicit provider failure, or max-runtime+ // wrap-up handles agents that do not write the sentinel.const doneSentinelTimer = doneSentinelPath ? setInterval(() => {try {if (finalized) return;@@ -1930,7 +1506,7 @@ export async function spawnTuiAgent({executionId,laneName,tuiSessionId: sessionId,- idleTimer,+ providerSignalTimer,promptTimer,doneSentinelTimer});@@ -1948,7 +1524,6 @@ export async function spawnTuiAgent({tuiSessionId: sessionId,tuiCommand: tuiConfig.commandLine,tuiKind,- tuiIdleTimeoutMs: idleTimeoutMs,tuiMaxRuntimeMs: tuiConfig.maxRuntimeMs}});diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex 6b3a4f61da..eb1043fd09 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -11,7 +11,6 @@ vi.mock('./shell.js', () => ({killSession: vi.fn(),getSession: vi.fn(),getSessionProcess: vi.fn(),- getLastInputAt: vi.fn().mockReturnValue(null),registerExternalSession: vi.fn(),}));@@ -86,10 +85,8 @@ vi.mock('./codeReview.js', () => ({})}));-// Only the mutable registries are stubbed; the module's pure predicates-// (isFalsyMeta et al., which the worktreeChangesExpected opt-out reads through)-// come from the real module — it is import-free, so there is nothing to isolate,-// and a hand-written copy would silently drift from the real metadata coercion.+// Only the mutable registries are stubbed; the module's other state helpers+// come from the real module so the test does not duplicate their behavior.vi.mock('./agentState.js', async (importOriginal) => ({...await importOriginal(),activeAgents: new Map(),@@ -99,30 +96,8 @@ vi.mock('./agentState.js', async (importOriginal) => ({unregisterSpawnedAgent: vi.fn(),}));-// ONE execGit double behind BOTH entry points. The commit half of the-// work-evidence probe moved to `lib/gitCommitProbe.js` (#3637), which reaches-// `lib/execGit.js` directly rather than through `git.js`'s re-export — so mocking-// only `git.js` would leave the probe shelling out to real git. Sharing the spy-// keeps every `vi.mocked(gitService.execGit)` override in this file authoritative-// for the probe too.-const { execGitMock, getPullRequestStateMock } = vi.hoisted(() => ({- execGitMock: vi.fn(),- getPullRequestStateMock: vi.fn().mockResolvedValue({ status: 'known', state: 'OPEN' }),-}));-vi.mock('../lib/execGit.js', () => ({ execGit: execGitMock }));-vi.mock('./github.js', () => ({- getPullRequestState: (...args) => getPullRequestStateMock(...args),-}));-vi.mock('./git.js', () => ({- // Default: worktree has changes so idle-complete succeeds. Tests that want- // to exercise the idle-no-changes failure path override via mockResolvedValueOnce.- getStatus: vi.fn().mockResolvedValue({ clean: false, files: [{ path: 'file.txt', status: 'M' }] }),getDiff: vi.fn().mockResolvedValue('diff content here'),- // `git rev-list --count --since=…` for the commit half of the work-evidence- // probe. Default: zero commits during the run, so a clean tree still fails —- // the commit-and-push test overrides this to a non-zero count.- execGit: execGitMock,// No owner-matched gh account by default → empty overlay (ambient auth kept).resolveForgeTokenEnv: vi.fn().mockResolvedValue({}),}));@@ -236,10 +211,6 @@ import { activeAgents, userTerminatedAgents } from './agentState.js';import {MAX_RUNTIME_WRAP_UP_GRACE_MS,SELF_CLEARING_RESUBMIT_INTERVAL_MS,- MERGE_QUEUE_IDLE_TIMEOUT_MS,- REVIEW_LOOP_IDLE_TIMEOUT_MS,- BACKGROUND_SHELL_IDLE_TIMEOUT_MS,- decideIdleReap,} from '../lib/tuiHandshake.js';// Real module, not a mock: the flag is a plain process-local boolean, so driving// it directly exercises the same code path production does.@@ -346,7 +317,7 @@ describe('agent TUI spawning', () => {expect(config.args).toEqual(['--dangerously-skip-permissions']);});- it('quotes TUI arguments and carries idle timing config', () => {+ it('quotes TUI arguments and carries prompt/runtime timing config', () => {const config = buildTuiSpawnConfig({id: 'claude-code-tui',name: 'Claude TUI',@@ -354,7 +325,7 @@ describe('agent TUI spawning', () => {command: 'claude',args: ['--dangerously-skip-permissions', '--add-dir', '/tmp/with space'],tuiPromptDelayMs: 1000,- tuiIdleTimeoutMs: 30000+ tuiMaxRuntimeMs: 7200000}, 'claude-sonnet');expect(config.args).toEqual([@@ -366,7 +337,8 @@ describe('agent TUI spawning', () => {]);expect(config.commandLine).toBe("claude --dangerously-skip-permissions --add-dir '/tmp/with space' --model claude-sonnet");expect(config.promptDelayMs).toBe(1000);- expect(config.idleTimeoutMs).toBe(30000);+ expect(config.maxRuntimeMs).toBe(7200000);+ expect(config).not.toHaveProperty('idleTimeoutMs');});it('namespaces the Ollama model under ollama/ for an OpenCode TUI', () => {@@ -393,29 +365,21 @@ describe('agent TUI spawning', () => {expect(claudeConfig.command).toBe('claude');});- it('applies default prompt-delay and idle-timeout when the provider omits them', () => {+ it('applies default prompt delay and max runtime when the provider omits them', () => {const config = buildTuiSpawnConfig({ id: 'codex-tui', command: 'codex', type: 'tui' }, null);expect(config.promptDelayMs).toBe(2500);- expect(config.idleTimeoutMs).toBe(180000);+ expect(config.maxRuntimeMs).toBe(10800000);+ expect(config).not.toHaveProperty('idleTimeoutMs');});- it('disables idle reaping for local-runtime TUI providers', () => {- const ollama = buildTuiSpawnConfig({- id: 'claude-ollama-tui', type: 'tui', command: 'claude', ollamaBacked: true,- tuiIdleTimeoutMs: 30000,- }, 'qwen3:35b');- expect(ollama.idleTimeoutMs).toBeNull();-- const mtplx = buildTuiSpawnConfig({- id: 'opencode-mtplx-tui', type: 'tui', command: 'opencode', mtplxBacked: true,- tuiIdleTimeoutMs: 30000,- }, 'mtplx');- expect(mtplx.idleTimeoutMs).toBeNull();-- const cloud = buildTuiSpawnConfig({- id: 'codex-tui', type: 'tui', command: 'codex', tuiIdleTimeoutMs: 30000,- }, 'gpt-5.6-terra');- expect(cloud.idleTimeoutMs).toBe(30000);+ it('does not configure an idle timeout for any TUI provider', () => {+ for (const provider of [+ { id: 'claude-ollama-tui', type: 'tui', command: 'claude', ollamaBacked: true },+ { id: 'opencode-mtplx-tui', type: 'tui', command: 'opencode', mtplxBacked: true },+ { id: 'codex-tui', type: 'tui', command: 'codex' },+ ]) {+ expect(buildTuiSpawnConfig(provider, 'example-model')).not.toHaveProperty('idleTimeoutMs');+ }});it('omits the --model flag when model is null/empty', () => {@@ -516,9 +480,8 @@ describe('spawnTuiAgent runtime', () => {args: [],commandLine: 'codex',promptDelayMs: 100,- idleTimeoutMs: 50,// Large so the wall-clock backstop never fires during the modest fake-timer- // advances the idle/paste tests perform (the max-runtime test overrides it).+ // advances the paste/handshake tests perform (the max-runtime test overrides it).maxRuntimeMs: 3600000};@@ -538,10 +501,6 @@ describe('spawnTuiAgent runtime', () => {cleanupWorktreeFn: vi.fn().mockResolvedValue(undefined),isTruthyMetaFn: (v) => !!v};- // Default the connectivity probe to "online" so the idle reaper behaves- // exactly as before for every existing test — no real network I/O. The- // outage tests below inject their own resolver.- const checkOnlineFn = overrides.checkOnlineFn ?? vi.fn().mockResolvedValue(true);return spawnTuiAgent({agentId,task,@@ -554,7 +513,6 @@ describe('spawnTuiAgent runtime', () => {agentDir,executionId,laneName,- checkOnlineFn,leanMode: overrides.leanMode ?? false,useDurableRunner: overrides.useDurableRunner ?? false,...helpers,@@ -618,16 +576,6 @@ describe('spawnTuiAgent runtime', () => {vi.mocked(existsSync).mockReturnValue(false);vi.mocked(readFile).mockResolvedValue('');- // Reset git mock: default is worktree has changes (idle-complete succeeds).- // Tests that want to exercise the idle-no-changes failure path override this.- vi.mocked(gitService.getStatus).mockResolvedValue({ clean: false, files: [{ path: 'file.txt', status: 'M' }] });- vi.mocked(gitService.getDiff).mockResolvedValue('diff content here');- vi.mocked(gitService.execGit).mockResolvedValue({ exitCode: 0, stdout: '0\n', stderr: '' });-- // Reset input-recency state: no input recorded by default. The- // recent-input test overrides this — clearAllMocks doesn't undo a- // mockReturnValue override, so it must be reset explicitly here.- vi.mocked(shellService.getLastInputAt).mockReturnValue(null);});afterEach(() => {@@ -834,538 +782,46 @@ describe('spawnTuiAgent runtime', () => {expect(releaseRetryHold).toHaveBeenCalledWith(expect.objectContaining({ success: true }));});- // ── 1. Successful idle-complete path ────────────────────────────────────────- it('idle-complete: calls finalizeAgent(success:true) with completionReason=idle-complete when idle fires after enough output and runtime', async () => {- // Wire finalizeAgent to resolve a promise we can await, so we can detect- // when the async finish() chain completes without polling.+ // ── CoS agents stay alive while provider output is silent ────────────────────+ it('does not finalize a CoS TUI merely because provider output goes silent', async () => {let resolveComplete;const completeDone = new Promise((r) => { resolveComplete = r; });vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });- runSpawn();-- // Flush initial async setup (updateAgent calls etc.)- await flushMicrotasks();-- // Feed a banner-style line so firstOutputAt is set — the paste timer- // gates on "we've seen at least one chunk of output" plus an idle window- // before sending the prompt (ready-signal detection).- await capturedOnData(Buffer.from('Codex booting...\n'));- await flushMicrotasks();-- // Advance past the prompt-delay floor (100ms) AND the readiness idle- // threshold (1200ms). The poll interval (300ms) ticks during this window- // and fires the paste once both gates open, setting promptSentAt.- await vi.advanceTimersByTimeAsync(2000);- await flushMicrotasks();-- // Emit the prompt echo so paste verification passes (issue #2192).- // In a real TUI, the paste is echoed in the input buffer; tests must- // simulate this or verification fails and Enter is never sent.- await capturedOnData(Buffer.from('do the thing\n'));- await flushMicrotasks();-- // Advance past PASTE_TO_ENTER_FALLBACK_MS (3500ms) so the submit-Enter fires- // and promptSubmittedAt is set — work-activity is only observed AFTER submit- // (the prompt echo before that must not be scanned; issue #1229 review).- await vi.advanceTimersByTimeAsync(3600);- await flushMicrotasks();-- // Feed PTY chunks AFTER submit that prove the model is actually WORKING — the- // elapsed working counter ADVANCING through two distinct values SPACED ACROSS- // WALL-CLOCK TIME (≥750ms apart). This sets lastOutputAt > promptSentAt AND- // trips the work-activity tracker, which the idle gate now requires before- // finalizing as success (issue #1229 — pure chrome churn, a single counter- // value, or two counters arriving at once must NOT count; see the no-activity- // and echoed-transcript tests).- await capturedOnData(Buffer.from('(1s · thinking with high effort)\n'));- await vi.advanceTimersByTimeAsync(800);- await capturedOnData(Buffer.from('(2s · thinking with high effort)\n'));-- // Advance past DEFAULT_TUI_MIN_RUNTIME_MS (15 000ms) + idleTimeoutMs (50ms).- // The idle setInterval ticks every 5 000ms; at the >=15s tick the- // conditions (runtime >= 15s, lastOutputAt > promptSentAt, idle >= 50ms)- // are all satisfied.- await vi.advanceTimersByTimeAsync(21000);-- // finish() is called as fire-and-forget inside the interval callback;- // switch to real timers and await our sentinel promise so the full async- // chain (finalizeAgent → ...) drains completely.- vi.useRealTimers();- await completeDone;-- expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(- expect.objectContaining({- agentId: 'agent-1',- success: true,- completionReason: 'idle-complete',- })- );- });-- it('does not idle-reap an Ollama-backed TUI while a local model is silent', async () => {- let resolveComplete;- const completeDone = new Promise((r) => { resolveComplete = r; });- vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });- const checkOnlineFn = vi.fn().mockResolvedValue(true);-- const spawnPromise = runSpawn({- provider: { id: 'claude-ollama-tui', name: 'Claude Ollama TUI', type: 'tui', command: 'claude', ollamaBacked: true, envVars: {} },- checkOnlineFn,- });+ const spawnPromise = runSpawn();await flushMicrotasks();- await capturedOnData(Buffer.from('Claude Code booting...\n'));+ await capturedOnData(Buffer.from('Codex booting...\\n'));await flushMicrotasks();await vi.advanceTimersByTimeAsync(2000);await flushMicrotasks();- await capturedOnData(Buffer.from('do the thing\n'));+ await capturedOnData(Buffer.from('do the thing\\n'));await flushMicrotasks();await vi.advanceTimersByTimeAsync(3600);await flushMicrotasks();- await capturedOnData(Buffer.from('(1s · thinking with high effort)\n'));- await vi.advanceTimersByTimeAsync(800);- await capturedOnData(Buffer.from('(2s · thinking with high effort)\n'));- // The supplied config has a 50ms idle window, but local-runtime providers- // disable it at the enforcement point. The max-runtime ceiling is hours out.- await vi.advanceTimersByTimeAsync(21000);+ // The agent has submitted its prompt. No output follows for substantially+ // longer than the old idle window, but the run must remain attached.+ await vi.advanceTimersByTimeAsync(60000);await flushMicrotasks();expect(agentLifecycle.finalizeAgent).not.toHaveBeenCalled();- expect(checkOnlineFn).not.toHaveBeenCalled();await capturedOnExit({ exitCode: 0, killed: false });await spawnPromise;- await completeDone;- expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(- expect.objectContaining({ success: true, completionReason: 'shell-exit' })- );- });-- // ── 1b. Idle timer must not reap a session that just received real input ────- // A large bracketed paste into a live agent TUI can sit in a silent- // reflow/commit window with no PTY output yet, which looks identical to- // "idle" to this timer. While input keeps arriving recently (within- // PASTE_INPUT_GRACE_MS), the idle reaper must not fire — gated on input- // RECENCY rather than "is a socket attached", since a regular Shell session- // keeps its socket bound after the viewer navigates away (only external- // one-shot runs release on `shell:release-views`), which would otherwise- // permanently suppress idle-complete for any agent glanced at once (caught- // in review — see shell.test.js for the isolated getLastInputAt coverage).- it('idle timer does not reap while getLastInputAt reports recent input', async () => {- vi.mocked(shellService.getLastInputAt).mockImplementation(() => Date.now());-- runSpawn();- await flushMicrotasks();-- await capturedOnData(Buffer.from('Codex booting...\n'));- await flushMicrotasks();-- await vi.advanceTimersByTimeAsync(2000);- await flushMicrotasks();-- await capturedOnData(Buffer.from('do the thing\n'));- await flushMicrotasks();-- await vi.advanceTimersByTimeAsync(3600);- await flushMicrotasks();-- await capturedOnData(Buffer.from('(1s · thinking with high effort)\n'));- await vi.advanceTimersByTimeAsync(800);- await capturedOnData(Buffer.from('(2s · thinking with high effort)\n'));-- // Advance well past DEFAULT_TUI_MIN_RUNTIME_MS + idleTimeoutMs — the- // un-guarded timer would have reaped by now (see test 1 above).- await vi.advanceTimersByTimeAsync(21000);- await flushMicrotasks();-- expect(agentLifecycle.finalizeAgent).not.toHaveBeenCalled();- });-- // ── 1a. Idle-out with NO work activity → failure (issue #1229) ───────────────- // The bug: when the prompt never submits, the TUI keeps repainting its banner /- // status line, so `lastOutputAt > promptSentAt` passes on pure chrome churn and- // the agent — which did ZERO work — was finalized as `success: idle-complete`.- // The fix gates idle-complete success on having seen a real work-activity- // signal (working counter / interrupt hint / "thinking"). With only chrome- // post-paste, idle must finalize as FAILURE with reason 'idle-no-activity'.- it('idle-no-activity: finalizes failure when idle fires but no work signal ever appeared (unsubmitted prompt)', async () => {- let resolveComplete;- const completeDone = new Promise((r) => { resolveComplete = r; });- vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });-- runSpawn();- await flushMicrotasks();-- await capturedOnData(Buffer.from('Codex booting...\n'));- await flushMicrotasks();- await vi.advanceTimersByTimeAsync(2000);- await flushMicrotasks();-- // Post-paste output, but ONLY chrome that repaints with an unsent prompt —- // the input footer + effort indicator from the real #1229 stuck transcript.- // None of this advances the working counter, so the work-activity tracker- // stays inactive.- await capturedOnData(Buffer.from('⏵⏵ bypass permissions on (shift+tab to cycle)\n'));- await capturedOnData(Buffer.from('● high · /effort\n'));-- await vi.advanceTimersByTimeAsync(21000);- vi.useRealTimers();- await completeDone;-- expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(- expect.objectContaining({- agentId: 'agent-1',- success: false,- completionReason: 'idle-no-activity',- })- );- });-- // ── 1a-ter. Idle-out with work activity but zero file changes → failure (#2191) ─- // Issue #2191: a TUI agent that shows the working counter (workActivity.active- // becomes true) but produces NO file changes in the worktree should fail, not- // succeed. Examples: the model rambled, made invalid tool calls, hit an error- // ("Model is not valid"), or ended at an interactive prompt with zero edits.- // The fix gates idle-complete success on evidence of work in the worktree- // (non-empty git status) in addition to the work-counter signal.- it('idle-no-changes: finalizes failure when work counter advanced but worktree is clean (zero file changes)', async () => {- // Override the default git mock to report a clean worktree (no changes, no diff).- vi.mocked(gitService.getStatus).mockResolvedValue({ clean: true, files: [] });- vi.mocked(gitService.getDiff).mockResolvedValue('');-- let resolveComplete;- const completeDone = new Promise((r) => { resolveComplete = r; });- vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });-- runSpawn();- await flushMicrotasks();-- await capturedOnData(Buffer.from('Codex booting...\n'));- await flushMicrotasks();- await vi.advanceTimersByTimeAsync(2000);- await flushMicrotasks();-- // Emit the prompt echo so paste verification passes (issue #2192) — without- // it the Enter is never sent, promptSubmittedAt stays null, and the run- // finalizes as idle-no-activity instead of exercising the idle-no-changes path.- await capturedOnData(Buffer.from('do the thing\n'));- await flushMicrotasks();-- // Advance past PASTE_TO_ENTER_FALLBACK_MS so submit fires.- await vi.advanceTimersByTimeAsync(3600);- await flushMicrotasks();-- // Feed PTY chunks that PROVE the model was working — the elapsed working- // counter ADVANCING through two distinct values. This sets workActivity.active- // to true, but the worktree is still clean (no file changes).- await capturedOnData(Buffer.from('(1s · thinking with high effort)\n'));- await vi.advanceTimersByTimeAsync(800);- await capturedOnData(Buffer.from('(2s · thinking with high effort)\n'));-- // Advance past DEFAULT_TUI_MIN_RUNTIME_MS + idleTimeoutMs.- await vi.advanceTimersByTimeAsync(21000);-- vi.useRealTimers();- await completeDone;-- expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(- expect.objectContaining({- agentId: 'agent-1',- success: false,- completionReason: 'idle-no-changes',- })- );- });-- // ── 1a-quater. worktreeChangesExpected:false skips the clean-tree gate (#3102) ─- // Issue #3102: the #2191 gate above assumes every agent's work product is a- // file change. A `reference-watch` run against a GitHub/GitLab/JIRA work- // tracker files ISSUES and — per its own prompt — edits no application code,- // so a run that did its whole job leaves a CLEAN worktree and was recorded as- // `idle-no-changes` failure. `worktreeChangesExpected: false` opts such a task- // out of the worktree gate, leaving `workActivity.active` as the sole signal.- //- // Drives the same PTY sequence as the idle-no-changes test: prompt echo →- // submit → an ADVANCING work counter → idle out, with a clean worktree.- // Shared PTY choreography: boot banner → prompt echo (paste verify) → submit- // Enter → an ADVANCING work counter (sets workActivity.active and- // lastOutputAt > promptSentAt). Leaves fake timers running at the second- // counter; callers add their own tail (idle advance + git/finalize/assertions).- async function driveToSubmittedAndWorking(overrides = {}) {- runSpawn(overrides);- await flushMicrotasks();-- await capturedOnData(Buffer.from('Codex booting...\n'));- await flushMicrotasks();- await vi.advanceTimersByTimeAsync(2000);- await flushMicrotasks();-- // Prompt echo so paste verification passes and the submit-Enter fires.- await capturedOnData(Buffer.from('do the thing\n'));- await flushMicrotasks();- await vi.advanceTimersByTimeAsync(3600);- await flushMicrotasks();-- // An ADVANCING work counter → workActivity.active becomes true.- await capturedOnData(Buffer.from('(1s · thinking with high effort)\n'));- await vi.advanceTimersByTimeAsync(800);- await capturedOnData(Buffer.from('(2s · thinking with high effort)\n'));- }-- async function driveIdleWithWorkOnCleanTree(overrides) {- vi.mocked(gitService.getStatus).mockResolvedValue({ clean: true, files: [] });- vi.mocked(gitService.getDiff).mockResolvedValue('');-- let resolveComplete;- const completeDone = new Promise((r) => { resolveComplete = r; });- vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });-- await driveToSubmittedAndWorking(overrides);-- await vi.advanceTimersByTimeAsync(21000);- vi.useRealTimers();- await completeDone;- }-- it('idle-complete: worktreeChangesExpected:false succeeds on a clean worktree (non-file work tracker)', async () => {- await driveIdleWithWorkOnCleanTree({- task: { id: 'task-1', description: 'do the thing', metadata: { worktreeChangesExpected: false } },- });-- expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(- expect.objectContaining({- agentId: 'agent-1',- success: true,- completionReason: 'idle-complete',- })- );- // The gate is skipped, so git status is never consulted — but the diff- // capture still runs unconditionally (a no-op on a clean tree, and useful- // for post-mortems either way).- expect(gitService.getStatus).not.toHaveBeenCalled();- expect(gitService.getDiff).toHaveBeenCalledWith('/tmp/ws', true);- expect(gitService.getDiff).toHaveBeenCalledWith('/tmp/ws', false);- });-- it("idle-no-changes: the TASKS.md string round-trip 'false' also opts out of the gate", async () => {- // Task metadata survives a markdown round-trip as strings, so the opt-out- // must read through isFalsyMeta rather than a bare `=== false`.- await driveIdleWithWorkOnCleanTree({- task: { id: 'task-1', description: 'do the thing', metadata: { worktreeChangesExpected: 'false' } },- });-- expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(- expect.objectContaining({ success: true, completionReason: 'idle-complete' })- );- });-- it('idle-no-changes: worktreeChangesExpected:true still fails on a clean worktree (no behavior change)', async () => {- await driveIdleWithWorkOnCleanTree({- task: { id: 'task-1', description: 'do the thing', metadata: { worktreeChangesExpected: true } },- });-- expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(- expect.objectContaining({ success: false, completionReason: 'idle-no-changes' })- );- });-- // ── 1a-sexies. A programmatic-I/O run is judged by its PAYLOAD, not the tree ──- // A layered-intelligence run reasons over the app's goals and returns JSON that- // a deterministic step files as one tracker issue; its prompt FORBIDS touching- // the repo. Measuring it by worktree evidence blamed it for exactly the thing it- // was told not to do — the failure read "zero file changes" on a task that must- // change no files — and buried the real miss: no `.agent-done` payload landed,- // so nothing was filed.- const liTask = (metadata = {}) => ({- id: 'task-1',- description: 'do the thing',- taskType: 'internal',- metadata: { analysisType: 'layered-intelligence', useWorktree: true, openPR: false, discardWorktree: true, ...metadata },- });-- it('idle-no-deliverable: a programmatic-I/O run with no sentinel fails on its OWN criterion', async () => {- await driveIdleWithWorkOnCleanTree({ task: liTask() });-- expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(- expect.objectContaining({ success: false, completionReason: 'idle-no-deliverable' })- );- // The worktree question is never asked — it measures nothing about this run.- expect(gitService.getStatus).not.toHaveBeenCalled();- });-- it('idle-no-deliverable: the failure names the missing payload, not missing file changes', async () => {- await driveIdleWithWorkOnCleanTree({ task: liTask() });-- const { error } = vi.mocked(agentLifecycle.finalizeAgent).mock.calls.at(-1)[0];- expect(error).toContain('.agent-done');- expect(error).not.toContain('zero uncommitted file changes');- });-- // A DIRTY tree doesn't rescue it either: this type ships a payload, and stray- // edits in a worktree that is discarded unmerged are not the deliverable.- it('idle-no-deliverable: a dirty worktree does not substitute for the payload', async () => {- vi.mocked(gitService.getStatus).mockResolvedValue({ clean: false, files: [{ path: 'f.txt', status: 'M' }] });- let resolveComplete;- const completeDone = new Promise((r) => { resolveComplete = r; });- vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });-- await driveToSubmittedAndWorking({ task: liTask() });- await vi.advanceTimersByTimeAsync(21000);vi.useRealTimers();await completeDone;- expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(- expect.objectContaining({ success: false, completionReason: 'idle-no-deliverable' })- );- });-- // The type-derived question must not leak to a code-editing task that merely- // carries the same worktree-disposal metadata: a quota-burn job can want a- // scratch checkout it builds in and never lands, and it declares that shape via- // `worktreeChangesExpected` instead.- it('idle-no-changes: a code-editing task keeps the worktree criterion', async () => {- await driveIdleWithWorkOnCleanTree({- task: { id: 'task-1', description: 'do the thing', metadata: { analysisType: 'security', discardWorktree: true } },- });-- expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(- expect.objectContaining({ success: false, completionReason: 'idle-no-changes' })- );- expect(gitService.getStatus).toHaveBeenCalled();- });-- // ── 1a-quinquies. A COMMIT during the run is evidence of work ────────────────- // The #2191 gate above read only UNCOMMITTED changes, so a job whose- // deliverable is a commit — `/do:release`, `/do:pr` — idled out on a clean- // tree *because it succeeded* and was scored a failure. Rationale and the- // 2026-08-08 release incident: worktreeHasWorkEvidence. The clean-tree +- // zero-commit failure stays covered by the sibling tests above, which run on- // the beforeEach default of `rev-list --count` → 0.- it('idle-complete: a commit made during the run counts as work on a clean tree (release/do:pr jobs)', async () => {- vi.mocked(gitService.execGit).mockResolvedValue({ exitCode: 0, stdout: '2\n', stderr: '' });- await driveIdleWithWorkOnCleanTree();-expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(expect.objectContaining({agentId: 'agent-1',success: true,- completionReason: 'idle-complete',+ completionReason: 'shell-exit',}));- // The probe is scoped to the run window by committer date, so commits that- // were already on the branch at spawn can't launder a no-op into a success.- expect(gitService.execGit).toHaveBeenCalledWith(- ['rev-list', '--count', expect.stringMatching(/^--since=\d{4}-/), 'HEAD'],- '/tmp/ws',- { ignoreExitCode: true, timeout: 10_000 }- );- });-- it('idle-no-activity: worktreeChangesExpected:false does NOT rescue a run with zero work-counter activity', async () => {- // The flag only relaxes the worktree-evidence gate. A prompt that never- // submitted (no working indicator ever appeared) must still fail — otherwise- // opting out of the file gate would silently launder a total no-op run.- vi.mocked(gitService.getStatus).mockResolvedValue({ clean: true, files: [] });- vi.mocked(gitService.getDiff).mockResolvedValue('');-- let resolveComplete;- const completeDone = new Promise((r) => { resolveComplete = r; });- vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });-- runSpawn({ task: { id: 'task-1', description: 'do the thing', metadata: { worktreeChangesExpected: false } } });- await flushMicrotasks();-- await capturedOnData(Buffer.from('Codex booting...\n'));- await flushMicrotasks();- await vi.advanceTimersByTimeAsync(2000);- await flushMicrotasks();-- // Chrome-only repaints — the working counter never advances.- await capturedOnData(Buffer.from('⏵⏵ bypass permissions on (shift+tab to cycle)\n'));- await capturedOnData(Buffer.from('● high · /effort\n'));-- await vi.advanceTimersByTimeAsync(21000);- vi.useRealTimers();- await completeDone;-- expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(- expect.objectContaining({ success: false, completionReason: 'idle-no-activity' })- );});- // ── 1d. Connectivity-aware idle reaper ──────────────────────────────────────- // When the machine loses internet, a live TUI goes silent (it can't reach the- // model) exactly like a hung or finished agent looks to the idle timer — so an- // outage would reap an agent that's only blocked on the network. The reaper is- // the ONLY liveness signal for a genuinely hung TUI, so it isn't removed —- // it's gated on a reachability probe and DEFERS while offline.- const OFFLINE_TUI_CONFIG = {- command: 'codex',- args: [],- commandLine: 'codex',- promptDelayMs: 100,- // A larger idle window than the fast default so the lead probe- // (idleTimeoutMs/2, capped) resolves on an earlier 5s tick than the reap- // tick — mirroring how a real 3-minute window spans many probe ticks.- idleTimeoutMs: 15000,- maxRuntimeMs: 3600000,- };-- async function driveToIdleSilence({ checkOnlineFn, silenceMs = 45000 }) {- await driveToSubmittedAndWorking({ tuiConfig: OFFLINE_TUI_CONFIG, checkOnlineFn });- // Go silent well past the 15s idle window (several 5s ticks) so the lead- // probe fires and resolves before the reap tick.- await vi.advanceTimersByTimeAsync(silenceMs);- await flushMicrotasks();- }-- it('idle reaper DEFERS while the machine is offline (does not reap an agent that lost internet)', async () => {- const checkOnlineFn = vi.fn().mockResolvedValue(false);- await driveToIdleSilence({ checkOnlineFn });-- expect(checkOnlineFn).toHaveBeenCalled(); // the reachability probe fired- expect(agentLifecycle.finalizeAgent).not.toHaveBeenCalled(); // …and the reap was deferred- });-- it('idle reaper still reaps on the SAME window when online (deferral is outage-specific, not a timing artifact)', async () => {- let resolveComplete;- const completeDone = new Promise((r) => { resolveComplete = r; });- vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });-- // dirty tree (default git mock) → idle-complete success- await driveToIdleSilence({ checkOnlineFn: vi.fn().mockResolvedValue(true) });- vi.useRealTimers();- await completeDone;-- expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(- expect.objectContaining({ success: true, completionReason: 'idle-complete' })- );- });-- it('idle reaper resumes reaping once connectivity RETURNS (deferral is not permanent)', async () => {- let resolveComplete;- const completeDone = new Promise((r) => { resolveComplete = r; });- vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });-- // Offline for the first probe, then the connection comes back. The reap is- // deferred through the outage, then fires after the reconnect grace window.- const checkOnlineFn = vi.fn().mockResolvedValueOnce(false).mockResolvedValue(true);- await driveToIdleSilence({ checkOnlineFn, silenceMs: 90000 });- vi.useRealTimers();- await completeDone;-- expect(checkOnlineFn.mock.calls.length).toBeGreaterThan(1); // probed again after the outage- expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(- expect.objectContaining({ success: true, completionReason: 'idle-complete' })- );- });-- // ── 1c. Absolute wall-clock backstop reaps a busy-but-stuck agent ───────────- // The idle reaper resets on every PTY chunk, so an agent whose working counter- // keeps repainting through a stalled provider retry never idles out and would- // run unbounded (real incident 2026-07-06: agent-b1c56083 churned for 98min).- // The max-runtime timer is the honest ceiling: it fires from submission+ // ── Absolute wall-clock backstop reaps a busy-or-silent stuck agent ──────────+ // The max-runtime timer fires from submission// regardless of PTY chatter and, with no .agent-done sentinel present,// finalizes as a needs-manual-finish FAILURE.it('max-runtime: reaps a still-chattering agent as failure once the wall-clock ceiling elapses', async () => {@@ -1373,10 +829,7 @@ describe('spawnTuiAgent runtime', () => {const completeDone = new Promise((r) => { resolveComplete = r; });vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });- // Idle window LARGER than the max-runtime ceiling so the idle reaper can't- // win — this isolates the wall-clock backstop (the real-world stuck agent- // keeps its working counter ticking, so idle never fires anyway).- runSpawn({ tuiConfig: { ...defaultTuiConfig, idleTimeoutMs: 600000, maxRuntimeMs: 30000 } });+ runSpawn({ tuiConfig: { ...defaultTuiConfig, maxRuntimeMs: 30000 } });await flushMicrotasks();await capturedOnData(Buffer.from('Codex booting...\n'));@@ -1391,8 +844,7 @@ describe('spawnTuiAgent runtime', () => {await vi.advanceTimersByTimeAsync(3600);await flushMicrotasks();- // A busy agent that keeps chattering — but the idle window (600s) is huge so- // only the 30s wall-clock ceiling can reap it. Advance past the ceiling.+ // A busy agent that keeps chattering still reaches the same wall-clock ceiling.await capturedOnData(Buffer.from('(1s · thinking with high effort)\n'));await vi.advanceTimersByTimeAsync(31000);await flushMicrotasks();@@ -1433,7 +885,7 @@ describe('spawnTuiAgent runtime', () => {const completeDone = new Promise((r) => { resolveComplete = r; });vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });- runSpawn({ tuiConfig: { ...defaultTuiConfig, idleTimeoutMs: 600000, maxRuntimeMs: 30000 } });+ runSpawn({ tuiConfig: { ...defaultTuiConfig, maxRuntimeMs: 30000 } });await flushMicrotasks();await capturedOnData(Buffer.from('Codex booting...\n'));@@ -1474,7 +926,7 @@ describe('spawnTuiAgent runtime', () => {const completeDone = new Promise((r) => { resolveComplete = r; });vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });- runSpawn({ tuiConfig: { ...defaultTuiConfig, idleTimeoutMs: 600000, maxRuntimeMs: 30000 } });+ runSpawn({ tuiConfig: { ...defaultTuiConfig, maxRuntimeMs: 30000 } });await flushMicrotasks();await capturedOnData(Buffer.from('Codex booting...\n'));@@ -1553,7 +1005,7 @@ describe('spawnTuiAgent runtime', () => {// raw.txt tail surfaced in the error.vi.mocked(readFile).mockResolvedValue('Error: claude exited at startup\n');- runSpawn();+ const spawnPromise = runSpawn();await flushMicrotasks();await capturedOnData(Buffer.from('booting...\n'));@@ -1581,12 +1033,12 @@ describe('spawnTuiAgent runtime', () => {});// ── 1c. claude waits for bracketed-paste mode (input ready) before pasting ───- const claudeTuiConfig = { command: 'claude', args: [], commandLine: 'claude', promptDelayMs: 100, idleTimeoutMs: 50 };+ const claudeTuiConfig = { command: 'claude', args: [], commandLine: 'claude', promptDelayMs: 100, maxRuntimeMs: 3600000 };// Antigravity (agy) gets the SAME positive input-ready gate as claude (#2705).// maxRuntimeMs is explicit for the same reason defaultTuiConfig pins it: left// undefined, the wall-clock backstop is a `setTimeout(…, undefined)` that fires// on the next tick and prods every one of these runs to wrap up.- const agyTuiConfig = { command: 'agy', args: [], commandLine: 'agy', promptDelayMs: 100, idleTimeoutMs: 50, maxRuntimeMs: 3600000 };+ const agyTuiConfig = { command: 'agy', args: [], commandLine: 'agy', promptDelayMs: 100, maxRuntimeMs: 3600000 };const pasteCount = () => vi.mocked(shellService.writeToSession).mock.calls.filter(([, d]) => typeof d === 'string' && d.includes('\x1b[200~')).length;// The launch shell turns bracketed-paste OFF to run the command, then claude@@ -1740,9 +1192,9 @@ describe('spawnTuiAgent runtime', () => {// ── 1c-bis. Antigravity (agy) uses the SAME positive input-ready gate (#2705) ─// agy's TUI emits the bracketed-paste-mode toggle exactly like claude, so it// must gate the paste on paste-mode-re-enabled rather than blind-pasting on the- // idle heuristic (which fired into agy's still-initializing banner and left the- // agent sitting at an empty prompt until it was reaped). Without the fix agy- // took the idle-heuristic path and WOULD have pasted after ~2s of banner idle;+ // quiet-startup heuristic (which fired into agy's still-initializing banner and+ // left the agent sitting at an empty prompt). Without the fix agy took that+ // path and WOULD have pasted after ~2s of banner silence;// asserting pasteCount()===0 there is what discriminates the fix.//// agy needs a SECOND gate on top of paste mode, because — unlike claude — it@@ -1812,7 +1264,7 @@ describe('spawnTuiAgent runtime', () => {expect(pasteCount()).toBe(1);});- it('agy tui-not-ready: an agy TUI that never signals input-ready fails fast instead of idle-reaping', async () => {+ it('agy tui-not-ready: an agy TUI that never signals input-ready fails fast instead of blind-pasting', async () => {let resolveComplete;const completeDone = new Promise((r) => { resolveComplete = r; });vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });@@ -1962,46 +1414,10 @@ describe('spawnTuiAgent runtime', () => {);});- // ── 1a-bis. Non-counter TUI provider keeps the permissive idle-complete ──────- // The work-counter signal only exists on Claude Code / Codex. On a provider- // that never renders it (Antigravity/Gemini), absence proves nothing — so a- // sentinel-less idle-out must stay SUCCESS (the original behavior), not be- // downgraded to failure. Regression guard for #1229 review (codex P2): gating- // idle-complete solely on a Claude/Codex screen pattern would falsely fail- // every sentinel-less completion on the other supported TUI providers.- it('idle-complete: a non-counter provider (gemini) stays success even with no work-counter signal', async () => {- let resolveComplete;- const completeDone = new Promise((r) => { resolveComplete = r; });- vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });-- runSpawn({ tuiConfig: { command: 'gemini', args: [], commandLine: 'gemini', promptDelayMs: 100, idleTimeoutMs: 50 } });- await flushMicrotasks();-- await capturedOnData(Buffer.from('Gemini booting...\n'));- await flushMicrotasks();- await vi.advanceTimersByTimeAsync(2000);- await flushMicrotasks();- await vi.advanceTimersByTimeAsync(3600); // submit fires- await flushMicrotasks();- // Real work output, but NO `(Ns ·` counter (gemini doesn't render one).- await capturedOnData(Buffer.from('Editing src/foo.js …\n'));- await vi.advanceTimersByTimeAsync(21000);- vi.useRealTimers();- await completeDone;-- expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(- expect.objectContaining({- agentId: 'agent-1',- success: true,- completionReason: 'idle-complete',- })- );- });-// ── 1b. Submit-Enter retries ─────────────────────────────────────────────────// A single `\r` after a large bracketed paste can be swallowed mid-paste-// commit, stranding the prompt unsent (the "I had to hit Enter myself" bug,- // which then idles out and is falsely marked success). The fallback path must+ // which was then falsely marked success by the old fallback). The submit path must// fire the Enter SUBMIT_ENTER_ATTEMPTS times, spaced apart, so one lands after// the paste settles. Asserts the bracketed paste is written once and `\r` is// written exactly SUBMIT_ENTER_ATTEMPTS times.@@ -2141,7 +1557,7 @@ describe('spawnTuiAgent runtime', () => {const completeDone = new Promise((r) => { resolveComplete = r; });vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });- runSpawn({ tuiConfig: { command: 'gemini', args: [], commandLine: 'gemini', promptDelayMs: 100, idleTimeoutMs: 50 } });+ runSpawn({ tuiConfig: { command: 'gemini', args: [], commandLine: 'gemini', promptDelayMs: 100, maxRuntimeMs: 3600000 } });await flushMicrotasks();// Same banner text codex prints — but this is a gemini session.await capturedOnData(Buffer.from('Starting MCP servers (0/3): a, b, c\n'));@@ -2400,12 +1816,11 @@ describe('spawnTuiAgent runtime', () => {const completeDone = new Promise((r) => { resolveComplete = r; });vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });- runSpawn();+ const spawnPromise = runSpawn();await flushMicrotasks();- // Drive the idle-complete success path (mirrors test 1) — the post-paste- // chunk must carry a work-activity signal so the idle gate finalizes as- // success (issue #1229).+ // Drive the prompt far enough to exercise normal post-submit output, then+ // use the ordinary shell-exit completion path.await capturedOnData(Buffer.from('Codex booting...\n'));await flushMicrotasks();await vi.advanceTimersByTimeAsync(2000);@@ -2416,9 +1831,10 @@ describe('spawnTuiAgent runtime', () => {await vi.advanceTimersByTimeAsync(3600); // submit-Enter fires → promptSubmittedAt setawait flushMicrotasks();await capturedOnData(Buffer.from('(1s · thinking with high effort)\n'));- await vi.advanceTimersByTimeAsync(800); // counter must tick across ≥750ms to count as work+ await vi.advanceTimersByTimeAsync(800);await capturedOnData(Buffer.from('(2s · thinking with high effort)\n'));- await vi.advanceTimersByTimeAsync(21000);+ await capturedOnExit({ exitCode: 0, killed: false });+ await spawnPromise;vi.useRealTimers();await completeDone;@@ -2617,213 +2033,5 @@ describe('spawnTuiAgent runtime', () => {);});- it('skips PR state polling when review-loop follow-up has an unresolved PR host (#4007)', async () => {- runSpawn({- task: {- id: 'task-4007',- description: 'do the thing',- metadata: {- reviewLoopFollowUp: 'true',- reviewLoopPRHost: null,- reviewLoopPRUrl: 'https://unknown-forge.example.com/owner/repo/pull/4007',- },- },- });-- await flushMicrotasks();- await capturedOnData(Buffer.from('Codex booting...\n'));- await flushMicrotasks();- await vi.advanceTimersByTimeAsync(2000);- await flushMicrotasks();- await capturedOnData(Buffer.from('do the thing\n'));- await flushMicrotasks();- await vi.advanceTimersByTimeAsync(3600);- await flushMicrotasks();- await capturedOnData(Buffer.from('(1s · thinking with high effort)\n'));- await vi.advanceTimersByTimeAsync(800);- await capturedOnData(Buffer.from('(2s · thinking with high effort)\n'));- await vi.advanceTimersByTimeAsync(16000);- await flushMicrotasks();-- expect(getPullRequestStateMock).not.toHaveBeenCalled();- });-- it('polls PR state when review-loop follow-up has a resolved github PR host (#4007)', async () => {- runSpawn({- task: {- id: 'task-4007-gh',- description: 'do the thing',- metadata: {- reviewLoopFollowUp: 'true',- reviewLoopPRHost: 'github.com',- reviewLoopPRUrl: 'https://github.com/owner/repo/pull/4007',- },- },- });-- await flushMicrotasks();- await capturedOnData(Buffer.from('Codex booting...\n'));- await flushMicrotasks();- await vi.advanceTimersByTimeAsync(2000);- await flushMicrotasks();- await capturedOnData(Buffer.from('do the thing\n'));- await flushMicrotasks();- await vi.advanceTimersByTimeAsync(3600);- await flushMicrotasks();- await capturedOnData(Buffer.from('(1s · thinking with high effort)\n'));- await vi.advanceTimersByTimeAsync(800);- await capturedOnData(Buffer.from('(2s · thinking with high effort)\n'));- await vi.advanceTimersByTimeAsync(16000);- await flushMicrotasks();-- expect(getPullRequestStateMock).toHaveBeenCalledWith('https://github.com/owner/repo/pull/4007', expect.anything());- });- });-});--// Issue #2074 — the idle reaper must extend its grace while a swarm orchestrator-// is in its Phase C merge queue, and, if the EXTENDED window still blows, surface-// a needs-manual-finish failure instead of a silent `status: completed`.-//-// Exercises the REAL `decideIdleReap` the idleTimer body calls (it was an inline-// copy here until the merge-follow-up branch below made the drift risk concrete-// — a copy would have "passed" while the shipped reaper still failed merged-// PRs). The real code keeps an async worktree-changes check (#2191) that can-// downgrade `idle-complete` to `idle-no-changes`; that's covered by the full-// fake-timer harness above, not by this pure function.-describe('agentTuiSpawning — idle reap decision (#2074)', () => {- const BASE = 180000;-- it('waits indefinitely when a local-runtime model disables idle reaping', () => {- const r = decideIdleReap({- idle: Number.MAX_SAFE_INTEGER,- baseIdleTimeoutMs: null,- mergeQueueActive: true,- reviewLoopActive: true,- backgroundShellActive: true,- workActive: false,- rendersCounter: true,- });- expect(r.action).toBe('wait');- expect(r.effectiveIdleTimeoutMs).toBe(Infinity);- });-- it('does NOT reap at the 3-min default while in a merge queue — grace extends to 15min', () => {- const r = decideIdleReap({ idle: BASE + 5000, baseIdleTimeoutMs: BASE, mergeQueueActive: true, workActive: true, rendersCounter: true });- expect(r.action).toBe('wait');- expect(r.effectiveIdleTimeoutMs).toBe(MERGE_QUEUE_IDLE_TIMEOUT_MS);- });-- it('reaps a merge-queue agent as needs-manual-finish once the EXTENDED window blows', () => {- const r = decideIdleReap({ idle: MERGE_QUEUE_IDLE_TIMEOUT_MS + 1, baseIdleTimeoutMs: BASE, mergeQueueActive: true, workActive: true, rendersCounter: true });- expect(r.action).toBe('reap');- expect(r.success).toBe(false);- expect(r.reason).toBe('merge-queue-idle-timeout');- });-- it('leaves the pre-#2074 idle-complete path untouched when NOT in a merge queue', () => {- const r = decideIdleReap({ idle: BASE + 1, baseIdleTimeoutMs: BASE, mergeQueueActive: false, workActive: true, rendersCounter: true });- expect(r.action).toBe('reap');- expect(r.success).toBe(true);- expect(r.reason).toBe('idle-complete');- });-- it('leaves the #1229 no-activity failure path untouched when NOT in a merge queue', () => {- const r = decideIdleReap({ idle: BASE + 1, baseIdleTimeoutMs: BASE, mergeQueueActive: false, workActive: false, rendersCounter: true });- expect(r.action).toBe('reap');- expect(r.success).toBe(false);- expect(r.reason).toBe('idle-no-activity');- });-- it('a merge-queue reap takes precedence over the no-activity downgrade', () => {- // Even with no work counter seen, a latched merge queue means real work was- // happening — surface it as needs-manual-finish, not a never-submitted prompt.- const r = decideIdleReap({ idle: MERGE_QUEUE_IDLE_TIMEOUT_MS + 1, baseIdleTimeoutMs: BASE, mergeQueueActive: true, workActive: false, rendersCounter: true });- expect(r.reason).toBe('merge-queue-idle-timeout');- });-- // Generalizes the #2074 fix to do:release/do:pr/do:rpr's multi-reviewer loop —- // observed 2026-07-02 on agent-61508f36 (PR #2084): a slow codex review pass- // went silent past the 3-minute default and the still-waiting release agent- // was reaped as a false `idle-complete` success before it ever merged.- it('does NOT reap at the 3-min default while in a review loop — grace extends to 15min', () => {- const r = decideIdleReap({ idle: BASE + 5000, baseIdleTimeoutMs: BASE, reviewLoopActive: true, workActive: true, rendersCounter: true });- expect(r.action).toBe('wait');- expect(r.effectiveIdleTimeoutMs).toBe(REVIEW_LOOP_IDLE_TIMEOUT_MS);- });-- it('reaps a review-loop agent as needs-manual-finish once the EXTENDED window blows', () => {- const r = decideIdleReap({ idle: REVIEW_LOOP_IDLE_TIMEOUT_MS + 1, baseIdleTimeoutMs: BASE, reviewLoopActive: true, workActive: true, rendersCounter: true });- expect(r.action).toBe('reap');- expect(r.success).toBe(false);- expect(r.reason).toBe('review-loop-idle-timeout');- });-- it('a review-loop reap takes precedence over the no-activity downgrade', () => {- const r = decideIdleReap({ idle: REVIEW_LOOP_IDLE_TIMEOUT_MS + 1, baseIdleTimeoutMs: BASE, reviewLoopActive: true, workActive: false, rendersCounter: true });- expect(r.reason).toBe('review-loop-idle-timeout');- });-- it('a merge-queue reap takes precedence over a review-loop reap when both are (implausibly) active', () => {- const r = decideIdleReap({ idle: 900001, baseIdleTimeoutMs: BASE, mergeQueueActive: true, reviewLoopActive: true, workActive: true, rendersCounter: true });- expect(r.reason).toBe('merge-queue-idle-timeout');- });-- it('a background-shell wait extends the window but carries no verdict of its own', () => {- const waiting = decideIdleReap({ idle: BASE + 1, baseIdleTimeoutMs: BASE, backgroundShellActive: true, workActive: true, rendersCounter: true });- expect(waiting.action).toBe('wait');- expect(waiting.effectiveIdleTimeoutMs).toBe(BACKGROUND_SHELL_IDLE_TIMEOUT_MS);- const blown = decideIdleReap({ idle: BACKGROUND_SHELL_IDLE_TIMEOUT_MS + 1, baseIdleTimeoutMs: BASE, backgroundShellActive: true, workActive: true, rendersCounter: true });- expect(blown.reason).toBe('idle-complete');- expect(blown.success).toBe(true);- });-- // The merge-follow-up false failure (task sys-rl-msr1j1a5 / PR #3909,- // 2026-08-13). The follow-up prompt QUOTES `gh pr checks` / `gh pr merge` /- // `--delete-branch`, so the TUI's echo of it latches `mergeQueueActive` before- // any work runs. The agent then merged the PR in ~60s, printed "PR Status:- // MERGED", made no commit (nothing to commit — it only merges), skipped the- // sentinel, and idled — and was recorded as `merge-queue-idle-timeout` 15- // minutes later, three times over, ending in Blocked with a HIGH "PR left- // open" card naming an already-merged PR.- describe('PR follow-up whose PR already merged', () => {- it('reaps as a SUCCESS at the BASE window even with the merge queue latched', () => {- const r = decideIdleReap({- idle: BASE + 1, baseIdleTimeoutMs: BASE,- mergeQueueActive: true, prFollowUpMerged: true, workActive: true, rendersCounter: true,- });- expect(r.action).toBe('reap');- expect(r.success).toBe(true);- expect(r.reason).toBe('pr-follow-up-merged');- });-- it('does not fire before the BASE window — a merged PR is not a reason to cut a working agent short', () => {- const r = decideIdleReap({- idle: BASE - 1, baseIdleTimeoutMs: BASE,- mergeQueueActive: true, prFollowUpMerged: true, workActive: true, rendersCounter: true,- });- expect(r.action).toBe('wait');- });-- it('outranks the no-activity downgrade too — the deliverable landed regardless of the work counter', () => {- const r = decideIdleReap({- idle: BASE + 1, baseIdleTimeoutMs: BASE,- prFollowUpMerged: true, workActive: false, rendersCounter: true,- });- expect(r.success).toBe(true);- expect(r.reason).toBe('pr-follow-up-merged');- });-- // The bug this whole branch exists to kill: without `prFollowUpMerged` the- // SAME signals produce the needs-manual-finish failure. Guards against a- // future refactor that quietly stops threading the forge answer through.- it('still fails as needs-manual-finish when the PR did NOT merge', () => {- const r = decideIdleReap({- idle: MERGE_QUEUE_IDLE_TIMEOUT_MS + 1, baseIdleTimeoutMs: BASE,- mergeQueueActive: true, prFollowUpMerged: false, workActive: true, rendersCounter: true,- });- expect(r.success).toBe(false);- expect(r.reason).toBe('merge-queue-idle-timeout');- });});});diff --git a/server/services/agentTuiSpawning/finalizeHelpers.js b/server/services/agentTuiSpawning/finalizeHelpers.jsindex bdd4edc932..edbcefb2ff 100644--- a/server/services/agentTuiSpawning/finalizeHelpers.js+++ b/server/services/agentTuiSpawning/finalizeHelpers.js@@ -35,40 +35,6 @@ export { commitsSince };// peak finalize memory bounded.export const RAW_TAIL_ANALYSIS_BYTES = 1024 * 1024;-/**- * Check if a worktree has any uncommitted changes. Returns true when the- * working tree is dirty (staged or unstaged changes exist). Used to gate- * idle-complete success — an agent that idled out with zero file changes- * should fail, not succeed.- */-export async function worktreeHasChanges(workspacePath) {- if (!workspacePath || typeof workspacePath !== 'string') return false;- const status = await git.getStatus(workspacePath).catch(() => null);- return status && !status.clean;-}--/**- * Did this agent leave any evidence of work behind? Dirty tree OR at least one- * commit made during the run.- *- * The commit half is what makes this correct for jobs whose deliverable is a- * COMMIT rather than a dirty tree — `/do:release` and `/do:pr` runs commit,- * push, and open a PR, so by the time they idle the tree is clean *because they- * succeeded*. Gating on `worktreeHasChanges` alone scored those as- * `idle-no-changes` failures: two consecutive release runs on 2026-08-08 each- * cut the release commit and opened/repaired the release PR, were reported as- * failures, and the task retried — holding the release for two days.- *- * Accepted trade-off: a run that pulls in a merge commit another agent pushed- * mid-run sees that commit stamped inside the window and counts it as work.- * That false success is rarer, and far cheaper, than failing every- * commit-and-push job.- */-export async function worktreeHasWorkEvidence(workspacePath, sinceMs) {- if (await worktreeHasChanges(workspacePath)) return true;- return (await commitsSince(workspacePath, sinceMs)) > 0;-}-/*** Capture the git diff (staged + unstaged) from a worktree and save it to the* agent archive dir. Called before worktree cleanup so post-mortems can see@@ -110,8 +76,8 @@ export async function captureWorktreeDiff(workspacePath, agentDir) {* short-circuits the analysis entirely.** `completionReason` / `completionError` carry the finalize path's OWN verdict- * (idle reaper, max runtime, spawn failure). The analyzer prefers that structural- * signal over a loose keyword match in the transcript — a repaint-driven PTY+ * (legacy idle-reaper reason, max runtime, spawn failure). The analyzer prefers+ * that structural signal over a loose keyword match in the transcript — a repaint-driven PTY* transcript is a whole session's worth of text, and any keyword in it (including* ones the agent itself typed) would otherwise classify the failure.*diff --git a/server/services/agentTuiSpawning/finalizeHelpers.test.js b/server/services/agentTuiSpawning/finalizeHelpers.test.jsindex 39e79b678f..aaaaddca63 100644--- a/server/services/agentTuiSpawning/finalizeHelpers.test.js+++ b/server/services/agentTuiSpawning/finalizeHelpers.test.js@@ -6,9 +6,7 @@ import { join } from 'path';// git + failure analyzer are mocked; fs/promises stays REAL so readFileTail /// captureWorktreeDiff are exercised against actual temp files.vi.mock('../git.js', () => ({- getStatus: vi.fn(),getDiff: vi.fn(),- execGit: vi.fn(),}));vi.mock('../agentErrorAnalysis.js', () => ({analyzeAgentFailure: vi.fn(),@@ -24,9 +22,7 @@ import { analyzeAgentFailure } from '../agentErrorAnalysis.js';import { commitsSince as commitsSinceMock } from '../../lib/gitCommitProbe.js';import {readFileTail,- worktreeHasChanges,commitsSince,- worktreeHasWorkEvidence,captureWorktreeDiff,resolveErrorAnalysis,RAW_TAIL_ANALYSIS_BYTES,@@ -72,29 +68,6 @@ describe('finalizeHelpers', () => {});});- describe('worktreeHasChanges', () => {- it('is true when git reports an unclean worktree', async () => {- vi.mocked(git.getStatus).mockResolvedValue({ clean: false });- expect(await worktreeHasChanges('/tmp/ws')).toBe(true);- });-- it('is false when git reports a clean worktree', async () => {- vi.mocked(git.getStatus).mockResolvedValue({ clean: true });- expect(await worktreeHasChanges('/tmp/ws')).toBe(false);- });-- it('is falsy (never throws) when getStatus rejects', async () => {- vi.mocked(git.getStatus).mockRejectedValue(new Error('not a repo'));- expect(await worktreeHasChanges('/tmp/ws')).toBeFalsy();- });-- it('is false for a non-string / empty path without touching git', async () => {- expect(await worktreeHasChanges(null)).toBe(false);- expect(await worktreeHasChanges('')).toBe(false);- expect(git.getStatus).not.toHaveBeenCalled();- });- });-// The probe's own behavior (git args, exit-code/timeout handling) is covered by// server/lib/gitCommitProbe.test.js — its new home (#3637). What matters HERE is// that this module's historical entry point still resolves to it.@@ -104,37 +77,6 @@ describe('finalizeHelpers', () => {expect(commitsSince).toBe(commitsSinceMock);});- describe('worktreeHasWorkEvidence', () => {- const SINCE = Date.parse('2026-08-08T18:23:30.000Z');-- it('is true on a dirty tree without consulting the commit log', async () => {- vi.mocked(git.getStatus).mockResolvedValue({ clean: false });- expect(await worktreeHasWorkEvidence('/tmp/ws', SINCE)).toBe(true);- expect(commitsSinceMock).not.toHaveBeenCalled();- });-- // The release-run regression: commit + push + open PR leaves a CLEAN tree,- // which the uncommitted-changes-only gate scored as "produced no work".- it('is true on a clean tree when the run committed something', async () => {- vi.mocked(git.getStatus).mockResolvedValue({ clean: true });- vi.mocked(commitsSinceMock).mockResolvedValue(1);- expect(await worktreeHasWorkEvidence('/tmp/ws', SINCE)).toBe(true);- expect(commitsSinceMock).toHaveBeenCalledWith('/tmp/ws', SINCE);- });-- it('is false on a clean tree with no in-window commits', async () => {- vi.mocked(git.getStatus).mockResolvedValue({ clean: true });- vi.mocked(commitsSinceMock).mockResolvedValue(0);- expect(await worktreeHasWorkEvidence('/tmp/ws', SINCE)).toBe(false);- });-- it('falls back to the dirty-tree signal alone when no window is given', async () => {- vi.mocked(git.getStatus).mockResolvedValue({ clean: true });- vi.mocked(commitsSinceMock).mockResolvedValue(0);- expect(await worktreeHasWorkEvidence('/tmp/ws')).toBe(false);- });- });-describe('captureWorktreeDiff', () => {it('writes a combined staged+unstaged diff and returns it', async () => {vi.mocked(git.getDiff).mockImplementation(async (_dir, staged) => (staged ? 'S-DIFF' : 'U-DIFF'));@@ -205,7 +147,7 @@ describe('finalizeHelpers', () => {});it('forwards the finalize path\'s own completion verdict to the analyzer', async () => {- // The idle reaper / max-runtime timer already knows WHY the run ended;+ // The finalize path already knows WHY the run ended;// that structural signal must reach analyzeAgentFailure so a stray keyword// in the transcript can't outrank it.const p = join(dir, 'raw.txt');diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.jsindex 4c228641b1..ac839f92dc 100644--- a/server/services/agentWorktreeCleanup.js+++ b/server/services/agentWorktreeCleanup.js@@ -365,7 +365,7 @@ async function runCleanupAgentWorktree(agentId, success, { prCreation = PR_CREAT// A run that owned its PR workflow and FAILED may still have opened the PR// before it died — the prompt has it open one at step 3 and merge at step 4,- // so a reap in between (max-runtime, idle reaper, spend limit, host shutdown)+ // so a forced termination in between (max-runtime, spend limit, host shutdown)// leaves a real PR with nothing watching it (#3733). The old flow could not// produce this: PortOS opened the PR only on success and spawned the follow-up// in the same breath. The retry adopts the PR ("if `gh` reports the pulldiff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.jsindex e2f1b29cc3..cd0af0e8e8 100644--- a/server/services/branchReconcile.js+++ b/server/services/branchReconcile.js@@ -946,7 +946,7 @@ const verifyGate = 'Rebase onto the default branch before opening or updating a// placeholder the agent fills in after opening it.const driveToMerge = (pr) => ['Opening (or approving) the PR is NOT the end state — a green PR left open is still an unfinished branch that this task will simply re-drive on its next run.',- `Wait for CI in-session by re-polling \`gh pr checks ${pr} --required\` every 30s — each poll prints output, which keeps this run clear of the idle reaper the way a silent \`--watch\` does not. Budget 15 minutes for the run; past that, leave the PR open and report that CI was still pending.`,+ `Wait for CI in-session by re-polling \`gh pr checks ${pr} --required\` every 30s so the run stays observable while CI is pending. Budget 15 minutes for the run; past that, leave the PR open and report that CI was still pending.`,'If a required check FAILS, fix it on the branch, push, and re-poll (max 3 rounds); if it is still red after that, leave the PR open and report exactly which check failed.',`Once every required check is green AND the PR is MERGEABLE, merge it — from the repo root, NOT from inside the branch's worktree (\`gh\` can't delete a branch that is checked out elsewhere): \`gh pr merge ${pr} --merge --delete-branch\`. Repos differ in which methods they allow, so on a "not allowed" error retry with \`--squash\`, then \`--rebase\`. Never \`--auto\`: a queued auto-merge outlives this run, so a check that goes red afterward has nobody left to fix it.`,'After the merge, remove the branch\'s worktree first, then delete the local branch — the delete fails while a worktree still has it checked out.'diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex b5c16fd4f5..490c654e4b 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -2792,12 +2792,12 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, st// for the app's resolved work tracker.const trackerFiling = await resolveTrackerFilingBlock(app, taskType);if (trackerFiling.workTracker) {- // Traceability + the TUI idle-complete gate, derived from the SAME resolved- // tracker that selected the {trackerInstructions} block above so the flag- // can't drift from the instructions the agent actually got: the PLAN.md path- // commits checklist items (dirty tree), while github/gitlab/jira file- // issues/tickets and leave the tree CLEAN. Without this a scheduled- // forge-tracker run is recorded as an `idle-no-changes` failure (#3102).+ // Traceability + deliverable posture, derived from the SAME resolved tracker+ // that selected the {trackerInstructions} block above so the flag can't drift+ // from the instructions the agent actually got: the PLAN.md path commits+ // checklist items (dirty tree), while github/gitlab/jira file issues/tickets+ // and leave the tree CLEAN. Without this downstream bookkeeping mistakes a+ // scheduled forge-tracker run for missing code work (#3102).metadata.workTracker = trackerFiling.workTracker;// Stamped unconditionally — a schedule/per-app `worktreeChangesExpected`// override would let the flag disagree with the instructions the agentdiff --git a/server/services/quotaBurnJobs/agentPrompt.js b/server/services/quotaBurnJobs/agentPrompt.jsindex 5a98c530bf..f8a269d950 100644--- a/server/services/quotaBurnJobs/agentPrompt.js+++ b/server/services/quotaBurnJobs/agentPrompt.js@@ -111,8 +111,8 @@ export async function run({ params, job, family, candidate, context } = {}) {// on a no-worktree job, tells it to `/do:push` to the branch it is standing// on, which is the app's default branch.noCodeOutput: landsNoCode,- // A run that correctly changed nothing must not be failed by the- // idle-complete gate, which otherwise requires a dirty tree.+ // A run that correctly changed nothing must retain its report-shaped+ // deliverable posture instead of being treated like code work.worktreeChangesExpected: !landsNoCode,reviewLoop: false,// Burn provenance, read back after the task round-trips throughdiff --git a/server/services/referenceRepos.js b/server/services/referenceRepos.jsindex ce3e3d22c8..37123d313a 100644--- a/server/services/referenceRepos.js+++ b/server/services/referenceRepos.js@@ -649,8 +649,8 @@ export async function triggerReferenceAnalysis(app, ref, snapshot) {// agent actually received: the PLAN.md path commits checklist items (dirty// tree), while the github/gitlab/jira paths file issues/tickets and — per// the prompt's "no source-code edits" contract — leave the tree CLEAN.- // Without this the TUI idle reaper records a run that did its whole job as- // `idle-no-changes` failure (#3102).+ // Without this downstream task bookkeeping treats a report-shaped run that+ // did its whole job with a clean worktree as missing code work (#3102).worktreeChangesExpected: isFileTracker(workTracker.resolved),// A multi-line payload here is the agent PROMPT, not the one-line human// note — `cosTaskStore.addTask` routes it to `metadata.prompt` on writediff --git a/server/services/repoIntake.js b/server/services/repoIntake.jsindex d7d4ea6dcb..98ff88a534 100644--- a/server/services/repoIntake.js+++ b/server/services/repoIntake.js@@ -151,7 +151,7 @@ export async function queueRepoStudy(link) {// telling the agent where to file, the tracker it names, and the// `worktreeChangesExpected` flag derived from that SAME tracker so the two can// never disagree (a github/gitlab/jira run files out of band and leaves the- // tree clean; without the flag it is scored `idle-no-changes`, #3102).+ // tree clean; without the flag it is mistaken for missing code work, #3102).const { trackerInstructions, workTracker, worktreeChangesExpected } =await resolveTrackerFilingBlock(app, 'repo-study');diff --git a/server/services/shell.js b/server/services/shell.jsindex fdf74a2fbd..050019522b 100644--- a/server/services/shell.js+++ b/server/services/shell.js@@ -309,7 +309,7 @@ export function createShellSession(socket, options = {}) {* so without this a TUI run stays "watched" (and its completion stays paused)* after the user switches to another tab. When a socket starts viewing a* different session, drop its binding to any OTHER external (TUI-run) view so- * that run resumes normal idle/timeout completion. Interactive shells keep their+ * that run resumes normal completion handling. Interactive shells keep their* lingering binding (the registry's one-socket-many-shells model is unchanged).*/function releaseExternalViews(socket, exceptId = null) {diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.jsindex f5c8a6ebbd..4537ea5a21 100644--- a/server/services/taskSchedule.js+++ b/server/services/taskSchedule.js@@ -247,8 +247,8 @@ export const SELF_IMPROVEMENT_TASK_TYPES = [// `readOnly: true` is NOT a substitute: it gates worktree CREATION// (agentWorkspacePrep.js) but the PR-claim check reads `metadata.openPR`// directly (agentTuiSpawning.js).-// * `worktreeChangesExpected` — a clean tree IS the success shape here, so the-// TUI idle-complete changes gate must not read it as "produced no work".+ // * `worktreeChangesExpected` — a clean tree IS the success shape here, so the+ // task's deliverable posture must record that this is not code work.// A guard test in taskSchedule.test.js asserts every member of that set carries// this posture, so a new coordinator type can't be added to one list only.const NON_COMMITTING_COORDINATOR_METADATA = { useWorktree: false, openPR: false, worktreeChangesExpected: false };@@ -465,7 +465,7 @@ export const MANAGED_AGENT_OPTIONS = {// `taskMetadata: null` clear — loadSchedule preserves that null (skipping the// defaults deep-merge), and enforceManagedAgentOptions rebuilds only the MANAGED// fields, so an unmanaged `worktreeChangesExpected` would silently go absent and the- // TUI idle-complete gate would fail the run as `idle-no-changes`.+ // task bookkeeping would otherwise treat the clean worktree as missing code work....Object.fromEntries(['branch-reconcile', 'branch-cleanup', 'issue-reconcile', 'jira-status-report'].map((t) => [t, ['useWorktree', 'openPR', 'worktreeChangesExpected']])diff --git a/server/services/taskTypeHooks.js b/server/services/taskTypeHooks.jsindex 92f1594799..2e364301a9 100644--- a/server/services/taskTypeHooks.js+++ b/server/services/taskTypeHooks.js@@ -187,8 +187,8 @@ export function isNonCommittingCoordinatorTask(task) {* accepted for EVERY task type (`cosValidation.js` ALLOWED keys → `POST* /api/apps/:id/task-types` → merged into `metadata` in* cosTaskGenerator.js#generateManagedAppImprovementTaskForType). It exists to- * opt a run out of the TUI idle-complete clean-tree gate; someone setting it- * there is not asking to disable success validation. Ungated, a `security` task+ * mark a run's deliverable as outside the worktree; someone setting it there is+ * not asking to disable success validation. Ungated, a `security` task* carrying it would exit 0 having committed nothing and be recorded as a pass* instead of the honest miss it is.*