Perfect! Now I have a comprehensive understanding. Let me create a summary document with all the key information:
Triage System Architecture Report
Based on my thorough exploration of the desloppify codebase, here's the complete triage stage flow architecture:
1. Stage Flow Overview (observe → reflect → organize → enrich → sense-check)
File: /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/runner/orchestrator_common.py
python Copy code
STAGES: tuple[str, ...] = ("observe", "reflect", "organize", "enrich", "sense-check")
2. Type Definitions for Triage Stages
Primary Schema File: /Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/schema/__init__.py
TriageStagePayload (Lines 115-126)
Persisted checkpoint for one triage stage:
python Copy code
class TriageStagePayload(TypedDict, total=False):
"""Persisted payload for one triage stage checkpoint."""
stage: str # Stage identifier
report: str # Stage output text
cited_ids: list[str] # Issue IDs mentioned
timestamp: str # ISO timestamp
issue_count: int # Count of issues processed
recurring_dims: list[str] # Recurring dimensions (reflect)
confirmed_at: str # Confirmation timestamp
confirmed_text: str # Attestation text
EpicTriageMeta (Lines 136-156)
Multi-stage triage flow metadata:
python Copy code
class EpicTriageMeta(TypedDict, total=False):
"""Metadata persisted for the multi-stage triage flow."""
triaged_ids: list[str] # Issues marked triaged
active_triage_issue_ids: list[str] # Issues in active queue
dismissed_ids: list[str] # Dismissed issues
undispositioned_issue_ids: list[str] # Unprocessed issues
undispositioned_issue_count: int
issue_snapshot_hash: str # Hash of issue state
strategy_summary: str
trigger: str
version: int
last_run: str
last_completed_at: str
triage_stages: dict[str, TriageStagePayload] # All stages
stage_snapshot_hash: str
stage_refresh_required: bool
last_triage: LastTriageSnapshot # Archived completion state
triage_defer_state: dict[str, Any]
triage_force_visible: bool
LastTriageSnapshot (Lines 128-134)
Archived state when triage completes:
python Copy code
class LastTriageSnapshot(TypedDict, total=False):
"""Archived triage stage state captured when triage is completed."""
completed_at: str
stages: dict[str, TriageStagePayload]
strategy: str
3. OBSERVE Stage (Parallel Batch Execution)
Entry Point: /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/stages/observe.py
Key Validation Function:
_cmd_stage_observe() - Records observe stage with issue assessments
Parses structured ObserveAssessment entries (see evidence_parsing.py)
Returns ObserveAssessment dataclass with verdict + files_read
Evidence Parsing: /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/stages/evidence_parsing.py
python Copy code
@dataclass
class ObserveAssessment:
"""A parsed per-issue assessment from an observe report (template format)."""
issue_hash: str
verdict: str # "genuine", "false positive", "exaggerated", "over-engineering"
verdict_reasoning: str = ""
files_read: list[str] = field(default_factory=list)
recommendation: str = ""
@dataclass
class ObserveEvidence:
"""Parsed observe-report evidence."""
entries: list[ObserveAssessment] = field(default_factory=list)
unparsed_citation_count: int = 0
has_parseable_ids: bool = True
Parallel Execution: /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/runner/orchestrator_codex_observe.py
Splits observe into batch_count parallel tasks
Each batch processes a dimension group
Merges batch outputs with dimension headers
4. REFLECT Stage (Coverage Ledger Parsing)
Entry Point: /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/stages/reflect.py
Key Validation Function: /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/validation/core.py (Lines 244-319)
python Copy code
def _analyze_reflect_issue_accounting(
*,
report: str,
valid_ids: set[str],
) -> tuple[set[str], list[str], list[str]]:
"""Return cited, missing, and duplicate issue IDs referenced by reflect."""
Coverage Ledger Format:
The parser detects the special ## Coverage Ledger section in reflect reports (Lines 277-304):
markdown Copy code
## Coverage Ledger
- abcd1234 -> cluster "cluster-name"
- efgh5678 -> skip "specific-reason-tag"
Parsing Logic (Lines 263-301):
Extracts ledger key from lines matching ^-\s*(.+?)\s*->
Resolves short IDs to full issue IDs via bucket lookup
Counts duplicates (appears > 1 time)
Returns: (cited_ids, missing_ids, duplicate_ids)
Ledger Hit Tracking:
Uses Counter to detect duplicates
Bucket-based resolution for short hex IDs
Hex short ID mapping with ambiguity detection
Validation: _validate_reflect_issue_accounting() (Lines 322-349)
Ensures every open issue cited exactly once
Blocks if missing_ids or duplicate_ids
Prints diagnostic: Reflect report must account for every open review issue exactly once
Reflect Stage Persistence: (Lines 96-136)
Records:
cited_ids: Sorted set of issue IDs mentioned
missing_issue_ids: Issues not mentioned
duplicate_issue_ids: Issues mentioned multiple times
recurring_dims: Dimension patterns from analysis
timestamp, issue_count
5. ORGANIZE Stage (Validation Against Reflect)
Entry Point: /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/stages/organize.py
Pre-flight Validation: /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/runner/orchestrator_codex_pipeline_execution.py (Lines 168-217)
python Copy code
def preflight_stage(
*,
stage: str,
plan: Mapping[str, Any],
triage_input: Any,
dry_run: bool,
append_run_log: Callable[[str], None],
validate_reflect_issue_accounting: Callable,
) -> tuple[bool, str | None]:
For organize stage (Lines 194-217):
Loads reflect report from plan.epic_triage_meta.triage_stages.reflect.report
Calls validate_reflect_issue_accounting(report=reflect_report, valid_ids=triage_input.open_issues)
If accounting fails: returns (False, "reflect_accounting_invalid(...)")
Otherwise: returns (True, None) allowing organize to proceed
Organize Submission Validation: (Lines 83-141)
Requires reflect stage auto-confirmation with issue accounting
Validates manual clusters exist (non-auto)
Validates cluster enrichment (description + steps)
Validates all review issues are in clusters
Enforces cluster activity since reflect (unless attested)
Validates report length and cluster mentions
Validates cluster reference evidence in report
Organize Persistence: (Lines 144-171)
Records to triage_stages.organize:
python Copy code
{
"stage": "organize",
"report": str,
"cited_ids": [], # Empty for organize
"timestamp": utc_now(),
"issue_count": len(open_review_ids),
"confirmed_at": optional, # Only if reused + previously confirmed
"confirmed_text": optional
}
6. Runner Flow (Pipeline Orchestration)
Main Pipeline: /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/runner/orchestrator_codex_pipeline.py
Sequence (Lines 165-249):
Load Prior Reports (Line 170)
Seed stage reports from plan.epic_triage_meta.triage_stages
For Each Stage (Lines 174-243):
Skip if already confirmed (Line 179)
Collect triage input
Execute stage:
Preflight Check → validates prerequisites
Parallel Path (observe, sense-check) → run_observe() / run_sense_check()
Subprocess Path (reflect, organize, enrich) → Codex subprocess
Report Recording → Stage handler persists result
Validation & Confirmation (Lines 225-234)
Reflect repair if accounting invalid (automatic retry)
Validate and confirm stage
Pipeline Finalization (Lines 252-335)
Auto-complete if full run + all stages successful
Otherwise print next-steps message
Stage Handlers: (Lines 91-130)
python Copy code
DEFAULT_STAGE_HANDLERS: dict[str, StageHandler] = {
"observe": StageHandler(
run_parallel=run_observe,
record_report=_record_observe_report,
),
"reflect": StageHandler(
record_report=_record_reflect_report,
),
"organize": StageHandler(
prompt_mode="self_record", # Self-persisting stage
),
"enrich": StageHandler(
prompt_mode="self_record",
),
"sense-check": StageHandler(
run_parallel=run_sense_check,
record_report=_record_sense_check_report,
),
}
7. Stage Execution Flow
Core Execution: /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/runner/orchestrator_codex_pipeline_execution.py (Lines 542-618)
python Copy code
def execute_stage(
context: StageRunContext,
*,
handlers: Mapping[str, StageHandler],
dependencies: StageExecutionDependencies,
) -> tuple[str, dict]:
Steps:
Preflight (Line 553) → preflight_stage() checks prerequisites
Parallel Execution (Line 575) → _execute_parallel_stage() if handler has run_parallel
Build Subprocess Prompt (Line 585) → _build_subprocess_prompt() via dependencies
Run Subprocess (Line 591) → _run_subprocess_stage() with Codex
Record Report (Line 606) → _record_stage_report_if_needed():
Special handling for reflect: repair if accounting invalid (Lines 479-517)
Calls handler.record_report() to persist
Validates stage was actually recorded
8. Reflect Report Repair Flow
Auto-Repair Logic: /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/runner/orchestrator_codex_pipeline_execution.py (Lines 267-335)
python Copy code
def repair_reflect_report_if_needed(
*,
report: str,
triage_input: Any,
prior_reports: Mapping[str, str],
repo_root: Path,
...,
dependencies: StageExecutionDependencies,
) -> tuple[str | None, str | None]:
Process:
Analyzes reflect report accounting (Line 283)
If missing/duplicate hashes found:
Builds targeted repair prompt (Lines 296-306)
Re-runs Codex subprocess with repair instructions
Validates repaired report accounting (Line 326)
Returns repaired report or error
Repair Prompt Instructions: (Lines 250-264)
Lists missing/duplicate hashes
Requires full Coverage Ledger section at top
One line per hash: - abcd1234 -> cluster "name" or - abcd1234 -> skip "reason"
Must mention every hash exactly once in ledger only
9. Prompt Building
Main Prompt Builder: /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/runner/stage_prompts.py (Lines 129-202)
python Copy code
def build_stage_prompt(
stage: str,
triage_input: TriageInput,
prior_reports: dict[str, str],
*,
repo_root: Path,
mode: PromptMode = "self_record", # "self_record" | "output_only"
cli_command: str = "desloppify",
stages_data: dict | None = None,
) -> str:
For reflect stage specifically:
Includes "Required Issue Hashes" section (Lines 64-70)
Includes "Coverage Ledger Template" section (Lines 72-80)
Template shows all open issue hashes with -> TODO placeholder
Relevant Prior Reports (Lines 103-126):
python Copy code
wanted = {
"reflect": ("observe",),
"organize": ("reflect",),
"enrich": ("organize",),
"sense-check": ("organize", "enrich"),
}.get(stage, tuple(prior_reports))
Also appends structured observe assessments table for reflect/organize if present.
10. Evidence Validation Patterns
All validation functions: /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/validation/core.py + stage-specific files
Stage Prerequisites: (Lines 91-119)
python Copy code
_STAGE_PREREQUISITES = {
"organize": (
StagePrerequisite("observe"),
StagePrerequisite("reflect"), # Must be present & confirmed for organize
),
"enrich": (
StagePrerequisite("observe"),
StagePrerequisite("reflect"),
StagePrerequisite("organize"),
),
"sense-check": (
StagePrerequisite("enrich", require_confirmation=True), # Must be confirmed
),
}
Reflect Auto-Confirm for Organize: (Lines 369-420)
Validates reflect accounting before allowing organize to proceed, sets:
missing_issue_ids
duplicate_issue_ids
Recurring dimension list
11. Key Files & Entry Points
File Path Purpose /Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/schema/__init__.pyTriageStagePayload, EpicTriageMeta types /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/workflow.pyTop-level command routing /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/runner/orchestrator_codex_pipeline.pyMain pipeline runner /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/runner/orchestrator_codex_pipeline_execution.pyStage execution + reflect repair /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/stages/observe.pyObserve stage recording /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/stages/reflect.pyReflect stage recording /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/stages/organize.pyOrganize stage recording /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/validation/core.pyShared validation + Coverage Ledger parsing /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/stages/evidence_parsing.pyObserveAssessment + evidence validation /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/runner/stage_prompts.pyPrompt building for stages /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/runner/orchestrator_common.pySTAGES constant, run_stamp()
12. Summary: Critical Validation Points
Observe → Records assessment evidence (verdict, reasoning, files, recommendation)
Reflect → Must cite every issue exactly once in Coverage Ledger section
Organize → Organizes issues into clusters; validates reflect accounting before proceeding
Auto-Repair → If reflect fails accounting, Codex automatically retries with targeted prompt
Prerequisites → Each stage validates all upstream stages exist and are confirmed