Skip to content

fix(cli): stop quietly when the stdout reader closes early - #3781

Merged
kaoru0822-kitauji merged 2 commits into
mainfrom
fix/cli-closed-stdout
Oct 15, 2026
Merged

kaoru0822-kitauji merged 2 commits into
mainfrom
fix/cli-closed-stdout

Conversation

@kaoru0822-kitauji

@kaoru0822-kitauji kaoru0822-kitauji commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

rea <command> | head crashed as soon as the reader closed the pipe. Agents and scripts pipe output into head all the time, and each such run produced a failure that looked like an analysis error:

  • TOON/YAML (default): an unhandled 'error' event with a Node stack trace on stderr, exit 1.
  • --format json: {"code":"UNKNOWN","message":"write EPIPE"} on stderr, exit 1.

Now the CLI stops writing, prints nothing to stderr and exits 141. That is the status git log | head and yes | head report when their reader closes the pipe.

Problem and expected behavior

When the reader closes early it declines the rest of the output; the command itself has not failed. process.stdout had no 'error' listener, so for Incur-rendered formats the EPIPE became an uncaught exception. On the JSON streaming path, writeOutputText rejected with EPIPE. Incur then reported that rejection as a command failure, and the entry point sent the report to stderr.

Change and scope

  • The entry point that owns process.stdout is scripts/rea.mjs. A shared guardClosedStdout(), called by both the ordinary CLI branch and mcp doctor, listens for EPIPE on stdout and records that the stream is closed. After that it skips further stdout writes, drops the failure report that the write rejection would otherwise send to stderr, and sets exit status 141.
  • Incur exits through process.exit(code) on its failure path. serve now receives an exit override that keeps 141 when the pipe was closed.
  • Other stdout errors keep their previous behavior. They stay unhandled, and so crash as before, unless a pending JSON write is listening and reports them.
  • docs/cli.md "Output and exit status" documents the new status.
  • Not included: MCP stdio mode, where a closed stdout means the client disconnected; that path has its own lifecycle.
  • Also not included: incur's own --token-offset past the end, which prints a reversed range (showing tokens 100000–1251 of 1251). It is an upstream rendering issue.

Contract and boundary impact

  • Semantic owner and earliest changed stage: CLI entry point stdout ownership (scripts/rea.mjs).
  • Contribution scope fit and linked maintainer decision: correctness fix within existing CLI output; not applicable.
  • CLI and MCP/tool-catalog contract: a new documented exit status 141 for a reader that closes early; schemas unchanged. MCP is unaffected.
  • Provider, bridge, target-format, or platform compatibility: all CLI commands. The regression test skips Windows, where a closed pipe reader is reported through a different error path; Windows behavior there is unverified.
  • Evidence, artifact, provenance, or reconstruction contract: unchanged; the operation still runs to completion.
  • Target selection, authority, upstream behavior, and cleanup details: unchanged.
  • Generated metadata, package, or installation impact: none.

Expected effects:

  • Documentation or usability only; no target interaction.

Evidence and regression coverage

  • Tests added: tests/boundary/cli/closedStdout.test.ts spawns the real scripts/rea.mjs. It covers capabilities (TOON and JSON) and mcp doctor --json with the reader closed before the first write. It also covers a 4 MiB streamed inspect-sqlite-database --format json result whose reader closes after the first chunk. Each case asserts exit 141 and empty stderr.
  • Base reproduction: against the unfixed scripts/rea.mjs, all 4 cases fail with code: 1 and a stderr containing node:events ... code: 'EPIPE'.
  • User-visible output before:
    $ rea trace-dylib-resolution /Applications/Ghostty.app | head -c 10
    node:events:487
          throw er; // Unhandled 'error' event
    Error: write EPIPE ...            # exit 1
    $ rea trace-dylib-resolution /Applications/Ghostty.app --format json | head -c 10
    { "code": "UNKNOWN", "message": "write EPIPE" }   # exit 1
    
    After: no stderr output, rea exits 141.
  • Remaining proof gaps: Windows closed-pipe behavior.

Validation performed

  • npm run test:focused -- tests/boundary/cli/jsonOutput.test.ts tests/boundary/cli/cliOutput.test.ts tests/boundary/cli/closedStdout.test.ts tests/boundary/cli/nativePlistCli.test.ts: 71 passed
  • npm run check:fast: passed; npm run docs:check: passed
  • Real app on macOS (Darwin 25.6, arm64). trace-dylib-resolution /Applications/Ghostty.app (143 KB of JSON) was piped into a reader that closes after 10 bytes, for TOON, JSON and YAML. Each run gave exit 141 and empty stderr; before the fix they gave exit 1 with a stack trace or an UNKNOWN error. A closed-before-first-write reader was also tested with capabilities (TOON/JSON), inspect-plist /nonexistent --format json and --llms-full: exit 141 and empty stderr in each case. Unchanged: a normal failure (inspect-plist /nonexistent --format json to a terminal) still prints its structured error and exits 1; a normal success exits 0.
  • Cost: no added work; the remaining output is simply not written once the reader is gone.

Compatibility, safety, and release

  • Breaking changes or migration steps: none. A script that treated exit 1 after a closed pipe as an analysis failure now sees 141, which matches standard Unix tools.
  • Real Hopper/Ghidra, browser, or OS coverage: macOS only.
  • Package or release metadata impact: none.
  • Security, privacy, process, or containment review: none; no new reads, writes or processes.

Author readiness

Human owner:

  • I reviewed the final diff and relevant existing code, understand the change and its edge cases, and take responsibility for the complete PR, including AI-assisted work.
  • I checked the evidence above, confirmed it supports the current change, and recorded meaningful validation gaps.
  • I declare this PR ready for initial maintainer review.

Before merge

  • This PR addresses a concrete problem or an agreed enhancement.
  • Material scope and authority questions are resolved, and any required maintainer scope decision covers the final diff.
  • The PR has one focused outcome and the title follows type(scope): outcome.
  • Related issue is linked, or the reason for not linking one is stated above. (Found while piping real CLI output; no existing issue.)
  • Tests cover changed observable behavior and meaningful failure paths.
  • Owning docs, contracts, and generated metadata are updated where needed.
  • User-visible CLI/MCP changes include representative output.
  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.

🤖 Generated with Claude Code

`rea ... | head` crashed once head closed the pipe. TOON and YAML output
raised an unhandled EPIPE 'error' event with a Node stack trace. JSON
output reported {"code":"UNKNOWN","message":"write EPIPE"} on stderr.
Both exited 1, as if the analysis had failed.

The CLI entry point owns process.stdout, so it now treats EPIPE as the
reader declining the rest of the output. It stops writing, suppresses
the failure report and exits 141 like a SIGPIPE-terminated writer, also
when Incur exits through its own failure path. Other stdout errors are
handled as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@kaoru0822-kitauji kaoru0822-kitauji added the track:bugs Small-bug loop track PRs label Oct 15, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-15T00:54:34.111262Z 0d441ee PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@greptile-apps

greptile-apps Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] Handles early pipe closure in the CLI runner.

Add the SQLite capability check before merging so the new test works across supported Node versions.

Findings

  1. P1 Tests fail on older Node ▶
Fix with agent prompt
### Issue 1
tests/boundary/cli/closedStdout.test.ts:54-56
This test runs on supported Node versions where SQLite inspection is unavailable, including Node 22 and early supported Node 24 releases. Without `DatabaseSync.limits`, the command returns a small unavailable result instead of the large row output. Closing the reader after that result cannot reliably trigger another write, so the test fails its exit-status assertion.

Gate this case with `SQLITE_NATIVE_LIMITS_AVAILABLE`, as the existing SQLite tests do, or use a large-output command available on every supported Node version.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

The PR makes closed CLI stdout pipes exit quietly with status 141.

  • The CLI stops quietly when a pipe reader closes early.

Reviews (2) · Last reviewed commit: "fix(cli): guard mcp doctor output and co..." · Reviewed by Greptile

Comment thread scripts/rea.mjs Resolved
Comment thread tests/boundary/cli/closedStdout.test.ts Resolved
The closed-reader guard was only installed for ordinary CLI commands. As a
result `rea mcp doctor | head` still crashed on EPIPE. The guard now lives
in one entry-point function shared by both CLI branches; MCP stdio keeps
its own lifecycle.

The tests now also close the reader after the first chunk of a 4 MiB
streamed JSON result, so later writes in writeJsonOutput are covered.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment on lines +54 to +56
cliTest(
"stops quietly when the reader closes during streamed JSON",
async ({ processes }) => {

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.

P1 Tests fail on older Node

This test runs on supported Node versions where SQLite inspection is unavailable, including Node 22 and early supported Node 24 releases. Without DatabaseSync.limits, the command returns a small unavailable result instead of the large row output. Closing the reader after that result cannot reliably trigger another write, so the test fails its exit-status assertion.

Gate this case with SQLITE_NATIVE_LIMITS_AVAILABLE, as the existing SQLite tests do, or use a large-output command available on every supported Node version.

Prompt To Fix With AI
This is a comment left during a code review.
Path: tests/boundary/cli/closedStdout.test.ts
Line: 54-56

Comment:
**Tests fail on older Node**

This test runs on supported Node versions where SQLite inspection is unavailable, including Node 22 and early supported Node 24 releases. Without `DatabaseSync.limits`, the command returns a small unavailable result instead of the large row output. Closing the reader after that result cannot reliably trigger another write, so the test fails its exit-status assertion.

Gate this case with `SQLITE_NATIVE_LIMITS_AVAILABLE`, as the existing SQLite tests do, or use a large-output command available on every supported Node version.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

@kaoru0822-kitauji
kaoru0822-kitauji merged commit 5e8f7c5 into main Oct 15, 2026
35 of 36 checks passed
@kaoru0822-kitauji
kaoru0822-kitauji deleted the fix/cli-closed-stdout branch October 15, 2026 01:20
@morluto morluto added area: cli CLI adapter and one-shot commands bug Something isn't working labels Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: cli CLI adapter and one-shot commands bug Something isn't working track:bugs Small-bug loop track PRs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants