Repository navigation
fix(hooks): stop orphaned managed markers from consuming user TOML - #20148
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:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📥 CommitsReviewing files that changed from the base of the PR and between 42437ddb7bc71ba05d9100af79664b204c1d936f and 47391f9. 📒 Files selected for processing (4)
🚧 Files skipped from review as they are similar to previous changes (1)
Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review. 📝 WalkthroughWalkthroughThe change adds shared TOML ownership utilities for marker blocks and recognized tables. Codex cleanup now fails closed on unterminated blocks and preserves EOL style. Kimi hook management uses validated ownership matching across status, installation, remote installation, removal, and event reading. Tests cover orphaned markers, user configuration preservation, duplicate blocks, idempotency, and CRLF handling. Priority: ➖ Normal Merge Risk: ⚪ Minimal · up to Managed TOML cleanup now preserves unrecognized user configuration while removing validated managed content, including malformed-marker and CRLF cases. No merge-blocking risk remains. 🚥 Pre-merge checks | ✅ 2 | ❌ 3❌ Failed checks (3 warnings)
✅ Passed checks (2 passed)
Full details: Linked Issues checkExplanation Issue Full details: Out of Scope Changes checkExplanation Issue
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 07706188-7d5b-4fb9-bb49-7a7284791650
📥 Commits
Reviewing files that changed from the base of the PR and between 7294915 and 9d4bdd33eefec6b7e6e085642542bdabd3e8c7c7.
📒 Files selected for processing (8)
config/tsconfig.cli.jsonsrc/main/agent-hooks/managed-toml-block-ownership.test.tssrc/main/agent-hooks/managed-toml-block-ownership.tssrc/main/codex/codex-hook-legacy-cleanup.tssrc/main/codex/codex-hook-legacy-profile-block.test.tssrc/main/kimi/hook-service.tssrc/main/kimi/kimi-hook-config-toml.test.tssrc/main/kimi/kimi-hook-config-toml.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.
9d4bdd3 to
3f6ae50
Compare
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes — a data-loss fix for Orca's marker-delimited TOML hook config blocks, applied to both the Kimi config block and the legacy Codex profile cleanup path.
managed-toml-block-ownership.ts— new shared, offset-based scanner that bounds an orphaned (end-marker-deleted) block to content a per-policy recognizer positively identifies, and fails closed when no recognizer is supplied; splices CRLF back verbatim.- Kimi config block —
applyManagedKimiHooks/removeManagedKimiHooks/readManagedKimiHookEventsnow route through the new module with a conservative[[hooks]]recognizer (exactevent/command/timeoutshape, known event, numeric timeout, command still pointing atkimi-hook.sh). - Legacy Codex profile block —
stripLegacyManagedProfileBlockfails closed on an orphan instead of deleting to EOF, and rejoins with the file's own terminator. - Tests — thorough coverage of orphan recovery, user-tail preservation, CRLF round-trips, duplicate/stray markers, and fail-closed behavior.
The core guarantee holds up under tracing: an orphaned block's ownership is bounded at the first line the recognizer rejects, so user tables appended below a hand-deleted end marker are preserved on both remove() and install(). The two documented fail-closed trades (Kimi tables stranded below user text survive and stay invisible to getStatus(); orphaned legacy Codex blocks are left in place) are the correct direction — "stale text remains" instead of "user keys and trust grants are gone."
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes (delta since the prior review at 9d4bdd3) — the fix was redesigned from "bound an orphan at the first unrecognized line" to a cleaner two-signal model, and the stranded-table trade was eliminated.
- Module renamed to
managed-toml-ownership.tsand the policy split: marker extent (terminated block owns everything between markers; an orphan owns only its stray marker line) is now independent of recognition. - Recognition decoupled from markers —
findRecognizedManagedTablesidentifies Orca-emitted tables anywhere in the file, andstripManagedTomlRegionsmerges the two region sets in one sorted splice so nesting/overlap can't double-remove. - Stranded-table trade removed — managed
[[hooks]]tables left below user text are now reclaimed onremove()/install()instead of silently firing, andreadManagedKimiHookEvents(now derived purely from recognition) reports them as live sogetStatus()can't claimnot_installed. - Recognizer tightened — the key run now terminates on a
#line (the end marker included), so the last managed table adjacent toBLOCK_ENDis still recognized; otherwise unchanged (exactevent/command/timeout, known event, numeric timeout, managed command path).
I re-traced the ownership logic end-to-end: the merge splice is correct for disjoint, overlapping, and nested regions; readManagedKimiHookEvents matches getStatus() to the tables actually still firing; and the file-wide recognition can't over-remove user content because a table only qualifies when its command still references agent-hooks/kimi-hook.sh. The orphan fail-closed guarantee for the legacy Codex block is preserved.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 3b1ee35a-fdb0-417e-8468-24c221f8b7d9
📥 Commits
Reviewing files that changed from the base of the PR and between 9d4bdd33eefec6b7e6e085642542bdabd3e8c7c7 and 3f6ae50.
📒 Files selected for processing (6)
config/tsconfig.cli.jsonsrc/main/agent-hooks/managed-toml-ownership.test.tssrc/main/agent-hooks/managed-toml-ownership.tssrc/main/codex/codex-hook-legacy-cleanup.tssrc/main/kimi/kimi-hook-config-toml.test.tssrc/main/kimi/kimi-hook-config-toml.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.
e7ed867 to
c8ec67c
Compare
There was a problem hiding this comment.
ℹ️ No critical issues — one edge case in the relaxed recognizer worth a look.
Reviewed changes — delta since the prior pullfrog review at 3f6ae50: the Kimi hook-table recognizer was relaxed to key only on the managed command path.
- Relaxed recognizer —
matchManagedHookTableno longer requires exactlyevent/command/timeout, a knownKIMI_HOOK_EVENTSevent, or a numeric timeout; a[[hooks]]table is Orca-owned whenever itscommandresolves to the managed script, so extra keys (e.g.matcher) no longer shield a customised hook from uninstall. - Status derived from recognition —
readManagedKimiHookEventsnow reads events from the same recognizer rather than re-parsing the marker block, keeping stranded tables visible togetStatus(). - Tests — exact-assertion coverage added for extra-key ownership, customised tables sitting outside any marker, multi-line-value fail-closed, and user hooks that don't invoke the managed script. Re-ran the three focused suites locally: 42 passed.
openrouter/deepseek/deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: ef0efa02-ea62-4009-9e05-aad2cb2cf304
📒 Files selected for processing (2)
src/main/kimi/kimi-hook-config-toml.test.tssrc/main/kimi/kimi-hook-config-toml.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.
c8ec67c to
42437dd
Compare
A managed block missing its end marker was treated as Orca-owned through EOF, so uninstall/reinstall deleted appended user tables. The same shape existed a second time in the Codex legacy profile cleanup. Ownership is now two separate claims: a marker pair proves extent, and a provider that can recognize its own emitted tables owns them wherever they sit. An orphaned marker owns only its own line. Recognition uses the same test for remove, install and status, so a table Orca cannot see is never one it leaves running. Co-authored-by: maoking <[email protected]> Fixes #18861
42437dd to
47391f9
Compare
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes — delta since the prior pullfrog review at c8ec67c: two review-driven hardening fixes plus the recognizer/status alignment raised in the prior thread.
- Exact marker matching —
findManagedTomlBlocksnow requires the whole trimmed line to equal a marker, so a user comment quoting a marker can no longer open or close a region and consume the file between two quoted lines. - Gap-inside-table guard —
matchManagedHookTablefails closed when a key line follows a blank line or comment before the next[header, so recognition cannot splice a table's installer-shaped prefix and strand the trailing keys (e.g.timeout) without their[[hooks]]header. - Status/remove agreement —
readTomlString/readEventNamenow parse basic and literal TOML strings and ignore inline comments, falling back to the raw literal for an unparseableevent; a tableremove()strips can no longer leavegetStatus()atnot_installed. - Legacy Codex cleanup —
stripLegacyManagedProfileBlockscans all block regions and strips the first terminated one, so a stray start marker above a complete block no longer hides it.
I traced the recognizer end-to-end against the new tests: exact matching still accepts the indented/trailing-whitespace marker forms and no longer fires on prefixed or altered markers; keysFollowGap only fails when genuine keys follow a gap before a header (consecutive [[hooks]] tables and a trailing end marker still recognize), and the event fallback keeps an unparseable literal out of not_installed. Ran the three focused suites locally — 50 passed.
openrouter/deepseek/deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

Fixes #18861
ELI5
Orca adds its own section to the bottom of some agent config files, and wraps that section in two comment lines that say "Orca's stuff starts here" and "Orca's stuff ends here". If the "ends here" line went missing — someone tidied the file, or a config tool rewrote it — Orca assumed everything from "starts here" to the end of the file was its own, and deleted all of it the next time it installed or uninstalled. Anything you had added below, like an API key or another tool's settings, silently disappeared. On top of that, if the marker comments went missing entirely, "uninstall" quietly found nothing to remove and left Orca's hooks running on your machine after you'd turned them off.
Now Orca only deletes two kinds of thing: what sits between a matched pair of markers, and lines it can positively recognise as text it wrote itself. If it can't prove a line is its own, it leaves it alone. So your settings survive, and uninstall actually removes the hooks even when the markers are long gone.
Why no screenshots
There is no UI for this. Managed hook install/remove is deliberately never exposed to the renderer (
src/main/ipc/agent-hooks.ts: "install/remove are intentionally not exposed to the renderer" — Orca auto-installs at startup), so the only human-facing surfaces are theorca agent hooks statusCLI output and the config file itself. Both are captured below as literal text. A screenshot here would be theatre.The bug (data loss, two separate paths)
Orca appends marker-delimited blocks to user-owned TOML config files. The end marker is the only proof of where Orca's bytes stop. Both managed-TOML-block implementations treated a missing end marker as "Orca owns everything through EOF" — so a single hand-edit that dropped the end marker turned the next uninstall or reinstall into a silent delete of every table the user had appended below.
Path 1 — Kimi
~/.kimi-code/config.toml(src/main/kimi/kimi-hook-config-toml.ts). The block regex ended in(?:BLOCK_END[^\n]*|$); the$alternative swallowed the rest of the file.Path 2 — Codex legacy profile
~/.codex/orca-agent-status.config.toml(src/main/codex/codex-hook-legacy-cleanup.ts). Same shape, spelled differently:This second one runs from
cleanupLegacyManagedHookRepresentations()on every Codex hook cleanup, against a file that also holds the user's[projects.*]trust entries. It is not a footnote — it is an independent way to lose user config.I re-swept
src/main/for a third instance: there are exactly two paired start/end marker conventions in the codebase (kimi-hook-config-toml.ts,codex-hook-legacy-cleanup.ts), both fixed here. The other=== -1 ? content.lengthhits inconfig-toml-hook-trust-blocks.ts,config-toml-hook-trust-read.tsandconfig-toml-project-trust.tsare not affected: those bound a block by the next TOML table header, which is the actual TOML grammar for a table's extent, not a marker convention that can go missing. The.orca-managed-*/@orca-managed-pi-extensionmarkers are whole-file ownership flags with no extent to get wrong.The policy
New shared module
src/main/agent-hooks/managed-toml-ownership.ts. Two independent things make a byte Orca's, and separating them is the whole fix:Marker extent — where a block starts and stops.
Recognition — content Orca can prove it wrote.
Kimi's recognizer: a
[[hooks]]table whosecommandis accepted bycreateManagedCommandMatcher('kimi-hook.sh'). That command path is the only reason the table fires, and it is there because Orca put it there — so the table is Orca's, extra keys and all. A table invoking anything else is the user's and is never touched. One shape guard remains: if a line in the table is not a simplekey = valuepair (a multi-line array or string, say) the table's extent is not knowable by line scanning, so recognition fails closed rather than splicing the wrong bytes.Ownership is deliberately the same test for remove, install and status. An asymmetry here is not a safety margin — it is a bug: if status cannot see a table that install does not remove, install appends a second table for the same event and the hook double-fires.
Codex's legacy block gets no recognizer on purpose. That body's shape is not derivable from current source (it was written by a version that no longer exists), so there is nothing to positively recognize and rule 7 applies.
Recovery therefore never has to guess. Orphan handling does not try to infer where Orca's bytes end — it deletes the stray marker and lets recognition reclaim the actual content, wherever a hand-edit or a rewriter left it.
Evidence on real files
Driven through the real code paths —
kimiHookService.install()/.remove()andcleanupLegacyManagedHookRepresentations()— against real files on disk, not test doubles. Pre-fix results come from running the parent commit's functions on byte-identical input.Kimi: end marker hand-deleted, user tables appended below
BEFORE (
3308bytes; end marker absent; managed[[hooks]]bodies elided for length):PRE-FIX
remove()→ 134 bytes. Everything from the stray marker to EOF is gone:install()on the same input loses the same bytes (3177bytes out,0occurrences of either user string).FIXED
remove()→ 299 bytes:FIXED
install()on the same orphan keeps both user tables, emits exactly1start marker and1end marker, and a secondinstall()is byte-identical — the recovery converges in one step.Kimi: the other cases
remove()diffclean)0markers and0managed commands left,[user.kept]intact[hand.written]below[hand.written]kept[user.table]kept[[hooks]]table outside any markerdiffclean)matcherkeydiffclean)Kimi: CRLF
Install onto a CRLF config, delete the end marker, append CRLF user tables, run the real
remove():For contrast, the pre-fix builder had no EOL detection at all and wrote LF into a CRLF file:
with CRLF, LF line terminators,bare LF count: 32.Codex legacy profile
BEFORE (
200bytes, end marker hand-deleted):PRE-FIX → 39 bytes. The user's trust grant is gone:
FIXED → 200 bytes,
diffagainst the input is empty: fail closed, file untouched byte-for-byte.Intact-block removal still works (230 → 90 bytes; managed block gone,
trust_levelkept), and the splice seam now rejoins with the file's own terminator, so a CRLF profile comes backwith CRLF line terminators/bare LF count: 0instead of the previous mixed endings.The CLI surface
orca agent hooks statuson a config whose markers were dropped by a TOML rewriter (7 managed hook tables, 0 markers):And on a config where only some managed tables survive, this PR reports the truth instead of silence:
Known behaviour changes
Called out so they are not a surprise in review:
[[hooks]]table with exactlyevent/command/timeout, a known Kimi event and a command pointing atagent-hooks/kimi-hook.shis Orca's wherever it sits. On main such a table survivedremove(); now it does not. That is the point of the change, but a user who deliberately copied Orca's table into their own section will find it gone after uninstall.installedfor a config containing no Orca markers. Correct — the hooks really are live — but it may look odd to someone reading their config for the marker comments.matcher = "Bash"to a table that invokeskimi-hook.shno longer protects it: uninstall removes it and reinstall replaces it with the canonical block. This matches what the markers already say ("managed by Orca; do not edit") and what happens to a customised table inside an intact block today. The alternative was worse — an earlier revision of this PR exempted such tables, which left the hook running after uninstall and double-firedStopafter the next startup install.Bonus: uninstall now works on a marker-less config
Recognition fixes a second, more reachable problem that predates #18861. Markers are TOML comments, so anything that round-trips the file through a TOML serializer —
kimi config set, a dotfile manager, any config editor — drops both markers while keeping the hook tables. Pre-fix,remove()then found nothing and left all 7 managed hooks live, permanently, with no way for Orca to ever find them again:Unlike the interleaved-orphan case, this one needs no hand-editing at all.
The one remaining fail-closed trade
An orphaned legacy Codex block is never removed. Rule 7 means the block stays in
orca-agent-status.config.tomlforever. That is acceptable because the stale profile is inert — the runtimeCODEX_HOMEsupersedes it, and it defines no live hook — so leaving it costs nothing next to destroying the[projects.*]trust entries sitting below it. The failure mode is "a stale comment block remains", not "a hook keeps running".There is deliberately no equivalent trade on the Kimi side. An earlier revision of this PR bounded orphan recovery at the first unrecognized line and accepted that managed tables stranded below user text would survive
remove(). That was wrong: those tables still execute. Verified against a real config — afterremove()a TOML reader still sawevent=PreToolUse managed=true,~/.orca/agent-hooks/kimi-hook.shwas still present and executable, and that script spools agent events to disk and POSTs them to Orca's hook server.getStatus()meanwhile reportednot_installed, and a subsequentinstall()produced twoPreToolUsetables and double-fired the event. Fail-closed on user bytes is right; fail-silent on Orca's own leftovers is a different thing and does not inherit the same justification. Recognition-based ownership removes the trade entirely:remove()on a stranded managed table[[hooks]]a TOML reader seesPreToolUse, live)getStatus()not_installed(wrong)not_installed(true)install()afterwardsPreToolUse×2, double-firesRelationship to open community PRs
#19033 — @cat-xierluo, "fix(kimi): bound orphaned managed-block recovery to installer-shaped tables". Same root cause, and their bounded-recovery mechanism is exactly the rule this PR started with: stop orphan recovery at the first line that is not installer-shaped. They are credited as co-author. Their patch is careful in ways I had to rediscover — CRLF-aware line boundaries, and a boundary check so a user table that reuses the installer field order but carries extra keys is left whole rather than truncated to its installer-shaped prefix.
This PR then goes further in three places, all found by pushing on that shared design:
src/main/codex/codex-hook-legacy-cleanup.tshad the same "no end marker means delete to EOF" shape against a file that also holds the user's[projects.*]trust entries. fix(kimi): bound orphaned managed-block recovery to installer-shaped tables #19033 fixes Kimi only.escapeRegex(BLOCK_START)without a line anchor, so — like this PR before review — a user quoting the marker in a comment of their own opens a region. CodeRabbit caught it here; both markers are now compared against the whole trimmed line.#18813 — @Djiit, "feat(vibe): add managed hook transport, live status, and session resume". Not a fix for #18861, but it is not unrelated: it adds
src/main/vibe/hook-config-toml.tscontaining a verbatim copy of the pre-fix regex,`\n*${escapeRegex(BLOCK_START)}[\s\S]*?(?:${escapeRegex(BLOCK_END)}[^\n]*|$)`, so merging it as-is reintroduces this data-loss bug for Vibe. @cat-xierluo flagged this lockstep risk on #19033 and they were right. Vibe is not onmain, so this PR cannot fix it; #18813 should adoptmanaged-toml-ownership.tsinstead of cloning the regex. Commented there.Verification
pnpm test src/main/kimi src/main/codex src/main/agent-hooks/managed-toml-ownership.test.ts src/main/agent-hooks/installer-utils.test.ts src/main/agent-hooks/remote-hook-service-installers.test.ts src/main/agent-hooks/managed-hook-detection-commands.test.ts— 8 files, 141 passed / 3 skippedpnpm tc— cleanoxlint— clean;oxfmt --check— cleanpnpm run check:code-quality:changed— 0 new findings across 7 changed filesSSH:
installRemoteshares the same recognizer, so a remote Kimi config orphaned or rewritten the same way recovers identically. No mobile-facing surface touched.Orca's own
writeConfigTomlis temp+rename atomic, so Orca cannot itself truncate a config into the orphaned state — it takes an external edit or an external writer. The marker-less case above needs neither.