Skip to content

feat(bin): add guarded Kimi turn-end wake - #1059

Merged
kunchenguid merged 6 commits into
mainfrom
fm/fm-kimi-turnend-hook-r2
Jul 26, 2026
Merged

kunchenguid merged 6 commits into
mainfrom
fm/fm-kimi-turnend-hook-r2

Conversation

@kunchenguid

Copy link
Copy Markdown
Owner

Intent

Enable Firstmate's Kimi Stop turn-end wake through a guarded per-worktree token and private registry while preserving the captain's shared Kimi config, skills, and memory. Install only a surgical marker-delimited Firstmate-owned region in ~/.kimi-code/config.toml, preserve every unrelated byte, remain idempotent and removable, fail closed on missing or malformed config and on missing jq, keep the runtime hook silent and always exit 0, and ensure sessions without a Firstmate token are unaffected. Do not use an isolated Kimi home or a second JSON parser fallback. The PR body must state the exact removal command 'bin/fm-kimi-turnend-hook.sh remove' and include demonstrated no-interference evidence: a real non-Firstmate session with the hook installed and no token completed normally in 4.05 seconds with zero hook output and no side effect in cwd; across 10 no-token hook runs the measured overhead was median 9.8 ms and maximum 11.6 ms, about 0.24 percent of that turn. It must also report the real positive proof that a registered Firstmate target was touched. Validate the rebased change fully through green CI.

What Changed

  • Add a guarded, silent Kimi Stop hook that surgically preserves shared config, skills, and memory; installation fails closed on unsafe config or missing jq, stays idempotent, and can be removed with bin/fm-kimi-turnend-hook.sh remove.
  • Register per-worktree tokens during Kimi crew spawn, touch only the authorized task turn-end marker, and clean up pointers and private registry entries during teardown.
  • Demonstrate no interference: a real non-Firstmate session completed normally in 4.05 seconds with zero hook output and no cwd side effects; 10 no-token runs measured 9.8 ms median and 11.6 ms maximum overhead, about 0.24% of that turn, while a registered Firstmate target was successfully touched.

Risk Assessment

✅ Low: The boundary fix now preserves appended captain TOML while retaining byte-identical pristine removal, includes focused regression coverage, and documents the deliberate newline behavior.

Testing

No separate baseline output was supplied. The focused Kimi harness test passed, and the recorded end-to-end flow demonstrated preservation of captain config, skills, memory, and a foreign hook; mode-700 registry creation; silent zero-exit no-token behavior with no cwd or target side effect; a registered target touch; idempotent installation; and byte-identical removal.

Evidence: Kimi turn-end end-to-end transcript
Kimi guarded turn-end hook end-to-end evidence
config_marker_count_after_install=1
captain_skills_line_preserved=1
captain_memory_line_preserved=1
foreign_hook_line_preserved=1
private_registry_permissions=700
idempotent_second_install=yes
ordinary_session_exit=0
ordinary_session_hook_output_bytes=0
ordinary_session_cwd_entries=0
target_touched_after_ordinary_session=no
registered_session_exit=0
registered_session_hook_output_bytes=0
registered_target_touched=yes
config_byte_identical_after_remove=yes
managed_hook_removed=yes
private_registry_removed=yes

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 1 issue found → auto-fixed (2) ✅
  • 🚨 bin/fm-kimi-turnend-hook.sh:220 - The required behavior says the installer must "remain idempotent and removable" and "preserve every unrelated byte," but outside = original[: region[0]] + original[region[1]:] can make removal fail after a normal edit. If the original config lacked a final newline, install uses the marker that owns the preceding newline; if the captain later appends valid TOML below the installed block, removal consumes both boundary newlines and concatenates the original final line with the appended first line. The resulting TOML is invalid, so remove refuses. Reconstruct this boundary so a Firstmate-owned separator is retained when a suffix exists, and cover the no-final-newline -> install -> append -> remove sequence.

🔧 Fix: Preserve Kimi config boundaries during hook removal
1 warning still open:

  • ⚠️ bin/fm-kimi-turnend-hook.sh:176 - The chosen fix explicitly required a comment explaining that the retained newline prevents joining the captain's preceding line to content appended after installation, but the new separator branch has no such comment. Add that explanation immediately above this branch so this deliberately asymmetric removal behavior is not later mistaken for an unnecessary newline.

🔧 Fix: Document Kimi removal newline safeguard
✅ Re-checked - no issues remain.

✅ **Test** - passed

✅ No issues found.

  • bash tests/fm-kimi-harness.test.sh
  • Manual isolated-home flow: install twice, invoke a tokenless Stop payload, invoke a registered Stop payload, then run bin/fm-kimi-turnend-hook.sh remove and compare the restored config byte-for-byte
  • git status --short after testing to verify no transient worktree artifacts remained
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

@kunchenguid
kunchenguid merged commit 4d6992a into main Jul 26, 2026
10 checks passed
@kunchenguid
kunchenguid deleted the fm/fm-kimi-turnend-hook-r2 branch July 26, 2026 04:50
quinnbot-ai added a commit to quinnbot-ai/firstmate that referenced this pull request Jul 26, 2026
* fix: preserve Claude watcher continuity across Stop hooks (kunchenguid#997)

* feat(claude): Stop-owned tokenless watcher continuity via asyncRewake auto-arm

Claude primaries (main home and marked secondmate homes) no longer depend
on the model remembering to re-arm the watcher after each wake. A tracked
Stop asyncRewake hook (bin/fm-claude-stop-autoarm.sh, timeout 28800s)
fires on every turn end, claims one home-scoped single-flight owner,
foregrounds bin/fm-watch-arm.sh inside the hook-owned process tree, and
translates an actionable close or typed watcher failure into exactly one
exit-2 rewake. The hook scopes to genuine primary checkouts, requires the
session lock to be held by its own harness ancestor, stays inert while
AFK owns triage or the home is idle, and hands AFK transitions mid-cycle
to the daemon without rewaking.

The synchronous turn-end guard gains a --claude cooperative mode: it
ignores stop_hook_active (true on every post-continuation stop, which is
what re-opened the 2026-07-21 blind window), waits briefly for a watcher
health proof, a live auto-arm owner claim, or a fresh rewake epoch, and
re-blocks only when the auto-arm genuinely failed to establish - bounded
to 3 consecutive blocks per session, safely below Claude Code's 8-block
override, then a degraded allow with a visible systemMessage. Codex
keeps the previous one-block loop guard byte-identically, and Pi,
OpenCode, and Grok adapters are untouched.

Continuity PreToolUse gate and durable wake queue are preserved; the
gate's recovery guidance now names the Stop-owned re-arm and reserves
manual background arms for auto-arm failure. Claude supervision protocol,
harness-adapters facts, architecture, configuration, and continuity docs
updated; docs/turnend-guard.md records the 2026-07-24 Claude 2.1.218
contract revalidation (tokenless multi-cycle rewake, no-dedup, timeout
process-group kill, 8-block cap, interactive non-stall) and the 2.1.219
product live E2Es.

Regression matrix: hermetic tests cover scope, identity, AFK, need,
single-flight, translation, guard cooperation, budget, and registration;
the new live E2E proves two full tokenless auto-arm rewake cycles with
zero model arm commands; Pi and OpenCode Option B live E2Es pass
unchanged.

* no-mistakes(review): Fix Claude X-mode auto-arm continuity backstop

* no-mistakes(review): Remove unsupported Claude contract-lab verification claims

* no-mistakes(document): Update Claude auto-arm continuity documentation

* fix(herdr): clean stale projections at session start (kunchenguid#996)

* Clean stale Herdr projections at session start

* no-mistakes(document): Document stale Herdr session-start projection cleanup

* no-mistakes(review): Enforce locked exact Herdr projection cleanup

* no-mistakes(review): Fail closed on unverified session lock ownership

* no-mistakes(review): Serialize session lock acquisition atomically

* no-mistakes(document): Align session-start and Herdr cleanup documentation

* no-mistakes(document): Generalize lock-refusal diagnostics

* no-mistakes(lint): Avoid reserved ke