Repository navigation
Conversation
|
Rebase status: HARD (draft, not pushed) — conflicts with latest |
Rebase status (2026-07-22)Attempted restack onto current Leaving draft until base PRs (#8872 close-intent, #9415 unknown-busy) land, then restack. Not closing — work is still intended, just blocked on a clean base. |
Restack onto rebased #9416 tipCherry-picked the two unique commits onto
Resolved one conflict in New head: |
9b72262 to
c641a22
Compare
Restack noteRebased onto rebased #9416 tip (force-with-lease). Stack base commits match #9416. Kept the two tip commits:
Tests: cursor/gemini/grok/command-code/droid/hermes + claude hook-service suites — 40 + 17 passed. Depends on #9416 landing first (or merge as stacked head including #9416 commits). |
c641a22 to
570d619
Compare
Restack + review guide (community, awaiting maintainer)Draft. Restacked onto rebased #9416 tip (force-with-lease). Stack base commits match #9416. +2 unique commits (11 total on branch including #9416). Unique vs main
Stack / depends
Tests (local)
Community author cannot merge. Leave draft until #9416 is accepted or stack is reviewed together. |
570d619 to
5d81dd7
Compare
|
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:
📝 WalkthroughWalkthroughAdds concurrency-safe local and remote hook JSON updates with atomic writes, retries, timeouts, and one-shot backups. Discovers marker-backed Claude configuration directories and installs, removes, and aggregates managed hooks across them. Refactors multiple agent integrations to perform non-destructive managed-hook removal. Adds Claude config-directory metadata to hook payloads, agent status state, IPC normalization, and renderer labels. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 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: 6
🧹 Nitpick comments (5)
src/main/command-code/hook-service.ts (1)
200-224: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract the shared "strip managed commands" removal loop into
installer-utils.ts.command-code/hook-service.tsandgrok/hook-service.tsduplicate the exact same orchestration aroundhookDefinitionHasManagedCommand/removeManagedCommands/updateHooksJsonWithRetry(and, per the PR description, the same pattern is repeated in cursor/droid/gemini'sremove()). A single shared helper would remove this five-way duplication.
src/main/command-code/hook-service.ts#L200-L224: replace the inline mutate callback with a call to a new shared helper, e.g.removeManagedCommandHooks(configPath, isManagedCommand), defined once ininstaller-utils.ts.src/main/grok/hook-service.ts#L322-L346: same replacement, reusing the identical shared helper instead of its own copy of the loop.♻️ Proposed shared helper (installer-utils.ts)
+export function removeManagedCommandHooks( + configPath: string, + isManagedCommand: (command: string | undefined) => boolean +): HooksConfig | null { + return updateHooksJsonWithRetry(configPath, (current) => { + const nextHooks = { ...current.hooks } + let changed = false + for (const [eventName, definitions] of Object.entries(nextHooks)) { + if (!Array.isArray(definitions)) { + continue + } + if (!definitions.some((d) => hookDefinitionHasManagedCommand(d, isManagedCommand))) { + continue + } + changed = true + const cleaned = removeManagedCommands(definitions, isManagedCommand) + if (cleaned.length === 0) { + delete nextHooks[eventName] + } else { + nextHooks[eventName] = cleaned + } + } + return changed ? { ...current, hooks: nextHooks } : null + }) +}Then each service's
remove()becomes a one-liner:- updateHooksJsonWithRetry(configPath, (current) => { - const nextHooks = { ...current.hooks } - let changed = false - for (const [eventName, definitions] of Object.entries(nextHooks)) { - if (!Array.isArray(definitions)) { - continue - } - if (!definitions.some((d) => hookDefinitionHasManagedCommand(d, isManagedCommand))) { - continue - } - changed = true - const cleaned = removeManagedCommands(definitions, isManagedCommand) - if (cleaned.length === 0) { - delete nextHooks[eventName] - } else { - nextHooks[eventName] = cleaned - } - } - return changed ? { ...current, hooks: nextHooks } : null - }) + removeManagedCommandHooks(configPath, isManagedCommand)src/main/agent-hooks/managed-agent-hook-controls.ts (1)
57-64: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low valueRun the primary
.clauderemoval before the discovered-dir sweep.
removeDiscoveredClaudeConfigDirHooks()executes first; any throw escaping it is caught byremoveManagedAgentHooks(Line 131-137) and the primaryclaudeHookService.remove()never runs — an optional flavor-dir path would block the main uninstall. Internals are fail-open today, so this is defensive ordering only.♻️ Proposed reorder
() => { // Why: each successful install leaves settings.json as a discovery marker, so removal needs no separate ownership ledger. - const configDirStatuses = removeDiscoveredClaudeConfigDirHooks() - return aggregateClaudeHookRemovalStatus(claudeHookService.remove(), configDirStatuses) + const primary = claudeHookService.remove() + return aggregateClaudeHookRemovalStatus(primary, removeDiscoveredClaudeConfigDirHooks()) }src/main/claude/hook-settings.ts (1)
15-20: 🔒 Security & Privacy | 🔵 Trivial | 💤 Low valueWidening to
stringdrops the compile-time guard on a value used to build a home-relative write path.Validation now only exists in
createClaudeConfigDirHookService;new ClaudeHookService({ settings: { configDirName, … } })bypasses it. A branded type (e.g.ClaudeConfigDirNameproduced only byisClaudeFlavorConfigDirName) would keep the boundary enforced by the type system.src/main/agent-hooks/sftp-file-primitives.ts (1)
152-173: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winProbe with
statinstead ofreaddirfor directory existence.
readdirtransfers the full entry list (with stats) for every existing segment — on$HOMEor.orcathis is a needless round-trip payload;sftp.statanswers the same question in one packet. Also, the comment claims the top-down walk avoids "a full readdir per segment", but the loop still issues exactly onereaddirper segment, so the rationale doesn't match the code.♻️ Proposed change
- // Why: walk the path top-down rather than bottom-up so an existing parent - // chain doesn't cost a full readdir per segment. POSIX-only — Windows- - // remote is out of scope for v1. + // Why: walk top-down and probe with stat (cheap) before mkdir. + // POSIX-only — Windows-remote is out of scope for v1. const segments = remotePath.split('/').filter((s) => s.length > 0) let current = remotePath.startsWith('/') ? '' : '.' for (const seg of segments) { current = current === '' ? `/${seg}` : current === '.' ? seg : `${current}/${seg}` try { - await readdir(sftp, current) + await statMode(sftp, current) } catch {src/main/cursor/hook-service.ts (1)
277-302: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winFive services now carry the same
updateHooksJsonWithRetryremoval updater. The root cause is that the null-on-no-change removal loop was copied per agent instead of being factored intosrc/main/agent-hooks/installer-utils.ts; each future fix (e.g. non-array bucket handling) must be applied five times.
src/main/cursor/hook-service.ts#L277-L302: replace the loop with a shared helper call, passing Cursor's extra top-levelcommandfilter as the optional post-filter.src/main/droid/hook-service.ts#L299-L318: replace the loop with the shared helper call (no post-filter).src/main/gemini/hook-service.ts#L280-L303: replace the loop with the shared helper call and move the non-array-bucket rationale comment into the helper.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 7e3eca31-505a-4abf-93b9-b8a9b75ee4da
📒 Files selected for processing (40)
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.tssrc/main/command-code/hook-service.test.tssrc/main/command-code/hook-service.tssrc/main/cursor/hook-service.test.tssrc/main/cursor/hook-service.tssrc/main/droid/hook-service.test.tssrc/main/droid/hook-service.tssrc/main/gemini/hook-service.test.tssrc/main/gemini/hook-service.tssrc/main/grok/hook-service.test.tssrc/main/grok/hook-service.tssrc/main/hermes/hook-service.test.tssrc/main/hermes/hook-service.tssrc/renderer/src/components/sidebar/worktree-card-compact-agent-row.tsxsrc/renderer/src/hooks/useIpcEvents.tssrc/renderer/src/store/slices/agent-status.test.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.ts
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
src/main/claude/hook-service.ts (1)
127-158: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicated retry-outcome/error-detail block between
install()andremove().Both methods declare
let retryOutcome, pass an identicalonOutcomeclosure, and build the same!updatederror-detail ternary. Consider extracting a small shared helper (e.g.runRetryOrError(configPath, mutate, agentLabel)) that returns either the updated config or a ready-made errorAgentHookInstallStatus, to avoid this logic drifting between call sites (and the other five agent hook-service files reportedly following the same pattern per the PR stack description).Also applies to: 255-284
src/main/claude/managed-hook-script.ts (1)
13-81: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider direct unit tests for the Windows/POSIX branching and Devin-skip guards.
This module is new and encodes non-trivial platform-specific branching (Devin default-vs-alternate config-dir detection, case-sensitivity differences between the
/IWindows compare and the exact POSIX compare). A focused test file exercisinggetManagedScript('local'|'posix', {skipWhenDevinImportsClaude})across these combinations would guard against regressions independent of the higher-levelhook-service.test.tscontract tests.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 65a08582-fd15-4eae-93bc-0377c46e4c11
📒 Files selected for processing (10)
config/tsconfig.cli.jsonsrc/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/remote-managed-hook-installers.tssrc/main/claude/claude-config-dir-discovery.test.tssrc/main/claude/hook-service.tssrc/main/claude/managed-hook-script.tssrc/renderer/src/components/sidebar/worktree-card-compact-agent-row.tsxsrc/renderer/src/store/slices/agent-status.ts
🚧 Files skipped from review as they are similar to previous changes (7)
- src/renderer/src/store/slices/agent-status.ts
- config/tsconfig.cli.json
- src/main/claude/claude-config-dir-discovery.test.ts
- src/main/agent-hooks/hooks-json-file.ts
- src/renderer/src/components/sidebar/worktree-card-compact-agent-row.tsx
- src/main/agent-hooks/remote-managed-hook-installers.ts
- src/main/agent-hooks/installer-utils-remote.ts
…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]>
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.
…isolate GROK_HOME in grok tests Review follow-up to the six-service remove() no-op change. - hermes remove() gated the config.yaml write on a pluginManaged flag captured before the plugin rmSync, so a managed-plugin home with a missing or unrelated config.yaml still had it created/reformatted (and .bak-rolled) after the plugin dir was deleted. Gate the write purely on orca-status being in plugins.enabled (the only key disablePlugin removes), checked directly so a malformed plugins.disabled cannot mask an enabled orca-status. Plugin removal stays independent. Add two regressions: managed plugin + deleted config.yaml, and managed plugin + byte-irregular user YAML — both must delete the plugin but neither create/rewrite config.yaml nor roll a .bak. - grok tests: getConfigPath() honors $GROK_HOME over the mocked homedir(), so an ambient GROK_HOME let the suite install/remove against the real Grok config. Save, clear, and restore GROK_HOME per test so the mocked temp home always wins. - Strengthen hermes tests: pristine case points HERMES_HOME at a not-yet-existing dir and asserts the config root is never created; install->remove preseeds user content and asserts it survives. Refs stablyai#9414.
…y outcome detail Address the PR review findings on the Claude config-dir hooks branch: - write the one-shot remote pristine backup via tmp + rename so a dropped SFTP connection mid-backup cannot leave a truncated .orca-backup that the existence probe would then keep forever, blocking every later backup - report the full remote settings path (not the bare dir name) in the discovered-dir error fallback, matching AgentHookInstallStatus.configPath usage elsewhere - distinguish 'settings.json keeps changing under us — retry' from 'Could not parse settings.json' when updateHooksJsonWithRetry returns null, via an optional onOutcome callback (install + remove) - split probe paths on the platform separator in the config-dir discovery test so the assertions hold on Windows (impl builds probes with path.join) - only append the CLAUDE_CONFIG_DIR flavor to Claude rows; child rows whose agentType is a task name must not inherit the pane's flavor label - include configDir in doneRetentionFieldsChanged so a flavor change on a reused done pane refreshes the retained row - split the managed hook script body out of claude/hook-service.ts into managed-hook-script.ts to keep the file inside the max-lines budget Co-Authored-By: Claude Fable 5 <[email protected]>
00671a7 to
06abfe0
Compare
Greptile SummaryThis PR fixes a bug where calling
Confidence Score: 5/5Safe to merge — the change is a targeted no-op guard on six remove() paths, the null-mutate pattern is already proven by the base branch, and all three test scenarios (pristine home, user file without managed entries, install→remove) pass for every affected service. The core change is well-scoped: five JSON services adopt the same null-mutate pattern already validated on the base branch, and hermes adds a direct membership check that is immune to plugins.disabled masking. The configDir sidebar feature is correctly bounded, only threaded for source === claude, and goes through React rendering so no injection risk. All write primitives move directory creation to after the identity check, so the no-op guarantee holds end-to-end. Tests are repro-first and cover the three required scenarios per service. Files Needing Attention: No files require special attention.
|
| Filename | Overview |
|---|---|
| src/main/agent-hooks/hooks-json-file.ts | New file extracting the hooks-JSON read/write contract; introduces updateHooksJsonWithRetry with null-mutate no-op, and moves writeHooksJson here (now returns boolean for stale-check signalling). mkdirSync correctly placed after the identity check so pristine remove() calls never touch the filesystem. |
| src/main/hermes/hook-service.ts | Hermes remove() now gates writeConfigFile on orca-status being in plugins.enabled, checked directly to avoid a malformed plugins.disabled masking the entry. Plugin dir rmSync remains unconditional and independent of the config write gate. |
| src/main/cursor/hook-service.ts | Cursor remove() refactored to use updateHooksJsonWithRetry with null-mutate; correctly suppresses all writes when no managed hook is present. Double-filter after removeManagedCommands preserved from prior code. |
| src/main/claude/hook-service.ts | Both install() and remove() now use updateHooksJsonWithRetry; getManagedScript extracted to managed-hook-script.ts. The null-mutate pattern correctly short-circuits the write on remove() when nothing is managed. createClaudeConfigDirHookService factory added for flavor config-dir hooks. |
| src/main/claude/claude-config-dir-discovery.ts | New file: discovers ~/.claude-name / ~/.claude.name dirs via stat-only probes (no file content read). Remote discovery has per-operation and deadline timeouts; fails open to avoid hanging startup. Candidate cap of 16 bounds worst-case SFTP round-trips. |
| src/main/claude/managed-hook-script.ts | Extracted from hook-service.ts; Devin guard now correctly allows alternate config-dir Claude launches to post status (only skips default .claude dir on Devin), and CLAUDE_CONFIG_DIR is posted as a form field for sidebar flavor labeling. |
| src/shared/agent-status-types.ts | Adds optional configDir field to AgentStatusEntry and AgentStatusPayload; bounded at 260 chars (AGENT_STATUS_CONFIG_DIR_MAX_LENGTH) to limit hostile-post impact. Correctly normalized via normalizeOptionalField. |
| src/renderer/src/components/sidebar/worktree-card-compact-agent-row.tsx | Adds getAgentIdentityLabel which appends a flavor suffix only for agentType === claude entries with a non-default configDir. Applied to both the secondary text and title attribute of the icon span. |
| src/main/agent-hooks/managed-agent-hook-registry.ts | Claude install/remove/getStatus entries now fan out to discovered config-dir flavor services. Removal uses discovery-based removeDiscoveredClaudeConfigDirHooks; failures are aggregated into a partial status rather than silently dropped. |
Flowchart
%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[remove called] --> B[readHooksJsonWithRaw]
B --> C{File exists?}
C -->|No| D[config = empty obj]
C -->|Yes| E{Valid JSON?}
E -->|No| F[return null unparseable]
E -->|Yes| D
D --> G[mutate config]
G --> H{Managed hook present?}
H -->|No| I[mutate returns null]
I --> J[Skip write - no dir or file created]
H -->|Yes| K[mutate returns nextConfig]
K --> L{attempt less than max?}
L -->|Yes - stale check on| M{Disk unchanged?}
M -->|Same| N[Rename tmp to file + roll bak]
M -->|Changed| O[Retry - re-read and re-merge]
L -->|No - force write| N
Reviews (2): Last reviewed commit: "fix(agent-hooks): avoid redundant hook f..." | Re-trigger Greptile
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: fdb0d0ff-e3bf-4229-8ab0-061d39be83f7
📒 Files selected for processing (1)
src/main/agent-hooks/hooks-json-file.ts
|
Closing as part of fork PR backlog cleanup. This branch is long-conflicted (DIRTY) against current |
fix(agent-hooks): make hook remove() a no-op when nothing is managed (six services)
Bug
On a pristine machine (an agent CLI was never installed), toggling agent hooks OFF
runs each hook service's
remove(). Six services — cursor, gemini, grok, command-code,droid (Factory), and hermes — created their config dir + settings file from scratch
instead of doing nothing:
readHooksJson()returns{},readConfigFile()returns{ ok: true, config: {} }).mkdirSync(dir, { recursive: true })before anything else(
hooks-json-file.ts:writeHooksJson,hermes/hook-service.ts:writeConfigFile), so aremove()on a home that never had the agent installed would create e.g.~/.cursor/,~/.gemini/,~/.grok/,~/.commandcode/,~/.factory/, or~/.hermes/plus itssettings file.
The same unconditional write also reformatted a user settings file that held no managed
entries and rolled its
.bak, even though Orca had nothing to remove.remove()must be a strict no-op when there is nothing managed to remove: no dir creation,no file creation, no reformat of a user file without managed entries, no backup roll.
Repro
~/.cursor,~/.gemini, … —whichever service).
remove()).After this fix: nothing is created or touched.
Fix
Apply the same no-op contract #9416 gave Claude/OpenClaude:
their removal through
updateHooksJsonWithRetry's null-mutate. The mutate strips managedcommands from every event, and returns
nullwhen no managed hook is present — whichskips the write entirely (no dir/file creation, no reformat, no
.bakroll) and, as abonus, gives
remove()the same concurrent-writer stale-checkinstall()already uses.Managed presence is detected with
hookDefinitionHasManagedCommand(matches by managedscript filename, so it still sweeps stale managed entries from older builds).
writeConfigFileon whetherorca-statusisactually in
plugins.enabled— the only keydisablePlugin()removes. The managed plugindir is still deleted independently (
rmSync), but theconfig.yamlwrite no longer keysoff the plugin files: gating on those would recreate a
config.yamlOrca had deleted, orreformat +
.bak-roll a user file that never enabledorca-status, after the plugin diris gone. Membership is checked directly (not via
getConfigEnablement()) so a malformedplugins.disabledcannot mask an enabledorca-status.No other refactoring; the install / status / remote paths are untouched.
Per-service verdict
~/.cursor/hooks.jsonupdateHooksJsonWithRetrynull-mutate~/.gemini/settings.jsonupdateHooksJsonWithRetrynull-mutate$GROK_HOME/hooks/orca-status.json(or~/.grok/…)updateHooksJsonWithRetrynull-mutate~/.commandcode/settings.jsonupdateHooksJsonWithRetrynull-mutate~/.factory/settings.jsonupdateHooksJsonWithRetrynull-mutate~/.hermes/config.yaml(+ plugin dir)config.yamlonly whenorca-statusis inplugins.enabledAll six were bugged; none were already safe.
Tests
Per service, three
remove()tests (mirroring the Claude no-op tests on the base branch),all using injected/mocked home dirs — no real
~/.*touched:remove()creates neither the config dir nor the settings file(state
not_installed).serialization: tabs / no trailing newline) and no
.bakis written.Repro-first check: the no-op tests were confirmed failing against the pre-fix source
(verified by reverting one service to base) and passing with the fix.
Review-round hardening
A follow-up review flagged two real gaps in the first cut, now fixed:
pluginManaged || enabledgate capturedpluginManagedbefore the pluginrmSync, soremove()on a managed-plugin home with amissing or unrelated
config.yamlstill created/reformatted it. Fixed by gating purely onorca-status ∈ plugins.enabled. Two regression tests were added (managed plugin + deletedconfig.yaml; managed plugin + byte-irregular user YAML) — both fail on the old gate, passon the new one.
getConfigPath()honors$GROK_HOMEover the mockedhomedir(),so an ambient
GROK_HOMEwould have let the grok suite install/remove against the realGrok config. The suite now saves, clears, and restores
GROK_HOMEinbeforeEach/afterEach.HERMES_HOMEat a not-yet-existing dir and asserts theconfig root is never created; the install→remove test preseeds user content (
model, anunrelated enabled plugin) and asserts it survives.
Verification
tsc --noEmit -p tsconfig.node.json(coverssrc/main/**/*, incl. the tests): no errors.oxlinton the touched files: clean (grok stays under the 300-linemax-linescap —no disable added).
vitest runon the sixhook-service.test.tsfiles: 40 passed / 0 failed / 5 skipped(Windows-only
#6078cases).and Windows-only cases (the 5 skipped).
ELI5
Removing managed agent hooks could still rewrite config files even when Orca had nothing managed in them. For six services, remove now does nothing when there is nothing to clean, so innocent config files stay untouched.