Skip to content

fix(agent-hooks): make hook remove() a no-op when nothing is managed - #9436

Closed
bbingz wants to merge 15 commits into
stablyai:mainfrom
bbingz:bbingz/hook-remove-noop-gate
Closed

bbingz wants to merge 15 commits into
stablyai:mainfrom
bbingz:bbingz/hook-remove-noop-gate

Conversation

@bbingz

@bbingz bbingz commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

fix(agent-hooks): make hook remove() a no-op when nothing is managed (six services)

Stacked on #9416 (reuses its no-op write machinery — updateHooksJsonWithRetry's
null-mutate). Its base branch orca/claude-config-dir-hooks is already pushed as PR
#9416; review the two commits after that PR's tip (a5826ea24d):
3e2e7e9598 (the six-service no-op change) and 804368b323 (review follow-up —
hermes enabled-membership gate + grok GROK_HOME test isolation). Refs #9414.

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:

  • The read primitives treat a missing file as empty (readHooksJson() returns {},
    readConfigFile() returns { ok: true, config: {} }).
  • The services then wrote unconditionally. Both write primitives call
    mkdirSync(dir, { recursive: true }) before anything else
    (hooks-json-file.ts:writeHooksJson, hermes/hook-service.ts:writeConfigFile), so a
    remove() on a home that never had the agent installed would create e.g. ~/.cursor/,
    ~/.gemini/, ~/.grok/, ~/.commandcode/, ~/.factory/, or ~/.hermes/ plus its
    settings 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

  1. Start from a home where the agent CLI has never run (no ~/.cursor, ~/.gemini, … —
    whichever service).
  2. Toggle that agent's Orca status hooks OFF (the settings UI calls the service's
    remove()).
  3. Before this fix: the config dir + an Orca-serialized settings file appear from nowhere.
    After this fix: nothing is created or touched.

Fix

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

  • Five Claude-shaped JSON services (cursor, gemini, grok, command-code, droid) route
    their removal through updateHooksJsonWithRetry's null-mutate. The mutate strips managed
    commands from every event, and returns null when no managed hook is present — which
    skips the write entirely (no dir/file creation, no reformat, no .bak roll) and, as a
    bonus, gives remove() the same concurrent-writer stale-check install() already uses.
    Managed presence is detected with hookDefinitionHasManagedCommand (matches by managed
    script filename, so it still sweeps stale managed entries from older builds).
  • Hermes (bespoke YAML write path) gates writeConfigFile on whether orca-status is
    actually in plugins.enabled — the only key disablePlugin() removes. The managed plugin
    dir is still deleted independently (rmSync), but the config.yaml write no longer keys
    off the plugin files: gating on those would recreate a config.yaml Orca had deleted, or
    reformat + .bak-roll a user file that never enabled orca-status, after the plugin dir
    is gone. Membership is checked directly (not via getConfigEnablement()) so a malformed
    plugins.disabled cannot mask an enabled orca-status.

No other refactoring; the install / status / remote paths are untouched.

Per-service verdict

Service Config file Had the bug? Fix
cursor ~/.cursor/hooks.json Yes updateHooksJsonWithRetry null-mutate
gemini ~/.gemini/settings.json Yes updateHooksJsonWithRetry null-mutate
grok $GROK_HOME/hooks/orca-status.json (or ~/.grok/…) Yes updateHooksJsonWithRetry null-mutate
command-code ~/.commandcode/settings.json Yes updateHooksJsonWithRetry null-mutate
droid (Factory) ~/.factory/settings.json Yes updateHooksJsonWithRetry null-mutate
hermes ~/.hermes/config.yaml (+ plugin dir) Yes write config.yaml only when orca-status is in plugins.enabled

All 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:

  1. pristine home → remove() creates neither the config dir nor the settings file
    (state not_installed).
  2. user file without managed entries → stays byte-identical (deliberately non-Orca
    serialization: tabs / no trailing newline) and no .bak is written.
  3. real install → remove → managed entries stripped, user-authored entries preserved.

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:

  • Hermes partial-install write — the original pluginManaged || enabled gate captured
    pluginManaged before the plugin rmSync, so remove() on a managed-plugin home with a
    missing or unrelated config.yaml still created/reformatted it. Fixed by gating purely on
    orca-status ∈ plugins.enabled. Two regression tests were added (managed plugin + deleted
    config.yaml; managed plugin + byte-irregular user YAML) — both fail on the old gate, pass
    on the new one.
  • Grok test isolation — getConfigPath() honors $GROK_HOME over the mocked homedir(),
    so an ambient GROK_HOME would have let the grok suite install/remove against the real
    Grok config. The suite now saves, clears, and restores GROK_HOME in beforeEach/afterEach.
  • The Hermes pristine test now points HERMES_HOME at a not-yet-existing dir and asserts the
    config root is never created; the install→remove test preseeds user content (model, an
    unrelated enabled plugin) and asserts it survives.

Verification

  • tsc --noEmit -p tsconfig.node.json (covers src/main/**/*, incl. the tests): no errors.
  • oxlint on the touched files: clean (grok stays under the 300-line max-lines cap —
    no disable added).
  • vitest run on the six hook-service.test.ts files: 40 passed / 0 failed / 5 skipped
    (Windows-only #6078 cases).
  • Not independently re-run this round: the full test suite, adjacent importer suites,
    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.

@bbingz

bbingz commented Jul 22, 2026

Copy link
Copy Markdown
Contributor Author

Rebase status: HARD (draft, not pushed) — conflicts with latest origin/main; lower-priority draft stack left for a follow-up session.

@bbingz

bbingz commented Jul 22, 2026

Copy link
Copy Markdown
Contributor Author

Rebase status (2026-07-22)

Attempted restack onto current main; this draft stack still has large multi-file conflicts (sidebar/worktree-status / lifecycle / hook-service) against recent main landings.

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.

@bbingz

bbingz commented Jul 22, 2026

Copy link
Copy Markdown
Contributor Author

Restack onto rebased #9416 tip

Cherry-picked the two unique commits onto bbingz/claude-config-dir-hooks @ 9cd2b37648 (already on current main):

  1. fix(agent-hooks): make hook remove() a no-op when nothing is managed
  2. fix(agent-hooks): gate hermes remove() write on enabled orca-status; isolate GROK_HOME in grok tests

Resolved one conflict in gemini/hook-service.ts (null-mutate no-op path).

New head: $(git rev-parse HEAD)
Still draft. Diff vs main includes #9416 + these two commits until #9416 lands.

@bbingz
bbingz force-pushed the bbingz/hook-remove-noop-gate branch 2 times, most recently from 9b72262 to c641a22 Compare July 23, 2026 02:41
@bbingz

bbingz commented Jul 23, 2026

Copy link
Copy Markdown
Contributor Author

Restack note

Rebased onto rebased #9416 tip (force-with-lease). Stack base commits match #9416.

Kept the two tip commits:

  1. fix(agent-hooks): make hook remove() a no-op when nothing is managed
  2. fix(agent-hooks): gate hermes remove() write on enabled orca-status; isolate GROK_HOME in grok tests

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).

@bbingz
bbingz force-pushed the bbingz/hook-remove-noop-gate branch from c641a22 to 570d619 Compare July 23, 2026 03:32
@bbingz

bbingz commented Jul 23, 2026

Copy link
Copy Markdown
Contributor Author

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

remove() no-op when nothing managed for: cursor, gemini, grok, command-code, droid, hermes

Stack / depends

Tests (local)

  • six hook-service suites — 40 passed (5 skipped)

Community author cannot merge. Leave draft until #9416 is accepted or stack is reviewed together.

@coderabbitai

coderabbitai Bot commented Jul 26, 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

Adds 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)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers summary and testing well, but it omits required template sections like Screenshots, AI Review Report, Security Audit, and Notes. Add the missing template sections, or explicitly state 'No visual change' plus concise AI review, security audit, and notes entries.
Docstring Coverage ⚠️ Warning Docstring coverage is 24.53% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main change: making remove() a no-op when no managed hooks exist.
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.

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: 6

🧹 Nitpick comments (5)
src/main/command-code/hook-service.ts (1)

200-224: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract the shared "strip managed commands" removal loop into installer-utils.ts. command-code/hook-service.ts and grok/hook-service.ts duplicate the exact same orchestration around hookDefinitionHasManagedCommand/removeManagedCommands/updateHooksJsonWithRetry (and, per the PR description, the same pattern is repeated in cursor/droid/gemini's remove()). 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 in installer-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 value

Run the primary .claude removal before the discovered-dir sweep.

removeDiscoveredClaudeConfigDirHooks() executes first; any throw escaping it is caught by removeManagedAgentHooks (Line 131-137) and the primary claudeHookService.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 value

Widening to string drops 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. ClaudeConfigDirName produced only by isClaudeFlavorConfigDirName) would keep the boundary enforced by the type system.

src/main/agent-hooks/sftp-file-primitives.ts (1)

152-173: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Probe with stat instead of readdir for directory existence.

readdir transfers the full entry list (with stats) for every existing segment — on $HOME or .orca this is a needless round-trip payload; sftp.stat answers 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 one readdir per 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 win

Five services now carry the same updateHooksJsonWithRetry removal updater. The root cause is that the null-on-no-change removal loop was copied per agent instead of being factored into src/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-level command filter 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

📥 Commits

Reviewing files that changed from the base of the PR and between 8f5a454 and 5d81dd7.

📒 Files selected for processing (40)
  • 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
  • src/main/command-code/hook-service.test.ts
  • src/main/command-code/hook-service.ts
  • src/main/cursor/hook-service.test.ts
  • src/main/cursor/hook-service.ts
  • src/main/droid/hook-service.test.ts
  • src/main/droid/hook-service.ts
  • src/main/gemini/hook-service.test.ts
  • src/main/gemini/hook-service.ts
  • src/main/grok/hook-service.test.ts
  • src/main/grok/hook-service.ts
  • src/main/hermes/hook-service.test.ts
  • src/main/hermes/hook-service.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.test.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

Comment thread src/main/claude/hook-service.ts Resolved
@nwparker nwparker added the bug Something isn't working label Jul 27, 2026

@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

🧹 Nitpick comments (2)
src/main/claude/hook-service.ts (1)

127-158: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicated retry-outcome/error-detail block between install() and remove().

Both methods declare let retryOutcome, pass an identical onOutcome closure, and build the same !updated error-detail ternary. Consider extracting a small shared helper (e.g. runRetryOrError(configPath, mutate, agentLabel)) that returns either the updated config or a ready-made error AgentHookInstallStatus, 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 win

Consider 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 /I Windows compare and the exact POSIX compare). A focused test file exercising getManagedScript('local'|'posix', {skipWhenDevinImportsClaude}) across these combinations would guard against regressions independent of the higher-level hook-service.test.ts contract tests.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 65a08582-fd15-4eae-93bc-0377c46e4c11

📥 Commits

Reviewing files that changed from the base of the PR and between 5d81dd7 and aeea020.

📒 Files selected for processing (10)
  • config/tsconfig.cli.json
  • 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/remote-managed-hook-installers.ts
  • src/main/claude/claude-config-dir-discovery.test.ts
  • src/main/claude/hook-service.ts
  • src/main/claude/managed-hook-script.ts
  • src/renderer/src/components/sidebar/worktree-card-compact-agent-row.tsx
  • src/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

Comment thread src/main/claude/managed-hook-script.ts Resolved
bbingz and others added 13 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.
…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]>
@bbingz
bbingz force-pushed the bbingz/hook-remove-noop-gate branch from 00671a7 to 06abfe0 Compare July 30, 2026 12:15
Comment thread src/main/agent-hooks/hooks-json-file.ts Resolved
Comment thread src/main/agent-hooks/hooks-json-file.ts Resolved
@greptile-apps

greptile-apps Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes a bug where calling remove() on any of six agent hook services (cursor, gemini, grok, command-code, droid, hermes) on a pristine machine would create config directories and settings files from scratch instead of doing nothing. The fix applies a null-mutate no-op pattern — remove() only writes if there is actually something managed to remove.

  • Five JSON-shaped services (cursor, gemini, grok, command-code, droid) now route removal through updateHooksJsonWithRetry with a mutate function that returns null when no managed command is present, suppressing all file system side effects (dir creation, file creation, reformat, .bak roll).
  • Hermes gates its config.yaml rewrite on orca-status membership in plugins.enabled, checked directly (not via getConfigEnablement()) so a malformed plugins.disabled cannot mask an enabled entry.
  • As a secondary change, the PR also introduces per-hook-script posting of CLAUDE_CONFIG_DIR so alternate Claude config-dir flavors (e.g. ~/.claude-grok) can be labeled "Claude · grok" in the sidebar.

Confidence Score: 5/5

Safe 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.

Important Files Changed

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
Loading

Reviews (2): Last reviewed commit: "fix(agent-hooks): avoid redundant hook f..." | Re-trigger Greptile

@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 Plus

Run ID: fdb0d0ff-e3bf-4229-8ab0-061d39be83f7

📥 Commits

Reviewing files that changed from the base of the PR and between 06abfe0 and a043403.

📒 Files selected for processing (1)
  • src/main/agent-hooks/hooks-json-file.ts

Comment thread src/main/agent-hooks/hooks-json-file.ts Resolved
@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.

@bbingz bbingz closed this Aug 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants