Skip to content

fix: coalesce queued Pi watcher wake follow-ups - #3986

Open
zxianzheng123-code wants to merge 4 commits into
kunchenguid:mainfrom
zxianzheng123-code:pi-watch-ride-queued-wake
Open

zxianzheng123-code wants to merge 4 commits into
kunchenguid:mainfrom
zxianzheng123-code:pi-watch-ride-queued-wake

Conversation

@zxianzheng123-code

Copy link
Copy Markdown

Intent

Stop the Pi primary session from piling up one 'FIRSTMATE WATCHER WAKE' follow-up per actionable watcher close while a wake is already queued. During a long turn several actionable closes each queued their own follow-up, so the model later ran one drain turn per queued message against an already-drained durable queue and Pi's queue view filled with stacked wake messages. Decision: fix it inside the Pi extension (.pi/extensions/fm-primary-pi-watch.ts), not in fm-wake-drain.sh and not via Pi's followUpMode setting, and build on the existing delivery-versus-consumption model (unconsumedWakes, replacement handoff) rather than replacing it. Design: main holds at most one unconsumed host follow-up; a later close, typed restoration failures included, rides that host as a rider (it counts as delivered with the host, exactly like the host counts as delivered once Pi accepts it); when Pi finalizes the host's user message the extension rewrites it in place through the message_end extension event (pi applies a same-role replacement in place) so the one delivered message lists the original reason plus every rider; riders are consumed only at that rewrite, so an unrewritten rider still rides the replacement handoff and is replayed like an unconsumed host; a host Pi settles without consuming and with nothing left queued (agent_settled with hasPendingMessages false, i.e. the queue was cleared by an abort) carries its reasons into the next host instead of being lost, deliberately not re-sent immediately so an abort by the captain never starts a turn on its own. Hostless failure notices (surfaceFailure) are tracked as hosts too so they coalesce; their synthetic tokens never collide with pending-record tokens. Constraints: never silently drop a reason; watcher continuity ordering (successor armed and handling confirmed before delivery, bounded retries, replacement replay of unconsumed records) is unchanged; the OpenCode and omp adapters are untouched, this is a Pi-only fix. Tests: four existing Pi cases (late unretired close, streaming-time chain, in-flight replacement handoff, late-retiring replacement) previously asserted a second main follow-up or read reasons from prompts; they now read the delivered wake through its message_end rewrite because the later reason rides the still-queued host, and the streaming-chain case now expects the handoff to carry exactly the unrewritten rider. A new case releases several closes behind one queued host and asserts coalescing, the rewrite content, that an unrelated user message never consumes the host or riders, dropped-host carry-over, and that a host still queued at agent_settled is kept. docs/watcher-continuity.md documents the contract. Test fixtures avoid apostrophes inside $(...) heredocs because bash 3.2 misparses them. The commit trailers (Co-Authored-By, Claude-Session) are the contributor's coding-harness attribution, not an agent claiming authorship.

What Changed

  • Coalesce later Pi watcher closes and failure notices behind one queued follow-up, rewriting its user message at message_end to include rider reasons.
  • Preserve unrewritten riders for replacement replay and carry dropped wake reasons into the next host without restarting a turn after abort.
  • Document the coalescing contract and expand regression coverage for message rewriting, replacement handoffs, dropped hosts, and cleanup failures.

Risk Assessment

✅ Low: The Pi-only change is bounded, preserves existing continuity handling, and addresses the prior findings without introducing substantiated material defects or unnecessary components.

Testing

Focused event-interface tests passed and captured coalesced messages, replacement carry-over, and deferred cleanup failures; the pre-fix reload regression failed as expected. Evidence uses a simulated Pi host, not a rendered TUI, so no screenshot was captured. Temporary files were removed; no full suite or static analysis ran.

Evidence: Emitted coalesced wake and abort carry-over messages

Source: Emitted coalesced wake and abort carry-over messages

{
  "scenario": "Three closes coalesce; unrelated user message; abort carry-over; queued host retained",
  "deliveredText": "⁣FIRSTMATE_OP: v1 watcher: FIRSTMATE WATCHER WAKE: signal: synthetic close 1\n\nAdditional watcher closes since the last delivered wake (2), coalesced into this one wake:\n- signal: synthetic close 2\n- signal: synthetic close 3\n\nRun bin/fm-wake-drain.sh first and handle the queued wake. Watcher continuity is extension-owned.",
  "prompts": [
    "⁣FIRSTMATE_OP: v1 watcher: FIRSTMATE WATCHER WAKE: signal: synthetic close 1\n\nRun bin/fm-wake-drain.sh first and handle the queued wake. Watcher continuity is extension-owned.",
    "⁣FIRSTMATE_OP: v1 watcher: FIRSTMATE WATCHER WAKE: signal: synthetic close 4\n\nRun bin/fm-wake-drain.sh first and handle the queued wake. Watcher continuity is extension-owned.",
    "⁣FIRSTMATE_OP: v1 watcher: FIRSTMATE WATCHER WAKE: signal: synthetic close 6\n\nAdditional watcher closes since the last delivered wake (2), coalesced into this one wake:\n- signal: synthetic close 4\n- signal: synthetic close 5\n\nRun bin/fm-wake-drain.sh first and handle the queued wake. Watcher continuity is extension-owned."
  ]
}
Evidence: Replacement messages, deferred cleanup failure, and persisted handoff

Source: Replacement messages, deferred cleanup failure, and persisted handoff

{
  "scenario": "Legacy coordinator reload, abort, replacement, hostless failure rider, malformed handoff cleanup",
  "prompts": [
    "⁣FIRSTMATE_OP: v1 watcher: FIRSTMATE WATCHER WAKE: signal: synthetic close 1\n\nRun bin/fm-wake-drain.sh first and handle the queued wake. Watcher continuity is extension-owned.",
    "⁣FIRSTMATE_OP: v1 watcher: FIRSTMATE WATCHER WAKE: signal: synthetic close 4\n\nAdditional watcher closes since the last delivered wake (2), coalesced into this one wake:\n- signal: synthetic close 1\n- signal: synthetic close 2\n\nRun bin/fm-wake-drain.sh first and handle the queued wake. Watcher continuity is extension-owned.",
    "⁣FIRSTMATE_OP: v1 watcher: FIRSTMATE WATCHER WAKE: signal: synthetic close 4\n\nAdditional watcher closes since the last delivered wake (3), coalesced into this one wake:\n- signal: synthetic close 1\n- signal: synthetic close 2\n- watcher: FAILED - Pi extension cannot restore continuity because this session no longer owns the lock\n  watcher: FAILED - synthetic hostless failure\n\nRun bin/fm-wake-drain.sh first and handle the queued wake. Watcher continuity is extension-owned.",
    "⁣FIRSTMATE_OP: v1 watcher: FIRSTMATE WATCHER WAKE: signal: synthetic close 6\n\nAdditional watcher closes since the last delivered wake (5), coalesced into this one wake:\n- signal: synthetic close 1\n- signal: synthetic close 2\n- watcher: FAILED - Pi extension cannot restore continuity because this session no longer owns the lock\n  watcher: FAILED - synthetic hostless failure\n- signal: synthetic close 4\n- watcher: FAILED - Pi extension could not clear a delivered replacement-session actionable wake\n  Unexpected token 'm', \"malformed\" is not valid JSON\n\nRun bin/fm-wake-drain.sh first and handle the queued wake. Watcher continuity is extension-owned."
  ],
  "persistedHandoffBeforeAbort": {
    "version": 2,
    "pending": [
      {
        "version": 1,
        "token": "52667-1788859538749-40",
        "message": "signal: synthetic close 4",
        "predecessorArmPid": "53296"
      }
    ]
  }
}

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 2 issues found → auto-fixed (2) ✅
  • 🚨 .pi/extensions/fm-primary-pi-watch.ts:633 - Dropped reasons do not survive session replacement. Queue closes A and B, abort before consumption, then use /new or reload before another close: this hunk moves their reasons into carriedReasons and finishConsumedWake removes their pending records. stopSessionGeneration persists only pendingActionables, while createGeneration initializes carriedReasons to []; neither reason reaches the next host. Likewise, newly coalesced hostless failure riders have no pending record and disappear on replacement before rewrite. This contradicts 'never silently drop a reason' and the required replacement replay of unrewritten riders. Preserve all undelivered reason state at the existing replacement-handoff boundary, including deferred carry-over without immediately sending it.
  • 🚨 .pi/extensions/fm-primary-pi-watch.ts:634 - An abort can itself enqueue a new turn when handoff cleanup fails. With a replayed host queued, make its handoff unwritable, then abort: agent_settled calls carryDroppedWakes, which calls finishConsumedWake; clearReplacementHandoff throws, and surfaceCleanupFailure immediately calls surfaceFailure/sendWake. Because the dropped host was already removed, that failure becomes a fresh Pi follow-up. This contradicts 'an abort by the captain never starts a turn on its own.' Defer cleanup-failure notification into the carried reasons on this path instead of sending it during dropped-host processing.

🔧 Fix: Preserve Pi wake reasons and defer abort cleanup failures
1 error still open:

  • 🚨 .pi/extensions/fm-primary-pi-watch.ts:209 - Reloading this update into a running pre-change Pi process breaks wake delivery. The base version already stores its coordinator on globalThis, but without carriedReasons. replacementCoordinatorFor returns that existing object unchanged, making this binding undefined. The next actionable close throws at carriedReasons.splice(0); its error notification follows the same failing sendWake path and is swallowed. Initialize the missing array on reused coordinators before returning them, preserving existing contents. Cover loading the old coordinator shape followed by the updated extension, not only updated-module-to-updated-module replacement.

🔧 Fix: Initialize carried reasons when reusing legacy Pi coordinators
✅ Re-checked - no issues remain.

✅ **Test** - passed

✅ No issues found.

  • /bin/bash tests/.pi-watch-targeted.test.sh: eight selected lifecycle cases covering successor ordering, coalescing, abort carry-over, replacement replay, streaming delivery, and late-retiring closes.
  • Repeated test_pi_queued_wakes_coalesce_into_one_follow_up and test_pi_carried_reasons_survive_replacement_and_cleanup_failure with runtime capture of emitted messages and persisted handoff state.
  • /bin/bash tests/.pi-watch-regression.test.sh: ran the legacy-coordinator regression against commit 48be6f1; reproduced missing first-host delivery.
  • Inspected captured message payloads; removed temporary test drivers and baseline source; verified git status --short was clean.
✅ **Document** - passed

✅ No issues found.

🔧 **Lint** - 1 issue found → auto-fixed ✅
  • ⚠️ linter found issues (exit code 1)

🔧 Fix: Lint passes with installed tools; no changes needed
✅ Re-checked - no issues remain.

✅ **Push** - passed

✅ No issues found.

zxianzheng123-code and others added 4 commits September 8, 2026 17:15
While a watcher wake follow-up was queued in Pi but not yet consumed, every
later actionable close queued another follow-up, so a long turn ended with a
pile of "FIRSTMATE WATCHER WAKE" messages that each ran a drain turn against an
already-drained durable queue.

Main now holds at most one unconsumed host follow-up. A later close (typed
restoration failures included) rides that host as a rider: it counts as
delivered with it, and when Pi finalizes the host's user message the extension
rewrites it in place through message_end so the one delivered message lists the
original reason plus every rider. Riders are consumed only at that rewrite, so
an unrewritten rider still rides the replacement handoff and is replayed like
an unconsumed host. A host Pi settles without consuming and with nothing left
queued (queue cleared by an abort) carries its reasons into the next host
instead of vanishing; nothing is re-sent on its own.

Tests: the late-close, streaming-chain, in-flight replacement, and late-retiring
replacement cases now read the delivered wake through its message_end rewrite,
and a new case releases several closes behind one queued host to pin
coalescing, the rewrite, unrelated-message isolation, and dropped-host carry.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RQ1TPXgirj9WQ9P71Hh9GV
@greptile-apps

greptile-apps Bot commented Sep 8, 2026

Copy link
Copy Markdown

Confidence Score: 5/5

The PR appears safe to merge with no concrete blocking or non-blocking defects identified.

The changed state transitions preserve pending actionable records through replacement, consume riders only when exposed by the message rewrite, and defer abort-dropped reasons to a later host as intended.

Reviews (1): Last reviewed commit: "no-mistakes(document): Clarify Pi coales..." | Re-trigger Greptile

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.

1 participant