Skip to content

perf(agent-hooks): start 7 processes per Claude hook event instead of 17 - #38180

Merged
AmoabaKelvin merged 4 commits into
stablyai:mainfrom
rikbrown:rikbrown/hook-precompute-opus
Nov 4, 2026
Merged

AmoabaKelvin merged 4 commits into
stablyai:mainfrom
rikbrown:rikbrown/hook-precompute-opus

Conversation

@rikbrown

@rikbrown rikbrown commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

Each time Claude Code uses a tool, Orca's hook script runs twice. Each run started about 17 small programs. Most of them
computed the same values again and again. Now each run starts 7 on macOS and 6 on Linux, and Orca gets the same data.

Files Added Deleted Net
Test 1 0 $\color{#cf222e}{\Huge{\mathbf{−}}}$​23 $\color{#cf222e}{\Huge{\mathbf{−}}}$​23
Prod 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​111 $\color{#cf222e}{\Huge{\mathbf{−}}}$​19 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​92

What Changed

Before: one Claude hook event started 17 processes on macOS, and 17 (dash) or 19 (bash) on Linux. The print-then-post
script of the Claude-compatible CLIs started 16.

After: 7 on macOS (8 when /bin/sh is dash), 6 on Linux (dash, bash and busybox), and one fewer for the
Claude-compatible CLIs. Users see no change. The hook server gets the same headers, body and decisions, byte for byte.

Mechanism, in src/main/claude/hook-script.ts and src/main/agent-hooks/:

  • Metadata header: orca_hook_pack_metadata packs the X-Orca-Hook-Metadata header once per pane into
    hook-metadata/pane-<id>, beside the endpoint file. It reuses the file only while all six inputs match exactly
    (length-prefixed key). It writes the file to a temporary name and renames it, so a concurrent event never reads half a
    line. It writes nothing when the endpoint file is not readable.
  • Agent identity: read again on each event, without a cache, because no shell builtin can tell a reused PID from the
    process that had it. Linux reads /proc/<pid>/stat (to EOF) and boot_id with read builtins. macOS skips uname
    when OSTYPE is darwin* and runs only exec /bin/ps. Shells without OSTYPE still run uname.
  • Payload: the capture subshell execs /bin/cat. The body still goes to curl through the printf | pipe. An
    earlier revision used a here-document; it added a trailing newline to the body and, under macOS /bin/sh (bash 3.2),
    wrote every payload to a temp file, so it was dropped.
  • Cleanup: the spool drain deletes hook-metadata files older than AGENT_HOOK_SPOOL_MAX_AGE_MS, in main and in the
    WSL and remote guest. Deleting the file of a live pane only costs one repack.

Other agents' scripts are byte for byte the same.

Why

With about 36 Claude Code panes on one Mac, the Orca hook started about 35 processes per second, the largest single hook
on the machine. Each PreToolUse waits for the hook, and on macOS each exec waits for AppleSystemPolicy, so under load
the wait grows with the number of processes. Orca rewrites the hook on each launch, so a user cannot change it locally.

Alternatives:

Linked Issue

Fixes #38179

Visual Proof

N/A: no UI or interaction change. The hook sends the same data to the hook server.

Testing

Tested on macOS 27.0 (Apple silicon). Linux scripts tested with dash, bash and busybox sh. Windows and SSH remote not
tested: the Windows scripts do not change, and the remote guest runs the same POSIX script and spool drain.

  • Process count, counted from the PID gap around each run with a warm metadata file, plus Claude Code's own sh -c:

    Claude hook before after
    macOS /bin/sh (bash 3.2) 17 7
    macOS dash 16 8
    Linux dash (Debian) 17 6
    Linux bash (Debian) 19 6
    Linux busybox sh (Alpine) 17 6

    The Claude-compatible CLI script is one lower in every row.

  • A/B: old and new scripts give byte-identical requests (method, URL, headers, body) and stdout. On macOS this ran
    against a fake hook server under /bin/sh, bash and dash: both scripts, both transports, with and without an endpoint
    file (cold and warm metadata file), four payloads including a 300 KB one, 192 runs. On Linux it ran in Debian and
    Alpine containers against a fake curl that records its arguments and stdin, 96 runs.

  • pnpm tc passes. In src/main/agent-hooks, src/main/claude and src/shared/agent-hook-listener, 3606 tests pass
    and 2 fail with spawnSync /bin/sh ETIMEDOUT at a load average of 226. On origin/main at the same load, the same 2
    tests fail, and also a third.

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

  • Every added test fails without this change and avoids the
    test anti-patterns

managed-hook-script-refresh.test.ts is updated for the new script text. A test in
managed-hook-stdin-lifecycle.test.ts that only matched the script text is deleted: the runtime stdin tests in the same
file run every generated script. No new test: the A/B run above covers the behaviour.

Risk

The riskiest part is the metadata file. If the key compare were wrong, a pane could send another pane's metadata. The
key contains all six inputs with length prefixes, and the pane ID is in the file name. A failed read or write falls back
to packing the header for that event.

Back out with a plain revert. Orca rewrites the managed script on the next launch. A revert leaves the hook-metadata
directory, and nothing reads it.

Level: Low

AI Disclosure

Written with Claude Code (Claude Opus 5.5). Reviewed by a second model.

Review

Agent skill upstream boundary

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests,
    fixtures, registry entries, path tables, comments, or documentation.

Notes

Ensure no issues in: Security, Cross-platform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards
compatibility, performance

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • I stated the risk: what could break, for whom, and how to back it out
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

🤖 Generated with Claude Code

rikbrown and others added 2 commits November 4, 2026 16:02
The managed Claude hook runs for every PreToolUse and PostToolUse. On macOS
each event started 17 processes; on Linux 17 (dash) or 19 (bash).

- Agent identity: Linux reads /proc/<pid>/stat and boot_id with `read`
  builtins. macOS skips `uname` when OSTYPE is darwin and runs only
  `exec /bin/ps`, without `sed` or `printf` subshells. The identity stays per
  event: no shell builtin can tell a reused PID from the process that had it.
- Metadata header: packed once per pane into hook-metadata/pane-<id> beside
  the endpoint file, and reused only while all six inputs match exactly.
- Payload: the capture subshell execs /bin/cat, curl reads the body from a
  here-document, and the PreToolUse reply subshell execs curl.

Other agents keep their scripts byte for byte. Against a fake hook server,
the old and new scripts give the same server records, stdout, spool records
and time limits; the raw JSON body gains one trailing newline from the
here-document, which JSON parsing ignores.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…une metadata files

- Only the reply subshell that execs curl reads the body from a
  here-document. The print-then-post path of Claude-compatible CLIs uses the
  printf pipe again, so its body stays byte for byte and needs no TMPDIR.
- The spool drain removes hook-metadata files older than
  AGENT_HOOK_SPOOL_MAX_AGE_MS, in main and in the WSL/remote guest.
- The Linux identity reads /proc/<pid>/stat to EOF, so a command name with
  a newline keeps its start time.
- Comments are one line each, and the string-index stdin test is deleted;
  the runtime stdin tests in the same file cover every generated script.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The managed POSIX hook changes how it captures stdin and process identity. Its POST builder can reuse packed metadata when the six metadata inputs match, and the managed hook enables this option for both POST paths. Spool draining removes metadata-cache entries older than the spool maximum age.

Merge Risk: Minimal · up to 8042e

The managed POSIX hook changes do not show a concrete behavior or reliability risk at the reviewed head.

Pre-merge checks: Passed 3 · Failed 2

Failed Failed checks: 2 warnings

Check name Status Explanation Resolution
Linked Issues check Warning Directly linked issue #38179 has four coding requirements, plus a process-count target. Status at reviewed head 8042ed9:

1. [#38179] Metadata header packed once per pane, reused only when all six inp…
Choose one path and record it on #38179 and in the PR:
(a) Restore a here-document, or another form that feeds curl, on the PreToolUse reply path. The body must match the current bytes exactly (no added trailing newline). Verify byte-identi…
Docstring Coverage Warning Docstring coverage is 50.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.
Passed Passed checks: 3 passed
Check name Status Explanation
Out of Scope Changes check Passed Each changed file connects to #38179 or supports one of its objectives:

- src/main/agent-hooks/hook-post-command.ts: metadata cache helper and cachedMetadata option (objective 1). The head file has n…
Title check Passed The title clearly identifies the main change: reducing processes started by Claude hook events. It is concise and specific, although it does not mention the different Linux count.
Description check Passed The description is thorough and follows the template closely. It has an ELI5, a detailed What Changed section with the mechanism, a Why section with alternatives considered, a linked issue (Fixes #381…
Full details: Out of Scope Changes check

Explanation

Each changed file connects to #38179 or supports one of its objectives:

  • src/main/agent-hooks/hook-post-command.ts: metadata cache helper and cachedMetadata option (objective 1). The head file has no exec curl option and no here-document. The prior review's reference to those is stale.
  • src/main/agent-hooks/hook-process-capture.ts: uncached identity with read builtins and macOS-only ps (objective 2).
  • src/main/agent-hooks/hook-stdin-contract.ts: POSIX_HOOK_STDIN_EXEC capture reader (objective 3). Not re-read at head in this pass.
  • src/main/claude/hook-script.ts: wires the cache and stdin contract into the Claude script.
  • src/shared/agent-hook-listener/transport/agent-hook-spool.ts: prunes expired hook-metadata files. This bounds the cache from objective 1.
  • managed-hook-script-refresh.test.ts and managed-hook-stdin-lifecycle.test.ts: test updates for the generated script text and runtime stdin behavior.

No change in the reviewed summaries touches HTTP hooks (#33451, #33452), Windows scripts, or the listener protocol.

Limit: the whole-PR and incremental text diffs could not be read because changed blobs are missing from the checkout. This result relies on the head file read for hook-post-command.ts and hook-process-capture.ts, and on the PR summaries for the other files.

Full details: Description check

Explanation

The description is thorough and follows the template closely. It has an ELI5, a detailed What Changed section with the mechanism, a Why section with alternatives considered, a linked issue (Fixes #38179), an N/A visual proof with a reason, a detailed Testing section across macOS and Linux shells with process-count and A/B results, a Risk section with level and back-out plan, and an AI Disclosure. Gaps: the 'pnpm lint, typecheck, test, and build' checklist item is unchecked, and the testing section states that 3606 tests pass while 2 fail under high system load. These gaps are minor and do not block the check. The description also contains a stale ELI5 and What Changed count that conflicts with the PR objectives (7/6 vs 5/4). The description is mostly complete, so the check passes.

Full details: Linked Issues check

Explanation

Directly linked issue #38179 has four coding requirements, plus a process-count target. Status at reviewed head 8042ed9:

  1. [#38179] Metadata header packed once per pane, reused only when all six inputs match: PASS. src/main/agent-hooks/hook-post-command.ts defines orca_hook_pack_metadata. It keys the cache with length-prefixed values and stores the file as hook-metadata/pane-<id>.
  2. [#38179] Agent identity read on each event, with no cache: PASS. src/main/agent-hooks/hook-process-capture.ts reads /proc/<pid>/stat and boot_id with read builtins on Linux. On macOS it skips uname when OSTYPE is darwin* and runs exec /bin/ps.
  3. [#38179] Capture subshell execs /bin/cat: not re-verified at head in this pass. The PR summary and the prior review report POSIX_HOOK_STDIN_EXEC in src/main/agent-hooks/hook-stdin-contract.ts.
  4. [#38179] curl reads the body from a here-document on the PreToolUse reply path: FAIL. At head, the raw-JSON branch of buildPosixAgentHookPostCommand runs printf '%s' "$payload" | curl on both paths. No here-document and no exec curl remain. Commit 8042ed9 removed the here-document, as the PR objectives state. The prior PASS for this requirement no longer holds.

Result counts: [#38179] the issue targets 5 processes on macOS, 4 on Linux, and 6 for Claude-compatible CLIs. The PR reports 7 on macOS and 6 on Linux after the revert. The 5 and 4 targets are not met. The current PR description still states 5 and 4 and describes the here-document. It conflicts with head and is superseded.

The author's reason for the revert is a behavior concern: a trailing newline, and temporary-file writes by macOS /bin/sh (bash 3.2). The issue requires keeping the existing behavior, so the revert is defensible. The issue still lists the here-document as a requirement, and the counts are not met.

Resolution

Choose one path and record it on #38179 and in the PR:
(a) Restore a here-document, or another form that feeds curl, on the PreToolUse reply path. The body must match the current bytes exactly (no added trailing newline). Verify byte-identical requests and stdout on macOS sh, bash and dash, and on Linux dash, bash and busybox sh, where the here-document must not write a temporary file. Then re-measure and show 5 processes on macOS and 4 on Linux.
(b) Keep the revert. Update #38179 to withdraw the here-document requirement and set the targets to 7 on macOS and 6 on Linux, with maintainer agreement. Update the PR description to match the head.

Full details: Docstring Coverage

Explanation

Docstring coverage is 50.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 4 functions across 5 files.

Resolution

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

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

Tip

🎯 Customize your risk assessments

Guide how CodeRabbit assesses merge risk and security architecture risk. Highlight sensitive changes and explain your security boundaries using Merge Risk Instructions and Security Risk Instructions in your review settings. Security architecture risk assessments require the Advanced plan or above.

✅ Automatic approvals, with your rules

Let CodeRabbit approve pull requests once required threads are resolved, pre-merge checks pass, and your risk limits are met. Enable Automatic approvals in review settings, with overrides for teams or file paths.

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
Recent 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: 96379e6f-07c0-45f8-9fca-b906cdd0c063
Commits

Reviewing files that changed from the base of the PR and between be91bc8 and 8042ed9.

Files selected for processing: 2
  • src/main/agent-hooks/hook-post-command.ts
  • src/main/claude/hook-script.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 4 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.

Nitpick comments: 1
src/main/agent-hooks/managed-hook-script-refresh.test.ts: 1

163-190: Trivial · Maintainability & Code Quality · Quick win

Exercise the decision-mode raw-JSON exec-curl path.

The refresh test currently leaves ORCA_AGENT_HOOK_TRANSPORT unset, so claude-hook.sh uses the pipe-based path. The timeout test checks raw JSON without execCurl: true, and the decision test does not assert the curl locale. A regression in the exec-curl locale assignments would therefore remain undetected.

               ORCA_AGENT_HOOK_ENDPOINT: '',
+              ORCA_AGENT_HOOK_TRANSPORT: 'raw-json-v1',
               ORCA_AGENT_HOOK_PORT: '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: c57a5272-0ecb-463b-a383-73a4e0d91a03
Commits

Reviewing files that changed from the base of the PR and between 2270f75 and 54dd31d.

Files selected for processing: 7
  • src/main/agent-hooks/hook-post-command.ts
  • src/main/agent-hooks/hook-process-capture.ts
  • src/main/agent-hooks/hook-stdin-contract.ts
  • src/main/agent-hooks/managed-hook-script-refresh.test.ts
  • src/main/agent-hooks/managed-hook-stdin-lifecycle.test.ts
  • src/main/claude/hook-script.ts
  • src/shared/agent-hook-listener/transport/agent-hook-spool.ts
Files with no reviewable changes: 1
  • src/main/agent-hooks/managed-hook-stdin-lifecycle.test.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.

…url path

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@rikbrown

rikbrown commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai Fixed in be91bc8: the refresh locale test sets ORCA_AGENT_HOOK_TRANSPORT to ORCA_HOOK_RAW_JSON_TRANSPORT, so claude-hook.sh runs the exec curl path with the here-document. With LC_ALL= LC_NUMERIC=C removed from that exec line, the test fails (|C expected).

@coderabbitai

coderabbitai Bot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

Analysis chain

Script executed:

#!/bin/bash
fd -i '^(managed-hook-script-refresh\.test\.ts|claude-hook\.sh)$'
ast-grep outline src/main/agent-hooks/managed-hook-script-refresh.test.ts
rg -n -C 18 'ORCA_HOOK_RAW_JSON_TRANSPORT|LC_NUMERIC|locale|claude-hook\.sh' src/main/agent-hooks/managed-hook-script-refresh.test.ts

Length of output: 6302


@rikbrown Thanks. The test now selects ORCA_HOOK_RAW_JSON_TRANSPORT, uses an executable fake curl, and asserts |C. This addresses the locale-coverage concern. I inspected the test source but did not rerun the test or the mutation check.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

You are interacting with an AI system.

The here-document added a trailing newline to the raw JSON body and,
under macOS /bin/sh (bash 3.2), wrote every payload to a temp file.
Pipe the body again so the hook server gets the same bytes as before.
@AmoabaKelvin

Copy link
Copy Markdown
Collaborator

Pushed 8042ed9: dropped the exec-curl here-document so the body is piped to curl again. The here-document added a trailing newline to the body, and macOS /bin/sh (bash 3.2) wrote every payload to a temp file. Requests are now byte-identical to main (checked on macOS sh/bash/dash and Linux dash/bash/busybox). Claude events go from 17 to 7 processes on macOS and from 17/19 to 6 on Linux.

@AmoabaKelvin AmoabaKelvin changed the title perf(agent-hooks): start 5 processes per Claude hook event instead of 17 perf(agent-hooks): start 7 processes per Claude hook event instead of 17 Nov 4, 2026
@AmoabaKelvin
AmoabaKelvin merged commit c06edaf into stablyai:main Nov 4, 2026
51 checks passed
nwparker added a commit that referenced this pull request Nov 20, 2026
…d Codex hook event (#45301)

* perf(agent-hooks): start one fewer process per Claude notify event and Codex hook event

- Claude: an event that asked for no decision (every event but PreToolUse and a
  blocking PermissionRequest) discarded the reply but still captured it in a
  command-substitution subshell. It now posts the same request straight to
  /dev/null, the form non-deciding Claude-compatible scripts already use.
- Codex: the payload capture subshell execs /bin/cat instead of forking it,
  the reader Claude's script has used since #38180. Same bytes; falls back to
  the old reader when /bin/cat is missing.

An old-vs-new harness against a fake hook server gave identical requests,
stdout, exit codes and spool files across 72 runs (local and posix scripts,
9 events, Orca up and down).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: drop the decision script test, which passes without the change

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
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.

[Feature]: Start fewer processes per event in the managed Claude command hook

2 participants