Very thorough exploration. I need to understand how desloppify's review batch runner works end-to-end — specifically the Codex subprocess execution model.
Look at these files in /Users/user_c042661f/Documents/desloppify/desloppify/:
app/commands/review/runner_parallel.py — How are batches executed in parallel? How does it manage multiple subprocesses?
app/commands/review/_runner_parallel_execution.py — The actual parallel execution logic
app/commands/review/_runner_process_attempts.py — How individual batch attempts work (subprocess spawning, output capture)
app/commands/review/_runner_process_io.py — How output is extracted from runner logs
app/commands/review/batch/execution.py — How batch prompts are built and dispatched
app/commands/review/batch/orchestrator.py — The full orchestration flow (prepare → run → merge → import)
Key questions:
How does the Codex subprocess get spawned? What's the exact command?
How are results collected from subprocesses?
How does the parallel runner manage concurrency (max parallel, timeouts, retries)?
How are batch results merged after all subagents complete?
What's the full lifecycle: prepare packet → build prompts → spawn → wait → validate → merge → import?
Return detailed findings with code snippets for the key patterns.
Assistant
I'll conduct a thorough exploration of the desloppify review batch runner to understand the Codex subprocess execution model end-to-end.
User
Very thorough exploration. I need to understand what data each triage stage consumes and produces, and what CLI commands the agent uses during each stage.
Look at these files in /Users/user_c042661f/Documents/desloppify/desloppify/:
engine/plan.py — Look at collect_triage_input, build_triage_prompt, detect_recurring_patterns, extract_issue_citations. What data structure does collect_triage_input return? What's in the triage prompt?
app/commands/plan/triage/services.py — The TriageServices dependency injection
app/commands/plan/triage/_stage_records.py — What gets recorded for each stage
app/commands/plan/triage/confirmations.py — The confirmation flow
app/commands/plan/triage/display.py — What gets displayed to the user after each stage
Also look at the cluster management commands — what CLI commands exist for creating, adding issues to, and enriching clusters:
Search for cluster in to find the cluster command handlers
Assistant
Now let me look at the runner_process.py file which contains the actual Codex subprocess spawning logic:
Assistant
I'll conduct a thorough exploration of the desloppify triage and cluster management systems. Let me start by examining the key files.
Assistant
Now let me look at the batch core module to see how prompts are built and what the full build_batch_prompt function looks like:
User
Thorough exploration. I need to understand how review batch prompts are built — the template/instruction system that tells subagents what to do.
Look at these files in /Users/user_c042661f/Documents/desloppify/desloppify/:
app/commands/review/prompt_sections.py — All the render_* functions that build prompt sections. How detailed are the instructions?
app/commands/review/batch/prompt_template.py — The batch-level prompt template
app/commands/review/batch/scope.py — How batch scope/files are determined
app/commands/review/external.py — Look at _build_claude_launch_prompt — how is the Claude prompt structured?
Also look at:
5. intelligence/review/ directory — what's in there? How are holistic review packets structured?
Key questions:
How detailed are the subagent prompts? What instructions do they contain?
How is scoring guidance provided?
How do prompts tell subagents to read files?
What's the output schema subagents must follow?
How does the blind packet differ from the full packet?
Return the prompt structure and key template snippets.
Assistant
Now let me look at the actual implementation of the triage functions to understand the data structures:
Assistant
I'll conduct a thorough exploration of the review batch prompt system. Let me start by examining the structure and then reading each file.
Assistant
Let me continue reading the core.py file to find the build_batch_prompt function:
Assistant
Now let me locate and read the key files you mentioned:
Assistant
Now let me examine the actual triage prompt and input collection:
Assistant
Now let me check the batches_runtime module to see build_batch_tasks:
Assistant
Now let me read the files in order of importance:
Assistant
Perfect. Now let me look at the types to understand the complete picture:
Assistant
Now let me look at the cluster management commands:
Assistant
Now let me read the external.py file to see _build_claude_launch_prompt:
Assistant
Now let me look at the intelligence/review directory structure and key files:
Assistant
Now let me look at the parallel types to see BatchTask:
Assistant
Let me continue reading the prepare_holistic_flow file and also look at the batch/core.py:
Assistant
Now let me look at the schema to understand the plan.json structure better:
Assistant
Let me look at the context_holistic directory to understand the holistic context structure:
Assistant
Let me read the context models file and the holistic context structure:
Assistant
Now let me look at the dimensions to understand the dimension prompts:
Assistant
Perfect. Now let me look at the playbook constants that were referenced in the display file:
Assistant
Now let me check the actual dimensions.json file to see what a dimension prompt looks like:
Assistant
Now let me check the main triage command entry point to see all the CLI commands available:
Assistant
Let me get more of the dimensions.json to see the system_prompt:
Assistant
Now let me gather information about the cluster command dispatch and helpers:
Assistant
Perfect. Now let me get more details on the batch execution to see how prompts are passed to subagents:
Assistant
Let me look at how prompts are created and passed to subagents in orchestrator:
Assistant
Perfect! Now let me look at the helpers file to understand what data helper functions exist:
Assistant
Let me continue reading the orchestrator to see how it calls the prompt template:
Assistant
Excellent! Now let me check the stage_helpers file to understand what validation exists:
Assistant
Perfect. Now let me look at the batch/core.py to see build_batch_prompt:
Assistant
Now let me check how the blind packet is built to understand what is exposed to the subagents:
Assistant
Now let me look at the prepare_batches.py to see how batches are built with seed files and concern signals:
Assistant
Assistant
Assistant
User
Assistant
I'll start by thoroughly exploring the desloppify codebase to understand the existing architecture before designing the plan.
Assistant
I'll explore the desloppify codebase thoroughly to understand the existing architecture before designing the plan.
Assistant
Let me now explore the key files - the review runner system and the triage system.
Assistant
Now let me read the key files in parallel.
Assistant
Now let me read the triage-related files.
Assistant
Now let me look at the batch orchestrator, the playbook, the triage helpers, and the engine-level triage code.
Assistant
Let me now look at the engine-level triage code and the CLI parser for plan commands.
Assistant
Now let me look at the review batch execution flow (the do_run_batches in execution.py).
Assistant
Now let me look at the confirmations module and the runtime paths.
Assistant
Let me also check what the review command's CLI parser looks like for the runner flags to understand the pattern.
Assistant
Now I have a thorough understanding of the codebase. Let me check one more thing -- the review command handler to see how --run-batches is routed.
Assistant
app/commands/plan/
What arguments do they take?
Key questions:
What's the full data payload available to each stage?
What does the triage prompt look like (the one built by build_triage_prompt)?
What cluster CLI commands exist and what do they do?
What does the plan.json structure look like (clusters, queue_order, epic_triage_meta)?
How does the confirmation flow work between stages?
Return detailed findings.
Perfect! Now let me compile detailed findings with comprehensive code snippets showing the end-to-end execution model. Let me create a summary document:
The Codex subprocess command is built deterministically:
python
def codex_batch_command(*, prompt: str, repo_root: Path, output_file: Path) -> list[str]:
"""Build one codex exec command line for a batch prompt."""
effort = os.environ.get("DESLOPPIFY_CODEX_REASONING_EFFORT", "low").strip().lower()
if effort not in {"low", "medium", "high", "xhigh"}:
effort = "low"
return [
"codex",
"exec",
"--ephemeral",
"-C",
str(repo_root),
"-s",
"workspace-write",
"-c",
'approval_policy="never"',
"-c",
f'model_reasoning_effort="{effort}"',
"-o",
str(output_file),
prompt,
]
Key pattern: The prompt text is passed as the final positional argument, and output is redirected to a file via -o flag. The working directory is set to the repo root via -C. Reasoning effort is configurable via DESLOPPIFY_CODEX_REASONING_EFFORT env var (defaults to "low").
The runner supports TWO execution modes, selected via deps.use_popen_runner:
Path A: Popen (Live Streaming + Stall Detection)
Used when use_popen is True:
python
def _run_via_popen(
cmd: list[str],
deps: CodexBatchRunnerDeps,
state: _RunnerState,
ctx: _AttemptContext,
interval: float,
stall_seconds: int,
) -> _ExecutionResult:
"""Execute batch via Popen with live streaming and stall recovery."""
writer_thread = _start_live_writer(state, ctx, interval)
try:
process = deps.subprocess_popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
bufsize=1, # Line buffering for live streaming
)
except OSError as exc:
state.stop_event.set()
writer_thread.join(timeout=2)
ctx.log_sections.append(f"{ctx.header}\n\nRUNNER ERROR:\n{exc}\n")
ctx.safe_write_text_fn(ctx.log_file, "\n\n".join(ctx.log_sections))
return _ExecutionResult(code=127, stdout_text="", stderr_text="", early_return=127)
# Spawn two daemon threads to drain stdout/stderr independently
stdout_thread = threading.Thread(
target=_drain_stream,
args=(process.stdout, state.stdout_chunks, state),
daemon=True,
)
stderr_thread = threading.Thread(
target=_drain_stream,
args=(process.stderr, state.stderr_chunks, state),
daemon=True,
)
stdout_thread.start()
stderr_thread.start()
# Main loop: poll for completion, check timeout, detect stall
timed_out = False
stalled = False
recovered_from_stall = False
output_signature: tuple[int, int] | None = None
output_stable_since: float | None = None
while process.poll() is None: # While still running
now_monotonic = time.monotonic()
elapsed = int(max(0.0, now_monotonic - ctx.started_monotonic))
# Timeout check
if elapsed >= deps.timeout_seconds:
with state.lock:
state.runner_note = f"timeout after {deps.timeout_seconds}s"
timed_out = True
_terminate_process(process)
break
# Stall detection (output hasn't changed AND no stream activity)
if stall_seconds > 0:
with state.lock:
last_activity = state.last_stream_activity
stalled, output_signature, output_stable_since = _check_stall(
ctx.output_file,
output_signature,
output_stable_since,
now_monotonic,
last_activity,
stall_seconds,
)
if stalled:
with state.lock:
state.runner_note = (
f"stall recovery triggered after {stall_seconds}s "
"with stable output state"
)
recovered_from_stall = _output_file_has_json_payload(ctx.output_file)
_terminate_process(process)
break
deps.sleep_fn(min(interval, 1.0))
# Cleanup: join threads, write snapshot
if process.poll() is None:
_terminate_process(process)
stdout_thread.join(timeout=2)
stderr_thread.join(timeout=2)
state.stop_event.set()
writer_thread.join(timeout=2)
_write_live_snapshot(state, ctx)
return _ExecutionResult(
code=int(process.returncode or 0),
stdout_text="".join(state.stdout_chunks),
stderr_text="".join(state.stderr_chunks),
timed_out=timed_out,
stalled=stalled,
recovered_from_stall=recovered_from_stall,
)
Key mechanisms:
Live streaming: Two daemon threads (stdout_thread, stderr_thread) continuously drain output pipes into state.stdout_chunks and state.stderr_chunks
Activity tracking: Each read updates state.last_stream_activity timestamp (thread-safe via lock)
Stall detection: Compares file signature (size + mtime) against previous snapshot; if signature is stable AND no stream activity for stall_seconds, triggers early termination
Stall recovery: Before terminating, checks if output file contains valid JSON payload—if yes, treats it as success (code 0)
Live log snapshots: A background thread writes periodic snapshots to the log file every interval seconds
If no STDOUT section found, tries parsing entire log
Prevents false positives by NOT falling back to full log if a concrete STDOUT section exists but is empty
KEY INSIGHTS
Subprocess Command Pattern: Prompt is a string argument; output is a file; working directory is explicit. The codex binary expects JSON output to the file.
Dual Execution Paths: Popen for live monitoring + stall detection (complex but recoverable), subprocess.run for simple cases (no live streaming).
Stall Recovery: Timeouts/stalls are NOT automatic failures—if the output file contains valid JSON, the batch is treated as successful. This handles processes that go quiet but complete.
Retry Strategy: Transient failures detected via string matching in combined stdout/stderr. Exponential backoff with configurable base.
Concurrency Model: ThreadPoolExecutor-based, not process-based. Each thread runs one batch sequentially (Codex is subprocess-spawned, not a thread).
Progress Model: Progress events (queued, start, done, heartbeat) are emitted via callback; the executor is decoupled from progress reporting.
Result Extraction: Two-stage: direct file read, then log fallback. Normalization happens after both stages succeed. Failed batches are tracked but processing continues (with --allow-partial flag).
Merge-First Architecture: All batch results are merged deterministically BEFORE import, so a single unified payload is imported into state.
Perfect! Now I have enough information. Let me create a comprehensive summary of the review batch prompt system.
Summary: Review Batch Prompt System
Based on my thorough exploration of the desloppify codebase, here's how the review batch prompt system works:
Architecture Overview
The system uses a multi-layer prompt construction approach where holistic review packets are broken into dimension-focused batches, each with its own subagent prompt containing:
Perfect! Now I have all the information I need. Let me compile a comprehensive summary of my findings.
Thorough Exploration: Desloppify Triage System
Based on my detailed analysis of the codebase, here are the complete findings on the desloppify triage system:
1. Triage Stages Data Flow
The system implements a 4-stage sequential workflow defined in TRIAGE_STAGE_IDS:
observe → reflect → organize → enrich → (commit/complete)
Each stage has explicit dependencies (in triage_playbook.py):
observe: no prerequisites
reflect: requires observe
organize: requires reflect
enrich: requires organize
commit: requires enrich
2. Data Structures and Payloads
TriageInput (collected before each stage, from epic_triage_prompt.py):
python
- open_issues: dict[str, dict] # All open review/concerns issues
- mechanical_issues: dict[str, dict] # Non-review issues (for context)
- existing_epics: dict[str, Cluster] # Current auto-triage clusters
- dimension_scores: dict[str, Any] # Dimension scoring data
- new_since_last: set[str] # Issue IDs new since last triage
- resolved_since_last: set[str] # Issue IDs resolved since last
- previously_dismissed: list[str] # IDs dismissed in prior triage
- triage_version: int # Next version number
- resolved_issues: dict[str, dict] # Full objects of resolved IDs
- completed_clusters: list[dict] # Clusters completed since last
TriageStagePayload (persisted for each stage, in schema.py):
python
- stage: str # "observe", "reflect", "organize", "enrich"
- report: str # Agent's analysis text
- cited_ids: list[str] # Issue IDs mentioned in report
- timestamp: str # ISO timestamp when recorded
- issue_count: int # How many issues were analyzed
- recurring_dims: list[str] # (reflect only) recurring dimension names
- confirmed_at: str # ISO timestamp when user confirmed
- confirmed_text: str # User's attestation text (80+ chars min)
EpicTriageMeta (top-level in plan.json):
python
- triaged_ids: list[str] # All IDs analyzed in current/last triage
- dismissed_ids: list[str] # IDs dismissed permanently
- issue_snapshot_hash: str # Hash of review issues at triage completion
- strategy_summary: str # High-level plan narrative
- version: int # Triage version counter
- last_run: str # ISO timestamp of last triage
- last_completed_at: str # ISO timestamp of last completion
- triage_stages: dict[str, TriageStagePayload] # Current stage progress
- stage_snapshot_hash: str # Hash of stage progress (for staleness detection)
- stage_refresh_required: bool # Flag if issues changed during triage
- last_triage: LastTriageSnapshot # Archived previous completion
3. Triage Prompt Structure
The prompt built by build_triage_prompt(TriageInput) contains these sections (in order):
Existing Epics — shows current auto-generated clusters with status, thesis, direction, and issue list
New issues since last triage — shows IDs and summaries of new review issues
Resolved since last triage — just lists IDs of resolved issues
All open review issues (main section) — formatted as:
Input: Plan with existing clusters and action_steps
Gate: All steps must have either:
detail: sub-points/paragraphs, OR
issue_refs: list of issue IDs addressed
Output: TriageStagePayload with:
report: enrichment summary (50+ chars)
shallow_count: number of steps without detail/refs
Confirmation: User writes 80+ char attestation mentioning at least one cluster name
Note: User can still reorganize (add/remove clusters, reorder) at this stage
5. Confirmation Flow
Located in confirmations.py, each stage has a _confirm_* function:
_validate_attestation(text, stage, dimensions, cluster_names) → validates that attestation text references actual data:
observe: must mention at least 1 dimension
reflect: must mention at least 1 dimension OR cluster name
organize: must mention at least 1 cluster
enrich: must mention at least 1 cluster
Cascade clearing: When a stage is re-recorded, all later confirmations are cleared (via cascade_clear_later_confirmations), forcing re-confirmation of downstream stages
Reuse logic: If no new --report provided and an existing stage has a report, it's reused (with no cascade clear if previously confirmed)
6. Cluster Management CLI Commands
From cluster_handlers.py, the full dispatch table (cmd_cluster_dispatch):
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage_playbook.py — Stage labels and canonical CLI commands
Design an implementation plan for adding subagent-delegated execution to desloppify's plan triage workflow. This is in the desloppify repo at /Users/user_c042661f/Documents/desloppify/desloppify/.
Context
Currently, triage has 4 stages (observe → reflect → organize → enrich → commit) where the calling agent (Claude Code or Codex) does all work inline — reading issues, analyzing code, creating clusters, enriching steps — and records each stage via CLI commands. There's no subagent delegation.
The review command already has two subagent models:
Claude external session: desloppify review --external-start --external-runner claude — generates blind packet + session, user pastes into Claude, submits back with --external-submit
We want to add the same two models to triage.
User Requirements
Subagents should actually RUN CLI commands (desloppify plan cluster create/add/update, desloppify plan skip, etc.) — not just return JSON. We wait for them to complete.
Deep instructions — subagents need thorough guidance on what to do
At least one subagent per stage, possibly more (e.g., observe could be split into sub-batches by dimension group)
ALL subagents should have access to the codebase (can read source files) and be instructed to use it
Follow the same patterns as the review runner system
previously_dismissed: IDs dismissed in prior triage
completed_clusters: clusters completed since last
What each stage does today
OBSERVE: Agent reads issue list, produces 100+ char analysis of themes, root causes, contradictions. No CLI commands, just analysis text via --stage observe --report "...".
REFLECT: Agent compares current issues vs resolved history, identifies recurring patterns, forms strategy. Must mention recurring dimensions. Records via --stage reflect --report "...".
ORGANIZE: Agent runs many CLI commands:
desloppify plan cluster create <name> --description "..."
desloppify plan cluster add <name> <issue-patterns>
desloppify plan cluster update <name> --steps "step1" "step2"
desloppify plan skip <patterns> --permanent --attest "..."
Then records via --stage organize --report "..."
Validation: all review issues must be in a cluster or skipped, all clusters must have description + steps
ENRICH: Agent enriches each cluster step with detail and issue refs:
desloppify plan cluster update <name> --update-step N --detail "sub-details" --issue-refs id1 id2
Then records via --stage enrich --report "..."
Validation: all steps must have detail or issue_refs
COMMIT: Agent writes strategy summary via --complete --strategy "...". Validates all stages confirmed, coverage checked.
Confirmation flow
Each stage needs confirmation: --confirm <stage> --attestation "80+ chars mentioning actual data". Later stages can auto-confirm earlier ones by passing --attestation.
Design Constraints
Subagents for organize and enrich MUST run CLI commands to modify plan state (not just return JSON)
Subagents need -s workspace-write (or equivalent) for file access
For Codex: subagents can call desloppify CLI directly since they're local subprocesses
For Claude external: this is trickier — Claude can't run CLI commands from an external session. Options:
a. Claude external could return structured JSON that gets applied by an importer (like review does)
b. Claude external could generate a script of commands to execute
c. Skip Claude external for triage initially (Codex-only)
Stages are sequential (reflect needs observe output), so parallelism is WITHIN a stage, not across stages
Each stage's output becomes input for the next stage's subagent prompt
Questions to Address in Your Plan
How should the CLI surface look? New flags on plan triage?
How should stage packets be structured? What goes in each stage's subagent prompt?
Should observe/reflect (analysis-only stages) have multiple subagents? How would you split them?
For organize/enrich (command-running stages), how do subagents coordinate? If multiple subagents are organizing, they'd conflict on cluster state.
How should the pipeline orchestrate stage → confirm → next stage automatically?
What's the merge/validation strategy after subagent completion?
How does Claude external work given that organize/enrich need to run commands?
Where in the file structure should new code live?
Please produce a detailed implementation plan with file paths, function signatures, and clear step-by-step implementation order.
I now have a comprehensive understanding of the architecture. Let me produce the detailed implementation plan.
The plan introduces a triage/runner/ module under app/commands/plan/triage/ that mirrors the structure of app/commands/review/ runner components. Triage stages are fundamentally different from review batches: review subagents return JSON that gets merged; triage subagents execute CLI commands that mutate plan state directly.
Key Design Decisions
1. CLI Surface
New flags on desloppify plan triage:
code
--run-stages # Codex subprocess mode: run all stages sequentially via subagents
--runner codex # Runner backend (only codex initially)
--dry-run # Generate prompts but don't execute
--stage-timeout # Per-stage timeout (default: 30 min)
No --parallel flag for across-stage parallelism (stages are sequential). Within-stage parallelism is not used initially because:
Observe/reflect are analysis-only (single subagent each)
Organize/enrich mutate shared plan state (concurrent CLI commands would race on plan.json)
2. Stage Packets (Subagent Prompts)
Each stage's subagent prompt contains:
TriageInput data (all open issues, resolved issues, existing clusters, dimension scores, deltas)
Prior stage outputs (observe report feeds into reflect prompt, etc.)
CLI command reference specific to that stage
Validation requirements (what the subagent needs to achieve for the stage to pass)
Codebase access instructions (repo root, how to read source files)
3. Stage Subagent Counts
Stage
Subagents
Rationale
Observe
1
Analysis only, needs holistic view of all issues
Reflect
1
Strategy formation needs full context including observe output
Organize
1
Mutates shared plan state; multiple subagents would race
Enrich
1
Mutates shared plan state; could split per-cluster later
Commit
0
Automated: validate + apply after enrich completes
4. Claude External for Triage
Deferred. Organize/enrich require running CLI commands which Claude external cannot do directly. The review external model works because it returns JSON. For triage, the subagent needs to actually modify plan.json via CLI calls. Two future options:
Option A: Claude returns a list of CLI commands as structured JSON, and an importer executes them
Option B: Claude generates a shell script that gets reviewed and executed
For now: Codex subprocess only (same as how review started).
5. Pipeline Orchestration
The pipeline runs all 5 stages sequentially in a single --run-stages invocation:
Each stage: (a) builds prompt, (b) spawns Codex subprocess, (c) waits for completion, (d) validates stage was recorded via CLI, (e) auto-confirms with the subagent's report as attestation, (f) proceeds to next stage.
6. Validation After Each Stage
After each subagent returns, the orchestrator:
Reloads plan.json from disk
Checks the stage was properly recorded (report exists, meets length requirements)
For organize: checks clusters exist, all issues covered, clusters enriched
For enrich: checks all steps have detail/issue_refs
Auto-confirms the stage with a generated attestation based on the actual data
File Structure
New files under /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/runner/:
code
triage/runner/
__init__.py
orchestrator.py # Main pipeline: run all stages sequentially
stage_prompts.py # Build per-stage subagent prompts
stage_validation.py # Post-subagent validation per stage
codex_runner.py # Codex subprocess execution (reuses runner_process.py)
Create run directory under .desloppify/triage_runs/<stamp>/
For each stage in ["observe", "reflect", "organize", "enrich"]:
a. Build stage prompt via stage_prompts.build_stage_prompt(stage, triage_input, prior_reports)
b. Write prompt to <run_dir>/prompts/<stage>.md
c. Execute via codex_runner.run_triage_stage(prompt, repo_root, output_file, log_file, ...)
d. Reload plan from disk (subagent has mutated it via CLI commands)
e. Validate stage was recorded: stage_validation.validate_stage(stage, plan)
f. If validation fails: report error and abort
g. Auto-confirm stage: build attestation from actual plan data, call confirmation
h. Collect stage report for next stage's prompt context
After all 4 stages pass: auto-complete triage with strategy derived from stages
Key details:
Uses run_codex_batch from review/runner_process.py directly (same Codex subprocess pattern)
codex_batch_command already handles -C <repo_root> -s workspace-write which gives subagents both file read access and the ability to run desloppify CLI commands
Each stage prompt explicitly lists available desloppify CLI commands and tells the subagent to run them
The subagent's output file is not used for JSON parsing -- instead we validate plan.json was modified correctly
Run log, per-stage logs, and prompt snapshots persist under the run directory
Reuses the existing validation logic from _stage_validation.py:
observe: check stages dict has "observe" with report >= min chars
reflect: check "reflect" exists with report >= min chars
organize: check clusters exist, all enriched, all issues covered (reuses _manual_clusters_or_error, _clusters_enriched_or_error, _unclustered_review_issues_or_error)
enrich: check _shallow_steps returns empty
Also:
python
def build_auto_attestation(stage: str, plan: dict, triage_input: TriageInput) -> str:
"""Generate a valid attestation from actual plan data for auto-confirmation."""
This generates attestation text that references real dimensions/cluster names to pass the _validate_attestation check. For example:
observe: "I have thoroughly analyzed {n} issues across dimensions {dim1}, {dim2}, {dim3} and identified root causes and contradictions in the codebase"
organize: "This plan correctly organizes issues into clusters {c1}, {c2}, {c3} with enriched steps and handles contradictions via skip/dismiss"
triage/runner/codex_runner.py
Thin wrapper around the existing runner_process.py:
python
def run_triage_stage(
*,
prompt: str,
repo_root: Path,
output_file: Path,
log_file: Path,
timeout_seconds: int,
) -> int:
"""Execute one triage stage via codex and return exit code."""
Uses codex_batch_command and run_codex_batch from review/runner_process.py. The output file isn't parsed for JSON -- it's just the Codex execution output for debugging. The real "output" is the mutations to plan.json via CLI commands.
No changes needed. The orchestrator uses TriageServices for plan loading/saving and the subagent uses CLI commands which go through the normal command path.
Implementation Order
triage/runner/__init__.py - Package setup
triage/runner/stage_prompts.py - Build prompts first (can test independently)
triage/runner/stage_validation.py - Post-stage validation (can test with mock plans)
triage/runner/orchestrator.py - Main pipeline (depends on 2-4)
parser_groups_plan_impl.py - Add CLI flags
triage_handlers.py - Add routing
Potential Challenges
Plan file locking: The subagent and the orchestrator both read plan.json. The orchestrator only reads after the subagent completes, so no concurrent access. But if the subagent crashes mid-write, plan.json could be corrupted. Mitigation: existing save_plan uses atomic write patterns.
Subagent prompt quality: The subagent needs to run multiple CLI commands correctly. The prompts must be explicit about exact command syntax. Include example commands with actual issue IDs from the data.
Attestation generation: Auto-generated attestations must pass the validation checks in _validate_attestation. The generator must reference actual dimension names and cluster names from the plan data.
Stage confirmation flow: The orchestrator needs to simulate what _cmd_confirm_stage does but programmatically. Rather than calling the CLI for confirmation, it can directly call the confirmation functions with synthesized args, or call the CLI as a subprocess (simpler, same pattern as the subagent).
Error recovery: If a stage fails validation, the orchestrator should leave the plan in whatever state the subagent left it. The user can then fix manually and resume, or re-run --run-stages which will detect existing stage progress and continue from where it left off.
Stage reuse: If observe is already recorded and confirmed, --run-stages should skip it and proceed to reflect. Check stages dict for existing confirmed stages.
Critical Files for Implementation
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/runner/orchestrator.py - Core pipeline logic to create (new file)
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/runner/stage_prompts.py - Per-stage prompt builders to create (new file)
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/review/runner_process.py - Existing Codex subprocess runner to reuse
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/stage_flow_commands.py - Existing stage recording logic to understand validation requirements
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/_stage_validation.py - Existing validation functions to reuse from orchestrator
Critical Files for Implementation
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/runner/orchestrator.py - New file: main sequential pipeline that spawns one Codex subprocess per stage, validates results, auto-confirms, and advances
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/runner/stage_prompts.py - New file: builds rich per-stage subagent prompts with issue data, prior reports, CLI command reference, and validation requirements
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/stage_flow_commands.py - Existing stage recording logic; defines what each stage requires (report format, validations, confirmation flow)
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage_handlers.py - Entry point to modify: add --run-stages routing to new orchestrator