Skip to content

fix(runtime): keep the output of workers that fail during startup - #37866

Closed
gsxdsm wants to merge 1 commit into
stablyai:mainfrom
gsxdsm:fix/hermes-worker-startup-capture
Closed

gsxdsm wants to merge 1 commit into
stablyai:mainfrom
gsxdsm:fix/hermes-worker-startup-capture

Conversation

@gsxdsm

@gsxdsm gsxdsm commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Problem

When a Hermes worker's launch fails (the agent dies, or never becomes ready), the launch command's output is lost: the PTY's exit drops the buffer, so worker-start reports a failure with no cause.

What changes

  • Retain the failed launch command's output through terminal exit, scoped to that process's own incarnation (a predecessor's tail is dropped).
  • Attach that output to the readiness-timeout error.
  • Carry it in the worker-start receipt.
  • Redact dispatch capabilities before the 2,000-character cut, so truncation cannot strip a dcap_ prefix and leave a fragment. One assertion in the existing launched-agent-exit-watch.test.ts case covers it.

How it relates to upstream #37563

#37563 makes worker-start fail promptly when the agent exits to its shell, and builds the error from the shell's last finished command. This keeps that behavior; its output reader moves into launched-agent-exit-output.ts so the exit path and the readiness-timeout path share it. Nothing #37563 covers is duplicated.

Testing

pnpm tc, pnpm check:changed --base=upstream/main, and launched-agent-exit-watch.test.ts (the new assertion fails without the redact-first order). No new test cases.

@coderabbitai

coderabbitai Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • Resume reviews
  • Trigger review
Walkthrough

The change adds shared parsing and sanitization for launched-agent exit output. PTY exit handling retains that output, and disconnected PTYs can provide it to readiness failure reporting. Readiness errors include available output for the matching failed process. Worker startup failure reasons are passed through dispatch-capability replacement before storage or return.

Severity of issue fixed: Medium

Merge Risk: Low · previous review f6410

Retained startup output is preserved in the common cases, but it can be lost in a few edge cases, and a partial capability fragment could appear in a failure reason. Fixing these before merge would make startup-failure receipts more reliable; none is likely to cause serious production failure.

Pre-merge checks: Passed 3 · Failed 2

Failed Failed checks: 2 warnings

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documenta… Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check Warning The PR description covers the problem, the changes, the relation to upstream #37563, and testing. It omits most of the required template sections: ELI5, Linked Issue (the "Fixes #" line is empty, thou… Add the missing template sections: 1) ELI5, a plain-language summary. 2) Link an actual issue in the Linked Issue section (for example, Fixes #37865, if that is the correct issue). 3) Visual Proof: write N/A with a reason, because the chang…
Passed Passed checks: 3 passed

Check name Status Explanation
Title check Passed The title names the main change: workers that fail during startup now keep their terminal output. The title is short and uses the conventional fix(runtime) prefix. The raw summary shows the change ret…
Linked Issues check Passed [#37865] requires terminal output that explains a worker startup failure to survive PTY exit. onPtyExit calls retainLaunchedAgentExitOutput before it deletes recent PTY output. The helper normaliz…
Out of Scope Changes check Passed The changes stay within [#37865]. Output extraction, PTY-exit retention, bounded diagnostic reporting, incarnation isolation, and capability redaction support startup-failure evidence. The related tes…
Full details: Title check

Explanation

The title names the main change: workers that fail during startup now keep their terminal output. The title is short and uses the conventional fix(runtime) prefix. The raw summary shows the change retains exit output for failed launched agents, sanitizes the failure reason, and attaches it to the failed worker record, which matches the title.

Full details: Linked Issues check

Explanation

[#37865] requires terminal output that explains a worker startup failure to survive PTY exit. onPtyExit calls retainLaunchedAgentExitOutput before it deletes recent PTY output. The helper normalizes terminal text and limits the retained tail to 2,000 characters. readRecentTerminalOutput and readinessFailure expose this output for the matching fresh-launch PTY incarnation. The added readiness and output tests cover retention, bounds, marker handling, ANSI removal, and exclusion for reattached, adopted, predecessor, and wrong-incarnation PTYs.

Full details: Out of Scope Changes check

Explanation

The changes stay within [#37865]. Output extraction, PTY-exit retention, bounded diagnostic reporting, incarnation isolation, and capability redaction support startup-failure evidence. The related tests verify these paths. The exit-listener cleanup change remains in the PTY exit path modified for retention. No unrelated behavior change is demonstrated.

Full details: Docstring Coverage

Explanation

Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 5 functions across 12 files.

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

Full details: Description check

Explanation

The PR description covers the problem, the changes, the relation to upstream #37563, and testing. It omits most of the required template sections: ELI5, Linked Issue (the "Fixes #" line is empty, though the objectives cite issue #37865), Visual Proof (no BEFORE/AFTER or N/A statement), Risk (no level and no revert or back-out plan), AI Disclosure, Review, the upstream skill boundary checkbox, and the checklist. The Testing section lists commands but does not mark the template checkboxes or state which platforms were tested. The description is mostly technical and specific, so it is not off-topic or vague.

Resolution

Add the missing template sections: 1) ELI5, a plain-language summary. 2) Link an actual issue in the Linked Issue section (for example, Fixes #37865, if that is the correct issue). 3) Visual Proof: write N/A with a reason, because the change has no UI impact, or attach evidence for the terminal-output behavior. 4) Risk: set the level (Low, Medium, or High), name the riskiest part (the 2,000-character retention and redaction order, and the PTY exit path), and state how to back it out with a plain revert. 5) AI Disclosure: state whether AI tools were used, or leave it blank if you are a StablyAI team member. 6) Complete the Review and Agent skill upstream boundary checkbox. 7) Mark the checklist and testing checkboxes. For Testing, state which platforms were tested (macOS, Linux, Windows, or SSH) and confirm the new or updated tests fail without the change. The description states "No new test cases," but the raw summary lists new tests in terminal-start-failure-readiness.test.ts and launched-agent-exit-output.test.ts. Reconcile this statement with the diff.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@coderabbitai coderabbitai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up Comments

Nitpick Retain the fulfilled exited-terminal durable-receipt case.

606-619: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Retain the fulfilled exited-terminal durable-receipt case.

The remaining exited-terminal fixtures exercise setup_start and setup_wait, not the default agent_readiness path. The current test exercises agent_readiness only after waitForTerminal rejects. A regression while handling a fulfilled exited wait can therefore pass without detecting an incorrect failure stage or residual-resource receipt.

Keep the redaction assertion and add a separate case for the removed fulfilled fixture.

Suggested fix
+  it('preserves durable residuals when readiness observes an exited terminal', async () => {
+    mockCreatedWorktree()
+    vi.mocked(runtime.waitForTerminal).mockResolvedValueOnce({
+      handle: 'term_worker',
+      condition: 'tui-idle',
+      satisfied: false,
+      status: 'exited',
+      exitCode: 1
+    })
+
+    const { result } = await startWorker({ name: 'exited-durable-effect' })
+
+    expect(result).toMatchObject({
+      state: 'failed',
+      failedStage: 'agent_readiness',
+      effects: expect.arrayContaining([
+        expect.objectContaining({ kind: 'worktree', id: 'repo::created' }),
+        expect.objectContaining({ kind: 'terminal', id: 'term_worker' })
+      ]),
+      residualResources: expect.arrayContaining([
+        expect.objectContaining({ kind: 'worktree', id: 'repo::created' }),
+        expect.objectContaining({ kind: 'terminal', id: 'term_worker' })
+      ])
+    })
+  })

Open the source location

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up Comments

Outside diff Skip launch-output retention when the record now belongs to a newer incarnation.

183-184: Minor · Functional Correctness · Quick win

Skip launch-output retention when the record now belongs to a newer incarnation.

Predecessor cleanup can run after a replacement spawn. Spawn clears lastExitOutput before cleanup, but cleanup then writes the predecessor's tail to the same record. A later silent replacement exit can keep that tail, which readRecentTerminalOutput returns after connected becomes false. The readiness failure then reports the predecessor's output as the replacement's launch output. The guard below retains output only when the record still belongs to the incarnation that is exiting.

Suggested fix
-      retainLaunchedAgentExitOutput(pty, this.recentPtyOutputById.get(ptyId))
+      if (pty && (!pty.incarnationId || pty.incarnationId === incarnationId)) {
+        retainLaunchedAgentExitOutput(pty, this.recentPtyOutputById.get(ptyId))
+      }

Open the source location

Outside diff Keep the launch-output tail for capacity receipts in failedWorkerStartReceipt, not in the shared fo…

79-82: Minor · Functional Correctness · Quick win

Keep the launch-output tail for capacity receipts in failedWorkerStartReceipt, not in the shared formatter.

formatTerminalStartFailure returns only the fixed capacity text. failedWorkerStartReceipt therefore drops the Last launch output tail that readinessFailure appends. A change inside the shared formatter would also reach other callers. federation-start-receipt.ts persists that result and returns it as lastError without replaceDispatchCapabilities. agent-launch-failure-code.ts stores it in the ledger without the refusal-text bound. Terminal output can contain dcap_ tokens, so this path can expose them.

Append the tail inside the worker receipt, then redact the combined text.

Suggested fix
-  const reason = replaceDispatchCapabilities(
-    formatTerminalStartFailure(args.error) ??
-      (args.error instanceof Error ? args.error.message : String(args.error))
-  ).value
+  const formatted = formatTerminalStartFailure(args.error)
+  const launchOutput =
+    args.error instanceof Error
+      ? (args.error.message.match(/\nLast launch output:\n[\s\S]*$/)?.[0] ?? '')
+      : ''
+  const reason = replaceDispatchCapabilities(
+    formatted === undefined
+      ? (args.error instanceof Error ? args.error.message : String(args.error))
+      : `${formatted}${launchOutput}`
+  ).value

Open the source location

Outside diff Redact dispatch capabilities in the federated start-failure receipt.

76-84: Major · Security & Privacy · Quick win

Redact dispatch capabilities in the federated start-failure receipt.

The readiness error appends raw launch output to its message. The federated failure receipt uses that message as reason without redaction. The reason is persisted as lastError and returned to the caller. A dispatch capability in the launch output can therefore reach the stored attachment row and the RPC response in raw form. The worker start receipt redacts the same reason. The federated receipt should apply the same replacement.

Suggested fix
 import { formatTerminalStartFailure } from '../../../../../../shared/terminal-start-failure'
+import { replaceDispatchCapabilities } from '../../../../orchestration/worker-terminal-redaction'
 import type { OrchestrationDb } from '../../../../orchestration/db'
@@ export function failFederatedAttachmentWithReceipt(args: {
-  const reason =
-    formatTerminalStartFailure(args.error) ??
-    (args.error instanceof Error ? args.error.message : String(args.error))
+  const reason = replaceDispatchCapabilities(
+    formatTerminalStartFailure(args.error) ??
+      (args.error instanceof Error ? args.error.message : String(args.error))
+  ).value

Open the source location

Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: f5b971e0-2301-4d59-b2e3-8c882d48e7aa
Commits

Reviewing files that changed from the base of the PR and between 19730ce and 49dc5cd.

Files selected for processing: 3
  • src/main/runtime/terminal-start-failure-readiness.test.ts
  • src/main/runtime/terminal/identity/pty-worktree-record.ts
  • src/main/runtime/terminal/lifecycle/pty-handle-invalidation.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.

@gsxdsm
gsxdsm force-pushed the fix/hermes-worker-startup-capture branch from 49dc5cd to 1e33405 Compare November 3, 2026 23:00

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (2)

Minor · Preserve retained launch output for capacity failures. · worker-start-receipt.ts:79-82

src/main/runtime/rpc/methods/orchestration/worker/worker-start-receipt.ts:79-82
Minor · Functional Correctness · Quick win

Preserve retained launch output for capacity failures.

When the error contains terminalStartFailure, formatTerminalStartFailure returns only the fixed Git Bash capacity message. Readiness may already have appended Last launch output to the error message, so this branch drops the retained diagnostic before persistence and receipt return. Combine the formatted message with that output suffix, then redact the combined value. (raw.githubusercontent.com)

Suggested fix
-  const reason = replaceDispatchCapabilities(
-    formatTerminalStartFailure(args.error) ??
-      (args.error instanceof Error ? args.error.message : String(args.error))
-  ).value
+  const formatted = formatTerminalStartFailure(args.error)
+  const raw = args.error instanceof Error ? args.error.message : String(args.error)
+  const launchOutput =
+    args.error instanceof Error
+      ? (raw.match(/\nLast launch output:\n[\s\S]*$/)?.[0] ?? '')
+      : ''
+  const reason = replaceDispatchCapabilities(
+    formatted === undefined ? raw : `${formatted}${launchOutput}`
+  ).value
Minor · Preserve launch output when a prompt hook finishes… · launched-agent-exit-watch.ts:17-18

src/main/runtime/launched-agent-exit-watch.ts:17-18
Minor · Functional Correctness · Quick win

Preserve launch output when a prompt hook finishes afterward.

When a prompt hook starts and finishes after the launch command, the watcher can reject after the prompt-hook finish and pass the current buffer to readLaunchedAgentExitOutput. The helper then selects the prompt-hook start and omits the launch diagnostic.

Capture the launch command boundary in failOnLaunchedAgentExit and pass it to the failure-output extraction path. Keep retainLaunchedAgentExitOutput on its existing latest-command behavior. Add a regression test for launch start, launch finish, prompt-hook start, and prompt-hook finish.

Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 9b7a62db-f955-4a23-9c5d-4db3d835bded
Commits

Reviewing files that changed from the base of the PR and between 49dc5cd and 1e33405.

Files selected for processing: 2
  • src/main/runtime/launched-agent-exit-watch.ts
  • src/main/runtime/rpc/methods/orchestration/worker/worker-start-receipt.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

@gsxdsm
gsxdsm force-pushed the fix/hermes-worker-startup-capture branch from 1e33405 to a73b9d3 Compare November 4, 2026 06:11

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 0e8df65c-763e-42bf-9573-5a5bf474deaf
Commits

Reviewing files that changed from the base of the PR and between 1e33405 and a73b9d3.

Files selected for processing: 2
  • src/main/runtime/launched-agent-exit-output.ts
  • src/main/runtime/launched-agent-exit-watch.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

Minor · Redact dispatch capabilities before truncating launch output. · launched-agent-exit-output.ts:25

src/main/runtime/launched-agent-exit-output.ts:25
Minor · Security & Privacy · Quick win

Redact dispatch capabilities before truncating launch output.

The 2,000-character cut can remove the dcap_ prefix from a token. The remaining body does not match DISPATCH_CAPABILITY_PATTERN, so redaction leaves that fragment unchanged. The fragment can then appear in the readiness error message and in the stored lastError. Redact the joined output first, then keep its last 2,000 characters.

Suggested fix
 import { applyTerminalLineControls } from './terminal-tail-line-controls'
+import { replaceDispatchCapabilities } from './orchestration/worker-terminal-redaction'
-  return recentOutput
+  const output = recentOutput
     .slice(started, stopAtFinish && finished > started ? finished : undefined)
     .replace(ZSH_PROMPT_SP, '')
     .split(/\r*\n/)
     .map((line) => terminalSafe(applyTerminalLineControls(line).text).trim())
     .filter(Boolean)
     .join('\n')
-    .slice(-LAUNCH_OUTPUT_MAX_CHARS)
+  return replaceDispatchCapabilities(output).value.slice(-LAUNCH_OUTPUT_MAX_CHARS)
Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 85af5228-b4c6-41f2-9bd9-cb4019c482d1
Commits

Reviewing files that changed from the base of the PR and between a73b9d3 and f6410d9.

Files selected for processing: 2
  • src/main/runtime/launched-agent-exit-output.test.ts
  • src/main/runtime/launched-agent-exit-output.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.

@gsxdsm
gsxdsm force-pushed the fix/hermes-worker-startup-capture branch 2 times, most recently from 0f2ac4d to 7a8b557 Compare November 5, 2026 16:00
Jinwoo-H added a commit that referenced this pull request Nov 5, 2026
A PTY exit frees its recent-output buffer before the readiness failure is formatted, so a launch that killed its terminal reported only terminal_exited. The exit now keeps what the last command printed on the PTY record, and the readiness failure for that exact incarnation reports it like a launch whose shell survived. The start receipt redacts dispatch capabilities from the reason.

Builds on #37866 by @gsxdsm.
A worker whose agent dies or never becomes ready lost the launch command's output, so the failure named no cause. Keep the output through terminal exit, attach it to the readiness-timeout error, and carry it in the start receipt. Dispatch capabilities are redacted before the 2,000-character cut so truncation cannot strip a dcap_ prefix.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@gsxdsm
gsxdsm force-pushed the fix/hermes-worker-startup-capture branch from 7a8b557 to 31dec6e Compare November 6, 2026 05:09
Jinwoo-H added a commit that referenced this pull request Nov 8, 2026
A PTY exit frees its recent-output buffer before the readiness failure is formatted, so a launch that killed its terminal reported only terminal_exited. The exit now keeps what the last command printed on the PTY record, and the readiness failure for that exact incarnation reports it like a launch whose shell survived. The start receipt redacts dispatch capabilities from the reason.

Builds on #37866 by @gsxdsm.
Jinwoo-H added a commit that referenced this pull request Nov 8, 2026
…startup (#38475)

* fix(runtime): keep the output of a worker whose PTY dies during startup

A PTY exit frees its recent-output buffer before the readiness failure is formatted, so a launch that killed its terminal reported only terminal_exited. The exit now keeps what the last command printed on the PTY record, and the readiness failure for that exact incarnation reports it like a launch whose shell survived. The start receipt redacts dispatch capabilities from the reason.

Builds on #37866 by @gsxdsm.

* fix(runtime): bind saved exit output to its incarnation and survive a repeated exit

* fix(runtime): redact secrets from a failed worker start's reason
@nwparker

Copy link
Copy Markdown
Contributor

Thanks for this! The change already landed on main in 14492c7, so I'm closing this PR. We appreciate the contribution.

@nwparker nwparker closed this Nov 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants