Skip to content

bug(#383): relay messages silently lost — no outbox, phase ends, watch keeps tailing dead session #645

Closed

Description

@admarble

Symptoms

Two sequant run sessions over a single quiet-mode batch (npx sequant run 504 505 -q) accepted sequant prompt messages cleanly but never produced any reply:

Issue Prompt sent Phase at archive Outcome
#504 03:33:57Z ("what's taking so long?") qa archived at 03:39:21Z (5m 24s later) inbox.jsonl archived under .sequant/logs/relay/504-qa-2026-05-14T03-39-21-296Z/ with messageCount: 1; no outbox.jsonl in archive
#505 03:37:22Z ("why are we stalled?") still in qa live inbox.jsonl has the entry, no outbox.jsonl, state.json shows relay.messageCount: 1

sequant watch 504 is still running and producing nothing — the underlying run advanced to ready_for_merge, the pidfile for #504 was removed, and the live relay dir is empty.

Both runs had relay.enabled: true in state.json and a populated pidfile; relay infrastructure was healthy. The issue is that the agent never wrote a reply.

Hypothesized gaps (each worth verifying individually)

Gap 1 — Cursor advances on hook render, not on agent reply (HIGH CONFIDENCE)

templates/hooks/relay-check.sh:101-105 unconditionally advances _CURSOR after rendering the frame to stdout. The frame instructs the agent to write outbox.jsonl, but the hook has no way to enforce that the agent actually did so. If the agent ignores the framing prompt (focused task, context pressure, parsed as tool output rather than directive), the message is silently consumed.

Verify: check whether either archive shows a cursor file matching the inbox line count with no outbox written.

Gap 2 — Sub-agent (Agent() sub-spawn) hook behavior unverified

The QA phase delegates to sequant-qa-checker sub-agents via Agent() tool calls. SEQUANT_RELAY / SEQUANT_WORKTREE are inherited via process env (phase-executor.ts:632-669), but it's unverified whether:

  • Sub-agent PostToolUse hooks run with the same .claude/settings.json config
  • The framing prompt reaches the sub-agent's context vs. the outer agent's
  • The sub-agent has write permission to <worktree>/.sequant/relay/outbox.jsonl under its tool allowlist

If the sub-agent does most of the QA tool calls but the framing prompt only reaches the outer agent (or vice versa), the user-facing latency claim ("after the next tool call") breaks for any phase that delegates heavily.

Verify: instrument relay-check.sh to log when it fires + which PID / which SEQUANT_ISSUE env is set; run a phase that delegates and inspect the log.

Gap 3 — sequant watch silently tails dead relays

Once a phase deactivates, the live <worktree>/.sequant/relay/outbox.jsonl is moved to .sequant/logs/relay/<archive>/ and the live dir becomes empty. sequant watch <issue> keeps tailing forever with no signal. Should detect via the pidfile being removed OR state.json relay being cleared, and exit with a clear message ("Run for #N ended at HH:MM:SS, N messages archived to , 0 replies").

Gap 4 — sequant prompt "Message sent" is misleading after phase ends

The CLI confirms the file write but has no liveness check. A "sent" message can be archived seconds later without ever being read. The prompt CLI already reads state.json (uses relay.pid for liveness on other paths) — could add a "warning: phase has ended since this message was queued, your message may not be answered" follow-up check, or refuse to send if the pidfile is stale.

Gap 5 — Archive meta.json doesn't surface unanswered messages

meta.json records messageCount: 1 (inbox) but not replyCount. A diff would let sequant logs / sequant status retrospectively report "N messages with no reply" so silent losses are at least visible.

Gap 6 — sequant prompt phase label is stale

Both prompts confirmed "exec phase, Nm Ns elapsed" while state.json showed phase: qa. The elapsed counter also appears run-relative rather than phase-relative. Minor UX bug compared to the others, but worth folding in.

Suggested approach

Treat gaps 1, 3, 4 as the user-visible "messages disappear" bug surface — each is a separate small fix. Gap 2 is the highest-impact behavioral question (whether sub-agent-heavy phases like QA can use relay at all) and needs an instrumented run before designing a fix. Gaps 5 and 6 are minor polish.

References

Activity

  1. added
    bug
    on May 14, 2026
  2. admarble commented on May 14, 2026

    @admarble
    ContributorAuthor

    Update — new evidence invalidates Gap 1, promotes Gap 2 to near-confirmed

    After filing, I sent npx sequant prompt 505 --type abort to test the abort path. State after 30+ minutes of live activity on #505:

    inbox.jsonl:  [query @ 03:37:22, abort @ 03:44:58]   ← both queued
    .cursor:      does not exist                          ← hook NEVER fired
    outbox.jsonl: does not exist                          ← agent never saw anything
    

    relay-check.sh:101-105 creates/updates .cursor after every successful render. No .cursor file across 30 min of execution means relay-check.sh has never fired in this session's PostToolUse chain — for either the query OR the abort.

    Corrections to original framing

    Gap 1 — invalidated. I assumed "hook fires → cursor advances → agent ignores frame." Wrong. The frame is never rendered in the first place. The agent has nothing to ignore.

    Gap 2 — promoted from hypothesis to likely confirmed. Most plausible explanation for no-cursor over a long execution: PostToolUse hooks aren't firing in the active execution context. Whether that's because the active context is a sub-spawned Agent() whose hook chain doesn't inherit post-tool.sh, or a broader env/wiring issue, needs the instrumented sentinel log proposed in Gap 2's verify step.

    New Gap 7 — --type abort is dead when the hook chain is broken

    If the hook never fires, no message type lands — query, directive, AND abort are all silently consumed. Abort is supposed to be the user's escape hatch when the agent is misbehaving; it's the path that needs to work even when other relay flow is broken.

    Suggested mitigation: an additional out-of-band abort path. Options:

    • sequant prompt <issue> --type abort --signal → after a short grace period (e.g. 30s) with no acknowledgment in outbox, send SIGINT to state.json:relay.pid. The signal goes to the parent sequant run orchestrator, which already has a clean ShutdownManager path that deactivates relay and releases locks.
    • Or a separate sequant abort <issue> command that bypasses the inbox entirely and signals the recorded PID directly, distinct from the relay channel.

    The CLI flag already exists (prompt --type abort); the missing piece is the fallback that doesn't depend on the agent honoring it.

    Practical guidance for users hitting this today

    The relay-channel abort cannot recover from the broken-hook state. The reliable escape:

    kill -INT <state.relay.pid>   # graceful — runs ShutdownManager teardown

    Followed by SIGTERM then SIGKILL if needed.

  3. admarble commented on May 14, 2026

    @admarble
    ContributorAuthor

    /spec — Plan

    Root cause identified

    Issue title mentions Gap 2 (sub-agent hook firing) as "near-confirmed." After empirical inspection, the root cause is simpler and more concrete: the installed hook file .claude/hooks/post-tool.sh is stale and does not source relay-check.sh, and .claude/hooks/relay-check.sh does not exist at all.

    File Last touched Has relay block?
    templates/hooks/post-tool.sh 515b616 (#383 / #638, May 13) ✅ Yes
    templates/hooks/relay-check.sh 515b616 (#383 / #638, May 13) ✅ Yes (it IS the block)
    .claude/hooks/post-tool.sh bb51991 (Mar 25) ❌ No
    .claude/hooks/relay-check.sh — ❌ File missing

    PR #638 added the relay feature to the templates but never updated the active hooks in .claude/hooks/. Every worktree in this repo inherits the stale checked-in copy, so the PostToolUse hook never sources relay-check.sh, never advances .cursor, and never renders the framing prompt. That explains the no-cursor / no-outbox / no-reply behavior on #504 and #505 directly — no sub-agent hook-inheritance investigation needed to close the user-visible bug.

    A secondary contributing factor: DEFAULT_MIRROR_PAIRS in src/lib/merge-check/types.ts:196 lists { source: "hooks", target: "templates/hooks" } — hooks/ doesn't exist; the correct source is .claude/hooks. The mirror check that should have caught this drift at merge time silently no-op'd.

    Acceptance Criteria

    • AC-1: .claude/hooks/relay-check.sh exists and is byte-identical to templates/hooks/relay-check.sh.
    • AC-2: .claude/hooks/post-tool.sh contains the if [[ "${SEQUANT_RELAY:-}" == "true" ]] block that sources relay-check.sh (matching the shape of templates/hooks/post-tool.sh:16-26).
    • AC-3: End-to-end smoke test: sequant run + sequant prompt <n> "status?" produces an outbox reply in the live worktree within a reasonable timeout. Documented in PR body.
    • AC-4: A Vitest test (src/lib/relay/__tests__/hook-sync.test.ts) asserts byte-equality of relay-check.sh and substring presence of the SEQUANT_RELAY block in post-tool.sh. Deliberately corrupting either file fails the test.
    • AC-5: DEFAULT_MIRROR_PAIRS uses .claude/hooks as the source (not hooks). Matching test in src/lib/merge-check/merge-check.test.ts updated if needed.
    • AC-6: Gap 3 — sequant watch <n> detects relay deactivation (pidfile removed) and exits cleanly with an end-of-run summary instead of polling forever.
    • AC-7: Gap 5 — Archive meta.json includes inboxCount + outboxCount as separate fields. messageCount is preserved as the sum for backward compatibility.

    Implementation plan

    Phase 1 — Root-cause fix

    1. Add .claude/hooks/relay-check.sh as a verbatim copy of templates/hooks/relay-check.sh (chmod 0755).
    2. Surgically insert the 11-line SEQUANT_RELAY sourcing block from templates/hooks/post-tool.sh:16-26 into .claude/hooks/post-tool.sh immediately after the CLAUDE_HOOKS_DISABLED rollback check. Do not wholesale-overwrite the file — it contains two local-only features (test coverage analysis, post-merge worktree cleanup) that are not in the template.

    Phase 2 — Drift guard
    3. Fix DEFAULT_MIRROR_PAIRS in src/lib/merge-check/types.ts: "hooks" → ".claude/hooks". Update any test expectations.
    4. Add src/lib/relay/__tests__/hook-sync.test.ts with the three assertions in AC-4.

    Phase 3 — Watch + archive metadata (Gaps 3, 5)
    5. src/commands/watch.ts: in the polling loop, also check readPidFile(). When the pid file is removed during a watch session, print a clean-exit message (referencing the most recent archive path via listArchives()) and exit 0.
    6. src/lib/relay/types.ts + src/lib/relay/archive.ts: extend RelayArchiveMetaSchema with inboxCount + outboxCount. archiveRelayDir() writes both alongside the existing messageCount.

    Phase 4 — Verification
    7. Run npm run build and npm test -- relay. Document a live sequant run + prompt repro in the PR body.

    Explicitly out of scope (filed as follow-ups iff requested)

    • Gap 4 — better sequant prompt UX when phase has ended (cleanupStalePid already mostly covers it).
    • Gap 6 — stale currentPhase label in the prompt confirmation (state-manager timing investigation).
    • Gap 7 — signal-based out-of-band --type abort fallback. Re-evaluate once Gap 2 is closed and we verify the in-band path works end-to-end.
    • Broader .claude/hooks/ drift (pre-tool.sh, etc.). Touches behavior outside relay; separate reconciliation issue.

    Design review

    • Where does this logic belong? Three layers: active hooks (.claude/hooks/), template source-of-truth (templates/hooks/), and a CI-enforced parity test (src/lib/relay/__tests__/). Same pattern as the existing .claude/skills/ ↔ templates/skills/ mirroring documented in CLAUDE.md.
    • Simplest correct approach? Surgical insertion of the relay block, not a wholesale file sync — the installed post-tool.sh has local-only features that should not be lost in this PR.
    • Existing pattern? Mirroring guard already exists for skills; DEFAULT_MIRROR_PAIRS was intended to enforce the same rule for hooks but used the wrong source path.
    • Senior reviewer pushback? "Why not sync the whole post-tool.sh?" Because that loses the test-coverage and post-merge-cleanup features unique to the installed copy. "Why is Gap 2 (sub-agent hook firing) deferred?" Because the simpler hypothesis (missing hook) fully explains the empirical evidence; only re-open if the smoke test in AC-3 still fails after Phase 1 lands.

    Open questions

    1. Should .claude/hooks/pre-tool.sh also be synced? Recommendation: no for this PR — separate reconciliation issue. pre-tool.sh has its own drift but doesn't affect relay.
    2. Should the drift test be byte-equality or substring? Byte-equality for relay-check.sh (no legitimate divergence ever expected); substring match for post-tool.sh (it has local-only features).

    Recommended workflow

    Phases: spec → exec → qa
    Quality loop: disabled
    Reasoning: Bug fix with concrete root cause, ~150 LOC, no UI/browser surface. /qa validates AC.

  4. added
    planned
    on May 14, 2026
  5. admarble commented on May 14, 2026

    @admarble
    ContributorAuthor

    /qa — Inline review

    Verdict: NEEDS_VERIFICATION (6/7 AC verified via Vitest + grep; AC-3 requires live smoke)

    AC walk-through

    AC Status Evidence
    AC-1 byte-identical relay-check.sh ✅ MET diff -q .claude/hooks/relay-check.sh templates/hooks/relay-check.sh returns clean; hook-sync.test.ts asserts byte equality
    AC-2 post-tool.sh sources relay-check.sh ✅ MET Lines 16-26 of .claude/hooks/post-tool.sh contain the SEQUANT_RELAY:- guard; hook-sync.test.ts asserts substring
    AC-3 end-to-end smoke (sequant run + prompt) ⏳ NEEDS_VERIFICATION Implementation complete; requires live process to verify. Steps in PR body.
    AC-4 drift guard fails on corruption ✅ MET Adversarial test: appending # corrupted to relay-check.sh causes hook-sync.test.ts to fail; restoration passes
    AC-5 DEFAULT_MIRROR_PAIRS uses .claude/hooks ✅ MET src/lib/merge-check/types.ts:196 now reads .claude/hooks; merge-check.test.ts fixture updated to .claude/hooks/pre-tool.sh
    AC-6 watch detects relay deactivation ✅ MET watch-dead-relay.test.ts covers both startup-no-relay (immediate exit with archive hint) and mid-watch pidfile removal (drain + exit with end-of-run message)
    AC-7 archive meta.json splits inbox/outbox ✅ MET archive-split-counts.test.ts confirms inboxCount=3, outboxCount=1, messageCount=4; schema accepts legacy archives without the new fields

    Test results

    • 7 new tests (2 hook-sync + 3 archive + 2 watch-dead-relay) — all passing
    • 289 tests across commands + relay + merge-check — all passing
    • npm run build (tsc) — clean

    Risk assessment

    Likely failure mode in production: If the SDK ever bypasses .claude/settings.json PostToolUse hooks (e.g., during sub-agent tool calls), the relay would still be silent. The drift guard catches our own breakage; it does NOT catch an upstream Claude Code behavioral change. Original Gap 2 hypothesis (sub-agent hook isolation) remains worth re-evaluating after AC-3 smoke confirms the single-agent path works.

    Not tested:

    Manual verification plan (post-PR)

    # In terminal 1
    gh issue list --state open | head            # pick a small open issue
    npx sequant run <issue> --no-mcp --phases exec
    
    # In terminal 2 (within 30s)
    npx sequant prompt <issue> "what's the current AC status?"
    npx sequant watch <issue>
    
    # Expected: outbox reply appears in watch within ~30s.
    # After run completes: watch prints "Run for #<issue> ended. Archive: ..." and exits 0.
    # Confirm <archive>/meta.json contains both inboxCount and outboxCount.

    Notes for the merger

    • Three commits on the branch:
      • d901eb5 — primary fix + drift guard + watch dead-relay + archive split
      • 945a531 — small follow-up: pass cwd to outboxPathFor for consistency
    • No Co-Authored-By per CLAUDE.md
    • Out-of-scope work (Gaps 4, 6, 7 + broader .claude/hooks/ drift) documented in spec; file follow-up issues only if the live smoke surfaces residual relay silence
  6. added a commit that references this issue on May 14, 2026
  7. admarble commented on May 14, 2026

    @admarble
    ContributorAuthor

    All-gaps progress

    After PR #646 closed the user-visible bug, three follow-up PRs cover the remaining gaps:

    PR Scope State
    #646 Root cause (Gap 2) + watch dead-relay (Gap 3) + archive split (Gap 5) + drift guard MERGED
    #648 sequant abort (Gap 7) + prompt --wait (Gap 4) + accurate phase label (Gap 6) OPEN, CI green (5/5)
    #649 Full .claude/hooks/ ↔ templates/hooks/ reconciliation + widened drift guard + npm run sync:hooks OPEN, CI in progress

    Gap-by-gap

    Gap Resolution
    1 Invalidated by user comment; no work needed
    2 Hook installed in #646. Single-agent wiring proven via offline shell test (.cursor advances when SEQUANT_RELAY=true). Sub-agent context proven on architectural reading; a sub-agent-heavy smoke run is the last empirical validation worth doing post-merge.
    3 sequant watch exits with archive pointer on relay deactivation (#646)
    4 sequant prompt --wait <seconds> tails outbox for matching reply (#648)
    5 Archive meta.json carries split inboxCount + outboxCount (#646)
    6 Prompt confirmation re-reads state.json with a fresh manager; omits phase label entirely when state is stale (#648)
    7 sequant abort <issue> — out-of-band SIGINT→SIGTERM→SIGKILL escalation, bypasses inbox (#648)
    Drift recurrence risk Full .claude/hooks/ reconciliation + byte-equality test for all hook files + npm run sync:hooks (#649)

    Test counts

    Remaining manual smoke (after #648 + #649 merge)

    # Single-agent path
    npx sequant run <issue> --no-mcp --phases exec
    npx sequant prompt <issue> "status?" --wait 30      # expect inline reply
    npx sequant abort <issue>                            # expect clean shutdown
    
    # Sub-agent-heavy path (covers Gap 2 final validation)
    npx sequant run <issue> --no-mcp --phases qa
    npx sequant prompt <issue> "status?" --wait 30

    If the sub-agent-heavy smoke fails, file a follow-up; PR #649's new hook environment (sourced relay-check.sh + correct env propagation) makes the only remaining failure mode an upstream Claude Code hook-firing behavior — which would need its own investigation cycle.

  8. added 2 commits that reference this issue on May 14, 2026
  9. admarble commented on May 14, 2026

    @admarble
    ContributorAuthor

    All gaps merged

    Three PRs merged in order. All gaps from this issue are now resolved on main:

    • #646 MERGED — root cause (hook drift) + Gap 3 (watch dead-relay) + Gap 5 (archive split counts) + initial drift guard
    • #648 MERGED — Gap 4 (prompt --wait) + Gap 6 (accurate phase label) + Gap 7 (sequant abort)
    • #649 MERGED — full .claude/hooks/ ↔ templates/hooks/ reconciliation + widened byte-equality drift guard + npm run sync:hooks

    Post-merge verification

    • npm run build (tsc): clean
    • npx vitest run src/lib/relay src/commands/__tests__: 37/37 passing
    • npx sequant doctor: 15/18 passed, 3 warnings (all pre-existing — upstream #43869 model-routing notice, etc.); no new regressions

    Remaining manual smoke

    The only verification I couldn't do from inside the agent context is the live sub-agent-heavy relay round-trip:

    npx sequant run <issue> --no-mcp --phases qa
    npx sequant prompt <issue> "status?" --wait 30
    npx sequant abort <issue>     # exercise the new escape hatch

    If --phases qa produces an outbox reply, the original Gap 2 hypothesis (sub-agent contexts not firing PostToolUse) is fully invalidated and the issue can be closed. If it doesn't, file a follow-up — the upstream Claude Code behavior would need investigation since all sequant-side wiring is now correct and CI-locked against drift.

    Closing this issue as resolved unless that smoke surfaces a regression.

  10. added 2 commits that reference this issue on Sep 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugplanned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions