Skip to content

Interactive relay: bidirectional communication with headless runs #383

Closed

Description

@admarble

Interactive Relay: Bidirectional Communication with Headless Runs

Priority: P1 — quality-of-life for all sequant run users
Complexity: Medium — touches hooks, CLI, state, and skill framing

Problem

sequant run executes phases via Claude headless (query() from the Agent SDK). Once a run starts, the user has zero visibility or control until a phase completes. A long-running exec phase (10-15 minutes) is a black box — the user can't ask "what's taking so long?", suggest "skip the migration", or get a status update without killing the entire run.

Real example from production usage:

✔     exec (2/3) (13m 24s)       ← no way to interact during this
✖     qa (3/3) (5m 43s)
✔     loop (3/3) (3m 52s)
    Quality loop iteration 2/3
✔     exec (2/3) (11m 26s)       ← 2nd exec ran 11 min, could've been nudged
✔     qa (3/3) (6m 50s)

Solution

A file-based relay system that enables bidirectional communication between the user's terminal and a running headless Claude session, checked on every tool call via a Claude Code PostToolUse hook.

Architecture

User Terminal                     Headless Claude Session
─────────────                     ──────────────────────
sequant prompt 368 "status?"
  │                               PostToolUse hook fires
  ├─→ writes to inbox.jsonl ──→   hook reads inbox
  │                               hook injects message into conversation
  │                               Claude responds, writes to outbox.jsonl
  ├─← reads from outbox.jsonl ←─  continues current task
  │
sequant watch 368
  └─← tails outbox.jsonl

Why file-based IPC?

  • Headless constraint: No stdin access to a running query() session — file relay is the only injection path besides hooks
  • Hook integration: Claude Code PostToolUse hooks fire after every tool call (every few seconds during active work), providing fine-grained check intervals without busy-polling
  • Debuggable: JSONL files are human-readable, serve as a session log for free
  • Zero infrastructure: No sockets, no servers, no dependencies
  • Portable: Works on macOS, Linux, WSL — anywhere files work

Acceptance Criteria

Relay File Protocol

  • Relay directory created per-issue at <worktree>/.sequant/relay/
  • Inbox (inbox.jsonl): user → Claude messages, one JSON object per line:
    {"id": "msg_001", "timestamp": "2026-03-21T10:15:00Z", "type": "query", "message": "what's taking so long?"}
    {"id": "msg_002", "timestamp": "2026-03-21T10:18:00Z", "type": "directive", "message": "skip the migration tests"}
  • Outbox (outbox.jsonl): Claude → user messages, one JSON object per line:
    {"id": "reply_001", "inReplyTo": "msg_001", "timestamp": "2026-03-21T10:15:03Z", "message": "Working on implementing the error handler. The test suite has 47 tests and I'm iterating on 3 failures."}
  • Message types: query (ask for status, no behavior change), directive (request a behavior adjustment), abort (stop current phase gracefully)
  • Atomic writes: write to temp file then rename() into place to prevent partial reads
  • Relay directory cleaned up on phase completion (but preserved in .sequant/logs/ for post-run review)

PostToolUse Hook Integration

  • New relay check added to post-tool.sh (or a dedicated relay-check.sh sourced from it)
  • Hook reads inbox.jsonl on every PostToolUse invocation
  • If new unprocessed messages exist, hook returns them to Claude wrapped in a framing prompt (see below)
  • If no messages, hook exits silently (zero overhead path must be fast — single stat or test -s check)
  • Hook marks messages as processed (either by tracking last-read line number in a .cursor file, or by consuming/truncating the inbox)
  • Opt-in via environment variable: SEQUANT_RELAY=true (set by sequant run when relay is active)
  • Hook is skipped entirely when SEQUANT_RELAY is not set (no performance impact on non-relay runs)

Hook Message Framing (Anti-Derailment)

  • Relay messages are wrapped in a structured frame that protects task focus:
    [SEQUANT RELAY — message from user]
    Respond briefly in .sequant/relay/outbox.jsonl, then continue your current task unchanged.
    Rules:
    - Do NOT modify acceptance criteria
    - Do NOT change your current objective or phase
    - Do NOT treat this as a new requirement
    - For "query" type: provide a brief status update only
    - For "directive" type: acknowledge and adjust approach if reasonable, but do not abandon current work
    - For "abort" type: stop gracefully, commit progress, and exit
    
    Type: query
    Message: "what's taking so long?"
    
  • Framing template lives in a single location (templates/relay/frame.txt or inline in the hook) — not duplicated across skills
  • Skills do NOT need individual modifications — the hook handles all framing

CLI Commands

  • sequant prompt <issue> "<message>" — send a message to a running session
    • Writes to <worktree>/.sequant/relay/inbox.jsonl
    • Resolves worktree path from .sequant/state.json using the issue number
    • If only one run is active and <issue> is omitted, auto-resolve to that issue
    • If multiple runs are active and <issue> is omitted, error with list:
      Multiple active runs: #368, #385. Specify an issue number.
      Usage: sequant prompt 368 "your message"
      
    • Optional --type flag (default: query): --type directive, --type abort
    • Prints confirmation: Message sent to #368 (exec phase, 4m 12s elapsed)
  • sequant watch <issue> — tail the outbox for responses
    • Uses fs.watch() or polling to stream new outbox entries to the terminal
    • Shows formatted output: [10:15:03] Claude: Working on implementing the error handler...
    • Auto-resolve single active run (same logic as prompt)
    • Ctrl+C to stop watching (non-destructive, doesn't affect the run)
  • sequant status — show all active runs (enhancement of existing status display)
    • Shows which issues are running, current phase, elapsed time, PID
    • Indicates relay availability

Active Run Detection

  • PID tracking: sequant run writes its PID to .sequant/run.pid (or per-issue: .sequant/pids/<issue>.pid)
  • Liveness check: sequant prompt verifies the PID is still alive before sending (avoids writing to a dead session's inbox)
  • Stale PID cleanup: if PID is dead, remove the pidfile and warn:
    Run for #368 is no longer active (process exited). Message not sent.
    
  • Multiple concurrent runs supported — each has its own relay directory scoped to its worktree
  • No serialization of runs — concurrent execution is preserved as a feature

State Schema Integration

  • Add optional relay field to IssueState:
    relay?: {
      enabled: boolean;
      pid: number;
      startedAt: string; // ISO 8601
      messageCount: number; // total messages exchanged
    };
  • State updated when relay is activated/deactivated
  • sequant status reads relay state for display

Design Considerations

Performance

The hot path (no pending messages) must be extremely fast. The hook fires on every tool call — hundreds of times per phase. The check should be:

# Fast path: single stat check, ~0.1ms
if [[ "${SEQUANT_RELAY:-}" == "true" ]] && [[ -s "$RELAY_INBOX" ]]; then
    # Only parse JSONL if file is non-empty
    ...
fi

Acceptance Criteria Protection

ACs are set by /spec and stored in .sequant/state.json. The relay explicitly cannot modify them:

  1. Hook framing says "Do NOT modify acceptance criteria" — this is the primary guard
  2. QA runs against spec artifacts — even if Claude's internal state drifts, QA validates against the original ACs stored in state
  3. Directive messages are suggestions, not commands — Claude may reasonably ignore a directive that conflicts with ACs

Security

  • Same trust boundary: The relay file is in the worktree. Anyone who can write to it can already modify source files that Claude reads. No new attack surface.
  • No network exposure: Purely local filesystem IPC. No sockets, no HTTP, no external services.
  • Outbox content: May contain code snippets or implementation details from Claude's response. Acceptable for single-user local usage. If relay ever becomes networked (future), outbox content would need access controls.
  • Prompt injection via relay: Mitigated by the structured framing wrapper. A malicious message would be presented to Claude inside the "[SEQUANT RELAY]" frame, making it harder to escape context. However, this is not a hard security boundary — it's a local-user feature with local-user trust.

What This Does NOT Solve

  • Mid-tool-call intervention: If Claude is inside a single long-running Bash command (e.g., a 5-minute test suite), the hook doesn't fire until that tool call completes. Intervention granularity is per-tool-call, not real-time.
  • Guaranteed response: Claude may briefly acknowledge and move on, or may give a detailed update. The response quality depends on the model's judgment.
  • Conversation-style interaction: This is a nudge channel, not a chat. Short, directive messages work best. Extended back-and-forth will degrade task focus.

File Structure

src/
├── commands/
│   ├── prompt.ts          # `sequant prompt` command
│   └── watch.ts           # `sequant watch` command
├── lib/
│   └── relay/
│       ├── types.ts       # RelayMessage, RelayResponse schemas
│       ├── writer.ts      # Write to inbox (used by CLI)
│       ├── reader.ts      # Read from inbox (used by hook)
│       └── pid.ts         # PID tracking and liveness checks
templates/
└── relay/
    └── frame.txt          # Hook message framing template

Hook integration point in templates/hooks/post-tool.sh:

# === RELAY CHECK ===
# Check for user messages in the relay inbox
if [[ "${SEQUANT_RELAY:-}" == "true" ]]; then
    source "$(dirname "$0")/relay-check.sh"
fi

Implementation Notes

  • The relay directory lives in the worktree (not the main repo) because each run is isolated to its worktree
  • spec phase runs in the main repo but relay targets the worktree path from state — the hook needs to resolve the relay path from SEQUANT_WORKTREE env var (already set by phase-executor)
  • For the spec phase specifically, the relay directory should be in the main repo's .sequant/relay/<issue>/ since there's no worktree yet
  • JSONL chosen over a single JSON file to avoid read-modify-write races and to support append-only semantics

Testing

  • Unit test: RelayWriter creates inbox.jsonl with correct schema
  • Unit test: RelayReader reads and marks messages as processed
  • Unit test: PID liveness check correctly identifies alive vs dead processes
  • Unit test: auto-resolve picks the single active run, errors on ambiguous
  • Unit test: message framing includes all required guardrails
  • Integration test: write to inbox → hook picks up → response in outbox (mock Claude session)
  • Manual test: sequant run 42 in one terminal, sequant prompt 42 "status?" in another

Non-Goals

  • No web UI or dashboard (local CLI only)
  • No multi-user relay (single user, single machine)
  • No persistent message history beyond the current run (logs are archived, not indexed)
  • No skill modifications required for v1
  • No changes to the Agent SDK integration

Activity

  1. added
    enhancement
    roadmap
    cli
    on Mar 22, 2026
  2. admarble commented on Apr 8, 2026

    @admarble
    ContributorAuthor

    Architecture Update — Unblocked

    The following new architecture issues remove the blockers for this feature:

    Once #508 lands, the MCP-side interactive relay becomes feasible in-process. The CLI-side relay (file-based IPC via PostToolUse hooks, sequant prompt, sequant watch) was never blocked and remains this issue's primary scope.

    Recommended sequencing: Wait for batch 3 (#508) to complete before starting this issue. The file-based relay design can proceed independently, but MCP integration should target the new in-process architecture.

  3. admarble commented on Apr 9, 2026

    @admarble
    ContributorAuthor

    Unblocked: RunOrchestrator extracted (#503 merged)

    PR #510 merged — RunOrchestrator is now a standalone class importable without CLI context:

    import { RunOrchestrator } from 'sequant';

    Key APIs available for interactive relay integration:

    • RunOrchestrator.run(init, issues) — full lifecycle with onProgress callback
    • new RunOrchestrator(config).execute(issues) — low-level dispatch (caller manages setup)
    • OrchestratorServices — injectable services (logWriter, stateManager, shutdownManager)
    • ProgressCallback — per-phase progress events (start | complete | failed)

    The onProgress callback provides a hook point for relay communication, and the injectable services pattern means the relay can intercept/extend logging and shutdown behavior.

    This removes the "must go through CLI entry point" blocker noted in this issue's dependencies.

  4. admarble commented on Apr 19, 2026

    @admarble
    ContributorAuthor

    Integration follow-up

    Once the live multi-issue TUI ships (#540), relay will surface in the TUI's focused issue box as a text input row — > nudge #47: ___ — submitting via sequant prompt <issue> "<msg>" and rendering outbox responses inline in the activity cell. Input row is hidden when relay isn't yet initialized for the current phase.

    No ACs change on this issue; integration is tracked as a planned follow-up of #540 (Milestone 5 in its body).

    Activation order:

    1. Live multi-issue dashboard for sequant run — concurrent box rendering (read-only TUI) #540 lands (M1 read-only TUI)
    2. Live multi-issue dashboard for sequant run — concurrent box rendering (read-only TUI) #540 follow-ups add keybindings + attention dock
    3. This issue (Interactive relay: bidirectional communication with headless runs #383) lands relay infrastructure
    4. A further follow-up on Live multi-issue dashboard for sequant run — concurrent box rendering (read-only TUI) #540 wires the text-input row to the relay CLI

    Step 4 is the point where relay becomes user-visible inside the TUI.

  5. admarble commented on May 13, 2026

    @admarble
    ContributorAuthor

    → PROCEED — File-based relay infrastructure (CLI-side); TUI input-row wiring stays out of scope

    Workflow: spec → testgen → exec → qa
    Command: npx sequant run 383 -q --testgen

    #540 (M1 read-only TUI) merged 2026-04-20; per the 2026-04-19 comment the CLI-side relay was never blocked and is this issue's primary scope. Step 4 of the activation order (wiring the TUI text-input row to the relay CLI) remains a #540 follow-up, NOT this issue. Large scope: inbox/outbox protocol, PostToolUse hook, two new CLI commands (sequant prompt, sequant watch), state schema field, PID liveness. testgen added because ACs explicitly name unit + integration tests.

  6. admarble commented on May 13, 2026

    @admarble
    ContributorAuthor

    Plan (spec phase complete)

    Complexity: Complex — 25 ACs across 6 directories. Scope verdict: SPLIT_RECOMMENDED, but features are tightly coupled (hook ↔ protocol ↔ CLI ↔ state). Recommend single-issue execution with quality loop auto-enabled.

    Workflow: spec → testgen → exec → qa

    Acceptance Criteria (with verification methods)

    Relay File Protocol

    • AC-1: Per-issue dir <worktree>/.sequant/relay/ (Integration)
    • AC-2: Inbox JSONL with msg_<hex> IDs (Unit)
    • AC-3: Outbox JSONL with inReplyTo (Unit)
    • AC-4: query|directive|abort Zod discriminated union (Unit)
    • AC-5: Atomic writes via O_APPEND + temp-rename (Unit)
    • AC-6: Archive to .sequant/logs/relay/<issue>-<phase>-<ts>/ on phase end (Integration)

    PostToolUse Hook

    • AC-7: relay-check.sh sourced from post-tool.sh when SEQUANT_RELAY=true (Integration)
    • AC-8: test -s fast path on every PostToolUse (Integration)
    • AC-9: One framing block per invocation, timestamp-ordered (Integration)
    • AC-10: Fast path <5ms p99 over 100 invocations (Unit perf + Integration)
    • AC-11: Cursor file tracks last-read line, atomic update (Unit)
    • AC-12: Opt-in via SEQUANT_RELAY=true (Unit)
    • AC-13: Existing post-tool.sh tests pass unchanged when unset (Unit)

    Hook Framing

    • AC-14: Frame matches templates/relay/frame.txt (Unit snapshot)
    • AC-15: Template contains verbatim 6 rules from issue body (Manual, mandatory fixture)
    • AC-16: No SKILL.md mentions relay/SEQUANT_RELAY — CI grep (Integration)

    CLI Commands

    • AC-17: sequant prompt <issue> "<msg>" writes inbox + confirms (Integration)
    • AC-17a: --type query|directive|abort validated (Unit)
    • AC-17b: Auto-resolve single run; error on ambiguous (Unit)
    • AC-18: sequant watch <issue> via fs.watch() + polling fallback (Integration)
    • AC-19: sequant status shows active runs + relay column (Integration)

    Active Run Detection

    • AC-20: .sequant/pids/<issue>.pid written at run start (Unit)
    • AC-21: Liveness reuses LockManager.isPidAlive (Unit)
    • AC-22: Stale PID cleanup + warning (Unit)
    • AC-23: Multiple concurrent runs preserved (Integration)

    State Schema

    • AC-24: Optional relay field on IssueState; legacy state still validates (Unit)
    • AC-25: State updated on activation/deactivation (Integration)

    Derived (quality planning):

    • AC-D1: Hot-path microbenchmark <5ms p99 on macOS + Linux (High)
    • AC-D2: Archive completes before worktree teardown (High)
    • AC-D3: SIGKILL'd run cleaned by next sequant prompt (Medium)
    • AC-D4: Archived dir includes meta.json (Medium)

    Implementation Phases

    1. Types + State — src/lib/relay/{types,pid}.ts, state-schema.ts field
    2. I/O Layer — src/lib/relay/{writer,reader}.ts
    3. Hook Integration — templates/relay/frame.txt, templates/hooks/relay-check.sh, wire into post-tool.sh, env injection in phase-executor.ts:632
    4. CLI Commands — src/commands/{prompt,watch}.ts; extend status.ts; register in bin/cli.ts
    5. Lifecycle — activation in run-orchestrator, archive-before-teardown in cleanup, settings + --no-relay flag

    Key Decisions

    • Reuse LockManager.isPidAlive — don't reimplement PID liveness.
    • Framing template as a file (frame.txt), not inline — single source per AC-15.
    • Per-phase relay reset; carryForward deferred to follow-up.
    • Soft abort via .aborting sentinel — hard kill not feasible from inside query().
    • Spec-phase fallback: relay dir in main repo when SEQUANT_WORKTREE unset.

    Open Questions for Reviewer

    1. Does Claude Code PostToolUse stdout become an additional context message? Smoke-test required in Phase 3 before fully wiring framing.
    2. Per-phase relay reset acceptable vs. carry-forward?
    3. spec-phase relay path in main repo OK?
    4. Multi-message framing: one block per invocation confirmed?
    5. abort semantics: soft (sentinel + Claude wraps up) vs. hard kill?
  7. added
    planned
    on May 13, 2026
  8. admarble commented on May 13, 2026

    @admarble
    ContributorAuthor

    Test Stubs Generated

    AC Group Verification Happy Path Failure Paths
    AC-1 (relay dir) Integration 2 tests 3 error scenarios
    AC-2, 3, 4, 5, 11, 14 (protocol/writer/reader/frame) Unit 14 tests 11 failure stubs
    AC-6, D2, D4 (archive + meta) Integration 4 tests 3 error scenarios
    AC-7, 8, 9 (hook wiring) Integration 7 tests 3 error scenarios
    AC-10, D1 (fast-path perf) Unit 3 tests 2 failure stubs
    AC-12, 13 (env opt-in + back-compat) Unit 6 tests 2 edge cases
    AC-15 (verbatim 6 rules) Manual — mandatory fixture
    AC-16 (no SKILL.md leakage) Integration 5 tests 1 error scenario
    AC-17, 18, 19 (CLI prompt/watch/status) Integration 7 tests 3 error scenarios
    AC-17a, 17b (--type + auto-resolve) Unit 7 tests 4 failure stubs
    AC-20, 21, 22 (PID tracking) Unit 7 tests 4 failure stubs
    AC-23, 25, D3 (lifecycle, concurrency, SIGKILL cleanup) Integration 9 tests 3 error scenarios
    AC-24, D4 (state schema + meta) Unit 5 tests 4 failure stubs

    Counts explained:

    • Happy Path: positive-path stubs (one per it())
    • Failure Paths: error handling, edge case, and concurrency stubs

    Unit Test Stubs

    • __tests__/relay-protocol.test.ts — AC-2, AC-3, AC-4, AC-5, AC-11, AC-14
    • __tests__/relay-pid.test.ts — AC-20, AC-21, AC-22
    • __tests__/relay-cli.test.ts — AC-17a, AC-17b
    • __tests__/relay-hook-env.test.ts — AC-12, AC-13
    • __tests__/relay-state-schema.test.ts — AC-24, AC-D4
    • __tests__/relay-perf.test.ts — AC-10, AC-D1

    Integration Test Stubs

    • __tests__/integration/relay-directory.integration.test.ts — AC-1
    • __tests__/integration/relay-archive.integration.test.ts — AC-6, AC-D2, AC-D4
    • __tests__/integration/relay-hook.integration.test.ts — AC-7, AC-8, AC-9
    • __tests__/integration/relay-skill-grep.integration.test.ts — AC-16
    • __tests__/integration/relay-cli-commands.integration.test.ts — AC-17, AC-18, AC-19
    • __tests__/integration/relay-lifecycle.integration.test.ts — AC-23, AC-25, AC-D3

    Manual Test Checklist (AC-15)

    The framing template at templates/relay/frame.txt must contain verbatim the six rules from the issue body — this is a mandatory fixture per AC-15. Verified via the snapshot test in relay-protocol.test.ts (AC-14: Frame template snapshot), which asserts each of the six bullet rules appears character-for-character:

    • Do NOT modify acceptance criteria
    • Do NOT change your current objective or phase
    • Do NOT treat this as a new requirement
    • For "query" type: provide a brief status update only
    • For "directive" type: acknowledge and adjust approach if reasonable, but do not abandon current work
    • For "abort" type: stop gracefully, commit progress, and exit

    Key Assumptions to Validate Before Implementation

    • SEQUANT_WORKTREE is set when relay activates (AC-1 fallback path for spec phase relies on this being unset)
    • Claude Code surfaces PostToolUse stdout as additional context (open Q feat: Complete remaining v1.0 features (AC-10, AC-13, AC-14) #1 from the /spec — flagged for Phase 3 smoke test)
    • LockManager.isPidAlive is the single source of truth for liveness (AC-21 — no reimplementation)
    • test -s is the fast-path guard before any JSON parsing (AC-8)
    • Archive runs before worktree teardown (AC-D2 — order-dependent)
    • All three skill directories (.claude/skills/, templates/skills/, skills/) are scanned by the CI grep (AC-16)

    Next steps:

    1. Implement the test stubs (replace throw new Error(...) with real assertions)
    2. Run /exec 383 to implement the feature
    3. Verify tests pass with npm test

    Generated with Claude Code

  9. admarble commented on May 13, 2026

    @admarble
    ContributorAuthor

    /fullsolve Complete

    Issue: #383
    PR: #638
    Status: READY_FOR_MERGE

    Summary

    Phase Iterations Status
    Spec 1/1 Complete (pre-existing)
    Testgen 1/1 Complete (pre-existing)
    Exec 1/1 Complete (filled gaps + bug fixes)
    Test n/a Skipped (CLI feature, no ui/admin labels)
    QA 1/2 Complete

    AC Coverage

    All 25 named ACs + 4 derived ACs met. See PR body for the table.

    Quality Metrics

    • Tests: 3297/3297 passed across 147 files (111 new tests in 12 new files: 6 unit + 6 integration)
    • Build: npm run build passes
    • Type safety: zero new any types in src/
    • Skill isolation (AC-16): zero violations across .claude/skills/, templates/skills/, skills/
    • Scope: 35 files (12 tests, 9 lib modules, 2 CLI commands, 7 wiring edits, 2 hooks, 1 template, 1 settings, 1 schema)

    Bugs found and fixed during EXEC

    1. relay-check.sh short-circuit — cond && return 0 || exit 0 would always exit when cond was false (the relay-enabled branch). Replaced with an explicit if block.
    2. archiveRelayDir was creating an empty archive on repeat deactivation; now no-ops when both inbox and outbox are absent.
    3. --no-relay Commander wiring — renamed RunOptions.noRelay to relay?: boolean to match how Commander surfaces --no-X (consistent with chain).

    Out of scope (recorded in PR body)


    Ready for human review and merge.

  10. added 2 commits that reference this issue on May 13, 2026
  11. admarble commented on May 13, 2026

    @admarble
    ContributorAuthor

    Documentation Generated

    File: docs/features/interactive-relay.md

    Sections Included:

    • Prerequisites (running session, relay enabled)
    • Setup (default-on, --no-relay opt-out, settings.run.relay)
    • What You Can Do (sequant prompt for query / directive / abort, sequant watch, single-run auto-resolve)
    • What to Expect (tool-call latency, brief replies by design, directive advisory semantics, archive location)
    • Command Reference (prompt, watch, run --no-relay, status relay column)
    • Message Type table (query / directive / abort)
    • Troubleshooting (stale PIDs, multiple active runs, no response causes, missing archive, JSONL inspection)

    Next Steps:

    1. Review generated documentation for accuracy
    2. Add screenshots of the relay column in sequant status if helpful (optional)
    3. Merge PR to deploy documentation

    Ready to merge!

  12. added a commit that references this issue on Jun 2, 2026
  13. added a commit that references 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

    clienhancementplannedroadmap

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions