Skip to content

Ticket Flow

IMPORTANT

TL;DR — A ticket flows through: scanning → interview → PRD → beads planning → execution setup → bead-by-bead coding → final test → integration → PR → cleanup (interview, PRD and beads are planning loops with LLM council drafting, voting, and refinement stages).

LoopTroop does not move a ticket through a tiny backlog -> coding -> done list. It runs a staged lifecycle with planning loops, approval gates, execution setup, bead-scoped coding, PR delivery, and explicit error recovery.

The canonical workflow metadata lives in shared/workflowMeta.ts, the executable transition rules live in server/machines/ticketMachine.ts, and the route handling lives under server/routes/ticketHandlers/.


1. At A Glance

text
DRAFT
  -> SCANNING_RELEVANT_FILES
  -> Interview loop
  -> PRD loop
  -> Beads loop
  -> PRE_FLIGHT_CHECK
  -> WAITING_EXECUTION_SETUP_APPROVAL
  -> PREPARING_EXECUTION_ENV
  -> CODING bead loop
  -> RUNNING_FINAL_TEST
  -> INTEGRATING_CHANGES
  -> CREATING_PULL_REQUEST
  -> WAITING_PR_REVIEW
  -> CLEANING_ENV
  -> COMPLETED

Any active phase can fail into BLOCKED_ERROR.
BLOCKED_ERROR -> RETRY -> previousStatus
BLOCKED_ERROR -> CONTINUE -> previousStatus (eligible preserved OpenCode sessions only)
Any non-terminal phase -> CANCELED
WAITING_PR_REVIEW -> merge or close-unmerged -> CLEANING_ENV

Useful mental model:

  • Before PRE_FLIGHT_CHECK you are still in editable planning territory: interview, PRD, beads, and setup artifacts can create archived versions and restart downstream work.
  • From PRE_FLIGHT_CHECK onward the workflow is in execution territory: repository mutations become isolated and tightly controlled, and recovery is driven by execution locks, retries, or explicit blocked-error decisions.
  • CODING is the versioning exception: retries reset the active bead/checkpoint instead of creating phase-attempt versions.

2. Detailed Flow Diagram

The flowchart below visualizes how tickets progress through planning, execution, and delivery, and how recovery pathways branch back to active phases:

The diagrams in this document are embedded SVGs so they render consistently in VS Code Markdown Preview.

Detailed ticket flow diagram

Loop semantics are omitted from the high-level chart to keep it readable:

  • WAITING_INTERVIEW_ANSWERS can self-loop for more batches, and interview coverage can send the ticket back to answers when gaps remain.
  • VERIFYING_PRD_COVERAGE can send the ticket back to REFINING_PRD until the spec is clean or the revision cap is reached.
  • VERIFYING_BEADS_COVERAGE can send the ticket back to REFINING_BEADS until the blueprint is clean or the revision cap is reached.
  • CODING repeats bead-by-bead until all executable beads are complete.
  • BLOCKED_ERROR stores previousStatus, so retry and eligible continue actions both return to the interrupted phase.

3. State Machine Transition Model

The underlying state machine enforces valid state transitions and recovery hooks deterministically. The diagrams below show the state transitions organized by workflow phase.

3.1 Entry & Discovery

Entry and discovery state diagram

3.2 Interview Loop

Interview loop state diagram

WAITING_INTERVIEW_ANSWERS self-loops while batches are still being answered, and VERIFYING_INTERVIEW_COVERAGE returns to answers when gaps require follow-up questions.

3.3 PRD Loop

PRD loop state diagram

VERIFYING_PRD_COVERAGE loops back to REFINING_PRD whenever the candidate spec still has gaps.

3.4 Beads Loop

Beads loop state diagram

VERIFYING_BEADS_COVERAGE loops back to REFINING_BEADS whenever the execution blueprint still misses required coverage.

3.5 Execution & Delivery

Execution and delivery state diagram

3.6 Error Recovery & Cancellation

Error recovery and cancellation state diagram

Recovery semantics:

  • RETRY: Re-enters previousStatus; non-implementation phases archive the failed attempt and create a fresh version first, while CODING resets the active bead/checkpoint path instead.
  • CONTINUE: Appears only when a preserved OpenCode session is still live and eligible; LoopTroop re-enters the interrupted phase and sends exactly continue please.
  • CANCEL: Available from every non-terminal workflow state and moves the ticket to the terminal canceled state after aborting active work.

3.7 Coverage Control

Interview, PRD, and beads coverage loops are managed by server/workflow/coverageControl.ts. Each phase uses a shared resolveCoverageRunState() mechanism that tracks:

  • Coverage pass number: How many times coverage has been run for the current artifact version.
  • Pass limit: The configured cap (maxCoveragePasses, maxPrdCoveragePasses, or maxBeadsCoveragePasses) per coverage phase.
  • Budget: The follow-up budget percentage that limits interview coverage depth.

resolveCoverageGapDisposition() determines whether the pass loop should:

  • Continue: Gaps were found and the pass limit has not been reached — return to refinement.
  • Terminate as clean: No gaps remain; advance to approval.
  • Terminate as capped: Gaps remain but the pass limit is exhausted; advance to approval with warnings.

Coverage budgets and limits apply independently per phase. Interview coverage budget is shared between compiled and follow-up questions; PRD and beads coverage use only pass counts.

3.8 Execution Band

The execution band (server/workflow/executionBand.ts) is the set of statuses between pre-flight readiness and environment cleanup:

PRE_FLIGHT_CHECK → WAITING_EXECUTION_SETUP_APPROVAL → PREPARING_EXECUTION_ENV
  → CODING → RUNNING_FINAL_TEST → INTEGRATING_CHANGES
  → CREATING_PULL_REQUEST → WAITING_PR_REVIEW → CLEANING_ENV

Only one ticket per project may occupy the execution band at a time. isExecutionBandStatus() validates membership and the project execution lock prevents concurrent execution tickets from creating Git conflicts in the same repository.

The single-ticket lock is enforced by the project execution lock check during PRE_FLIGHT_CHECK: if another ticket for the same project is already in the execution band, the incoming ticket blocks with a concurrency error.

Key Observations

The transition model enforces these invariants:

  • Approval Gates are explicit workflow states, not transient UI flags.
  • The Interview Loop can self-loop dynamically during active batching or coverage verification.
  • Spec & Blueprint Coverage Loops remain bounded inside their groups, revising automatically until clean or capped.
  • BLOCKED_ERROR stores previousStatus in its context to allow precise, phase-scoped recovery.
  • Cancellation is a workflow-wide safety valve for every non-terminal state, even though the most visible decision points remain approvals, blocked errors, and PR review.
  • Archived phase attempts preserve non-implementation retries, regenerations, and planning restarts as read-only history instead of overwriting the last run.
  • Execution-time human input can happen without a status change when OpenCode asks a question during runtime setup or coding.

4. Workflow Groups & Board Locations

Status Groups

The UI and API categorize all ticket states into distinct lifecycle groups:

GroupMeaning
todoBacklog item before AI planning activity begins.
discoveryCodebase indexing and file scanning before requirements.
interviewQuestionnaire compilation, Q&A batching, coverage, and interview approval.
prdRequirements spec drafting, voting, refinement, coverage, and PRD approval.
beadsExecution blueprint drafting, voting, refinement, coverage, expansion, and approval.
pre_implementationPre-flight readiness verification, runtime setup plan drafting, and tool environment setup.
implementationBead-by-bead isolated coding loop.
post_implementationHolistic testing, branch squashing, PR publishing, review gates, and worktree cleanup.
doneSuccessful completion or cancellation.
errorsThe dedicated recovery gateway for blocked errors.

Kanban Board Locations

Every ticket belongs to exactly one Kanban board location determined by its kanbanPhase. These locations simplify board layout by indicating who or what owns the next move:

Board LocationkanbanPhaseMeaningIncluded Statuses
To DotodoInactive backlog item.DRAFT
Needs Inputneeds_inputPaused; waiting for user action, approval, or error recovery.Interview Q&A, all approvals, PR review, and BLOCKED_ERROR.
In Progressin_progressActive; LoopTroop is running background calculations, councils, or coding sessions.Scanning, deliberating, voting, refining, preparing, coding, testing, squashing.
DonedoneTerminal status.COMPLETED, CANCELED

Note: BLOCKED_ERROR maps to needs_input rather than a unique board column, because recovery requires manual retry, session continuation, or cancellation.


5. Phase Inventory

The canonical properties for every workflow phase are detailed in the inventory below:

PhaseLabelGroupuiViewkanbanPhaseReview ArtifactEditableMulti-Model LogsProgress Indicator
DRAFTBacklogtododrafttodoyesno
SCANNING_RELEVANT_FILESScanning Filesdiscoverycouncilin_progressyesno
COUNCIL_DELIBERATINGDrafting Questionsinterviewcouncilin_progressyesyes
COUNCIL_VOTING_INTERVIEWVoting on Questionsinterviewcouncilin_progressyesyes
COMPILING_INTERVIEWRefining Interviewinterviewcouncilin_progressyesno
WAITING_INTERVIEW_ANSWERSInterviewinginterviewinterview_qaneeds_inputyesnoquestions
VERIFYING_INTERVIEW_COVERAGEInterview Coverageinterviewcouncilin_progressyesno
WAITING_INTERVIEW_APPROVALApproving Interviewinterviewapprovalneeds_inputinterviewyesno
DRAFTING_PRDDrafting Specsprdcouncilin_progressyesyes
COUNCIL_VOTING_PRDVoting on Specsprdcouncilin_progressyesyes
REFINING_PRDRefining Specsprdcouncilin_progressyesno
VERIFYING_PRD_COVERAGEPRD Coverageprdcouncilin_progressyesno
WAITING_PRD_APPROVALApproving Specsprdapprovalneeds_inputprdyesno
DRAFTING_BEADSDrafting Blueprintbeadscouncilin_progressyesyes
COUNCIL_VOTING_BEADSVoting on Blueprintbeadscouncilin_progressyesyes
REFINING_BEADSRefining Blueprintbeadscouncilin_progressyesno
VERIFYING_BEADS_COVERAGEBeads Coveragebeadscouncilin_progressyesno
EXPANDING_BEADSExpanding Blueprintbeadscouncilin_progressyesno
WAITING_BEADS_APPROVALApproving Blueprintbeadsapprovalneeds_inputbeadsyesno
PRE_FLIGHT_CHECKChecking Readinesspre_implementationcodingin_progressyesno
WAITING_EXECUTION_SETUP_APPROVALApproving Setuppre_implementationapprovalneeds_inputexecution_setup_planyesno
PREPARING_EXECUTION_ENVPreparing Runtimepre_implementationcodingin_progressnono
CODINGImplementingimplementationcodingin_progressnonobeads
RUNNING_FINAL_TESTTestingpost_implementationcodingin_progressnono
INTEGRATING_CHANGESSquashing Commitspost_implementationcodingin_progressnono
CREATING_PULL_REQUESTCreating PRpost_implementationcodingin_progressnono
WAITING_PR_REVIEWReviewing PRpost_implementationcodingneeds_inputnono
CLEANING_ENVCleaning Uppost_implementationcodingin_progressnono
COMPLETEDDonedonedonedonenono
CANCELEDCanceleddonecanceleddonenono
BLOCKED_ERRORErrorerrorserrorneeds_inputnono

Note: editable: yes means the review artifact or planning document can be manually saved from that phase. Interview and PRD edits are accepted only before PRE_FLIGHT_CHECK; setup-plan edits are also accepted during PREPARING_EXECUTION_ENV, where they trigger a one-step rewind back to setup approval.


6. UI & Frontend Consequences

The state machine metadata directly drives the React user interface. Developers modifying the workflow must ensure backend descriptors align, as:

  • uiView decides which top-level layout panel is mounted (e.g., council, approval, interview_qa).
  • reviewArtifactType controls which approval schema editor and custom comparison components are loaded.
  • progressKind controls specialized progress tracking visuals (e.g., question batch tallies vs. bead graph lists).
  • editable toggles raw markdown edit boxes for planning and setup specs.
  • multiModelLogs decides whether the UI should search for multi-agent council tabs and scoring matrices or render single-model log output.
  • phaseAttempt-scoped artifact/log loading keeps archived retries and regenerations separated from the live SSE stream.

7. Status-By-Status Detail

Entry & Discovery

  • DRAFT: Backlog item. Ticket metadata (title, description, assignee) can be edited freely. No worktree isolation or AI routines have run. Exiting via start triggers indexing.
  • SCANNING_RELEVANT_FILES: The Main Implementer scans the project folder under AI Response Timeout and registers target files, writing results to .ticket/relevant-files.yaml.

Interview Loop

  • COUNCIL_DELIBERATING: All configured council members draft interview strategies in parallel, producing candidate question lists.
  • COUNCIL_VOTING_INTERVIEW: Council models rate the anonymized questionnaires using a structural rubric to select the best intake framework.
  • COMPILING_INTERVIEW: LoopTroop normalizes the selected plan into the canonical interview.yaml session file.
  • WAITING_INTERVIEW_ANSWERS: The dashboard pauses for user answers. Questions are presented in adaptive, dynamic batches of 1 to 3 to optimize cognitive load. Skip and "skip all" choices are supported.
  • VERIFYING_INTERVIEW_COVERAGE: The winner checks the answers for ambiguities or gaps, spawning targeted follow-up rounds if budget permits.
  • WAITING_INTERVIEW_APPROVAL: Gatekeeper review. The user approves the structured YAML specs with content-hash protection (expectedContentSha256 matching check).

Specs Loop (PRD)

  • DRAFTING_PRD: Models resolve skipped questions into a Full Answers artifact (answered_by: ai_skip), then draft comprehensive feature requirements.
  • COUNCIL_VOTING_PRD: Anonymized votes are cast on rival PRD drafts based on completeness, risk, and feasibility metrics.
  • REFINING_PRD: The winner incorporates the strongest elements from competing drafts into PRD Candidate v1.
  • VERIFYING_PRD_COVERAGE: The candidate PRD is audited against the approved Full Answers context, revising in-phase until clean or capped.
  • WAITING_PRD_APPROVAL: Gatekeeper review of the PRD requirements spec with content-hash matching, supported by the winning Full Answers reference context.

Blueprint Loop (Beads)

  • DRAFTING_BEADS: Council members draft blueprints decomposing the approved spec into semantic dependency graphs of beads.
  • COUNCIL_VOTING_BEADS: Blueprints are rated on graph logic, file target isolation, and testing strategy.
  • REFINING_BEADS: Winning blueprint merges strong verification steps from alternative drafts.
  • VERIFYING_BEADS_COVERAGE: Blueprint is verified against the PRD, revising in-phase when missing criteria are found.
  • EXPANDING_BEADS: LoopTroop expands the blueprint into live execution bead lists, specifying exact file scopes and test suites.
  • WAITING_BEADS_APPROVAL: Gatekeeper review of the dependency graph and executable plan before coding starts.

Pre-Implementation

  • PRE_FLIGHT_CHECK: Verifies workspace sanitation, Git worktree hygiene, OpenCode reachability, and execution locks. Committable changes outside LoopTroop fail the checks.
  • WAITING_EXECUTION_SETUP_APPROVAL: The setup-plan draft presents the readiness assessment, required temporary setup steps, and regenerate history. The user can approve, edit, or regenerate it with commentary.
  • PREPARING_EXECUTION_ENV: Runs only the approved temporary setup, verifies wrappers/probes, may perform setup-scoped online lookup, and emits the reusable execution-setup profile under .ticket/runtime/execution-setup/**.

Implementation (Coding)

  • CODING: The executor processes one bead at a time in dependency order. The agent gets narrow contexts and structured completion reminders. Uncommitted project changes are captured in local bead commits, while retries reset the active bead/checkpoint rather than creating a new phase attempt.

Post-Implementation & Delivery

  • RUNNING_FINAL_TEST: The implementer constructs a whole-ticket test plan, executes it with the approved runtime profile, and records a final-test file-effects audit alongside the test outputs.
  • INTEGRATING_CHANGES: Squashes bead-level changes and audited candidate files into a clean candidate commit on the main ticket branch. If final testing produced unclassified files, integration blocks for a human include/discard decision.
  • CREATING_PULL_REQUEST: Performs a final candidate audit (reconciling inclusions/exclusions) before pushing the branch and drafting the PR title/description.
  • WAITING_PR_REVIEW: Review window. Exits successfully via merge (which locks, checks, and finishes) or close_unmerged.
  • CLEANING_ENV: Deletes transient lockfiles, wrapper hooks, and session directories, preserving planning files and audit trails.

Error & Terminal States

  • BLOCKED_ERROR: Recovery gate that preserves previousStatus, structured diagnostics, and any continuation candidate. Depending on the failure, the user can retry, continue a preserved OpenCode session, resolve final-test file-effects, or cancel.
  • COMPLETED: Terminal success state after cleanup finishes and execution locks are released. Ticket artifacts, logs, and archived attempts remain available for audit.
  • CANCELED: Terminal stop state for user-driven cancellation or intentional planning rewinds. Existing artifacts/history remain, but no further automation continues.

8. User Actions & Guard Systems

getAvailableWorkflowActions() defines the static action floor, and the server adds dynamic actions for resumable OpenCode sessions and final-test file-effects recovery. In practice, the main user actions are:

WhereMain actionsNotes
DRAFTstart, cancelstart locks the ticket's model/configuration choices and creates the isolated workspace.
WAITING_INTERVIEW_ANSWERSbatch answer, edit answer, skip all, cancelInterview input is batch-oriented; skip all writes a synthetic clean coverage result and jumps straight to interview approval.
Approval gatesapprove, cancelInterview, PRD, beads, and setup-plan approvals require expectedContentSha256; stale approvals return 409 instead of advancing.
WAITING_EXECUTION_SETUP_APPROVAL / PREPARING_EXECUTION_ENVedit, regenerate, approve/rewindSetup-plan saves or regenerations during runtime setup stop the active setup session, archive the current setup/runtime attempts, preserve the tool cache, and require approval again.
WAITING_PR_REVIEWmerge, close_unmerged, cancelReview resolution decides whether the ticket exits with a merged PR or a closed unmerged branch.
BLOCKED_ERRORretry, optional continue, optional file-effects overrides, cancelcontinue appears only when a preserved OpenCode session is still live. include-final-test-files / discard-final-test-files appear only for FINAL_TEST_FILE_EFFECTS_UNCLASSIFIED.
Any other non-terminal statuscancelCancellation is not limited to gates; the route accepts it from every non-terminal workflow state.
PREPARING_EXECUTION_ENV / CODINGreply/reject OpenCode questionsOpenCode can request human input mid-session without changing the main ticket status; answering or rejecting the request unblocks that live session in place.

Planning Edit Restarts

Approved interview and PRD documents can still be edited manually while in planning (before PRE_FLIGHT_CHECK). Saving manual changes triggers session cancellation downstream to keep artifacts consistent:

  • Editing Interview from PRD/Beads archives the approved interview, aborts downstream sessions, clears downstream drafts, saves/approves the edit, and jumps to DRAFTING_PRD.
  • Editing PRD from Beads archives the approved PRD, aborts downstream sessions, clears downstream blueprint drafts, saves/approves the edit, and jumps to DRAFTING_BEADS.
  • Editing or regenerating the Execution Setup Plan while PREPARING_EXECUTION_ENV is active performs a runtime rewind: LoopTroop stops setup, archives both setup attempts, preserves .ticket/runtime/execution-setup/tool-cache, clears stale runtime outputs, returns to WAITING_EXECUTION_SETUP_APPROVAL, and requires a fresh approval before setup resumes.

9. Retry, Continue, And Blocked-Error Semantics

When a phase encounters a fatal block, it routes to BLOCKED_ERROR while storing the failed status in previousStatus. Recovery pathways are phase-scoped:

The Retry Path (RETRY)

  • Archives the active phase attempt and initializes a fresh run.
  • Planning Phases: Manual retries create a new version of the draft spec or blueprint in the UI.
  • CODING Exception: CODING does not create new phase attempts. It runs a bead-scoped recovery loop: resets the active bead's worktree back to its recorded beadStartCommit snapshot and schedules it again.

The Continue Path (CONTINUE)

  • Resumes an in-progress session without resetting or creating new attempts.
  • Used for continuable, transient errors (HTTP 402, rate/usage limits, overload capacity, provider timeouts) where the remote OpenCode session is still active and addressable.
  • LoopTroop locks onto the preserved session and sends exactly:
    text
    continue please

Phase Attempts And Version History

  • Every non-implementation manual retry archives the failed phase attempt and creates a fresh active attempt; artifacts and logs can later be inspected through phaseAttempt-scoped history.
  • Setup-plan regenerations and post-approval planning edits follow the same versioned-history model instead of overwriting the last approved generation.
  • CODING is the exception: recovery stays bead-scoped (bead_execution:* artifacts, checkpoint finalization, and worktree reset) rather than creating phase-attempt versions.

10. Safe Resume & Interruption Recovery

LoopTroop is designed to survive crashes, restarts, and disconnects. The table below outlines how specific interruption events are safely handled:

InterruptionExpected Resume Behavior
Browser Closes / SSE DisconnectsThe next UI mount requests the Hono server REST state. SSE reconnects pass Last-Event-ID to replay stream indicators without reloading active panels.
Frontend CrashesActive draft forms and interview inputs are written to local ticket UI-state files on page unload.
Backend Process RestartsLoopTroop validates the serialized XState snapshot on startup: valid snapshots are rehydrated and immediately processed, resuming the active task; corrupt states trigger BLOCKED_ERROR.
OpenCode Server RestartsLoopTroop queries local opencode_sessions active keys; missing sessions are cleanly abandoned, and fresh contexts are created.
Model Fails / Returns GarbagePlanning phases run automatic structured retries; rejected attempts are saved as Raw attempts for inspection.

11. Artifact Checkpoints

Durable checkpoints are saved to the project directory at critical milestones:

Point in FlowDurable Artifact Location / State
Discovery.ticket/relevant-files.yaml index + companion scanner results.
Interview.ticket/interview.yaml + Q&A snapshots + progress markers.
PRD Specs.ticket/prd.yaml + per-model Full Answers + candidate coverage histories.
Blueprints.ticket/beads/<flow>/.beads/issues.jsonl + coverage reports.
Pre-Implementationexecution_setup_plan artifacts + generation reports + approved SHA hashes + .ticket/runtime/execution-setup-profile.json.
Execution.ticket/runtime/execution-log.jsonl + setup profile/tool cache + bead notes, checkpoints, and diffs.
Recovery & HistoryArchived phase attempts, final_test_file_effects_audit, continuation candidates, and read-only prior planning generations addressable by phaseAttempt.
EditsAppend-only user_edit_receipt:* documents recording change differentials and approval resets.
DeliveryHolistic test plans, file-effects audits, and Git PR creation reports.

12. Advanced Workflow Mechanics

Several orchestrator modules drive the complex mechanics behind the scenes:

  • Coverage Control (server/workflow/coverageControl.ts): Manages the PRD and Beads coverage tracking loops, determining whether candidate specs have gaps and whether follow-up verification rounds are needed.
  • Execution Band (server/workflow/executionBand.ts): Demarcates the boundary between planning (editable, cancellable restarts) and runtime execution (strict isolated worktree changes).
  • Phase Attempts (server/storage/ticketPhaseAttempts.ts): Versions non-implementation retries, setup-plan regenerations, and archived planning generations so prior artifacts stay immutable.
  • Session Logging (server/workflow/sessionStatusLogging.ts): Handles the durable recording of session state transitions and OpenCode interactions.
  • Integration Phase (server/workflow/phases/integrationPhase.ts): Orchestrates the commit squashing and target branch integration logic after coding and final tests are complete.
  • Execution Setup Phase (server/workflow/phases/executionSetupPlanPhase.ts): Manages the pre-flight checks and setup plan drafting, explicitly separating environment prep from active bead coding.
  • Ticket Handlers (server/routes/ticketHandlers/**): Implement the route-driven behaviors that sit around the state machine edges, including approval hashes, planning restarts, setup rewinds, blocked-error recovery actions, and OpenCode question replies.

LoopTroop documentation for the current runtime.