Skip to content

feat(droid): migrate managed hooks into hooks.json - #47840

Closed
noter wants to merge 4 commits into
stablyai:mainfrom
codeious:ac/04-d1-droid-hooks-json
Closed

noter wants to merge 4 commits into
stablyai:mainfrom
codeious:ac/04-d1-droid-hooks-json

Conversation

@noter

@noter noter commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

Droid reads hooks from ~/.factory/hooks.json ahead of the older settings.json hooks. Orca's status hooks move to the new file so Droid keeps running them, without touching the user's own hooks.

What Changed

Part 4 of 9 in a stack that adds Droid features on top of main's ACP Droid chat. Built on main at 59f3122; all 9 branches also merge cleanly into current main. It depends on PRs 1 to 3; until they merge, this diff also shows their commits. Review only this PR's commit 2c2530b5c3.

  • Writes Orca's managed Droid hooks to ~/.factory/hooks.json and removes them from settings.json, keeping user hooks and unrelated settings.
  • Carries settings.json events that hooks.json lacks into it, since a hooks.json event replaces the same event from settings.json.
  • Keeps recovery backups and refuses to write when either file is malformed.
  • Remote (SSH) installs stay atomic; WSL organization-policy reads stay scoped to the policy path.
  • Splits hook-service.ts into config, script, status and org-policy modules.

Why

Per Factory's hook docs, an event defined in hooks.json replaces the same event in that directory's settings.json. Once a user saves any hook with /hooks, Orca's managed hooks in settings.json stop running for that event and Droid terminal status stops updating.

Linked Issue

Fixes #47825

Visual Proof

N/A: no UI change; the effect is that Droid terminal status keeps updating.

Testing

Local macOS only.

  • ORCA_CODE_QUALITY_BASE=ac/03-f7-process-exit-watch pnpm check:changed passed on this commit (format, oxlint, typecheck, tests importing the change, selected ratchets).
  • Golden E2E journeys on the stack tip (tests/e2e/golden-journeys, electron-headless, 2 workers): 8 passed, 4 skipped (Windows-only). golden-fresh-profile-terminal failed; it fails the same way on main at 59f3122 on this machine (the Home terminal starts Claude Code instead of a shell).

Not run: Linux, Windows, or SSH remote hosts.

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below
  • Every added test fails without this change and avoids the test anti-patterns

Changed test files:

  • src/main/droid/hook-service.test.ts

Performance

None, because this runs only at hook install time and reads two small JSON files, as before.

Risk

Level: Medium

This rewrites files in the user's ~/.factory. A bug could drop a user hook or leave Orca's hooks in the shadowed file. Malformed files are refused and backups are kept. A revert stops the migration but does not move hooks back into settings.json. config/main-blocking-helper-baseline.txt gains rows with a # why; these need reviewer signoff.

AI Disclosure

Review

Self-reviewed this PR's single commit for correctness, security, and performance. Merge the stack in order:

  1. test(config): guard every agent home in tests #47837 test(config): guard every agent home in tests
  2. refactor(agent-hooks): add provider hook state slots #47838 refactor(agent-hooks): add provider hook state slots
  3. feat(agent-status): add a bounded agent process exit watch #47839 feat(agent-status): add a bounded agent process exit watch
  4. feat(droid): migrate managed hooks into hooks.json #47840 feat(droid): migrate managed hooks into hooks.json (this PR)
  5. feat(droid): preserve terminal ownership during child work #47841 feat(droid): preserve terminal ownership during child work
  6. feat(droid): finish terminal rows after proven process exit #47842 feat(droid): finish terminal rows after proven process exit
  7. feat(droid): list Droid models before a chat starts #47843 feat(droid): list Droid models before a chat starts
  8. feat(droid): open Droid chats in a terminal from a copy #47844 feat(droid): open Droid chats in a terminal from a copy
  9. feat(droid): run Orca's Plan mode as Droid Spec #47845 feat(droid): run Orca's Plan mode as Droid Spec

Agent skill upstream boundary

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

Notes

Considered security, macOS/Linux/Windows paths, SSH remote hosts, mobile compatibility, folder workspaces, and performance. Execution coverage is limited to the checks listed under Testing.

Checklist

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

Merge message

feat(droid): migrate managed hooks into hooks.json

A hooks.json event replaces the same settings.json event, which
shadows Orca's managed Droid hooks. Move them into hooks.json without
losing user hooks or unrelated settings, keep recovery backups,
refuse malformed files, and keep remote installs atomic.

Add the remaining agent home folders (.factory, .grok, .pi, .omp, .hermes,
.commandcode) to the real-home write guard and clear their inherited
home/config overrides, including Droid's FACTORY_HOME_OVERRIDE, before
tests pick their own homes.

No runtime, wire, storage, desktop, or mobile behavior changes.
…se timers

Provider-owned pane maps now register with ProviderHookStateSlots, so pane
teardown, moves and claim checks reach them without each map being listed
in listener-state by hand. Claude's two claim-bearing maps and its prompt
turn order move onto slots.

Claude's owed-notification timers become one lease provider behind a
generic AgentLeaseExpiryTimers, which main and the WSL relay both arm
after every stored row. Claude rows restate exactly as before.
…ng its end

AgentProcessExitWatch probes a pane's agent process after it reports a
session end, backing off from 250 ms to 8 s for at most 90 s, and stops as
soon as the probe confirms the exit, has nothing to check, or the pane no
longer holds what the watch started for. A probe that settles after a stop
or restart is ignored.

Hook providers whose SessionEnd can precede the process exit (a /clear also
ends a session) use it to end the row only once the process is gone.
Droid loads hooks.json events ahead of legacy settings.json entries.
Move managed hooks without losing user hooks or unrelated settings.
Preserve recovery backups and refuse malformed configuration files.
Keep remote installs atomic and WSL organization policy reads scoped.
@coderabbitai

coderabbitai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Walkthrough

Droid hook management now reads and updates both hooks.json and settings.json, preserves unmanaged hooks, and resolves status using hook coverage and organization policy. Remote installation accepts a platform, and WSL can read designated organization policy files. Agent hook state and lease expiry use shared provider-based helpers. A keyed process-exit watch schedules and stops process probes.

Severity of issue fixed: Medium

Merge Risk: Moderate · up to 2c253

Moving Orca's Droid hooks into hooks.json has several rough edges. A valid hooks.json containing comments is rejected, so hooks cannot be installed. A hook file with an unexpected entry shape can crash status, install and removal after the hook script has already been written. An organization-level hooks-disabled setting is not reported as a silenced state. Remote installs can overwrite a user edit made at the same moment. These should be fixed or explicitly accepted before merging.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title "feat(droid): migrate managed hooks into hooks.json" matches the main change: Orca's managed Droid status hooks move from settings.json to hooks.json, with user hooks and unrelated settings …
Description check Passed The description follows the repository template closely. It has ELI5, What Changed, Why, Linked Issue (Fixes #47825), Visual Proof (N/A with reason), Testing with platforms stated, Performance with a …
Linked Issues check Passed Issue #47825 has coding requirements only. The reviewed commit 2c2530b covers each one:
- Install to hooks.json: applyDroidInstall in src/main/droid/droid-hook-config.ts adds managed commands to ho…
Out of Scope Changes check Passed The reviewed commit 2c2530b changes map to #47825: the Droid hook config, script, status, org-policy, and remote-file modules, the hook-service split, the remote installer platform parameter, the W…
Full details: Title check

Explanation

The title "feat(droid): migrate managed hooks into hooks.json" matches the main change: Orca's managed Droid status hooks move from settings.json to hooks.json, with user hooks and unrelated settings preserved. The changeset adds droid-hook-config, droid-hook-status, and droid-org-policy modules and rewrites hook-service.ts to use them, all of which support this migration. The title is specific and follows the conventional-commit style used in the repository.

Full details: Description check

Explanation

The description follows the repository template closely. It has ELI5, What Changed, Why, Linked Issue (Fixes #47825), Visual Proof (N/A with reason), Testing with platforms stated, Performance with a 'None, because' reason, Risk with level and revert guidance, AI Disclosure left as the template comment, Review, Agent skill boundary, Notes, and Checklist. The Testing section names only local macOS and says Linux, Windows, and SSH were not run. The 'pnpm lint, typecheck, test, build' checklist item is unchecked, and the 'I manually tested' box is unchecked, which the author should confirm. The description also includes a merge message section beyond the template. Overall the description is mostly complete.

Full details: Linked Issues check

Explanation

Issue #47825 has coding requirements only. The reviewed commit 2c2530b covers each one:

  • Install to hooks.json: applyDroidInstall in src/main/droid/droid-hook-config.ts adds managed commands to hooks.json. Events missing from hooks.json are copied from settings.json first, so the shadowing does not drop them.
  • Remove only managed entries from settings.json: applyDroidRemove strips managed commands only. User hooks and unrelated settings are kept. hook-service.test.ts covers migration with user hooks and settings preserved.
  • Recovery backup: writeDroidHookFileRemote writes <path>.bak atomically before replacing a changed file. The test suite checks that the original backup is kept across unchanged reinstalls and repeated removals.
  • Refuse malformed files: status and install/remove read both files and return an error when either cannot be parsed. Tests reject malformed hook or settings files without modifying them or writing scripts.
  • Atomic SSH installs: the remote path uses the atomic .bak and write helper. No remote test is shown, and SSH was not run.
  • WSL policy reads scoped: wsl-hook-fs-bridge reads outside home only for paths in AGENT_HOOK_POLICY_READ_PATHS. Other reads stay home-scoped.
    The evidence comes from the PR summary and the changed-file summaries. Local behavior is covered by tests. Remote and WSL behavior is supported by code evidence but not by a test shown in the summary.
Full details: Out of Scope Changes check

Explanation

The reviewed commit 2c2530b changes map to #47825: the Droid hook config, script, status, org-policy, and remote-file modules, the hook-service split, the remote installer platform parameter, the WSL policy read allowlist, and the blocking-helper baseline rows. The whole-PR diff against merge base 59f3122 also contains three earlier stack commits: 8c3306e (test guard), da23b8c (provider state slots and shared lease timers), and 08e425a (agent process exit watch). The PR description discloses these as dependencies from PRs 1 to 3 and asks reviewers to review only this commit. They are not treated as changes made by this PR. Their scope was not assessed against #47825. Test and baseline-file changes support the migration work and are not out of scope.

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

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: ba2e1606-bb26-4b42-a6e8-2a84a6aab8df
Commits

Reviewing files that changed from the base of the PR and between 50f0c54 and 2c2530b.

Files selected for processing: 29

  • config/main-blocking-helper-baseline.txt
  • config/scripts/test-runtime/environment/vitest-real-agent-home-write-guard.ts
  • src/main/agent-hooks/installation/remote-managed-hook-installers.ts
  • src/main/agent-hooks/server/server-cleanup.ts
  • src/main/agent-hooks/server/server-lifecycle.ts
  • src/main/agent-hooks/server/server-status-row-mutation.ts
  • src/main/agent-hooks/wsl-relay/wsl-hook-fs-adapter.ts
  • src/main/droid/droid-hook-config.ts
  • src/main/droid/droid-hook-file-remote.ts
  • src/main/droid/droid-hook-script.ts
  • src/main/droid/droid-hook-status.ts
  • src/main/droid/droid-hooks-file.test-fixture.ts
  • src/main/droid/droid-org-policy.ts
  • src/main/droid/hook-service.test.ts
  • src/main/droid/hook-service.ts
  • src/shared/agent-hook-listener/leases/agent-lease-expiry-timers.ts
  • src/shared/agent-hook-listener/leases/hook-lease-expiry-timers.ts
  • src/shared/agent-hook-listener/listener-state.ts
  • src/shared/agent-hook-listener/pane-state-claims.ts
  • src/shared/agent-hook-listener/providers/claude/background-tasks/claude-owed-notification-expiry-timers.ts
  • src/shared/agent-hook-listener/state/provider-hook-state-slots.ts
  • src/shared/agent-hook-listener/transport/agent-hook-policy-read-paths.ts
  • src/shared/agent-status/process/agent-process-exit-watch.test.ts
  • src/shared/agent-status/process/agent-process-exit-watch.ts
  • src/shared/droid/droid-org-settings-path.ts
  • src/wsl-guest/agent-hooks/results/agent-hook-result-retry-scheduler.ts
  • src/wsl-guest/agent-hooks/server/agent-hook-request.ts
  • src/wsl-guest/agent-hooks/server/agent-hook-server.ts
  • src/wsl-guest/commands/wsl-hook-fs-bridge.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this review.

if (existing !== null) {
await writeTextFileRemoteAtomic(sftp, `${path}.bak`, existing)
}
await writeHooksJsonRemote(sftp, path, config, { serialized })

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.

Minor · Data Integrity & Integration · Quick win

Reject hooks writes when the remote file changed after the snapshot.

writeHooksJsonRemote replaces the remote file whenever its contents differ from the new serialized config, and it never checks against the snapshot used to build that config. A user save that lands between the snapshot read and the rename is overwritten. The backup does not keep that save in the live file.

Before publishing, compare the remote contents with the snapshot. If they differ, do not replace the file silently. Define the conflict behavior, either rejecting the write or rereading and reapplying only the managed entries, and keep all user entries in either case. writeTextFileRemoteAtomic already supports this check through computedFrom.

* is an empty policy, which is what Factory documents for an invalid one.
*/
export function orgAllowsManagedHooksOnly(orgSettingsPath: string): boolean {
return readHooksJson(orgSettingsPath)?.allowManagedHooksOnly === true

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.

Minor · Functional Correctness · Quick win

Report org-level hooks.hooksDisabled as a silenced Droid state.

An organization can set hooks.hooksDisabled: true in its managed settings. Droid then runs no hooks, including user and project hooks. The status check does not read this setting. orgAllowsManagedHooksOnly reads only allowManagedHooksOnly, and hooksAreDisabled reads only the member-level hooksDisabled values. When the org sets only hooks.hooksDisabled: true, resolveDroidHookCoverage can report complete coverage while Droid runs none of the hooks.

Read the org hooks.hooksDisabled value from the org settings file on both the local and remote paths. Pass it into resolveDroidHookCoverage. Report it as a silenced state, as the member-level hooksDisabled case already does.

].join('\r\n')
function readDroidHookFiles(): DroidHookFiles | { error: AgentHookInstallStatus } {
const configPath = getHooksJsonPath()
const hooksFile = readHooksJson(configPath)

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.

Major · Functional Correctness · Heavy lift

Accept JSONC comments in hooks.json before reporting a parse error.

parseHooksJsonText passes the text directly to JSON.parse, which rejects comments. Factory accepts JSONC comments in hook files, so a valid hooks.json with comments returns null. readDroidHookFiles then reports "Could not parse Factory hooks.json", and the install preflight cannot use the file. Parsing must accept JSONC comments, as Factory does, while keeping the existing BOM handling. Malformed JSON must still produce the parse error. The string-aware comment handling must not remove // or /* sequences inside JSON string values.

if (!settings) {
return { error: errorStatus(configPath, 'Could not parse Factory settings.json') }
}
return { hooksFile, settings }

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.

Minor · Stability & Availability · Quick win

Reject malformed event entries when reading the Droid hook files.

readDroidHookFiles and readRemoteDroidHookFiles accept any array as an event value. A hooks.json value such as {"Stop":[null]} passes the root-object check, and then:

  • getStatus() throws at definition.hooks in resolveDroidHookCoverage.
  • Local install() publishes the managed script, then throws in removeManagedCommands before any config file is written. The exception leaves install().
  • Remote installRemote() publishes the script, then returns an error status from its catch.
  • remove() throws in hookDefinitionHasManagedCommand without publishing anything.

Validate each event value as an array of plain-object entries. Also validate that any hooks value on an entry is an array of plain objects. Apply the same check to both readers. Return an error status from the read step. Both install() and installRemote() run that read before they publish the script, so a malformed file then fails before publication.

@nwparker

Copy link
Copy Markdown
Contributor

Thanks @noter! This issue (#47825) was fixed in #47853, which landed the same approach (install Orca's Droid hooks where Droid actually reads them) and credits you as a co-author. Closing this one as superseded — really appreciate the investigation.

@nwparker nwparker closed this Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Droid ignores Orca's status hooks once ~/.factory/hooks.json defines the same event

2 participants