Repository navigation
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe 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 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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. Comment |
There was a problem hiding this comment.
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 swallowsupdateHooksJsonWithRetryfailures.Unlike
install()(lines 222-233), which checks the return value and reportsstate: '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, butremove()still proceeds togetStatus()without ever surfacing anerrorstate ordetailexplaining 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.jsonsrc/cli/cli-build-electron-free.test.tssrc/cli/runtime/metadata.tssrc/main/agent-hooks/hooks-json-file.tssrc/main/agent-hooks/installer-utils-remote.test.tssrc/main/agent-hooks/installer-utils-remote.tssrc/main/agent-hooks/installer-utils.test.tssrc/main/agent-hooks/installer-utils.tssrc/main/agent-hooks/managed-agent-hook-controls.tssrc/main/agent-hooks/remote-hook-service-installers.test.tssrc/main/agent-hooks/remote-managed-hook-installers.tssrc/main/agent-hooks/sftp-file-primitives.tssrc/main/agent-hooks/wsl-hook-relay-manager.test.tssrc/main/claude/claude-config-dir-discovery.test.tssrc/main/claude/claude-config-dir-discovery.tssrc/main/claude/claude-config-dir-hook-controls.test.tssrc/main/claude/claude-config-dir-hook-controls.tssrc/main/claude/hook-service.test.tssrc/main/claude/hook-service.tssrc/main/claude/hook-settings.tssrc/renderer/src/components/sidebar/worktree-card-compact-agent-row.tsxsrc/renderer/src/hooks/useIpcEvents.tssrc/renderer/src/store/slices/agent-status.tssrc/shared/agent-hook-listener.test.tssrc/shared/agent-hook-listener.tssrc/shared/agent-status-types.test.tssrc/shared/agent-status-types.tssrc/shared/claude-config-dir-label.tssrc/shared/orca-user-data-path.ts
|
Addressed the remaining non-inline finding from CodeRabbit review #9416 (review) in f8dd301863. |
There was a problem hiding this comment.
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 winRemove redundant
remainingarray to prevent potential race conditions.The
remainingarray collects directories that encountered an error during removal. However, because these directories are never added to theremovedSet, they are inherently preserved by thecurrent.filter((dirName) => !removed.has(dirName))logic.Concatenating
...remainingis 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...remainingwill 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.jsonsrc/main/agent-hooks/installer-utils-remote.test.tssrc/main/agent-hooks/installer-utils-remote.tssrc/main/claude/claude-config-dir-discovery.tssrc/main/claude/claude-config-dir-hook-controls.test.tssrc/main/claude/claude-config-dir-hook-controls.tssrc/main/claude/claude-config-dir-ledger.tssrc/main/claude/hook-service.test.tssrc/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
|
Taking a look! |
f8dd301 to
0f56526
Compare
|
Thanks for the thorough implementation — I rebased this onto current |
0f56526 to
9cd2b37
Compare
|
@brennanb2025 Rebased onto current Conflict resolution notes:
|
There was a problem hiding this comment.
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.jsonsrc/main/agent-hooks/hooks-json-file.tssrc/main/agent-hooks/hooks-json-read.tssrc/main/agent-hooks/installer-utils-remote.test.tssrc/main/agent-hooks/installer-utils-remote.tssrc/main/agent-hooks/installer-utils.test.tssrc/main/agent-hooks/installer-utils.tssrc/main/agent-hooks/managed-agent-hook-controls.tssrc/main/agent-hooks/remote-hook-service-installers.test.tssrc/main/agent-hooks/remote-managed-hook-installers.tssrc/main/agent-hooks/sftp-file-primitives.tssrc/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
|
@brennanb2025 Rebased onto current Ready for re-review / merge when you have a moment. |
9cd2b37 to
152f8f2
Compare
Restack noteRebased onto latest No intentional behavior change beyond resolving main drift. |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
src/main/agent-hooks/installer-utils-remote.ts (1)
208-217: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winWrite 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-backupis left behind; on the next callstatModefinds 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.jsonsrc/main/agent-hooks/hooks-json-file.tssrc/main/agent-hooks/hooks-json-read.tssrc/main/agent-hooks/installer-utils-remote.test.tssrc/main/agent-hooks/installer-utils-remote.tssrc/main/agent-hooks/installer-utils.test.tssrc/main/agent-hooks/installer-utils.tssrc/main/agent-hooks/managed-agent-hook-controls.tssrc/main/agent-hooks/remote-hook-service-installers.test.tssrc/main/agent-hooks/remote-managed-hook-installers.tssrc/main/agent-hooks/sftp-file-primitives.tssrc/main/agent-hooks/wsl-hook-relay-manager.test.tssrc/main/claude/claude-config-dir-discovery.test.tssrc/main/claude/claude-config-dir-discovery.tssrc/main/claude/claude-config-dir-hook-controls.test.tssrc/main/claude/claude-config-dir-hook-controls.tssrc/main/claude/hook-service.test.tssrc/main/claude/hook-service.tssrc/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
152f8f2 to
16689eb
Compare
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.
Restack + review guide (community, awaiting maintainer)Rebased onto latest Unique vs mainMain has no Claude alternate-config-dir discovery / install:
StackDepends on
Tests (local)
Community author cannot merge; ready for upstream review. |
16689eb to
1237de3
Compare
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.
|
Heads-up after the latest restack (force-with-lease, The PR body has been rewritten to match your tip commits (
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? |
…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.
…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]>
149fdea to
68f98d8
Compare
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 SummaryThis PR extends Orca's managed Claude status hooks to all discovered
Confidence Score: 5/5Safe 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 Files Needing Attention: The stale-check in
|
| 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
Reviews (3): Last reviewed commit: "fix(agent-hooks): preserve config projec..." | Re-trigger Greptile
|
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. 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. |
|
Closing as part of fork PR backlog cleanup. This branch is long-conflicted (DIRTY) against current |

agent-hooks: install managed Claude hooks into discovered
CLAUDE_CONFIG_DIRconfig dirsPart 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 genuineclaudelaunched withCLAUDE_CONFIG_DIR=$HOME/.claude-<name>— a common wrapper pattern foralternate 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.jsonwrites pointing at the same script.Discovery rules and privacy posture
^\.claude[-.]<suffix>(no vendor names anywhere in code — dir basenamesare user-observed data), excluding
.claudeand.openclaudethemselves(already managed), AND a marker file exists inside it:
settings.json|.claude.json|.credentials.json.readdir+statONLY. These dirs hold credentials, sofile 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-foohas no children, so its markerstat fails and it is excluded.
have to be parsed as code to find
CLAUDE_CONFIG_DIRassignments, and envinspection 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.
extra dirs" and never blocks the default
.claudeinstall.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
partialdetail; 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:
updateHooksJsonWithRetryre-reads the file just before the tmp→renamereplace; 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
nullto signal "nothing to change", which skips the writeentirely —
remove()uses this so a no-op removal never creates a missingsettings.json, reformats a user file Orca never managed, or rolls its
.bak.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
.bakcopy + rename, leaving a small TOCTOU window even on guardedattempts. Both are bounded and accepted: install re-runs on next app
start, and converging beats failing here.
settings.json.orca-backupbefore Orca's FIRST modification of anexisting file. Unlike the local rolling
.bakit is never rotated, so thepre-Orca original stays recoverable across a transport with more
partial-failure modes.
Remote parity (SSH + WSL)
Discovery runs inside
installRemoteManagedAgentHooksover the sameSFTP-shaped transport, after the static agents — so SSH (real
SFTPWrapper,after
ssh-relay-sessionresolves remote$HOME) and WSL (the fs-bridgeadapter, which has readdir/stat) inherit it with zero per-host wiring.
POSIX remotes only, matching the existing scope. The
REMOTE_MANAGED_HOOK_INSTALLER_AGENTSparity invariant intentionally keepscovering static agents only: discovered dirs are dynamic per-host instances
of the already-registered
claudeagent, exercised by their own remote andWSL 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
.cmdvariant post aconfigDirformfield — the
CLAUDE_CONFIG_DIRpath string only, never tokens; empty fordefault installs (cmd batch context expands an undefined
%VAR%to empty).normalizeHookPayloadthreads it into the parsed status payload for claudeposts; 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-freeconsole.warn(local and remote flows alike) — dir names are user-privateobserved 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-linesbumps allowed), so two mechanical extractions ride along:hooks-json-file.ts(hooks settings JSON types + read/write/retry,re-exported from
installer-utils.tsso call sites keep their importsurface) and
sftp-file-primitives.ts(the timeout-guarded ssh2 wrappers).No behavior change.
Known limitations
$HOMEdot-dir convention are missed: an absoluteCLAUDE_CONFIG_DIR=/opt/agents/claude-x, or a dir whose name doesn'tstart with
.claude-/.claude., is invisible to stat-only discovery.Deliberate trade-off — see the privacy posture above.
them (POSIX script bodies only), and discovered dirs follow that scope.
config dir to trust the hook command, exactly as it did for the first
.claudeinstall. Expected, one-time, per dir.flow exists today for any agent).
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(noseparator),
.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 writesmanaged 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 amissing settings.json/config dir, leaves a user file with no managed
hooks byte-identical (no reformat, no
.bak), and still cleans managedentries while preserving user hooks after a real install.
installer-utils.test.ts— concurrent settings.json mutation between readand 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 firstmodification, never rotated, absent on first install.
remote-hook-service-installers.test.ts— aggregate SSH installer writesmanaged 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 installsinto a discovered guest config dir.
agent-hook-listener.test.ts/agent-status-types.test.ts—configDirround-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 --noEmiton all three projects (node, cli, web): clean.oxlinton every touched file, plus type-aware switch-exhaustiveness,max-lines ratchet, reliability gates: clean.
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.