Skip to content

arch: phase plugin registry — user-extensible workflow phases #505

Closed

Description

@admarble

Problem (User Impact)

Users cannot add custom workflow phases (e.g., deploy, perf-test, accessibility-audit, i18n-check) without modifying Sequant's source code. Adding a new phase today requires changes in 5+ locations:

  1. PhaseSchema Zod enum in src/lib/workflow/types.ts
  2. PHASE_PROMPTS in src/lib/workflow/phase-executor.ts
  3. AIDER_PHASE_PROMPTS in phase-executor.ts
  4. ISOLATED_PHASES array in phase-executor.ts
  5. Phase detection logic in src/lib/workflow/phase-detection.ts
  6. Skill template in templates/skills/<phase>/SKILL.md

This is a closed system. For a workflow orchestrator, extensibility is a core value proposition — users should be able to define project-specific phases without forking.

Why Now

  • feat: add OpenAI Codex CLI agent driver #497 (Codex driver) and Multi-agent support: expand Sequant beyond Claude Code #373 (multi-agent support) both add new execution backends — phases and drivers should follow the same extensibility pattern
  • The skill template system already provides the execution mechanism (SKILL.md files). The missing piece is phase registration and discovery
  • Phase detection via GitHub labels is hardcoded (BUG_LABELS, UI_LABELS, DOCS_LABELS in phase-mapper) — users can't add their own label-to-phase mappings

Acceptance Criteria

  • AC-1: PhaseDefinition interface that describes a phase:
    interface PhaseDefinition {
      name: string;
      skill: string;                    // skill template directory name
      promptTemplate: string;           // with {issue}, {worktree}, {base} interpolation
      requiresWorktree: boolean;
      retryStrategy?: { maxRetries: number; backoffMs?: number; coldStartThreshold?: number };
      detect?: { labels?: string[]; bodyPatterns?: RegExp[] };  // auto-detection rules
      order?: number;                   // execution ordering (default 0)
    }
  • AC-2: PhaseRegistry class with register(definition), get(name), list(), has(name) methods
  • AC-3: All 9 built-in phases (spec, security-review, exec, testgen, test, verify, qa, loop, merger) registered via the same mechanism — no special-casing
  • AC-4: User-defined phases discoverable from .sequant/phases/ directory — each subdirectory containing a phase.json (or phase.ts) matching PhaseDefinition schema
  • AC-5: --phases CLI flag validates against the registry at runtime (not a compile-time Zod enum). Clear error message if a phase name is unknown: "Unknown phase 'deploy'. Available: spec, exec, qa, deploy-staging, ..."
  • AC-6: Phase detection (phase-detection.ts, phase-mapper.ts) uses registry-provided detect rules instead of hardcoded label arrays
  • AC-7: phase-executor.ts reads prompt template and retry config from the registry instead of PHASE_PROMPTS and inline constants
  • AC-8: Aider-specific prompts handled via an optional driverOverrides field in PhaseDefinition — not a parallel hardcoded map
  • AC-9: Documentation: sequant phases command lists all registered phases (built-in + user-defined) with their detection rules

Scope & Gaps to Watch

  • Gap: Phase ordering in pipelines — The default pipeline is [spec, exec, qa]. User-defined phases need a way to insert into this pipeline (e.g., "run security-review after exec but before qa"). The order field handles explicit ordering; auto-detection handles label-triggered phases. Document both patterns
  • Gap: Phase dependencies — Phase A might require phase B to have completed first (e.g., testgen needs exec). This issue covers simple ordering; full dependency resolution is out of scope
  • Gap: Skill template validation — A registered phase with skill: "deploy" must have a corresponding templates/skills/deploy/SKILL.md. Validate at registration time, not at execution time
  • Gap: Settings migration — Existing .sequant/settings.json files reference phases by string. Ensure backwards compatibility — old configs with "phases": ["spec", "exec", "qa"] must continue working
  • Risk: Over-abstraction — The registry should be ~150 lines. Don't build a full plugin lifecycle (init/setup/teardown hooks). Phase execution is already handled by skills

Technical Notes

  • Best practice from research: Rollup/Vite pattern — plugin is an object with name + hook methods. Discovery via filesystem scan + import(). Validation at startup, fail fast
  • Current PhaseSchema: z.enum(["spec", "security-review", "exec", ...]) in types.ts — becomes z.string().refine(name => registry.has(name))
  • Current PHASE_PROMPTS: Record<Phase, string> with 9 entries in phase-executor.ts:25-81 — migrated to registry
  • Current ISOLATED_PHASES: hardcoded array — becomes registry.list().filter(p => p.requiresWorktree)
  • phase-mapper.ts constants: BUG_LABELS = ["bug", "fix", ...] etc. — becomes registry.get("exec").detect.labels

Dependencies

Batch Group

sequant run batch 2 (parallel with event system 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 significantly descoped. The current design is a full plugin framework for 9 hardcoded phases maintained by 1 person. Zero users have asked for custom phases.

    What to keep

    • AC-1 (PhaseDefinition interface) — yes, formalize what a phase is
    • AC-2 (PhaseRegistry class with register/get/list/has) — yes
    • AC-3 (all 9 built-in phases registered uniformly, no special-casing) — yes, this is the main win
    • AC-7 (phase-executor.ts reads from registry instead of PHASE_PROMPTS dict) — yes
    • AC-8 (driver overrides in PhaseDefinition, not a parallel map) — yes

    What to remove

    • AC-4 (user-defined phases from .sequant/phases/ directory) — speculative. No user has asked for this. Add when someone files an issue.
    • AC-9 (sequant phases CLI command) — only useful with user-defined phases

    What to simplify

    • AC-5 (--phases validates against registry) — keep, but registry is only populated with built-ins at startup. No filesystem discovery.
    • AC-6 (phase detection uses registry data) — keep, but no user-supplied detect rules. Built-in label mappings move into PhaseDefinition objects instead of hardcoded arrays.

    Rationale

    The real problem today is that phase definitions are scattered across 5+ locations (PhaseSchema, PHASE_PROMPTS, AIDER_PHASE_PROMPTS, ISOLATED_PHASES, phase-detection.ts). A registry class consolidates these into one source of truth — that's valuable internal cleanup.

    The plugin framework (filesystem discovery, phase.json schema, skill template validation, CLI listing command) is solving a problem nobody has. The interface will be ready for extensibility later, but don't build the discovery/validation machinery until a second user asks for custom phases.

    Updated AC checklist

    • PhaseDefinition interface describing a phase (name, skill, prompt, worktree, retry, detect rules, driver overrides)
    • PhaseRegistry class with register(), get(), list(), has()
    • All 9 built-in phases registered via the same mechanism
    • phase-executor.ts reads from registry (eliminates PHASE_PROMPTS, AIDER_PHASE_PROMPTS, ISOLATED_PHASES)
    • phase-detection.ts uses registry-provided detect rules (eliminates BUG_LABELS, UI_LABELS, etc.)
    • --phases CLI flag validates against registry at runtime
    • User-defined phases deferred to follow-up issue (when requested)
  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 — Phase plugin registry (user-extensible workflow phases)

    Workflow: spec → exec → qa · 9 ACs

    npx sequant run 505 -q
    

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

    ⚠ Explicitly independent of #504 (event system) and #506 (async I/O) — no chaining required

  6. admarble commented on May 14, 2026

    @admarble
    ContributorAuthor

    → PROCEED — Descoped registry + built-in consolidation

    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/7/8 (PhaseDefinition interface, PhaseRegistry class, all 9 built-ins registered uniformly, phase-executor reads from registry, driver overrides field) plus AC-5 runtime --phases validation and AC-6 registry-provided detect rules. Drop AC-4 (.sequant/phases/ filesystem discovery) and AC-9 (sequant phases CLI) — defer to follow-up when a user asks.

    Independent of #504 — safe to run in parallel.

  7. admarble commented on May 14, 2026

    @admarble
    ContributorAuthor

    Spec — phase plugin registry

    Complexity: Standard (6 ACs descoped from 9, 2 directories: src/lib/workflow/, bin/)

    Authoritative scope: the 2026-04-09 descoping comment supersedes the original 9-AC body. This plan tracks the 6 descoped ACs; the original AC-4 (.sequant/phases/ discovery) and AC-9 (sequant phases CLI) are explicitly deferred until a user requests them.


    AC Quality Check

    ✅ All 6 descoped ACs pass the linter (no vague/unmeasurable/incomplete/open-ended/title-body-tension flags).


    Scope Assessment

    Non-Goals (from descoping comment):

    • No filesystem discovery of user phases (.sequant/phases/)
    • No phase.json / phase.ts schema validation
    • No sequant phases CLI listing command
    • No plugin lifecycle hooks (init/setup/teardown)
    • No registry mutation at runtime (built-ins only, populated at module load)
    Metric Value Status
    Feature count 1 (registry consolidation) ✅
    AC items 6 ⚠️ (at yellow threshold = 6)
    Directory spread 2 (src/lib/workflow/, bin/) ✅

    Verdict: ⚠️ SCOPE_WARNING — sits at the yellow AC threshold and rewires 5 load-bearing files (types.ts, phase-executor.ts, phase-mapper.ts, state-schema.ts, run-log-schema.ts). The descoping already removed the speculative ACs, so further splitting is not recommended; quality loop should stay enabled to catch regressions in the typed-enum migration.


    Acceptance Criteria

    AC-1: PhaseDefinition interface describing a phase

    Verification: Unit Test (type assertions + Zod shape)
    Scenario: Given a TypeScript module importing PhaseDefinition → When constructing a definition with name, skill, promptTemplate, requiresWorktree, retryStrategy?, detect?, driverOverrides?, order? → Then the type-checker accepts it and a Zod validator (if used) parses it.
    Assumptions: driverOverrides is a Record<string, { promptTemplate?: string }> keyed by driver name ("aider", future "codex"). detect.labels is string[]; detect.bodyPatterns deferred (no current consumer).

    AC-2: PhaseRegistry class with register(), get(), list(), has()

    Verification: Unit Test
    Scenario: Given a fresh PhaseRegistry → When register(def) is called and then get(def.name) / has(def.name) / list() are queried → Then values round-trip; duplicate register calls throw; get on unknown name throws with a "did you mean" message that includes registered names.
    Assumptions: Registry is mutable internally but only mutated by the built-in bootstrap module at import time (no unregister).

    AC-3: All 9 built-in phases registered via the same mechanism

    Verification: Unit Test (snapshot equality)
    Scenario: Given the built-in bootstrap module is imported → When registry.list().map(p => p.name) is computed → Then the set equals ["spec", "security-review", "exec", "testgen", "test", "verify", "qa", "loop", "merger"] and every phase has the same fields populated (no if (phase === "qa") {...} branches anywhere in the codebase).
    Assumptions: Existing WORKFLOW_PHASES constant in state-schema.ts becomes registry.list().map(p => p.name).

    AC-4 (was AC-7): phase-executor.ts reads from registry

    Verification: Unit Test
    Scenario: Given a phase name and agent driver → When getPhasePrompt(phase, issueNumber, agent) is invoked → Then the prompt template comes from registry.get(phase).promptTemplate (or driverOverrides[agent]?.promptTemplate if present) — PHASE_PROMPTS, AIDER_PHASE_PROMPTS, and ISOLATED_PHASES constants are deleted. requiresWorktree and retryStrategy.coldStartThreshold come from registry entries.
    Assumptions: Existing phase-executor.test.ts tests "uses AIDER_PHASE_PROMPTS for non-claude agents" / "uses PHASE_PROMPTS for claude-code agent" continue to pass after refactor (behavioral contract preserved). Aider's full self-contained prompts move into the registry's driverOverrides.aider.promptTemplate.

    AC-5 (was AC-6, simplified): phase-mapper.ts consumes registry-provided detect rules

    Verification: Unit Test
    Scenario: Given an issue with ["ui"] labels → When detectPhasesFromLabels(labels) is called → Then the result derives from registry.list().filter(p => p.detect?.labels?.some(l => labels.includes(l))) rather than the hardcoded UI_LABELS/SECURITY_LABELS arrays. UI_LABELS and SECURITY_LABELS constants are removed.
    Assumptions: BUG_LABELS, DOCS_LABELS, and COMPLEX_LABELS are issue-type metadata (not phase-trigger rules — see phase-mapper.ts:77-80) and stay in a labels module (or move to issue-types.ts) — they are out of scope for the registry. phase-detection.ts (issue body says "phase-detection.ts, phase-mapper.ts") does not use any label arrays — only phase-mapper.ts is rewired. Plan note: confirm during exec and update the issue body if the user wants phase-detection.ts removed from AC-5's wording.

    AC-6 (was AC-5, simplified): --phases CLI flag validates against registry at runtime

    Verification: Integration Test (spawn bin/cli.ts run 1 --phases foo)
    Scenario: Given an unknown phase name passed via --phases deploy,exec → When the CLI parses the flag → Then it exits non-zero with stderr Unknown phase 'deploy'. Available: spec, security-review, exec, testgen, test, verify, qa, loop, merger. PhaseSchema becomes z.string().refine(name => registry.has(name), { message: ... }) instead of the literal z.enum([...]).
    Assumptions: Validation occurs after registry bootstrap (top-level import side effect). All Zod consumers — run-log-schema.ts, state-schema.ts, phase-types.test.ts, run-log-schema.test.ts, assess-skill.test.ts (which reads PhaseSchema.options) — continue working. Risk: PhaseSchema.options is an array literal on z.enum; switching to z.string().refine removes .options. Plan: add a sibling getPhaseNames() helper and migrate the four call sites that read .options.


    Implementation Plan

    Phase 1: Foundation — interface + registry

    1. Create src/lib/workflow/phase-registry.ts exporting:
      • PhaseDefinition interface (name, skill, promptTemplate, requiresWorktree, retryStrategy?, detect?, driverOverrides?, order?)
      • PhaseRegistry class (register/get/list/has)
      • Singleton phaseRegistry instance
    2. Create src/lib/workflow/built-in-phases.ts — registers all 9 built-ins by calling phaseRegistry.register(...) at module load. Migrate the literal prompts from PHASE_PROMPTS and AIDER_PHASE_PROMPTS (the latter into driverOverrides.aider.promptTemplate). Set requiresWorktree: true for the 6 ISOLATED_PHASES, false for spec/verify/merger.
    3. Add a getPhaseNames() helper on the registry (or as a sibling export) returning string[] — replaces the removed PhaseSchema.options for the four current call sites.

    Phase 2: Rewire the type system

    1. In src/lib/workflow/types.ts: change PhaseSchema from z.enum([...]) to z.string().refine(n => phaseRegistry.has(n), { message: ... }). Keep Phase = z.infer<typeof PhaseSchema> (becomes string). Import phaseRegistry from phase-registry.ts. Beware import cycles — built-in-phases.ts must run before any Zod parse that touches PhaseSchema; resolve via lazy registration in a barrel module.
    2. Migrate the four PhaseSchema.options call sites to getPhaseNames():
      • state-schema.ts:27 (WORKFLOW_PHASES)
      • phase-types.test.ts:32, 36, 49-51
      • run-log-schema.test.ts:27
      • assess-skill.test.ts:27

    Phase 3: Rewire phase-executor

    1. In phase-executor.ts:
      • Delete PHASE_PROMPTS, AIDER_PHASE_PROMPTS, ISOLATED_PHASES constants.
      • getPhasePrompt: look up registry.get(phase).promptTemplate (default) or registry.get(phase).driverOverrides?.[agent]?.promptTemplate (when agent !== "claude-code").
      • The worktreePath && ISOLATED_PHASES.includes(phase) checks (lines 576, 582) become worktreePath && registry.get(phase).requiresWorktree.
      • The cold-start retry threshold currently lives as a top-level constant; leave it global for now and add a per-phase retryStrategy.coldStartThreshold override only for phases that need it (currently none — defer to a separate issue if a phase requires custom retry).
    2. Keep phase-executor.test.ts:421-435 tests intact — they validate prompt selection by agent. After migration they should still pass because the behavior is preserved, just sourced from the registry.

    Phase 4: Rewire phase-mapper

    1. In phase-mapper.ts:
      • Delete UI_LABELS and SECURITY_LABELS constants.
      • detectPhasesFromLabels: iterate registry.list(), filter by p.detect?.labels?.some(...), sort by p.order ?? 0.
      • Keep BUG_LABELS, DOCS_LABELS, COMPLEX_LABELS as-is (they are metadata helpers consumed by batch-executor.ts:758 and the quality-loop trigger — not phase-trigger rules). Add a code comment explaining the distinction.
      • hasUILabels(labels) becomes a thin shim over registry.get("test").detect?.labels or is deleted if its callers can use the registry directly.

    Phase 5: CLI validation

    1. In bin/cli.ts (around line 197 — --phases <list> option): add a post-parse validation step that calls phaseRegistry.has() for each comma-separated phase. On miss, log Unknown phase '<name>'. Available: ${phaseRegistry.list().map(p => p.name).join(", ")} to stderr and process.exit(1).
    2. Add an integration test under src/lib/workflow/phase-registry.integration.test.ts that spawns the CLI with --phases bogus,exec and asserts non-zero exit + error message.

    Step dependencies: 1 → 2 → 3 must be sequential (3 imports the bootstrap from 2). 4–5 (Zod rewire) depend on 3. 6–7 (executor) and 8 (mapper) are independent and can be parallelized. 9–10 (CLI) depend on 4.


    Design Review

    1. Where does this logic belong? A new phase-registry.ts module inside src/lib/workflow/ — the same layer that owns phase-executor.ts, phase-mapper.ts, and types.ts. Co-locates the source of truth with its consumers without adding a new layer.
    2. What's the simplest correct approach? A singleton class with a Map<string, PhaseDefinition>, registered at module load by a sibling built-in-phases.ts. Rejected alternatives: (a) Factory function returning a frozen object — fine, but harder to extend later when AC-4-deferred ships; (b) Zod-validated registration — premature, no external input today.
    3. What existing pattern does this follow? Sequant's own drivers/index.ts getDriver(name) pattern — name-keyed lookup over a fixed registry. The PhaseDefinition shape is also analogous to Rollup/Vite's plugin object (per the issue's technical notes), minus the hook lifecycle.
    4. What would a senior reviewer challenge?
      • "Why a class and not a plain Map?" — class lets us swap implementations later (lazy registration, validation) without breaking the import contract. Justifiable cost.
      • "You're switching z.enum to z.string().refine — does that break exhaustiveness checking in TS switch statements?" — Yes, marginally. The Phase type widens from "spec" | "exec" | ... union to string. We'll lose compile-time exhaustiveness on switch (phase). Mitigation: there is currently exactly one such switch (mapAgentSuccessToPhaseResult in phase-executor.ts:421) and it only special-cases qa and exec. Keep that as runtime string comparison — explicit comment noting that exhaustiveness moved to runtime.
      • "Import-cycle risk." — Real. types.ts (PhaseSchema) and phase-registry.ts and built-in-phases.ts form a triangle. Resolve by: (a) phase-registry.ts exports the class but no instance; (b) a barrel/init module constructs the singleton and registers built-ins; (c) types.ts imports the singleton via the barrel.

    Feature Quality Planning

    Notable items:

    • Backwards compatibility (memory: feedback_full_suite_on_api_breaks.md): This changes the inferred Phase type from a string-literal union to string. Run the full test suite locally before pushing — type widening can cascade into unrelated callers that pattern-match on the literal type.
    • Phase ordering invariant: Today the canonical order lives in the Zod enum (spec, security-review, exec, testgen, test, verify, qa, loop, merger). After migration the order comes from registry.list() insertion order in built-in-phases.ts. Add a unit test asserting registry.list().map(p => p.name) equals that exact 9-element array — guards against future reorderings.
    • Quality-loop linkage: COMPLEX_LABELS in phase-mapper.ts triggers qualityLoop: true, not a phase. It does not migrate to the registry. Document this in a code comment to prevent a follow-up cleanup from incorrectly folding it in.
    • AC-5 wording vs. reality: The original AC names phase-detection.ts and phase-mapper.ts. Only phase-mapper.ts actually uses the label arrays. Plan recommends updating the issue body to drop phase-detection.ts from AC-5 — or note in the PR description that it was a no-op for that file.

    Open Questions

    1. Testgen recommended? The descoped ACs are unit-test-heavy. /assess chose spec → exec → qa (no testgen). Recommendation: skip testgen — the existing phase-executor.test.ts / phase-mapper.test.ts / phase-types.test.ts files already cover the contract this refactor must preserve, and adding stubs risks the untracked-test cleanup pattern from memory. Impact if wrong: minor — testgen can be added in a follow-up.
    2. Lazy-registration vs. eager? If the registry is imported before built-in-phases.ts runs (e.g., a test that imports types.ts first), PhaseSchema.refine() will fail. Recommendation: use eager registration by making built-in-phases.ts a side-effect-only module that's imported at the top of types.ts. Impact if wrong: test flakes in non-deterministic import-order environments.
    3. retryStrategy field — populated for built-ins? AC-1 includes retryStrategy in the interface, but the existing COLD_START_THRESHOLD_SECONDS / COLD_START_MAX_RETRIES / SPEC_RETRY_BACKOFF_MS / SPEC_EXTRA_RETRIES are top-level constants in phase-executor.ts. Recommendation: keep retry constants global for this PR — populate retryStrategy field on the spec phase only (where SPEC_EXTRA_RETRIES is phase-specific) and leave loop phase's retryStrategy: { maxRetries: 0 } to encode the "skip cold-start retries for loop" rule at phase-executor.ts:827. Impact if wrong: harmless — can be refined later when more phases need per-phase retry tuning.

    Conflict Risk Analysis

    ⚠️ Parallel worktree active: feature/504-arch-typed-workflow-event-system-for-decoupled-pro. #504 is currently clean (no commits ahead of origin/main), but its scope also touches src/lib/workflow/. Likely overlap:

    • Both PRs may touch phase-executor.ts (registry consumer here, event emitter there).
    • Both may touch types.ts (Phase type here, event types there).

    Mitigation options:


    Recommended Workflow

    Phases: spec → exec → qa
    Quality Loop: enabled
    Reasoning: Standard tier with a yellow scope flag. The refactor touches the canonical PhaseSchema typed enum that downstream Zod schemas (state-schema.ts, run-log-schema.ts) depend on — regression risk is high enough to warrant the quality loop. No UI changes, no security surface, no new unit-test ACs that benefit from stubs — testgen skipped.


    Label Review

    Current: enhancement, roadmap, backlog
    Recommended: enhancement, refactor, roadmap — drop backlog (active per /assess), add refactor (so the quality loop auto-enables and the assess heuristic correctly classifies the work).
    Reason: Issue is actively being worked (multiple /assess PROCEEDs); backlog is misleading. refactor triggers COMPLEX_LABELS → qualityLoop: true, which matches the recommendation above.

    → gh issue edit 505 --remove-label backlog --add-label refactor


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

    @admarble
    ContributorAuthor

    /exec Progress Update — Phase plugin registry implementation

    PR: #644 (opened, awaiting QA)

    Pre-PR AC Verification

    AC Source Description Status Evidence
    AC-1 Original PhaseDefinition interface (name, skill, promptTemplate, requiresWorktree, retryStrategy, detect, driverOverrides, order) ✅ Implemented src/lib/workflow/phase-registry.ts:53-91
    AC-2 Original PhaseRegistry class with register/get/list/has ✅ Implemented src/lib/workflow/phase-registry.ts:93-148 + 5 unit tests
    AC-3 Original All 9 built-in phases registered uniformly ✅ Implemented phase-registry.ts:168-323; snapshot test asserts canonical order
    AC-4 (was AC-7) Original phase-executor.ts reads from registry ✅ Implemented Deleted PHASE_PROMPTS / AIDER_PHASE_PROMPTS / ISOLATED_PHASES
    AC-5 (was AC-6) Original phase-mapper.ts consumes registry-provided detect rules ✅ Implemented Removed UI_LABELS / SECURITY_LABELS; new detectPhasesFromRegistry()
    AC-6 (was AC-5) Original --phases CLI validates against registry at runtime ✅ Implemented bin/cli.ts:76-100 + 3-case integration test
    AC-8 Original Aider prompts handled via driverOverrides field ✅ Implemented Test asserts all 9 phases have driverOverrides.aider.promptTemplate

    Deferred (per descoping comment):

    • AC-4 (original) — .sequant/phases/ filesystem discovery
    • AC-9 (original) — sequant phases CLI command

    Files Changed

    File Lines Purpose
    src/lib/workflow/phase-registry.ts (new) +323 PhaseDefinition interface + PhaseRegistry class + 9 built-in registrations
    src/lib/workflow/phase-registry.test.ts (new) +189 16 unit tests for AC-1/2/3/8
    src/lib/workflow/phase-registry.integration.test.ts (new) +69 3 integration tests spawn the CLI for AC-6
    src/lib/workflow/phase-executor.ts −78 / +14 Deleted PHASE_PROMPTS / AIDER_PHASE_PROMPTS / ISOLATED_PHASES; reads from registry
    src/lib/workflow/phase-mapper.ts −19 / +43 Removed UI_LABELS / SECURITY_LABELS; detectPhasesFromRegistry() + registry-driven hasUILabels + parseRecommendedWorkflow
    src/lib/workflow/types.ts +9 / −10 PhaseSchema switches from z.enum to z.string().refine; Phase widens to string
    src/lib/workflow/state-schema.ts +4 / −1 WORKFLOW_PHASES migrates from PhaseSchema.options → getPhaseNames()
    src/lib/workflow/phase-types.test.ts +3 / −3 Migrates .options references to getPhaseNames()
    src/lib/__tests__/assess-skill.test.ts +1 / −1 Migrates PhaseSchema.options to getPhaseNames()
    bin/cli.ts +28 / −1 validatePhasesFlag() + wires it as the --phases argument parser
    CHANGELOG.md +4 Adds [Unreleased] Changed entry

    Checks Run

    Check Result Notes
    npm run build ✅ Passed TypeScript clean (Zod v4 error: (issue) => ... form for refine messages)
    npm run lint ✅ Passed 0 errors / 0 warnings
    npm test (unit) ✅ 3052/3052 passed All existing behavioral tests preserved
    Integration tests (phase-registry.integration.test.ts, cli.integration.test.ts) ✅ 7/7 passed CLI --phases validation works end-to-end

    Quality Plan Alignment

    Quality Dimension Items Addressed Notes
    Phase-type unification ✅ PhaseSchema / state-schema / run-log-schema still reference the same object; WORKFLOW_PHASES regenerated from registry
    Phase ordering invariant ✅ New snapshot test (phase-registry.test.ts:92-110) pins the 9-phase canonical order
    Backwards compatibility ✅ Full test suite passes — no behavioral drift in getPhasePrompt / detectPhasesFromLabels / hasUILabels
    Quality-loop linkage ✅ COMPLEX_LABELS deliberately left out of the registry (it's a quality-loop trigger, not a phase trigger); code comment documents the distinction
    AC-5 wording vs. reality ✅ Confirmed phase-detection.ts does not use label arrays — only phase-mapper.ts rewired (matches plan note)

    Pre-PR Confidence Check

    • Weakest part: The ESM-cycle resolution. I initially split built-in registrations into a separate built-in-phases.ts module per the plan, but ESM hoisting evaluated phaseRegistry.register(...) calls before the phaseRegistry = new PhaseRegistry() const was initialized (binding TDZ-like behavior), causing test failures in any test that imported phase-mapper.ts without going through types.ts. Resolved by colocating built-in registrations at the bottom of phase-registry.ts — same pattern as drivers/index.ts. No remaining cycle, all tests green.
    • Coverage gaps: None on the changed files — every modified source file has corresponding test coverage. bin/cli.ts is covered via the integration test that actually spawns the CLI.

    Quality Plan Items

    All applicable items from the spec's Feature Quality Planning section addressed. The "lazy-registration vs. eager" open question (#3) is resolved by the colocation approach — registrations run as part of module load, synchronous with phaseRegistry creation.

    Next Steps

    • QA pass via /qa 505
  10. added a commit that references this issue on May 14, 2026
  11. admarble commented on May 14, 2026

    @admarble
    ContributorAuthor

    /fullsolve Complete

    Issue: #505
    Status: READY_FOR_MERGE
    PR: #644

    Progress

    Phase Iterations Status
    Spec 1/1 Complete (resumed from prior marker 2026-05-14)
    Exec 1/1 Complete (resumed from prior marker 2026-05-13)
    Test — Skipped (no UI labels)
    QA 1/2 Complete — READY_FOR_MERGE

    AC Coverage (7/7 in-scope)

    Authoritative scope is the 2026-04-09 descoping comment. The PR uses renumbered ACs in its description; mapping shown below.

    AC (Original) Description Status
    AC-1 PhaseDefinition interface ✅ MET — phase-registry.ts:56-86
    AC-2 PhaseRegistry class with register/get/list/has ✅ MET — phase-registry.ts:96-148
    AC-3 All 9 built-in phases registered uniformly ✅ MET — phase-registry.ts:174-333
    AC-4 .sequant/phases/ filesystem discovery ⏭️ DEFERRED (descoping)
    AC-5 (was AC-6) --phases validates against registry at runtime ✅ MET — bin/cli.ts:76-97
    AC-6 (was AC-5) phase-mapper.ts consumes registry detect rules ✅ MET — phase-mapper.ts:54-63
    AC-7 (was AC-4) phase-executor.ts reads from registry ✅ MET — prompt template + requiresWorktree sourced from registry
    AC-8 Driver overrides via driverOverrides field ✅ MET — Aider prompts moved for all 9 phases
    AC-9 sequant phases CLI command ⏭️ DEFERRED (descoping)

    Quality Metrics

    • Build: ✅ clean (TypeScript)
    • Targeted tests: ✅ 173/173 pass across 6 test files
    • CI checks: ✅ 5/5 SUCCESS (build 20.x, build 22.x, typecheck, validate-skills, validate-plugin)
    • Type safety: 0 any types added
    • Deleted tests: 0
    • Branch behind origin/main: 0
    • CHANGELOG entry: ✅ present with (#505) reference

    Risk Assessment

    • Likely failure mode: A future phase added without driverOverrides.aider is caught by the AC-8 contract test; duplicate registration throws at module load (fail-fast).
    • Coverage gap: retryStrategy field is registered as metadata only — phase-executor.ts still uses hardcoded SPEC_RETRY_BACKOFF_MS / SPEC_EXTRA_RETRIES / COLD_START_* constants. Acknowledged in code comments at phase-registry.ts:181-184. Per the descoping comment, only the PHASE_PROMPTS dict was in scope for AC-7 — strictly met. Optional follow-up if telemetry begins consuming retryStrategy.
    • Type widening: Phase is now string (no longer string-literal union). Switch exhaustiveness traded for extensibility; lone surviving switch (phase) site only branches on "qa" and "exec" and is protected by runtime equality.

    Documentation

    • CHANGELOG: ✅ entry under [Unreleased] / Changed
    • docs/features/phase-type-definitions.md: rewritten for registry pattern (commit 173a26f)
    • README: no change needed (registry is internal architecture; user-visible behavior unchanged)

    Ready for human review and merge.

  12. added 2 commits that reference this issue on May 14, 2026
  13. admarble commented on May 14, 2026

    @admarble
    ContributorAuthor

    Gap-fix follow-up — complete

    Two non-blocking QA observations from the prior review have been addressed, plus a cross-PR merge with #504.

    Commits on top of the original PR #644

    SHA Type Summary
    82d7bb0 refactor(#505) Wire retryStrategy consumption + idiomatic CLI error
    f940c53 chore(#505) Merge origin/main (resolves cross-PR conflict with #504 / commit b4e8814)

    What changed in 82d7bb0

    1. phase-executor.ts now consumes retryStrategy from the registry

      • SPEC_RETRY_BACKOFF_MS / SPEC_EXTRA_RETRIES are derived from phaseRegistry.get("spec").retryStrategy at module load (with the prior literals as misconfiguration fallbacks).
      • The loop-skip rule is now phaseRegistry.has(phase) && phaseRegistry.get(phase).retryStrategy?.maxRetries === 0 instead of phase === "loop". Any future phase registered with maxRetries: 0 inherits the skip-cold-start-retries behavior without a code change.
    2. bin/cli.ts:validatePhasesFlag throws InvalidArgumentError

      • Replaces console.error + process.exit(1). Commander wraps the error with the offending flag name, so the user-facing message becomes error: option '--phases <list>' argument 'deploy' is invalid. Unknown phase 'deploy'. Available: ... — more informative than before. The existing 3-case integration test passes unchanged (assertions match the preserved message substrings).

    Cross-PR merge in f940c53

    PR #504 (typed workflow event system) merged to main mid-session and touched types.ts, CHANGELOG.md, phase-executor.ts, phase-mapper.ts, and bin/cli.ts. The merge resolved cleanly:

    Verification

    Gate Result
    npm run build ✅ Clean
    Targeted vitest (workflow + spec-retry + phase-registry) ✅ 178/178 before merge, 188/188 after picking up #504's event-emitter tests
    Full workflow test directory (37 files) ✅ 878/878 after merge
    CI on PR #644 ✅ 5/5 SUCCESS (build 20.x, build 22.x, typecheck, validate-skills, validate-plugin)
    mergeable ✅ MERGEABLE

    PR #644 is ready for human merge.

  14. added a commit that references this issue on May 14, 2026
  15. added a commit that references this issue on May 14, 2026
  16. admarble commented on May 14, 2026

    @admarble
    ContributorAuthor

    Documentation Review Complete

    The PR (#644) rewrote docs/features/phase-type-definitions.md as part of the implementation — 81 lines covering Prerequisites, registry architecture, "Adding a New Phase", What to Expect, and Troubleshooting. That doc is the authoritative reference for the registry pattern.

    One reference-doc gap was outside the PR's diff and has been patched on main (884e4fd):

    docs/reference/run-command.md updates

    • --phases table row now describes the new runtime validation behavior with the exact error format (error: option '--phases <list>' argument 'X' is invalid. Unknown phase 'X'. Available: ...).
    • Available Phases table updated to list all 9 registered phases in canonical pipeline order (was 6: spec, testgen, exec, test, qa, loop → now adds security-review, verify, merger).
    • Label triggers documented for the two auto-detected phases (security-review, test) so users know when each gets inserted.
    • Cross-link added from the Available Phases table to docs/features/phase-type-definitions.md for the registry pattern and "how to add a new phase" walkthrough.

    Files

    Ready for any reader of sequant run --help followups.

  17. added a commit that references this issue on May 20, 2026
  18. added a commit that references this issue on Jul 31, 2026
  19. 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

    backlogenhancementplannedroadmap

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions