Skip to content

feat(agent-hooks): install managed Claude hooks into discovered CLAUDE_CONFIG_DIR config dirs - #9416

Closed
bbingz wants to merge 18 commits into
stablyai:mainfrom
bbingz:bbingz/claude-config-dir-hooks
Closed

bbingz wants to merge 18 commits into
stablyai:mainfrom
bbingz:bbingz/claude-config-dir-hooks

Conversation

@bbingz

@bbingz bbingz commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

agent-hooks: install managed Claude hooks into discovered CLAUDE_CONFIG_DIR config dirs

Part of #9414. Independent of the
close-intent PR — the two can land in either order.

Problem

Orca's managed Claude status hooks are only written to ~/.claude/settings.json
(and ~/.openclaude). A genuine claude launched with
CLAUDE_CONFIG_DIR=$HOME/.claude-<name> — a common wrapper pattern for
alternate Anthropic-compatible endpoints — loads settings exclusively from that
dir, so it never picks up Orca's hooks and posts no status events: no sidebar
state, no working/done transitions, no tool readout. This affects local, SSH,
and WSL hosts equally.

What this PR does

Discovers Claude-shaped config dirs in the home directory and installs the
SAME managed hooks into each of them, on all three host kinds. No new hook
endpoints: these agents are genuine claude and post to the existing
/hook/claude, via the one shared ~/.orca/agent-hooks/claude-hook.sh(.cmd)
script — N dirs mean N settings.json writes pointing at the same script.

Discovery rules and privacy posture

  • A home-dir entry qualifies when its NAME matches the structural convention
    ^\.claude[-.]<suffix> (no vendor names anywhere in code — dir basenames
    are user-observed data), excluding .claude and .openclaude themselves
    (already managed), AND a marker file exists inside it:
    settings.json | .claude.json | .credentials.json.
  • Validation is readdir + stat ONLY. These dirs hold credentials, so
    file contents are never read, and dir listings / entry names are never
    logged (tests assert both). The marker probe doubles as the directory
    check: a regular file named .claude-foo has no children, so its marker
    stat fails and it is excluded.
  • Why no rc parsing or env reads: shell rc files and wrapper scripts would
    have to be parsed as code to find CLAUDE_CONFIG_DIR assignments, and env
    inspection of running processes leaks exactly the secrets-adjacent context
    we refuse to touch. The dot-dir convention is observable with two cheap,
    content-free syscalls and covers the wrapper pattern in the wild.
  • Discovery fails open: an unlisting home dir or erroring probe yields "no
    extra dirs" and never blocks the default .claude install.

Install lifecycle (marker-based, no ledger)

Each successful install leaves a managed-hooks block in that dir's
settings.json, which itself satisfies the discovery marker on later runs.
Uninstall therefore re-runs live discovery and removes managed entries from
exactly the dirs that currently qualify — no separate ownership ledger is
kept. Trade-off (accepted in review): a dir whose marker file was deleted
after install falls out of discovery and is not cleaned on uninstall; the
residue is inert hook entries in a dir nothing loads anymore.

Status folds per-dir health into the existing claude row as a count-only
partial detail; dir names never appear in status text or logs.

Concurrency safety (from adversarial review)

The settings.json read-modify-write had no stale check: a write by the CLI
itself (or a second Orca instance) landing between Orca's read and its
atomic replace was silently clobbered. Now:

  • updateHooksJsonWithRetry re-reads the file just before the tmp→rename
    replace; on divergence the attempt is discarded and re-run against fresh
    content (bounded attempts; the final attempt drops the guard so install
    still converges under a pathological writer). Claude install/remove — and
    therefore every discovered-dir service — use it. A mutate callback may
    return null to signal "nothing to change", which skips the write
    entirely — remove() uses this so a no-op removal never creates a missing
    settings.json, reformats a user file Orca never managed, or rolls its
    .bak.
  • Residual lost-update window (deliberate): the final retry attempt writes
    unguarded, so a writer that races us on every attempt can still have keys
    written inside the last read→rename window clobbered (only keys present at
    our final read survive). The guard's CAS re-read also happens just before
    the .bak copy + rename, leaving a small TOCTOU window even on guarded
    attempts. Both are bounded and accepted: install re-runs on next app
    start, and converging beats failing here.
  • Remote (SFTP) settings writes additionally take a one-shot
    settings.json.orca-backup before Orca's FIRST modification of an
    existing file. Unlike the local rolling .bak it is never rotated, so the
    pre-Orca original stays recoverable across a transport with more
    partial-failure modes.

Remote parity (SSH + WSL)

Discovery runs inside installRemoteManagedAgentHooks over the same
SFTP-shaped transport, after the static agents — so SSH (real SFTPWrapper,
after ssh-relay-session resolves remote $HOME) and WSL (the fs-bridge
adapter, which has readdir/stat) inherit it with zero per-host wiring.
POSIX remotes only, matching the existing scope. The
REMOTE_MANAGED_HOOK_INSTALLER_AGENTS parity invariant intentionally keeps
covering static agents only: discovered dirs are dynamic per-host instances
of the already-registered claude agent, exercised by their own remote and
WSL tests. The remote flow is install-only today, so no remote uninstall
exists to consume (documented in code).

Flavor label

The POSIX hook script and the Windows .cmd variant post a configDir form
field — the CLAUDE_CONFIG_DIR path string only, never tokens; empty for
default installs (cmd batch context expands an undefined %VAR% to empty).
normalizeHookPayload threads it into the parsed status payload for claude
posts; it persists/hydrates like any other payload field. The compact
sidebar agent row renders Claude · <flavor> (~/.claude-grok → "grok",
.claude.foo → "foo") when an entry carries a non-default configDir.
Payloads without the field behave exactly as today, so already-installed
scripts keep working unchanged (protocol stays v1 — the field is additive).

Diagnosability

A per-dir install that ends in state: 'error' emits one name-free
console.warn (local and remote flows alike) — dir names are user-private
observed data and never appear in logs; detailed health remains visible via
the aggregated hook status.

Incidental refactor

The concurrency guard pushed two files over the 300-line lint cap (no
max-lines bumps allowed), so two mechanical extractions ride along:
hooks-json-file.ts (hooks settings JSON types + read/write/retry,
re-exported from installer-utils.ts so call sites keep their import
surface) and sftp-file-primitives.ts (the timeout-guarded ssh2 wrappers).
No behavior change.

Known limitations

  • Config dirs outside the $HOME dot-dir convention are missed: an absolute
    CLAUDE_CONFIG_DIR=/opt/agents/claude-x, or a dir whose name doesn't
    start with .claude-/.claude., is invisible to stat-only discovery.
    Deliberate trade-off — see the privacy posture above.
  • Windows SSH remotes are unchanged: the remote installer flow already skips
    them (POSIX script bodies only), and discovered dirs follow that scope.
  • One-time hook-trust prompt: Claude Code may prompt once per NEWLY hooked
    config dir to trust the hook command, exactly as it did for the first
    .claude install. Expected, one-time, per dir.
  • Discovered-dir installs on remotes are install-only (no remote uninstall
    flow exists today for any agent).
  • A dir created after startup is picked up on the next install pass (app
    start or toggling agentStatusHooksEnabled), not live.

Tests

  • claude-config-dir-discovery.test.ts — fixture home with .claude,
    .claude-grok (marker), .claude.vertex (dot separator), .claudeX (no
    separator), .claude-empty (no marker), a regular file .claude-file,
    unrelated dot-dirs; asserts stat/readdir-only via the injected fs, probe
    paths restricted to marker files of matching candidates, nothing logged,
    fail-open on listing/probe errors; SFTP-shaped discovery incl. failure
    path; label derivation (~/.claude-grok → "grok", .claude.foo → "foo",
    Windows paths, null cases).
  • claude-config-dir-hook-controls.test.ts — multi-dir install writes
    managed entries into every discovered dir (same shared script); uninstall
    cleans exactly the rediscovered dirs and leaves other dirs untouched;
    count-only status aggregation; name-free warn on per-dir install failure;
    no logging on the success path.
  • hook-service.test.ts — remove() no-op contract: does not create a
    missing settings.json/config dir, leaves a user file with no managed
    hooks byte-identical (no reformat, no .bak), and still cleans managed
    entries while preserving user hooks after a real install.
  • installer-utils.test.ts — concurrent settings.json mutation between read
    and write takes the retry path with no lost user keys; unparseable file
    aborts without writing; final attempt converges under a pathological
    writer.
  • installer-utils-remote.test.ts — one-shot backup written before first
    modification, never rotated, absent on first install.
  • remote-hook-service-installers.test.ts — aggregate SSH installer writes
    managed hooks into a discovered remote dir, skips marker-less matches;
    parity invariant still green.
  • wsl-hook-relay-manager.test.ts — end-to-end WSL fs-bridge run installs
    into a discovered guest config dir.
  • agent-hook-listener.test.ts / agent-status-types.test.ts — configDir
    round-trips into the status payload; absent/empty field unchanged
    (back-compat); length-capped; hook script bodies carry the field and never
    a token (asserted for POSIX and the win32 .cmd).

Verification

  • tsc --noEmit on all three projects (node, cli, web): clean.
  • oxlint on every touched file, plus type-aware switch-exhaustiveness,
    max-lines ratchet, reliability gates: clean.
  • Targeted vitest post-rebase (src/main/agent-hooks/): 472 passed,
    3 skipped (win32-only, on macOS).

ELI5

Claude status hooks are installed into every discovered CLAUDE_CONFIG_DIR, not only ~/.claude. Alternate Claude configs (common for wrappers and custom endpoints) get Orca's managed hooks so status still works.

@coderabbitai

coderabbitai Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

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

Walkthrough

The change adds Claude flavor config-directory discovery and lifecycle management for local, remote, and WSL environments. Hook settings persistence now uses atomic writes, backups, stale-write detection, retries, and shared SFTP primitives. Claude hook commands report CLAUDE_CONFIG_DIR, while normalized status payloads preserve the value through IPC, storage, and sidebar rendering. CLI compilation includes the new modules, and tests cover discovery, lifecycle operations, remote backups, retries, and status propagation.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 27.94% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the main change: installing managed Claude hooks into discovered CLAUDE_CONFIG_DIR config dirs.
Description check ✅ Passed The description is detailed and covers the change, testing, and limitations, but it omits the template's explicit Screenshots, AI Review Report, and Security Audit sections.

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

Comment @coderabbitai help to get the list of available commands.

@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: 4

Caution

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

⚠️ Outside diff range comments (1)
src/main/claude/hook-service.ts (1)

305-330: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

remove() silently swallows updateHooksJsonWithRetry failures.

Unlike install() (lines 222-233), which checks the return value and reports state: 'error' when the retry-update fails, remove() discards the result entirely. If all retry attempts fail (unparseable baseline or repeated write/backup failures under concurrent settings.json edits), the managed hooks are not actually removed, but remove() still proceeds to getStatus() without ever surfacing an error state or detail explaining why removal did not take effect.

🛡️ Proposed fix mirroring install()'s error handling
-    updateHooksJsonWithRetry(configPath, (current) => {
+    const updated = updateHooksJsonWithRetry(configPath, (current) => {
       const { config: next, changed } = removeManagedHooks(
         current,
         getManagedScriptFileName(this.options.settings)
       )
       return changed ? next : null
     })
+    if (!updated) {
+      return {
+        agent: this.options.agent,
+        state: 'error',
+        configPath,
+        managedHooksPresent: false,
+        detail: `Could not parse ${this.options.displayName} settings.json`
+      }
+    }
     return this.getStatus()

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 9b972146-206b-4003-905f-181777cc5193

📥 Commits

Reviewing files that changed from the base of the PR and between 02ff7c7 and a5826ea24d034aea692f9305ac2b75c3a122d748.

📒 Files selected for processing (29)
  • config/tsconfig.cli.json
  • src/cli/cli-build-electron-free.test.ts
  • src/cli/runtime/metadata.ts
  • src/main/agent-hooks/hooks-json-file.ts
  • src/main/agent-hooks/installer-utils-remote.test.ts
  • src/main/agent-hooks/installer-utils-remote.ts
  • src/main/agent-hooks/installer-utils.test.ts
  • src/main/agent-hooks/installer-utils.ts
  • src/main/agent-hooks/managed-agent-hook-controls.ts
  • src/main/agent-hooks/remote-hook-service-installers.test.ts
  • src/main/agent-hooks/remote-managed-hook-installers.ts
  • src/main/agent-hooks/sftp-file-primitives.ts
  • src/main/agent-hooks/wsl-hook-relay-manager.test.ts
  • src/main/claude/claude-config-dir-discovery.test.ts
  • src/main/claude/claude-config-dir-discovery.ts
  • src/main/claude/claude-config-dir-hook-controls.test.ts
  • src/main/claude/claude-config-dir-hook-controls.ts
  • src/main/claude/hook-service.test.ts
  • src/main/claude/hook-service.ts
  • src/main/claude/hook-settings.ts
  • src/renderer/src/components/sidebar/worktree-card-compact-agent-row.tsx
  • src/renderer/src/hooks/useIpcEvents.ts
  • src/renderer/src/store/slices/agent-status.ts
  • src/shared/agent-hook-listener.test.ts
  • src/shared/agent-hook-listener.ts
  • src/shared/agent-status-types.test.ts
  • src/shared/agent-status-types.ts
  • src/shared/claude-config-dir-label.ts
  • src/shared/orca-user-data-path.ts

Comment thread src/main/claude/hook-service.ts Resolved
@bbingz

bbingz commented Jul 20, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the remaining non-inline finding from CodeRabbit review #9416 (review) in f8dd301863. ClaudeHookService.remove() now checks the updateHooksJsonWithRetry result and returns an error status when the guarded update cannot complete; a forced-update-failure regression test covers this path.

@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 platform limitations.

⚠️ Outside diff range comments (1)
src/main/claude/claude-config-dir-hook-controls.ts (1)

125-144: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Remove redundant remaining array to prevent potential race conditions.

The remaining array collects directories that encountered an error during removal. However, because these directories are never added to the removed Set, they are inherently preserved by the current.filter((dirName) => !removed.has(dirName)) logic.

Concatenating ...remaining is not only redundant but can introduce a race condition: if a concurrent process successfully removes one of these directories from the ledger before this callback executes, unconditionally appending ...remaining will erroneously resurrect the deleted directory.

🧹 Proposed fix to rely strictly on the `removed` Set
-  const remaining: string[] = []
   const removed = new Set<string>()
   for (const dirName of readClaudeConfigDirLedger(ledgerPath)) {
     let status: AgentHookInstallStatus
     try {
       status = createService(dirName).remove()
     } catch (error) {
       status = errorStatus(dirName, error)
     }
-    if (status.state === 'error') {
-      remaining.push(dirName)
-    } else {
+    if (status.state !== 'error') {
       removed.add(dirName)
     }
     statuses.push(status)
   }
-  updateClaudeConfigDirLedger(ledgerPath, (current) => [
-    ...current.filter((dirName) => !removed.has(dirName)),
-    ...remaining
-  ])
+  updateClaudeConfigDirLedger(ledgerPath, (current) =>
+    current.filter((dirName) => !removed.has(dirName))
+  )

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 033efd53-ee65-4cdc-91c5-266b94085983

📥 Commits

Reviewing files that changed from the base of the PR and between a5826ea24d034aea692f9305ac2b75c3a122d748 and f8dd301863187e3a6a970a736798202c19ff5b6c.

📒 Files selected for processing (9)
  • config/tsconfig.cli.json
  • src/main/agent-hooks/installer-utils-remote.test.ts
  • src/main/agent-hooks/installer-utils-remote.ts
  • src/main/claude/claude-config-dir-discovery.ts
  • src/main/claude/claude-config-dir-hook-controls.test.ts
  • src/main/claude/claude-config-dir-hook-controls.ts
  • src/main/claude/claude-config-dir-ledger.ts
  • src/main/claude/hook-service.test.ts
  • src/main/claude/hook-service.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • config/tsconfig.cli.json
  • src/main/claude/claude-config-dir-hook-controls.test.ts
  • src/main/agent-hooks/installer-utils-remote.ts
  • src/main/claude/hook-service.ts

@brennanb2025

Copy link
Copy Markdown
Contributor

Taking a look!

@brennanb2025
brennanb2025 force-pushed the bbingz/claude-config-dir-hooks branch from f8dd301 to 0f56526 Compare July 21, 2026 03:54
@brennanb2025

Copy link
Copy Markdown
Contributor

Thanks for the thorough implementation — I rebased this onto current main and kept the structural, content-free discovery approach across local, SSH, and WSL hosts. I replaced the persistent install ledger with live marker discovery: every successful install creates settings.json, so the same discovery is sufficient for status and removal; this removes the ledger race and extra CLI/user-data plumbing while preserving clean uninstall. I also require regular-file markers, revalidate config-dir names at the service boundary, preserve cancellation and per-dir failure isolation remotely, and clear stale flavor identity when a pane is reused. Validation is clean: 327 tests passed (4 platform-skipped), node/CLI/web typechecks passed, and touched-file standard/type-aware lint plus reliability and max-lines gates passed.

@bbingz
bbingz force-pushed the bbingz/claude-config-dir-hooks branch from 0f56526 to 9cd2b37 Compare July 22, 2026 01:27
@bbingz

bbingz commented Jul 22, 2026

Copy link
Copy Markdown
Contributor Author

@brennanb2025 Rebased onto current origin/main and force-pushed (bbingz/claude-config-dir-hooks → 9cd2b37648).

Conflict resolution notes:

  • Kept main's Claude statusline install/remove path while adopting the PR's updateHooksJsonWithRetry concurrent-write guard (including no-op null return + parse-failure error on remove).
  • Sidebar flavor label + configDir payload fields merged with main's newer compact-row secondary text / model max-length constants.
  • Preserved your simplified alternate-config-dir lifecycle commit and factory-boundary name validation.

@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

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 94ea77bd-a1bf-4aa9-b3d0-d8763e795c30

📥 Commits

Reviewing files that changed from the base of the PR and between f8dd301863187e3a6a970a736798202c19ff5b6c and 9cd2b37648e6bda2dcc384aee1f74f5d9bf77faf.

📒 Files selected for processing (12)
  • config/tsconfig.cli.json
  • src/main/agent-hooks/hooks-json-file.ts
  • src/main/agent-hooks/hooks-json-read.ts
  • src/main/agent-hooks/installer-utils-remote.test.ts
  • src/main/agent-hooks/installer-utils-remote.ts
  • src/main/agent-hooks/installer-utils.test.ts
  • src/main/agent-hooks/installer-utils.ts
  • src/main/agent-hooks/managed-agent-hook-controls.ts
  • src/main/agent-hooks/remote-hook-service-installers.test.ts
  • src/main/agent-hooks/remote-managed-hook-installers.ts
  • src/main/agent-hooks/sftp-file-primitives.ts
  • src/main/agent-hooks/wsl-hook-relay-manager.test.ts
🚧 Files skipped from review as they are similar to previous changes (7)
  • src/main/agent-hooks/wsl-hook-relay-manager.test.ts
  • src/main/agent-hooks/installer-utils.test.ts
  • src/main/agent-hooks/remote-hook-service-installers.test.ts
  • src/main/agent-hooks/remote-managed-hook-installers.ts
  • src/main/agent-hooks/installer-utils-remote.test.ts
  • src/main/agent-hooks/installer-utils-remote.ts
  • src/main/agent-hooks/sftp-file-primitives.ts

Comment thread src/main/agent-hooks/hooks-json-file.ts Resolved
@bbingz

bbingz commented Jul 22, 2026

Copy link
Copy Markdown
Contributor Author

@brennanb2025 Rebased onto current main (head 9cd2b37648), keeping your simplified alternate Claude hook lifecycle commit and resolving the hook-service.ts conflict against main’s statusline install/remove path.

Ready for re-review / merge when you have a moment.

@bbingz
bbingz force-pushed the bbingz/claude-config-dir-hooks branch from 9cd2b37 to 152f8f2 Compare July 23, 2026 02:40
@bbingz

bbingz commented Jul 23, 2026

Copy link
Copy Markdown
Contributor Author

Restack note

Rebased onto latest main (force-with-lease). All 9 commits applied cleanly.

No intentional behavior change beyond resolving main drift.

@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: 2

🧹 Nitpick comments (1)
src/main/agent-hooks/installer-utils-remote.ts (1)

208-217: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Write the one-shot backup atomically to protect the pristine original.

The main file write deliberately uses tmp + rename "so a partial network drop mid-write does not leave a truncated settings.json." The backup write here uses a direct, non-atomic writeFile. If it is interrupted mid-write, a truncated .orca-backup is left behind; on the next call statMode finds it, short-circuits at Line 209-210, and that corrupt file is permanently treated as the pre-Orca original — defeating the recovery guarantee this suffix exists for.

Mirror the tmp + rename flow for the backup as well.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9c6cdff0-ece0-42ab-baf8-fde958b6db04

📥 Commits

Reviewing files that changed from the base of the PR and between 9cd2b37648e6bda2dcc384aee1f74f5d9bf77faf and 152f8f2fb0e6d378646e7b23790a5dfa19a4411b.

📒 Files selected for processing (19)
  • config/tsconfig.cli.json
  • src/main/agent-hooks/hooks-json-file.ts
  • src/main/agent-hooks/hooks-json-read.ts
  • src/main/agent-hooks/installer-utils-remote.test.ts
  • src/main/agent-hooks/installer-utils-remote.ts
  • src/main/agent-hooks/installer-utils.test.ts
  • src/main/agent-hooks/installer-utils.ts
  • src/main/agent-hooks/managed-agent-hook-controls.ts
  • src/main/agent-hooks/remote-hook-service-installers.test.ts
  • src/main/agent-hooks/remote-managed-hook-installers.ts
  • src/main/agent-hooks/sftp-file-primitives.ts
  • src/main/agent-hooks/wsl-hook-relay-manager.test.ts
  • src/main/claude/claude-config-dir-discovery.test.ts
  • src/main/claude/claude-config-dir-discovery.ts
  • src/main/claude/claude-config-dir-hook-controls.test.ts
  • src/main/claude/claude-config-dir-hook-controls.ts
  • src/main/claude/hook-service.test.ts
  • src/main/claude/hook-service.ts
  • src/main/claude/hook-settings.ts
🚧 Files skipped from review as they are similar to previous changes (15)
  • src/main/agent-hooks/hooks-json-read.ts
  • src/main/claude/hook-settings.ts
  • src/main/claude/claude-config-dir-discovery.test.ts
  • src/main/agent-hooks/hooks-json-file.ts
  • src/main/agent-hooks/wsl-hook-relay-manager.test.ts
  • src/main/agent-hooks/managed-agent-hook-controls.ts
  • src/main/agent-hooks/remote-hook-service-installers.test.ts
  • src/main/agent-hooks/installer-utils.test.ts
  • src/main/agent-hooks/installer-utils-remote.test.ts
  • config/tsconfig.cli.json
  • src/main/agent-hooks/remote-managed-hook-installers.ts
  • src/main/agent-hooks/sftp-file-primitives.ts
  • src/main/claude/hook-service.test.ts
  • src/main/claude/hook-service.ts
  • src/main/agent-hooks/installer-utils.ts

@bbingz
bbingz force-pushed the bbingz/claude-config-dir-hooks branch from 152f8f2 to 16689eb Compare July 23, 2026 03:32
bbingz added a commit to bbingz/orca that referenced this pull request Jul 23, 2026
On a pristine machine (an agent CLI never installed), toggling agent hooks
OFF ran each service's remove(), and cursor, gemini, grok, command-code,
droid (Factory), and hermes each created their config dir + settings file
from scratch: readHooksJson()/readConfigFile() treat a missing file as {},
then the code wrote unconditionally (writeHooksJson/writeConfigFile always
mkdirSync the config dir). remove() also reformatted a user settings file
that held no managed entries and rolled its .bak.

Apply the same no-op contract stablyai#9416 gave Claude/OpenClaude:

- The five Claude-shaped JSON services (cursor, gemini, grok, command-code,
  droid) now run their removal through updateHooksJsonWithRetry's null-mutate
  — returning null when no managed hook is present skips the write entirely
  (no dir/file creation, no reformat, no .bak roll) and adds the same
  concurrent-writer stale-check install() already uses.
- Hermes (bespoke YAML write path) gates writeConfigFile behind a
  managed-present check: rewrite config.yaml only when the managed plugin was
  on disk or orca-status was in plugins.enabled.

Per service, add remove() tests: a pristine home creates neither the config
dir nor the settings file; a user file without managed entries stays
byte-identical (no .bak); a real install->remove still strips managed entries
and preserves user content.

Refs stablyai#9414.
@bbingz

bbingz commented Jul 23, 2026

Copy link
Copy Markdown
Contributor Author

Restack + review guide (community, awaiting maintainer)

Rebased onto latest main (force-with-lease). 9 commits, behind=0. Stack base for #9436.

Unique vs main

Main has no Claude alternate-config-dir discovery / install:

  • Discover ~/.claude-* / ~/.claude.* by structural convention (marker-only)
  • Install managed hooks into each discovered dir (local + SSH/WSL)
  • Concurrent settings.json CAS; ledger; sidebar flavor label from CLAUDE_CONFIG_DIR

Stack

#9416 (this)  ← review first
  └── #9436 (draft) remove() no-op for six services when nothing managed

Depends on

  • Nothing hard-blocked. Orthogonal to foreground / kill / transport clusters.

Tests (local)

  • claude config-dir + hook-service — 26 passed (2 skipped)

Community author cannot merge; ready for upstream review.

@bbingz
bbingz force-pushed the bbingz/claude-config-dir-hooks branch from 16689eb to 1237de3 Compare July 26, 2026 14:36
bbingz added a commit to bbingz/orca that referenced this pull request Jul 26, 2026
On a pristine machine (an agent CLI never installed), toggling agent hooks
OFF ran each service's remove(), and cursor, gemini, grok, command-code,
droid (Factory), and hermes each created their config dir + settings file
from scratch: readHooksJson()/readConfigFile() treat a missing file as {},
then the code wrote unconditionally (writeHooksJson/writeConfigFile always
mkdirSync the config dir). remove() also reformatted a user settings file
that held no managed entries and rolled its .bak.

Apply the same no-op contract stablyai#9416 gave Claude/OpenClaude:

- The five Claude-shaped JSON services (cursor, gemini, grok, command-code,
  droid) now run their removal through updateHooksJsonWithRetry's null-mutate
  — returning null when no managed hook is present skips the write entirely
  (no dir/file creation, no reformat, no .bak roll) and adds the same
  concurrent-writer stale-check install() already uses.
- Hermes (bespoke YAML write path) gates writeConfigFile behind a
  managed-present check: rewrite config.yaml only when the managed plugin was
  on disk or orca-status was in plugins.enabled.

Per service, add remove() tests: a pristine home creates neither the config
dir nor the settings file; a user file without managed entries stays
byte-identical (no .bak); a real install->remove still strips managed entries
and preserves user content.

Refs stablyai#9414.
@bbingz

bbingz commented Jul 26, 2026

Copy link
Copy Markdown
Contributor Author

Heads-up after the latest restack (force-with-lease, 1237de310):

The PR body has been rewritten to match your tip commits (16689eb84/1237de310) — the old body still described the persistent claude-config-dirs.json install ledger and its CLI electron-free guard test, both of which your marker-based redesign removed. The body now documents:

  • Install lifecycle (marker-based, no ledger): each install leaves the managed-hooks block in the dir's settings.json, which itself satisfies the discovery marker; uninstall re-runs live discovery instead of consulting a ledger.
  • The accepted trade-off: a dir whose marker file is deleted post-install falls out of discovery and is not cleaned on uninstall (residue = inert hook entries in a dir nothing loads).
  • Verification section updated to the post-rebase run: targeted vitest src/main/agent-hooks/ — 472 passed, 3 skipped (win32-only, on macOS).

No code changes on top of your tip — the rebase was clean (255 → 0 behind), all 9 commits preserved as-is. Could you re-check the rewritten body against your intent for the marker design, especially the "Known limitations" and trade-off wording?

@nwparker nwparker added the enhancement New feature or request label Jul 27, 2026
bbingz added 2 commits July 30, 2026 20:12
…l convention

Home-dir entries matching .claude-<name> / .claude.<name> are treated as
Claude config dirs when a marker file (settings.json | .claude.json |
.credentials.json) exists inside. stat/readdir only — contents are never
read and listings are never logged (these dirs hold credentials). Works
over local fs and any SFTP-shaped transport (SSH, WSL fs bridge). The
shared flavor-label helper turns a configDir path into the sidebar label
suffix (~/.claude-grok -> grok).
- updateHooksJsonWithRetry: read-modify-write with a compare-and-retry
  stale check (re-read before replace, bounded attempts, guard dropped on
  the final attempt so install converges). ClaudeHookService install/remove
  now re-merge instead of clobbering keys a concurrent writer (the CLI
  itself, a second Orca instance) added between read and replace.
- Remote (SFTP) writes take a one-shot .orca-backup of an existing
  settings file before Orca's first modification; never rotated later.
- Widen ClaudeCompatibleHookSettings.configDirName to string so discovered
  CLAUDE_CONFIG_DIR flavor dirs can reuse the per-dir service shape.
bbingz and others added 8 commits July 30, 2026 20:13
…g dirs (local)

One ClaudeHookService per discovered ~/.claude-<name> dir — N dirs mean N
settings.json writes all pointing at the one shared claude-hook script.
The lifecycle rides the existing claude entry in the managed
install/remove/status flow (same agentStatusHooksEnabled gate).

Install ledger under userData/agent-hooks records every dir Orca wrote
into (union across runs, written before installing), so uninstall cleans
exactly the touched dirs even when discovery results change later.
Ledger entries are re-validated against the naming convention on read.
Status folds per-dir health into the claude row as a count-only detail —
dir names never appear in status text or logs.
…and WSL remotes

installRemoteManagedAgentHooks now runs config-dir discovery over the same
SFTP-shaped transport after the static agents, so SSH remotes and the WSL
fs bridge both inherit it with no per-host wiring. POSIX remotes only, as
before (Windows remotes stay skipped upstream). Discovery/install failures
degrade status reporting only and log no dir names. The static-agent
parity invariant is unchanged by design — dynamic dirs are instances of
the registered claude agent, covered by their own remote + WSL tests.
…into modules

Mechanical extraction, no behavior change: the hooks settings JSON contract
(types + read/write/retry primitives) moves to hooks-json-file.ts and the
timeout-guarded ssh2 wrappers move to sftp-file-primitives.ts. Restores the
max-lines budget the concurrency guard exceeded; installer-utils re-exports
the JSON surface so call sites keep their single historical import.
…sidebar

The POSIX hook script and the Windows .cmd variant post a configDir form
field (path string only — never tokens; empty for default installs). The
listener threads it into the parsed status payload for claude posts, it
persists/hydrates like other payload fields, and the compact sidebar agent
row renders 'Claude · <flavor>' (~/.claude-grok -> grok) when an entry
carries a non-default config dir. Payloads without the field behave
exactly as before (back-compat with already-installed scripts).
- Make claude-config-dir-hook-controls electron-free: the module rides in
  the standalone orca CLI build (ELECTRON_RUN_AS_NODE, no electron in
  packaged node_modules), so a static electron import crashed every CLI
  command. Lazy-require electron and fall back to the shared userData
  convention, extracted to src/shared/orca-user-data-path.ts and reused by
  src/cli/runtime/metadata.ts. Guard test scans the whole tsconfig.cli.json
  include set for static electron imports.
- Reinstate the remove() no-op gate: updateHooksJsonWithRetry mutate may
  return null (nothing to change) so a no-op removal no longer creates a
  missing settings.json, reformats/.bak-rolls a user file without managed
  hooks, or resurrects a deleted flavor dir.
- Prune ledger entries whose dir was deleted entirely (install persists the
  prune, status skips them) so a legitimately deleted dir cannot pin the
  aggregated claude status at 'partial' forever.
- Emit one name-free console.warn when a discovered-dir install fails,
  matching the remote flow's diagnosability.
… following symlinks

CodeRabbit findings on the flavor-dir discovery loop:

- Major: readdir can return an unbounded candidate list, and each
  candidate costs up to three sequential 10s SFTP stat probes — a huge
  or wedged remote home could delay startup arbitrarily. Cap the probe
  list at 16 candidates and enforce a 15s overall discovery deadline;
  anything past the deadline keeps the dirs already confirmed.
- Minor: marker probes used stat (follows symlinks) locally and
  remotely, so a symlinked marker inside a candidate dir could vouch
  for a target outside it. Use lstat locally and prefer lstat over
  SFTP (falling back to stat for transports without it).

Co-Authored-By: Claude Fable 5 <[email protected]>
@bbingz
bbingz force-pushed the bbingz/claude-config-dir-hooks branch from 149fdea to 68f98d8 Compare July 30, 2026 12:14
bbingz added a commit to bbingz/orca that referenced this pull request Jul 30, 2026
On a pristine machine (an agent CLI never installed), toggling agent hooks
OFF ran each service's remove(), and cursor, gemini, grok, command-code,
droid (Factory), and hermes each created their config dir + settings file
from scratch: readHooksJson()/readConfigFile() treat a missing file as {},
then the code wrote unconditionally (writeHooksJson/writeConfigFile always
mkdirSync the config dir). remove() also reformatted a user settings file
that held no managed entries and rolled its .bak.

Apply the same no-op contract stablyai#9416 gave Claude/OpenClaude:

- The five Claude-shaped JSON services (cursor, gemini, grok, command-code,
  droid) now run their removal through updateHooksJsonWithRetry's null-mutate
  — returning null when no managed hook is present skips the write entirely
  (no dir/file creation, no reformat, no .bak roll) and adds the same
  concurrent-writer stale-check install() already uses.
- Hermes (bespoke YAML write path) gates writeConfigFile behind a
  managed-present check: rewrite config.yaml only when the managed plugin was
  on disk or orca-status was in plugins.enabled.

Per service, add remove() tests: a pristine home creates neither the config
dir nor the settings file; a user file without managed entries stays
byte-identical (no .bak); a real install->remove still strips managed entries
and preserves user content.

Refs stablyai#9414.
@greptile-apps

greptile-apps Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR extends Orca's managed Claude status hooks to all discovered ~/.claude-<name> / ~/.claude.<name> config directories, enabling proper hook delivery to Claude instances launched with a non-default CLAUDE_CONFIG_DIR. It also adds a CAS-based retry layer to the settings.json read-modify-write path to prevent clobbering concurrent Claude CLI writes.

  • Multi-dir discovery and install: both local (synchronous lstat) and remote (SFTP/WSL) paths discover flavor config dirs by name pattern + marker-file probe, cap candidates at 16, and install the same shared hook script into each discovered dir's settings.json, with per-dir errors surfaced as name-free console.warn.
  • Concurrency guard: updateHooksJsonWithRetry re-reads the file just before the atomic tmp→rename replace; a stale baseline causes a discard-and-retry up to 3 times, and remove() now skips the write entirely when no managed entries are present (preventing unnecessary file creation, reformatting, or .bak rotation).
  • Flavor label: the POSIX and .cmd hook scripts post configDir=%CLAUDE_CONFIG_DIR% as an extra form field; normalizeHookPayload threads it into the status payload, and the sidebar renders Claude · <flavor> when it is non-default.

Confidence Score: 5/5

Safe to merge; the core retry/install paths are well-tested and the previous marker-inside-mutate defect has been properly resolved.

Discovery, installation, and removal all follow clear fail-open contracts. The previously identified issue where the statusline marker was written inside the mutate callback (causing permanent skip on retry) has been fixed by extracting recordManagedStatusLine to run only after updateHooksJsonWithRetry confirms success. Concurrency guards, candidate caps, and the allowedAgents filter are all in place and covered by targeted tests.

Files Needing Attention: The stale-check in hooks-json-file.ts passes the already-resolved writePath into readRawHooksFile, which re-resolves it via resolveHooksJsonWritePath a second time (flagged as a P2 in a prior review cycle and still present).

Important Files Changed

Filename Overview
src/main/agent-hooks/hooks-json-file.ts New file: atomic tmp+rename writer with rolling .bak, CAS retry loop, and a stale-check that reads via readRawHooksFile—which re-resolves the already-resolved writePath through resolveHooksJsonWritePath a second time (previously noted P2; still present).
src/main/claude/hook-service.ts Refactored to use updateHooksJsonWithRetry; statusline marker write correctly moved out of the mutate callback into recordManagedStatusLine, fixing the previously-noted P1 retry-skip bug. Devin guard updated to pass-through for alternate config-dir launches.
src/main/claude/claude-config-dir-discovery.ts New file implementing local and remote flavor-dir discovery with 16-candidate cap applied before marker probes, lstat-only checks (no content reads), fail-open on listing errors, and per-operation timeouts for the SFTP path.
src/main/claude/claude-config-dir-hook-controls.ts New file: thin orchestration layer for install/remove/status across discovered dirs; aggregates per-dir errors into a count-only partial detail (names never logged); mirrors the remote warn pattern.
src/main/agent-hooks/remote-managed-hook-installers.ts Added installRemoteDiscoveredClaudeConfigDirHooks; now guarded by allowedAgents check (discovered dirs run only when no filter or when claude is included), fixing the previously-noted bypass regression.
src/main/agent-hooks/managed-agent-hook-registry.ts Claude installer now fires installDiscoveredClaudeConfigDirHooks inline; remover aggregates discovered-dir removal errors; status reader folds discovered-dir statuses into the primary row.
src/main/claude/statusline-hook-installation.ts Extracted from hook-service.ts; installManagedStatusLine is called inside the mutate callback (correct: pure config transformation), and recordManagedStatusLine writes the marker only after the retry succeeds.
src/shared/agent-status-types.ts Added configDir optional field to AgentStatusPayload and AgentStatusEntry; length-capped at 260 chars; normalized like other optional fields.
src/shared/agent-hook-listener.ts Extracts configDir from the form-encoded hook payload (claude source only); threads it into the transport payload without exposing it in non-claude sources.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[App Start / Toggle Hooks] --> B[claudeHookService.install]
    B --> C[Write shared hook script\n~/.orca/agent-hooks/claude-hook.sh]
    C --> D[updateHooksJsonWithRetry\n~/.claude/settings.json]
    D --> E{Stale check\npasses?}
    E -->|Yes| F[Rename tmp → settings.json\nWrite .bak]
    E -->|No, retry ≤3| D
    E -->|All stale| G[Return null → state: error]
    B --> H[installDiscoveredClaudeConfigDirHooks]
    H --> I[discoverLocalClaudeConfigDirNames\n~/.claude-* / ~/.claude.*]
    I --> J[Filter by name pattern\nCap at 16 candidates\nlstat marker probe only]
    J --> K{For each\ndiscovered dir}
    K --> L[createClaudeConfigDirHookService\ndirName]
    L --> M[updateHooksJsonWithRetry\n~/.claude-grok/settings.json]
    M -->|Success| N[state: installed]
    M -->|Fail| O[console.warn name-free\nstate: error]

    subgraph Remote [SSH / WSL Remote Path]
        R1[installRemoteManagedAgentHooks] --> R2[Static agent loop]
        R2 --> R3{allowedAgents\nincludes claude?}
        R3 -->|Yes| R4[installRemoteDiscoveredClaudeConfigDirHooks]
        R4 --> R5[discoverRemoteClaudeConfigDirNames\nSFTP readdir + lstat\n10s op / 15s total deadline]
        R5 --> R6[updateHooksJsonRemoteWithRetry\nper discovered dir]
    end

    subgraph Status [Status Aggregation]
        S1[getStatus for claude row] --> S2[claudeHookService.getStatus\nprimary .claude]
        S2 --> S3[aggregateClaudeHookStatusWithConfigDirs\nfold broken count into partial detail]
        S3 --> S4[Single sidebar row\nClaude · flavor when configDir set]
    end
Loading

Reviews (3): Last reviewed commit: "fix(agent-hooks): preserve config projec..." | Re-trigger Greptile

@brennanb2025

brennanb2025 commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Maintainer review update: exact current head da5cb1f carries config-directory discovery and projection across local, SSH, WSL, Windows paths, and folder workspaces, plus no-replace/CAS hardening for concurrent hooks/settings writes.

Exact-head gates are clean: bounded perf remained 12/24/204 warm operations; independent Fable and GPT review/reproduction lanes were CLEAN; 1,547 focused tests and full typecheck passed. Fresh Electron QA passed through the built installer, installed managed script, authenticated listener, snapshot, renderer store, and visible compact sidebar with zero renderer errors and byte-identical user settings; prior Linux SSH/non-git folder-workspace evidence remains applicable.

Exact-head full-app Electron QA

GitHub reports this head MERGEABLE and Greptile successful, but the merge state remains UNSTABLE and the saved low spec windows runtime is still unavailable. Native Windows runtime QA therefore remains a blocker, so I am not calling this merge-ready.

@bbingz

bbingz commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

Closing as part of fork PR backlog cleanup.

This branch is long-conflicted (DIRTY) against current main and is not on the active campaign rebase list. Feel free to reopen or cut a fresh PR from an updated branch if the change is still needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants