Skip to content

arch: typed workflow event system for decoupled progress, logging, and MCP streaming #504

Closed

Description

@admarble

Problem (User Impact)

Users running parallel workflows get no real-time visibility — the MCP server polls log files, the dashboard can't stream updates, and progress reporting is hardcoded into the execution path. Adding any new consumer (webhook notification, Slack integration, VS Code extension) requires modifying batch-executor internals.

Currently:

Why Now

Depends on RunOrchestrator extraction (#503) — once the engine is a standalone class, it needs a clean way to communicate state changes to multiple consumers without direct coupling.

Acceptance Criteria

  • AC-1: WorkflowEventEmitter class with typed events: run_started, run_completed, phase_started, phase_completed, phase_failed, issue_status_changed, qa_verdict, progress (at minimum)
  • AC-2: Events are typed using TypeScript — consumers get autocomplete and type checking on event payloads. Use Node.js EventEmitter with a typed wrapper (not RxJS or a pub/sub library)
  • AC-3: RunOrchestrator (arch: extract RunOrchestrator — decouple execution engine from CLI wiring #503) emits events at each lifecycle point. Emitting is fire-and-forget for non-critical consumers (logging, progress) and does not block the execution pipeline
  • AC-4: LogWriter refactored to be an event listener — subscribes to phase/run events instead of being called directly from batch-executor
  • AC-5: MetricsWriter refactored to be an event listener
  • AC-6: CLI progress display (spinners, phase status) refactored to be an event listener — parallel mode suppression becomes a listener config, not an if-statement in batch-executor
  • AC-7: MCP server can subscribe to events for real-time progress notifications (replaces log file polling). Actual MCP notification wiring is a follow-up, but the subscription mechanism must work
  • AC-8: Event payloads include enough context for any consumer: { issueNumber, phase, timestamp, duration?, verdict?, error? }
  • AC-9: Async listener support via await Promise.allSettled(listeners) wrapper — a slow listener cannot crash the pipeline

Scope & Gaps to Watch

  • Gap: Event ordering guarantees — In parallel execution, events from multiple issues interleave. Consumers must handle this. Document the contract: events are emitted in execution order per-issue, but interleaved across issues
  • Gap: Backpressure — If a listener is slow (e.g., webhook with network latency), it must not block phase execution. The emit wrapper must be fire-and-forget with error swallowing for non-critical listeners
  • Gap: Serialization — Event payloads must be JSON-serializable for MCP/webhook consumers. No class instances or circular references in payloads
  • Risk: Over-engineering — This should be ~200 lines of code total. Node's EventEmitter is sufficient. Don't introduce a message queue, event store, or replay mechanism

Technical Notes

  • Best practice from research: Use Node's built-in EventEmitter with a typed wrapper (e.g., strict-event-emitter-types or a manual generic). Zero runtime dependencies, battle-tested
  • Current progress reporting: onProgress callback in executeBatch(), spinner suppression via config.parallel check in batch-executor.ts:396-398
  • Current log writing: LogWriter.logPhase() called directly from batch-executor.ts — becomes emitter.on('phase_completed', (e) => logWriter.logPhase(e))
  • Current metrics: MetricsWriter.recordRun() called at end of run — becomes emitter.on('run_completed', ...)

Dependencies

Batch Group

sequant run batch 2 (parallel with phase registry and async I/O — all depend only on #503)

Activity

  1. added
    enhancement
    roadmap
    on Apr 8, 2026
  2. admarble commented on Apr 9, 2026

    @admarble
    ContributorAuthor

    Architecture Review: Recommended Descoping

    After an overcomplexity assessment of the #503-#508 target architecture, this issue should be descoped. The current design builds a full event bus for 2-3 actual consumers — the ROI isn't there yet.

    What to keep

    • AC-1 (WorkflowEventEmitter class) — yes, build the emitter
    • AC-2 (typed events with TypeScript autocomplete) — yes
    • AC-8 (structured event payloads with context) — yes
    • AC-9 (async listener safety via Promise.allSettled) — yes

    What to remove

    • AC-4 (refactor LogWriter into event listener) — works fine as a direct call today
    • AC-5 (refactor MetricsWriter into event listener) — same
    • AC-6 (refactor CLI progress/spinners into event listener) — same

    These three subsystems are the only current consumers. Refactoring them into subscriber patterns is churn for decoupling that only pays off at 4+ independent listeners. Two of the five diagrammed listeners (Webhooks, MCP Notifications) are future/speculative.

    What to downgrade

    • AC-7 (MCP subscription mechanism) — note as future, not required for this issue. The emitter API will support it when needed; no need to wire it now.

    Rationale

    • 1 developer, 0 external users — every abstraction is a tax paid on every change
    • The current callback + stderr approach is pragmatic and works
    • Build the emitter, wire it into RunOrchestrator, but let existing consumers opt in organically when a real 4th consumer arrives (webhooks, VS Code extension, etc.)
    • Net scope: ~100 lines instead of ~200 + 3 refactors

    Updated AC checklist

    • WorkflowEventEmitter class with typed events
    • TypeScript-typed event payloads (autocomplete, type checking)
    • RunOrchestrator emits events at lifecycle points (fire-and-forget)
    • Structured payloads: { issueNumber, phase, timestamp, duration?, verdict?, error? }
    • Async listener safety (Promise.allSettled wrapper)
    • Existing consumers (LogWriter, MetricsWriter, spinners) remain as direct calls — migration deferred until a 4th consumer justifies it
  3. added 2 commits that reference this issue on Apr 9, 2026
  4. added
    backlog
    on Apr 15, 2026
  5. admarble commented on Apr 17, 2026

    @admarble
    ContributorAuthor

    → PROCEED — Typed event system (unblocks #383, #486)

    Workflow: spec → exec → qa · 9 ACs

    npx sequant run 504 -q
    

    Context: #503 (RunOrchestrator extraction) merged via PR #510, so the stated dependency is resolved. Descoped per roadmap — confirm scope during /spec.

    ⚠ 9 ACs across batch-executor, MCP, and dashboard — multi-file scope

  6. admarble commented on May 14, 2026

    @admarble
    ContributorAuthor

    → PROCEED — Descoped event emitter + RunOrchestrator wiring

    Workflow: spec → exec → qa · -q

    npx sequant run 504 505 -q
    

    Scope reminder: the 2026-04-09 descoping comment is authoritative — keep AC-1/2/3/8/9 (emitter, typed events, orchestrator wiring, structured payloads, async listener safety). Drop AC-4/5/6 (LogWriter/MetricsWriter/spinner refactors — only migrate when a 4th consumer arrives). AC-7 (MCP subscription) noted as future, not required for this issue.

    Independent of #505 — safe to run in parallel.

  7. admarble commented on May 14, 2026

    @admarble
    ContributorAuthor

    Complexity: Standard (5 ACs, 1 directory)

    AC Quality Check

    Operating on the post-descope AC list from the 2026-04-09 architecture review (re-affirmed 2026-05-14): keep AC-1/2/3/8/9; drop AC-4/5/6 (consumer migrations); AC-7 noted as future. Renumbered AC-1 … AC-5 below.

    AC Status Notes
    AC-1 (emitter + event names) ✅ Measurable — 8 named events
    AC-2 (typed events) ✅ Measurable — Node EventEmitter + typed wrapper, no third-party lib
    AC-3 (orchestrator emits fire-and-forget) ✅ Measurable — emission non-blocking
    AC-4 (payload shape) ✅ Measurable — fixed field set
    AC-5 (Promise.allSettled wrapper) ⚠️ Linter flagged "slow listener" as unmeasurable. Verdict: false positive — the word is descriptive of failure mode, not a timing budget. The contract ("listener exceptions/rejections do not propagate") is enforced by Promise.allSettled, which is the measurable test.

    Scope Assessment

    Non-Goals: Implicit in descoping comment. Recommend appending an explicit Non-Goals section to the issue body once /spec lands:

    • ❌ Refactoring LogWriter, MetricsWriter, or CLI progress display into listeners
    • ❌ Wiring MCP server subscription end-to-end (mechanism only)
    • ❌ Webhook / Slack / VS Code consumers
    • ❌ Event replay, persistence, or backpressure beyond Promise.allSettled
    Metric Value Status
    Feature count 1 (emitter + orchestrator integration) ✅
    AC items 5 ✅
    Directory spread 1 (src/lib/workflow/) ✅

    Verdict: ✅ SCOPE_OK


    Acceptance Criteria

    AC-1: WorkflowEventEmitter class with typed events

    Verification: Unit Test
    Scenario: Given a fresh WorkflowEventEmitter → When emit('phase_started', payload) is called with each of the 8 event names → Then registered listeners receive the typed payload; emitting an unknown event name fails TypeScript compilation.
    Required events (8): run_started, run_completed, phase_started, phase_completed, phase_failed, issue_status_changed, qa_verdict, progress.
    Assumptions: Event name set is closed (no string-keyed catchall). Add new events by extending the type map, not by adding string index signature.

    AC-2: TypeScript-typed events (no third-party pub/sub)

    Verification: Unit Test + manual TS check
    Scenario: Given emitter.on('phase_completed', (e) => …) → When typing e. in an editor → Then autocomplete shows { issueNumber, phase, timestamp, duration } only; e.verdict (wrong event) fails compilation.
    Implementation note: Hand-rolled generic preferred (class TypedEmitter<E extends Record<string, unknown>> extends EventEmitter). Reject strict-event-emitter-types and similar packages per technical notes ("zero runtime dependencies"). The wrapper is ~30 LOC.
    Assumptions: node:events's EventEmitter covers the runtime needs; we only need compile-time typing on .on() / .emit() / .off().

    AC-3: RunOrchestrator emits events at lifecycle points (fire-and-forget)

    Verification: Integration Test (with RunOrchestrator.run)
    Scenario: Given an orchestrator with a registered listener that throws synchronously and a second listener that resolves after 200ms → When a phase completes → Then the pipeline proceeds without delay and without error propagating to the run.
    Lifecycle points (from run-orchestrator.ts + batch-executor.ts):

    • run_started → top of RunOrchestrator.run() after config resolution
    • run_completed → before return in RunOrchestrator.run()
    • issue_status_changed → state transitions in applyProgressEvent (queued → running → passed/failed)
    • phase_started / phase_completed / phase_failed → existing call sites in batch-executor.ts:526/579/587/792/844/852
    • qa_verdict → phase-executor.ts:434 after verdictMatch
    • progress → existing onActivity ping (batch-executor.ts:86, throttled ~10 Hz)
      Assumptions: Emitter is owned by RunOrchestrator, threaded into BatchExecutionContext (replacing or coexisting with onProgress). See Open Question 1.

    AC-4: Structured event payloads

    Verification: Unit Test + JSON-roundtrip test
    Scenario: Given each emitted event → When JSON.stringify(payload) is called → Then the result roundtrips through JSON.parse without loss; no class instances or circular refs are present.
    Base shape: { issueNumber: number, phase?: string, timestamp: string /* ISO 8601 */, duration?: number, verdict?: QaVerdict, error?: string }
    Per-event refinements: run_* events omit phase; qa_verdict requires verdict; progress adds text?: string (the existing activity line). Document via a discriminated union keyed by event name.
    Assumptions: Consumers expecting wall-clock duration get seconds (matches PhaseLog.durationSeconds); timestamp is ISO 8601 (matches existing log schema).

    AC-5: Async listener safety wrapper

    Verification: Unit Test
    Scenario: Given 3 listeners (sync-throwing, async-rejecting, async-resolving) attached to phase_completed → When emitter.emit('phase_completed', payload) is awaited → Then all 3 listeners are invoked, both failures are isolated, and the third still completes; orchestrator code that did await emitter.emit(...) does not throw.
    Implementation note: Override emit() to return Promise<void> and wrap listener invocations in Promise.allSettled with logging of rejections at verbose level. Callers in critical paths (e.g. run_completed) await; fire-and-forget callers (e.g. progress) do not.
    Assumptions: Rejection logging goes through console.log at verbose, mirroring logNonFatalWarning (run-orchestrator.ts:1187). No retry, no dead-letter queue (out of scope per descope).


    Implementation Plan

    Phase 1: Emitter scaffold

    1. New file src/lib/workflow/event-emitter.ts (~120 LOC budget):
      • TypedEmitter<E> generic base class wrapping node:events.EventEmitter
      • WorkflowEvents type map (discriminated union, one entry per event name in AC-1)
      • WorkflowEventEmitter extends TypedEmitter<WorkflowEvents>
      • Override emit() to Promise.allSettled the listener calls (AC-5)
      • Export from src/lib/workflow/types.ts or a barrel — match local convention.
    2. Unit tests event-emitter.test.ts (~150 LOC budget): type-error fixtures, payload-shape tests, Promise.allSettled failure-isolation tests.

    Phase 2: RunOrchestrator wiring

    1. Add emitter: WorkflowEventEmitter field to RunOrchestrator; instantiate in constructor.
    2. Expose via getEmitter() so external consumers (TUI, MCP, follow-up Interactive relay: bidirectional communication with headless runs #383/Add subagent lifecycle hooks for token cost visibility and diagnostics #486) can subscribe.
    3. Emit at the 7 lifecycle points listed in AC-3 above. Reuse existing call sites in batch-executor.ts (lines 526/579/587/792/844/852) — add a single emitter.emit(...) next to each existing emitProgressLine(...)/onProgress?.(...) invocation. Do not delete emitProgressLine or onProgress; they remain in place (descoped — see Non-Goals).
    4. Thread the emitter through BatchExecutionContext so phase-executor.ts can emit qa_verdict at line 434 without reaching back to the orchestrator.

    Phase 3: Integration test + smoke

    1. Integration test: spin up RunOrchestrator.run(...) in dry-run mode, subscribe to all 8 events, drive a one-issue stub, assert the expected event sequence + payload roundtrip.
    2. Backward-compat smoke: existing batch-executor.test.ts and run-orchestrator tests must continue to pass — no behavior change for callers that don't subscribe.

    Design Review

    1. Where does this logic belong? src/lib/workflow/ — sibling to run-orchestrator.ts. The emitter is workflow-domain plumbing, not generic infra (rejected: src/lib/events/).
    2. What's the simplest correct approach? Hand-rolled TypedEmitter<E> generic over node:events.EventEmitter. Rejected alternatives:
      • strict-event-emitter-types — adds a dep for ~20 LOC of typing
      • RxJS — explicitly rejected in AC-2
      • Replace onProgress callback wholesale — out of scope per descope
    3. What existing pattern does this follow? The orchestrator's existing ProgressCallback pattern (types.ts:364) is the closest neighbor. The emitter generalizes it from one consumer (the renderer) to N consumers. The verbose-gated non-fatal warning pattern (run-orchestrator.ts:1187) is the model for listener rejection logging.
    4. What would a senior reviewer challenge?
      • "Why both emitter and onProgress callback?" — onProgress is the synchronous TUI render hook; events are the async multi-subscriber surface. The descope explicitly defers consolidating them. Document this dual API in the emitter file header.
      • "Promise.allSettled blocks the pipeline if all listeners are slow." — Only when the caller awaits the emit. Fire-and-forget paths (progress event) don't await. Document which lifecycle points await and which don't.
      • "Event names use snake_case but the rest of the codebase is camelCase." — Issue body specifies snake_case (run_started etc.). Keep snake_case for event names; payload fields stay camelCase.

    Feature Quality Planning

    All standard checks pass. Notable items:

    • AC-5 linter false positive — "slow listener" flagged as unmeasurable but is descriptive of failure mode, not a timing budget. No AC change needed.
    • Concurrent worktree (arch: phase plugin registry — user-extensible workflow phases #505) on same src/lib/workflow/ directory — see Conflict Risk Analysis below.
    • onProgress coexistence is a deliberate non-goal, not an oversight. If a reviewer pushes to consolidate, point them at the descoping comment.

    Conflict Risk Analysis

    feature/505-arch-phase-plugin-registry-... worktree exists at the same HEAD as main (no commits yet). #505 touches src/lib/workflow/types.ts, phase-executor.ts, and phase-detection.ts. #504 touches types.ts (new export), run-orchestrator.ts, batch-executor.ts, and adds event-emitter.ts.

    Overlap: src/lib/workflow/types.ts — both will add exports; merge conflict possible if both append to the same region.
    Mitigation: #504 adds a new file (event-emitter.ts) and a small re-export in types.ts. Keep the types.ts touch minimal (1–3 lines, append at end) to reduce merge surface. Issue assess comment confirms "independent of #505 — safe to run in parallel."


    Open Questions

    1. Emitter ownership vs. onProgress callback — Recommendation: coexist, emitter owned by RunOrchestrator, exposed via getEmitter(). onProgress stays as-is for the TUI's synchronous render path. Impact if wrong: if we replace onProgress instead, TUI render latency grows by one event-loop tick per phase event — measurable on the dashboard. Recommend coexist.
    2. Should progress (activity ping ~10 Hz) be an event at all? — High-frequency stream may pressure listeners. Recommendation: include it, but document that subscribing to progress is opt-in and listeners must be cheap (no I/O). Impact if wrong: a misbehaving subscriber degrades the run. Mitigation lives in AC-5.
    3. Emitter teardown — Recommendation: call emitter.removeAllListeners() in the finally block of RunOrchestrator.run() (alongside orchestrator.markDone() at line 773) to prevent leaks across multiple run() invocations in the same process (MCP server use case). Impact if wrong: memory leak under repeated MCP sequant_run calls.

    Recommended Workflow

    Phases: spec → testgen → exec → qa
    Quality Loop: enabled
    Reasoning: All 5 ACs are Unit Test or Integration Test verification — testgen adds value here. Quality loop is enabled per /assess recommendation; AC-3 (fire-and-forget) and AC-5 (Promise.allSettled) have subtle failure modes that benefit from iterative refinement.


    Label Review

    Current: enhancement, roadmap, backlog
    Recommended: enhancement, roadmap, planned (drop backlog since work is starting)
    Reason: Issue moved from backlog to active execution per /assess PROCEED. The roadmap label remains accurate (still an arch-roadmap item); backlog no longer applies.
    Quality Loop: Will auto-enable per /assess quality-loop=true marker.

    → gh issue edit 504 --add-label planned --remove-label backlog

  8. added
    planned
    and removed
    backlog
    on May 14, 2026
  9. admarble commented on May 14, 2026

    @admarble
    ContributorAuthor

    /exec Progress Update

    PR: #643

    AC Coverage (post-descope, renumbered AC-1…AC-5)

    AC Status Evidence
    AC-1 ✅ WorkflowEventEmitter class with 8 typed events in src/lib/workflow/event-emitter.ts
    AC-2 ✅ Hand-rolled typed wrapper over node:events — no third-party pub/sub dependency
    AC-3 ✅ RunOrchestrator emits at lifecycle points; all emits are fire-and-forget (void emitter.emit(...))
    AC-4 ✅ Discriminated payload types; JSON.stringify roundtrip verified in unit + integration tests
    AC-5 ✅ Promise.allSettled wrapper with onListenerError hook (which itself swallows throws)

    Files Changed

    • src/lib/workflow/event-emitter.ts (new, 234 LOC) — WorkflowEventEmitter + payload types
    • src/lib/workflow/event-emitter.test.ts (new) — 10 unit tests
    • src/lib/workflow/run-orchestrator.ts — emitter field, getEmitter(), lifecycle emits, listener teardown in markDone()
    • src/lib/workflow/types.ts — emitter on BatchExecutionContext + IssueExecutionContext; barrel re-exports
    • __tests__/run-orchestrator-events.test.ts (new) — 9 integration tests
    • CHANGELOG.md — [Unreleased] Added entry

    Quality Plan Alignment

    Dimension Items Notes
    Error Handling 1/1 Listener errors isolated via Promise.allSettled
    Test Coverage 2/2 All 5 ACs covered in unit + integration suites (19 new tests)
    Code Quality 2/2 No new deps; JSDoc documents dual-API coexistence with onProgress
    Best Practices 1/1 Verbose-gated logNonFatalWarning for listener errors

    Derived ACs: None — spec did not list a Derived ACs table.

    Verification Results

    • npm run build ✅
    • npm run lint ✅ (zero warnings)
    • npx vitest run src/lib/workflow/ __tests__/run-orchestrator*.test.ts __tests__/integration/run-orchestrator.integration.test.ts ✅ 907/907 pass
    • npx vitest run __tests__/mcp-progress-notifications.test.ts __tests__/mcp ✅ 47/47 pass

    Notes

    • onProgress coexists with the emitter per the spec's open-question 1 recommendation. The existing synchronous TUI render hook is unchanged; the emitter is the async multi-subscriber surface.
    • AC-7 (MCP subscription wiring) is intentionally deferred per the descope. The mechanism (orchestrator.getEmitter().on(...)) is in place and works today; the actual MCP-side notification consumer is follow-up work.
    • executeBatch not wired: that function is unused in src/ — the orchestrator calls runIssueWithLogging directly. The emitter is still threaded through BatchExecutionContext so the type contract is preserved.
  10. admarble commented on May 14, 2026

    @admarble
    ContributorAuthor

    QA Review for Issue #504

    AC Coverage

    The original 9 ACs were descoped per the 2026-04-09 architecture-review comment. The reduced contract (kept items below) is what this implementation must satisfy.

    AC Source Description Status Notes
    AC-1 Original WorkflowEventEmitter with 8 typed events MET All 8 declared in WorkflowEvents (event-emitter.ts:105-114): run_started, run_completed, phase_started, phase_completed, phase_failed, issue_status_changed, qa_verdict, progress. Verified by event-emitter.test.ts:17-74.
    AC-2 Original TypeScript-typed events, Node EventEmitter + typed wrapper (no RxJS) MET Hand-rolled generic wrapper over node:events.EventEmitter (event-emitter.ts:138-238). on/off/emit are narrowed to keyof WorkflowEvents; unknown event names fail compilation. Zero new runtime deps.
    AC-3 Original RunOrchestrator emits at lifecycle points; fire-and-forget MET All emits use void this.emitter.emit(...) (run-orchestrator.ts:344, 365, 393, 405, 419, 436, 1084, 1093, 1101). Slow-listener integration test (run-orchestrator-events.test.ts:365-389) confirms a hung listener doesn't block run completion.
    AC-4 (orig) Original Refactor LogWriter into event listener DESCOPED Removed by 2026-04-09 architecture review — kept as direct call. Documented in CHANGELOG.
    AC-5 (orig) Original Refactor MetricsWriter into event listener DESCOPED Same as above.
    AC-6 (orig) Original Refactor CLI progress into event listener DESCOPED Same as above.
    AC-7 Original (downgraded) MCP subscription mechanism works MET Mechanism in place: orchestrator.getEmitter().on('progress', ...) works today (proven by integration tests). Actual MCP-side wiring is explicit follow-up per the descope.
    AC-8 Original Structured payloads with context MET BaseEventPayload (event-emitter.ts:38-43) requires issueNumber + timestamp; each event extends with phase, duration, verdict, error, iteration as appropriate. JSON-serializable verified by roundtrip test (event-emitter.test.ts:112-139 + run-orchestrator-events.test.ts:295-338).
    AC-9 Original Async listener safety via Promise.allSettled MET emit() wraps each listener in Promise.resolve().then(() => listener(payload)) then Promise.allSettled (event-emitter.ts:221-225). Trampoline correctly reifies synchronous throws — verified by event-emitter.test.ts:143-174. Error handler itself swallows throws (event-emitter.test.ts:207-227).

    Coverage: 5/5 retained ACs MET; 3 descoped per architecture-review; 1 downgraded (mechanism MET, consumer deferred).


    CI Status

    Check State Bucket Impact
    typecheck SUCCESS pass ✅ MET
    build (20.x) SUCCESS pass ✅ MET
    build (22.x) SUCCESS pass ✅ MET
    validate-skills SUCCESS pass ✅ MET
    validate-plugin SUCCESS pass ✅ MET

    CI Summary: 5 passed, 0 pending, 0 failed.
    Mergeable state: MERGEABLE (UNSTABLE briefly during in-progress builds, now resolved).


    Quality Metrics

    Metric Value Status
    Type issues (any added) 0 OK
    Deleted tests 0 OK
    Files changed 6 (4 src + CHANGELOG + 2 new test files) OK
    Lines added +1042 -
    Lines deleted -2 -
    Test:code ratio ~1.7:1 (658 test LOC vs ~380 impl LOC) OK

    Test Coverage Analysis

    Changed File Tier Has Tests? Test File
    src/lib/workflow/event-emitter.ts Standard ✅ Yes src/lib/workflow/event-emitter.test.ts (10 tests)
    src/lib/workflow/run-orchestrator.ts Standard ✅ Yes __tests__/run-orchestrator-events.test.ts (9 tests)
    src/lib/workflow/types.ts Optional N/A Types-only (re-exports)

    Coverage: 2/2 changed source files have tests. All 5 retained ACs exercised by both unit and integration suites.

    Vitest run locally (just the new suites): 19/19 pass, ~3s wall-clock.


    Code Review

    Strengths:

    • Clean separation: event-emitter.ts knows nothing about orchestration; run-orchestrator.ts knows nothing about how listeners are invoked. The contract is the WorkflowEvents map.
    • The Promise.resolve().then() trampoline in emit() (event-emitter.ts:221-225) is the right pattern — without it, a synchronous throw in a non-async listener would bypass Promise.allSettled and propagate. Test at line 143-174 documents this exact failure mode.
    • setMaxListeners(0) (event-emitter.ts:156) is deliberate — multiple consumers subscribing to progress would otherwise trigger Node's leak warning. Comment explains why.
    • markDone() drains listeners (run-orchestrator.ts:285-289), addressing the MCP-server re-use leak called out in the spec's Open Question Doctor: Add Claude Code CLI check #3.
    • Caller-supplied vs auto-generated timestamp semantics are clear and tested.
    • onListenerError is wrapped in try { ... } catch {} (event-emitter.ts:230-235) so a misbehaving error handler can't sink the pipeline either — belt-and-suspenders.

    Minor observations (non-blocking):

    • Asymmetry: run_completed not emitted if runIssueWithLogging throws. executeOneIssue emits run_started at run-orchestrator.ts:1084, awaits runIssueWithLogging, then emits run_completed. If the awaited call throws, run_completed is skipped. In practice runIssueWithLogging returns IssueResult { success: false } rather than throwing (so this is theoretical), but a try { ... } finally { emit("run_completed", ...) } would harden the contract for future call paths. Out of scope for this PR.
    • BatchExecutionContext.emitter / IssueExecutionContext.emitter are currently unused inside batch-executor. Exec note acknowledges this — the field is threaded for future use. Acceptable as a forward-compatibility hook; would be dead weight if no follow-up issue picks it up.
    • emit() signature is Promise<void>, called with void. The unhandled-rejection-by-design pattern is documented in the file header; Promise.allSettled swallowing keeps it safe. Worth a one-line comment at each void this.emitter.emit(...) call site explaining the intentional discard? Not blocking — JSDoc on emit() already covers it.

    Suggestions (deferable):

    • Consider a once<E>() overload for one-shot listeners (e.g. MCP's "wait for first qa_verdict"). Trivially implementable via inner.once(). File a follow-up if the MCP consumer needs it.
    • Event names use snake_case (per the issue body); the rest of the codebase is camelCase. The decision is documented in the spec plan — flag it in CONTRIBUTING / a header comment so future contributors don't "fix" it.

    Test Quality Review

    Category Status Notes
    Behavior vs Implementation ✅ OK Tests assert on emitted payloads + listener invocation counts, not on EventEmitter internals.
    Coverage Depth ✅ OK Sync-throw, async-throw, slow-listener, no-listener, error-handler-throws all covered.
    Mock Hygiene ✅ OK Integration suite mocks the heavy edges (batch-executor, worktree-manager, state-manager, p-limit) but exercises real WorkflowEventEmitter + RunOrchestrator.applyProgressEvent/executeOneIssue.
    Test Reliability ✅ OK One setTimeout(5ms) in the "slow listener" assertion — bounded and deterministic. No flake risk.

    Anti-Pattern Detection

    Dependency Audit

    N/A — package.json unchanged. AC-2 (no third-party pub/sub library) satisfied.

    Code Patterns

    No any casts added. No empty catches. No hardcoded secrets. No SQL/HTML injection surface. The single try { ... } catch {} in onListenerError invocation is deliberately empty with an explanatory comment.


    Call-Site Review

    New exported functions detected: WorkflowEventEmitter class (constructor, on, off, emit, listenerCount, removeAllListeners), RunOrchestrator.getEmitter().

    Function Call Sites Loop? Conditions AC Match
    emitter.emit("run_started") run-orchestrator.ts:1084 No (per-issue) Unconditional after ctx assembly ✅ AC-3
    emitter.emit("run_completed") run-orchestrator.ts:1101 No Unconditional after runIssueWithLogging resolves ✅ AC-3 (see asymmetry note above)
    emitter.emit("qa_verdict") run-orchestrator.ts:1093 Yes (over phaseResults) pr.phase === "qa" && pr.verdict ✅ Correct — at most one QA verdict per QA result
    emitter.emit("phase_started") run-orchestrator.ts:344 No event === "start" branch ✅ AC-3
    emitter.emit("phase_completed") / phase_failed" run-orchestrator.ts:393, 405 No Branch on event === "failed" ✅ AC-3
    emitter.emit("issue_status_changed") run-orchestrator.ts:349, 412, 432 No Only when prev !== next (de-duped) ✅ Correct — no spurious from === to events
    emitter.emit("progress") run-orchestrator.ts:368 Implicit (activity ping) Only when line non-empty ✅ AC-3
    getEmitter() tests + future consumers - - ✅ AC-7 mechanism

    Findings: All call sites match AC constraints. The from !== to de-dup on issue_status_changed is a nice touch.


    Execution Evidence

    N/A — no scripts/ or CLI option changes.


    Skill Command Verification

    N/A — no .claude/skills/**/*.md files changed.


    Detection Pattern Verification

    N/A — no skill markdown / regex / grep / awk / jq changes.


    CLI Registration Verification

    N/A — RunOptions not modified; no new CLI flags.


    Smoke Test

    Test Command Result Notes
    Type compile npm run build ✅ clean
    Lint npm run lint (--max-warnings 0) ✅ zero warnings
    New unit + integration npx vitest run src/lib/workflow/event-emitter.test.ts __tests__/run-orchestrator-events.test.ts ✅ 19/19 in ~3s
    CI matrix GitHub Actions on PR #643 ✅ typecheck + build (20.x + 22.x) + validate-skills + validate-plugin all SUCCESS

    Smoke Test Status: Complete.


    CHANGELOG Verification

    Check Status
    CHANGELOG.md exists ✅ Found
    User-facing changes ✅ Yes (feat(#504): commit)
    [Unreleased] entry ✅ Present, under "Added"
    Entry format ✅ Includes issue number (#504), names new files, documents descope decision

    Result: CHANGELOG requirements met.


    Risk Assessment

    • Likely failure mode: The emitter is in place but has no real consumers wired yet (the original AC-4/5/6 refactor of LogWriter/MetricsWriter/spinners was explicitly descoped). The first real consumer (MCP notifications, dashboard streaming) will exercise payload shapes that today are only round-tripped through JSON.stringify in tests. If the MCP consumer needs additional fields, the payload types will need extension — but the discriminated WorkflowEvents map makes that a typed, additive change.
    • Not tested: End-to-end with an actual MCP server subscriber. The mechanism is verified by integration tests but the consuming MCP server is follow-up work.
    • Sibling sites considered: None — the event system is net-new and additive. The descope explicitly keeps existing LogWriter/MetricsWriter/spinner code as direct calls; no parallel sibling implementation to compare against.
    • Sibling-line audit: N/A — single new file plus a localized orchestrator integration; no sibling call sites in the same file with the same root-cause pattern.

    Adversarial Re-Read

    Findings: Walked the diff once more adversarially:

    1. Verbatim motivating-example fixtures from issue body: the issue body's "current state" examples (5-minute polling window, onProgress threading through 4+ signatures, tightly-coupled writers) are descriptive, not testable fixtures. The discriminated WorkflowEvents map literally enumerates the AC-1 event names — that fixture is covered by event-emitter.test.ts:20-29.
    2. Evidence claims audited: every "MET" above cites a code line or test, not a promise. The Promise.allSettled test (event-emitter.test.ts:143-174) is a post-fix validation (proves listeners A and C both run after B throws), not a bug repro.
    3. Process state inspected: worktree HEAD = 053946b, branch up to date with origin/main, no uncommitted changes, no stashed work.
    4. Sibling sites cited: §5 cross-file = none (additive feature); §4 Q5 intra-file = the orchestrator's three issue_status_changed emit sites all use the prev !== next guard pattern uniformly, no asymmetry between them.
    5. Non-Goals from issue body: "Don't introduce a message queue, event store, or replay mechanism" — confirmed: implementation is a thin wrapper over node:events, no queue, no replay, no persistence. "~200 lines of code total" — actual implementation is ~239 LOC for the emitter, within target.

    One asymmetry surfaced (run_completed not emitted if runIssueWithLogging throws), already noted under Code Review as non-blocking because the awaited function returns failure rather than throwing.

    Status: Clean


    Verdict: READY_FOR_MERGE

    All 5 retained ACs MET; the three descoped ACs are explicitly out of scope per the 2026-04-09 architecture-review comment; AC-7's downgrade is satisfied by the in-place getEmitter() subscription mechanism.

    • CI: all 5 checks green
    • Build + lint + tests: green locally and in CI
    • Code quality: clean, well-documented, zero new deps, zero any types
    • Test coverage: 19 new tests covering all retained ACs at both unit and integration levels
    • CHANGELOG: present and accurate

    Documentation: Before merging, run /docs 504 to surface the new getEmitter() API for downstream consumers. The header comment on event-emitter.ts already documents the onProgress coexistence decision, but a CONTRIBUTING note about snake_case event names would help future contributors not "fix" the casing.

    Next Steps

    1. Merge PR feat(#504): typed workflow event system for decoupled progress + MCP streaming #643.
    2. File the follow-up issue for MCP-server subscription wiring (the consumer side of AC-7).
    3. Consider whether executeOneIssue should wrap the runIssueWithLogging call in try { ... } finally { void emit("run_completed", ...) } so the bracket events stay symmetric for future call paths.
  11. added
    ready-for-review
    on May 14, 2026
  12. added a commit that references this issue on May 14, 2026
  13. added 3 commits that reference this issue on May 14, 2026
  14. 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

    enhancementplannedready-for-reviewroadmap

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions