Skip to content

fix(run): spec recommendation handoff parses ephemeral chat text — recommended phases silently dropped; move the contract to a structured comment marker #921

Closed

Description

@admarble

Problem

The spec→run phase handoff is an unenforced prose contract, and it silently loses phases when it breaks.

parseRecommendedWorkflow (src/lib/workflow/phase-mapper.ts:118-120) regexes ## Recommended Workflow / **Phases:** over the spec agent's accumulated chat text — claude-code.ts:182-187 captures only assistant text blocks; tool-use inputs are excluded. It never reads the GitHub comment the spec agent posts.

Proven failure (#814, 2026-07-26): the spec agent wrote the plan to a temp file and posted it with a body file, so ## Recommended Workflow existed only as tool input. Chat text (~2.3KB across 6 blocks) had no matching section → parse returned null → label fallback ran exec → qa. The spec's recommended testgen phase was silently dropped (spec said spec → testgen → exec → qa). The label fallback (phase-mapper.ts:73-103) can never produce testgen. Same failure on #760/#762 (2026-07-15). Positive control the same night: an ad-motion run parsed fine because that agent happened to restate the block in chat. So the outcome depends on whether the agent happens to echo a section into chat — pure nondeterminism.

Irony: the durable artifact works. Running the exact regex against #814's real GitHub comment captures spec → testgen → exec → qa. The parser reads the ephemeral artifact and ignores the durable one.

Diagnosability gap: the parse outcome is one yellow console line (batch-executor.ts:1181-1185). Nothing in .sequant/logs/*.json records whether a run parsed or fell back, so this failure class is invisible in any audit of past runs.

Asymmetry: an unparseable QA verdict is a hard failure with two distinct error messages (phase-executor.ts:861-935, #853); an unparseable spec recommendation is a silent fallback that changes which phases run.

Design

Three options were considered:

A. Prompt contract only — require the final chat message to restate the section, mirroring QA's one-shot hardening (phase-registry.ts:288). Rejected as primary: keeps the contract in the ephemeral channel, still nondeterministic under summarization/deferral, adds no audit trail.

B. Comment prose fallback only (~10 lines: on chat-parse null, fetch the plan comment and rerun the same regex). Fixes the recorded failure but keeps an unanchored regex-over-prose contract with two sources of truth.

C. Structured marker in the durable artifact (chosen), with B as fallback. The spec plan comment carries a machine-readable marker, <!-- SEQUANT_SPEC: {"phases":["testgen","exec","qa"],"qualityLoop":true} -->, JSON-parsed and Zod-validated. This is not a new concept: it is exactly the system's existing idiom — <!-- SEQUANT_PHASE: {json} --> (phase-detection.ts:67, JSON + Zod + code-fence stripping) and the /assess HTML markers (assess-comment-parser.ts, "parsers consume markers, humans copy commands"). The durable, human-reviewed artifact becomes the single source of truth; the recommendation survives session summarization, body-file posting, and driver changes (the marker channel is driver-agnostic, which matters for the multi-backend roadmap #862).

Resolution order: comment marker → comment prose (existing regex) → chat text (existing regex) → label fallback, with the winning source recorded in the run log. Comment fetching reuses the existing GitHubProvider plumbing that phase-detection already uses.

Explicitly rejected: building a generic SDK structured-output channel. The driver call (claude-code.ts:121-145) has no schema mechanism today, and inventing one for this defect is disproportionate — the marker channel already exists and is tested.

Effect on process and code quality

  • Recommended phases actually run. testgen currently survives only if the spec agent echoes a block into chat. This restores the designed spec→testgen→exec flow and removes a silent workflow downgrade.
  • Converts an LLM-behavior dependency into a deterministic gate — the fix(qa): §7 gates must be reachable — lint the skill's own enforcement chain (§2h has been unwired since it shipped) #834 lesson (automated checks reliably catch exactly what is a deterministic gate) applied to orchestration instead of review.
  • Auditability: run logs record {source: "marker"|"comment-prose"|"chat"|"label-fallback", phases}, so fallback frequency becomes measurable and regressions visible (today: zero trace).
  • Zero added token cost — no extra LLM pass; the marker is one line in a comment the agent already posts.
  • Bounded blast radius: old issues without markers resolve through the existing fallbacks unchanged.

Acceptance Criteria

  • AC-1: The spec Output Template emits <!-- SEQUANT_SPEC: {json} --> (phases + qualityLoop) inside the posted plan comment, mirrored across all 3 skill copies (npx tsx scripts/check-skill-sync.ts clean).
  • AC-2: A Zod schema validates the marker; phase names are checked against the phase registry, and an invalid/unknown-phase marker logs a visible warning and falls through to the next resolution step — never a silent drop.
  • AC-3: sequant run resolves the recommendation via the ordered chain comment-marker → comment-prose → chat-text → label-fallback, with marker parsing reusing the code-fence-stripping behavior of parsePhaseMarkers so documentation examples can't false-positive.
  • AC-4: The run log JSON records the resolution source and resolved phases for every spec-led run; the console line remains but is no longer the only trace.
  • AC-5: Motivating fixture: a captured chat-text stream containing NO ## Recommended Workflow section plus fix(sync): plain sync overwrites CUSTOMIZABLE_FILES (constitution) — copyDir ignores force and never consults isCustomizableFile #814's real comment shape must resolve testgen via the comment path — gate test mutation-verified per CLAUDE.md (delete the marker from the fixture, confirm exactly that test fails, record result in the PR body).
  • AC-6: Legacy comments without a marker still resolve via the comment-prose fallback (backward-compat test).
  • AC-7: CHANGELOG entry under Unreleased referencing this issue.

Non-Goals

  • Migrating parseQaVerdict/parseQaSummary to markers — QA already hard-fails loudly and carries a one-shot prompt contract; if the marker pattern proves out here, that is a separate follow-up, not this diff.
  • Wiring or removing the dead <!-- SEQUANT_SPEC_TIER: --> marker (spec/SKILL.md:90, no TS consumer) — noted for cleanup, out of scope.
  • Any change to /fullsolve, which does not use this parser (its orchestrating LLM reads the spec output directly).

References

Complexity

medium — one new Zod schema + resolution chain in batch-executor/phase-mapper, template edits across 3 skill mirrors, fixtures. No new subsystems.

Self-assessed workflow

spec → testgen → exec → qa (quality loop enabled) — the fix is parser/orchestration logic with clear fixtures; testgen is apt given this issue is literally about testgen being dropped.

Activity

  1. admarble commented on Aug 9, 2026

    @admarble
    ContributorAuthor

    #921 — fix(run): spec recommendation handoff parses ephemeral chat text — recommended phases silently dropped; move the contract to a structured comment marker
    OPEN
    ────────────────────────────────────────────────────────────────

    → PROCEED — Well-specified parser fix, design already chosen (Option C) with fixtures named

    Commands:
    sequant run 921 -Q --testgen

    spec → testgen → exec → qa · 7 ACs

    Flags:
    -Q orchestration parser change with an asymmetric-fallback failure mode (#814-class silent drop)
    --testgen issue is literally about the testgen phase being silently dropped; codify the resolution-chain fixtures first
    ────────────────────────────────────────────────────────────────
    Cleanup:
    gh issue edit 921 --add-label bug,cli # unlabeled; fix()-prefixed CLI/orchestration bug
    ────────────────────────────────────────────────────────────────
    ⚠ Modifies batch-executor.ts (overlaps #920, #915) and spec/SKILL.md (overlaps #922); land sequentially
    ────────────────────────────────────────────────────────────────

  2. admarble commented on Aug 9, 2026

    @admarble
    ContributorAuthor

    /spec Plan — #921: spec recommendation handoff → structured comment marker

    Complexity: Standard (7 ACs, ~4 directories) · Scope: ⚠️ SCOPE_WARNING (quality loop auto-enabled)

    Acceptance Criteria

    • AC-1: Output Template emits SEQUANT_SPEC marker (phases + qualityLoop) in the posted plan comment, mirrored across all 3 skill copies — Integration Test (region-scoped gate, mutation-verified) + check-skill-sync clean
    • AC-2: Zod schema validates the marker; phase names checked against the phase registry; invalid/unknown-phase marker logs a visible warning and falls through — Unit Test
    • AC-3: Resolution chain comment-marker → comment-prose → chat-text → label-fallback, with code-fence stripping reused from parsePhaseMarkers — Unit + Integration Test
    • AC-4: Run log JSON records resolution source + resolved phases for every spec-led run — Integration Test
    • AC-5: Motivating fixture (fix(sync): plain sync overwrites CUSTOMIZABLE_FILES (constitution) — copyDir ignores force and never consults isCustomizableFile #814 shape: chat text with NO ## Recommended Workflow + real comment) resolves testgen via the comment path — Integration Test, mutation-verified per CLAUDE.md gate-test rule
    • AC-6: Legacy comments without a marker resolve via comment-prose fallback — Unit Test (backward-compat)
    • AC-7: CHANGELOG entry under Unreleased — Manual

    Implementation Plan

    Phase 1 — Marker module (src/lib/workflow/spec-recommendation.ts, new)

    1. SpecRecommendationSchema (Zod): phases: string[] (validated against phaseRegistry), qualityLoop: boolean (default false). Follows PhaseMarkerSchema idiom in state-schema.ts.
    2. Export stripMarkdownCode from phase-detection.ts and reuse it; marker regex <!-- SEQUANT_SPEC: {json} --> (flat JSON — the existing \{[^}]+\} capture shape works since arrays don't contain }).
    3. Invalid JSON / schema failure / unknown phase → visible chalk.yellow warning + return null (falls through), never silent.

    Phase 2 — Resolution chain (batch-executor.ts:1167-1192)
    4. Replace the two-branch parse with resolveSpecRecommendation(...) returning {phases, qualityLoop, source} where source ∈ marker | comment-prose | chat | label-fallback. Comment fetch via existing GitHubProvider.fetchIssueCommentBodiesSync (already returns [] on error → chain degrades gracefully offline). Latest marker-bearing comment wins. Console lines preserved.

    Phase 3 — Run log (run-log-schema.ts, log-writer.ts)
    5. Additive optional specRecommendation: {source, phases, qualityLoop} on IssueLogSchema + LogWriter.setSpecRecommendation(...) following the setPRInfo pattern — required because the spec PhaseLog is written (line ~1120) before the parse runs (~1169).

    Phase 4 — Skill template (3 mirrors: .claude/skills/spec/, templates/skills/spec/, skills/spec/)
    6. Add marker emission to the Output Template's draft-comment section; run npx tsx scripts/check-skill-sync.ts.

    Phase 5 — Tests + fixtures + CHANGELOG
    7. #814-shape fixture, mutation-verified gates (commit before mutating), legacy-comment test, invalid-marker warning test, CHANGELOG.

    Key Decisions

    • AC-4 lands on IssueLog, not the spec PhaseLog — write ordering makes a post-hoc setter (setPRInfo precedent) the smallest correct change.
    • Export stripMarkdownCode rather than duplicating — satisfies AC-3's "reusing the code-fence-stripping behavior" literally.
    • New module over growing phase-mapper.ts — the chain needs GitHubProvider + registry + Zod; keeps phase-mapper dependency-light (it's re-exported by run-compat.ts).

    Open Questions

    1. Multiple SEQUANT_SPEC markers (re-run specs): which wins? — Recommendation: last marker in comment order (marker has no timestamp; matches "latest comment" intuition). Impact if wrong: a stale re-spec could resolve old phases.
    2. Should the marker also carry the spec tier? — Recommendation: no; SEQUANT_SPEC_TIER is explicitly out of scope (Non-Goals). Keep the schema minimal: phases + qualityLoop.

    Conflict Risk

    Worktrees for #915/#916/#919 exist but have zero commits vs origin/main today. #915 (open) will touch batch-executor.ts; #922 (open) will touch spec/SKILL.md. Land sequentially; re-fetch origin/main before push.

    Recommended Workflow

    Phases: spec → testgen → exec → qa · Quality Loop: enabled
    Reasoning: Concurs with /assess (PROCEED, -Q --testgen). Unit/Integration verification ACs → testgen; SCOPE_WARNING + asymmetric-fallback failure mode → quality loop.

  3. added
    planned
    bug
    cli
    on Aug 9, 2026
  4. added a commit that references this issue on Aug 9, 2026
  5. admarble commented on Aug 9, 2026

    @admarble
    ContributorAuthor

    /fullsolve Complete

    Issue: #921
    Status: READY_FOR_MERGE

    Summary

    • AC: 7/7 met
    • Build: clean · Lint: clean · Tests: 1408/1408 passed (2 skipped) across the workflow directory + integration tests
    • QA: all checks passed (type-safety, scope/size, security sub-agents; skill-sync 44/44; CI 8/8 green)

    Iterations

    • Exec: 1/1 (no loop needed)
    • Test phase: skipped (no ui/frontend/admin labels)
    • QA loop: 0/2 (READY_FOR_MERGE on first pass)

    Risk Assessment (from QA)

    • Likely failure mode: a hand-edited or out-of-order SEQUANT_SPEC comment marker — the resolver takes the last marker in comment order, correct for normal chronological posting but undefended against manual tampering.
    • Not tested: no test exercises resolveSpecRecommendation against a live GitHubProvider/gh call (only the DI stub); the real fetch path is exercised indirectly via phase-detection.ts's existing tests, which share the same plumbing.

    PR: #925 (merged, squashed into main at 9ae2e1b4)

    Notable

    During implementation, exec's own AC-4 test caught a real bug before it shipped: LogWriter.completeIssue() copies Partial<IssueLog> fields into the final record via an explicit whitelist, and the new specRecommendation field wasn't in it — the setter appeared to work but the value was silently dropped at completeIssue() time. Fixed and covered by 3 dedicated tests.

    Post-merge build + sequant doctor smoke test both clean on main.


    Ready — already merged.

  6. added 2 commits that reference this issue on Oct 1, 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

    bugcliplanned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions