I need to review the uncommitted changes on the current branch (wip/triage-runner). There are ~825 lines added across 38 files plus 2 new files. Please read through the full diff and the new files, and give me a detailed summary of what the changes do, organized by theme/area. Flag anything that looks wrong, inconsistent, or suspicious.
Run: git diff HEAD to get the full diff, and also read the two new untracked files:
For context, this is a Python CLI tool for codebase health tracking. The branch has been adding tests and hardening triage/review flows.
Organize your findings into:
Summary of changes by area
Any issues, bugs, or concerns
Whether the changes are coherent and make sense together
Assistant
I'll analyze the uncommitted changes on the wip/triage-runner branch. Let me start by getting the full diff and reading the new files.
Assistant
Let me read the full diff from the saved file and the two new files:
Assistant
Let me read the new files first, then break the diff into sections:
Assistant
Now let me read the full diff in sections. Let me break it into chunks:
Assistant
Let me continue reading the diff:
Assistant
Let me continue:
Assistant
Let me continue reading the diff:
Assistant
Let me continue to see the remaining test changes:
Assistant
User
Search the entire codebase (not just the diff) for where confirmed_at is SET on triage stage records in production code (not tests). Look in:
Stage completion handlers
_stage_records.py
Any stage flow files
Any place that writes triage stage dicts
I need to know: is confirmed_at actually written by production code when a stage is confirmed, or is it only in tests?
Search broadly: grep for "confirmed_at" across the whole codebase, then read relevant files to understand the context.
Assistant
I'll search the entire codebase for confirmed_at to understand where it's being set.
Assistant
Now let me read the key production files to see where confirmed_at is actually being set:
Assistant
Good! Now let me read the key production files where it's being SET:
User
I need to check three concerns about uncommitted changes on the current branch:
Preflight behavior change: Read desloppify/app/commands/scan/preflight.py and check the git diff for that file. The concern is that scans now block when queue has ANY items (not just objective). Is this intentional? Are there comments explaining the change?
plan_start_scores clearing: Read desloppify/app/commands/scan/plan_reconcile.py and check if there's error handling or guarantees that _reset_cycle_for_force_rescan() always runs when needed. Is there a risk of scores not being cleared if reconciliation fails?
Mid-cycle logic spread: Check if there are any comments linking the mid-cycle pieces together across:
stage_prompts.py — Added _format_assessments_table() and updated _relevant_prior_reports() to append structured assessments table from observe to reflect reports
stage_prompts_instruction_blocks.py — Completely rewrote observe template documentation to prefer YAML-like format with concrete examples
stage_prompts_instruction_shared.py — Updated CLI reference to require --attest "I have reviewed...not gaming..." (exact phrase validation)
stage_prompts_observe.py — Switched from loose one-line format to structured template; warns against old bracket format
stage_prompts_validation.py — Added evidence validation requirement to observe stage checks
Change: Instructions now demand structured per-issue assessments (hash, verdict, verdict_reasoning, files_read, recommendation) rather than loose prose.
3. Stage Validation Hardening
File: runner/stage_validation.py
New evidence validation integrated into validate_stage():
Observe: Parses evidence and blocks on missing verdict, verdict_reasoning, files_read, or recommendation
Reflect: Validates skip-reason format (non-empty reason text required)
Organize: Checks cluster name mentions in report; counts cluster operations since reflect (minimum 3 or cluster count)
Sense-check: Validates file path citations and cluster name mentions
Also added stale issue ref check to enrich quality validation.
4. Flow Stage Handlers Updated
Files modified:
stage_flow_observe_reflect_organize.py — Integrated evidence parsing; stores assessments as dicts for structured access
stage_flow_sense_check.py — Added file path and cluster name validation checks
stage_flow_enrich.py — Added check for cluster_update operations since organize stage
All stage handlers now use the new validation functions from _stage_evidence_parsing.
5. Mid-Cycle Scan Logic (Infrastructure)
Files modified:
plan_reconcile.py — Added:
_reset_cycle_for_force_rescan() — Clears triage stages, workflow items, plan-start scores when user runs --force-rescan
_is_mid_cycle_scan() — Detects if plan cycle is active and queue has items
Modified _sync_post_scan_with_policy() to skip auto-clustering and triage injection during mid-cycle scans
Logs when mid-cycle scan skips cluster regeneration
preflight.py — Refactored to block scans when ANY queue items remain (not just objective items). --force-rescan no longer clears plan scores in preflight (moved to reconciliation)
workflow.py — Added force_rescan field to ScanRuntime dataclass
Rationale: Mid-cycle scans (via --force-rescan or when queue items remain) regenerate issue IDs and clusters, which breaks triage state and reorders the queue. These destructive operations are now skipped mid-cycle and deferred to cycle boundaries.
6. Plan Constants & Helpers
File: engine/_plan/constants.py
Added confirmed_triage_stage_names() function — extracts triage stage names that have an explicit confirmed_at timestamp marker. Used throughout codebase to distinguish confirmed vs. recorded stages.
7. Review Import Tracking
Files modified:
reconcile_review_import.py — ReviewImportSyncResult now tracks:
triage_injected_ids: list[str] — which triage stages were injected
triage_deferred: bool — whether injection was deferred due to mid-cycle guard
plan_sync.py — Logs these new fields in execution log
8. Subjective Dimension Sync Refinement
File: engine/_plan/sync_dimensions.py
Mid-cycle behavior tightened:
Prune ALL subjective IDs from queue mid-cycle (not just unscored ones)
Never resurface skipped unscored dimensions mid-cycle
Don't inject unscored dimensions mid-cycle
Stale dimension sync adjusted for mid-cycle to only keep stale if no objective backlog
9. Triage Auto-Start & Logging
File: engine/_work_queue/synthetic.py
Uses new confirmed_triage_stage_names() helper to identify which stages have been confirmed.
10. Completion & Confirmation Flow
File: stage_completion_commands.py
Reordered imports (cleanup)
Modified apply_completion() call to pass:
completion_mode="confirm_existing"
completion_note=note (user's note about why reuse is valid)
Updated completion message to "reused the current enriched cluster plan" (more explicit)
File: _stage_records.py (touched by tests)
Confirm-existing now stores:
reused_existing_plan: bool = True
completion_note: str (user's justification)
previous_strategy_summary: str (saved old summary for audit)
11. Test Updates (Extensive)
Key test changes:
Evidence parsing tests — New comprehensive test suite for YAML/legacy parsing and all validators
Stage validation tests — Tests updated to include cluster operation counts, attestation requirements
Triage runner tests — Updated to:
Pass non-hex issue IDs to bypass evidence parsing (when test doesn't need validation)
Include cluster names in sense-check report
Include file paths in sense-check report
Triage completion tests — New test test_confirm_existing_rewrites_strategy_summary_to_explicit_reuse_message validates confirm-existing flow
Preflight tests — Flipped expectations: subjective items now BLOCK scans (not allow); both updated to explain mid-cycle risk
Dependency guard tests — Added confirmed_at timestamp to triage stages
Review import tests — New test test_sync_plan_after_import_logs_triage_provenance validates triage injection/deference tracking
Split modules tests — Updated orchestrator helper expectations to accept runner parameter and log triage auto-start events
Epic triage tests — Updated sync tests to include confirmed_at markers and test unconfirmed stages remaining pending
Issues, Bugs, or Concerns
1. ISSUE: Inconsistent field naming in assessments storage
In stage_flow_observe_reflect_organize.py, parsed evidence entries are converted to dicts:
python
assessments = [
{
"hash": entry.issue_hash,
"verdict": entry.verdict,
...
}
for entry in evidence.entries
]
But the stored YAML template uses hash: field. Verify that the field names match downstream consumers (e.g., in _format_assessments_table() which expects hash, verdict, recommendation). Looks OK — dict keys match expected names.
2. ISSUE: confirmed_at marker is being added to stages, but not documented in schema
Tests add "confirmed_at": "2026-01-01T00:00:00Z" to triage stage dicts, but this field wasn't in the original schema. The parsing logic in confirmed_triage_stage_names() expects it, but:
Where is confirmed_at set? Grep shows it in test stubs, but where does real code set it?
Should check _stage_records.py and stage completion handlers to confirm they set this field.
Action needed: Verify that stage confirmation handlers actually set confirmed_at on stages when confirming them.
3. ISSUE: Import organization is inconsistent across stage handlers
In stage_flow_observe_reflect_organize.py and stage_flow_sense_check.py, evidence validation imports are done INSIDE the function (local imports). This is unusual for this codebase. More typical would be top-level imports.
Why? Likely to avoid circular imports or because these modules were added mid-development. Not a bug, but inconsistent style.
4. ISSUE: validate_report_references_clusters() silently succeeds if report is empty
In _stage_evidence_parsing.py, line 451-454:
python
report_lower = report.lower()
for name in cluster_names:
if name.lower() in report_lower:
return [] # Early exit on first match
If cluster_names is non-empty but report is empty, this returns one failure. But the logic is: "if ANY cluster name appears, validation passes." This is correct but worth noting — a long report with no cluster names will fail, but a short report with one cluster name will pass. This is the intended behavior.
This accepts paths like @weird-name/file.x which may not be valid. However, the docstring says "permissive path regex — detects whether any file path was mentioned. NOT used to validate existence." So this is intentional and acceptable for a permissive "did they mention ANY file?" check.
6. ISSUE: Mid-cycle scan logic is complex and spread across multiple files
This is a major behavioral change (scans now block when queue has ANY items, not just objective items). Make sure tests cover all combinations.
7. ISSUE: Preflight no longer clears plan_start_scores on --force-rescan
Old behavior (now removed):
python
plan["plan_start_scores"] = {}
save_plan(plan)
New behavior: _reset_cycle_for_force_rescan() is called in plan_reconcile.py during post-scan reconciliation, not in preflight.
Risk: If reconciliation fails to run (exception, early return), plan_start_scores won't be cleared. However, reconciliation runs right after scan in the workflow, so this should be OK. Verify: Check that prepare_scan_runtime() always passes force_rescan to reconciliation.
✓ Verified: plan_reconcile.py line 520-521 reads force_rescan from runtime.
8. ISSUE: Test test_force_rescan_with_valid_attest_passes was simplified
Old test: verified that plan_start_scores were cleared.
New test: just calls preflight, expects no exception.
This change is consistent with the architectural move to reconciliation, but it means the test no longer validates that scores ARE cleared. This is probably intentional since reconciliation tests (test_sync_split_modules_direct.py) now own that validation.
9. ISSUE: Inconsistent use of is_mid_cycle() helper
In sync_dimensions.py and sync_triage.py, both call is_mid_cycle(plan) to check if plan_start_scores is set. But _is_mid_cycle_scan() in plan_reconcile.py adds an extra check: len(active_items) > 0.
Questions:
Are these the same function? Or different implementations?
Why does reconciliation check for remaining items while dimensions sync only checks plan_start_scores?
Looking at imports: from desloppify.engine.plan import ... is_mid_cycle ... — so is_mid_cycle() is imported from engine.plan module. The _is_mid_cycle_scan() in reconciliation is LOCAL. They serve different purposes:
is_mid_cycle(plan) = does plan have active cycle? (plan_start_scores set)
_is_mid_cycle_scan(plan, state) = is the cycle ACTIVE with work remaining? (plan_start_scores + non-empty queue)
This distinction is subtle but important. No bug, but documentation could be clearer.
10. ISSUE: Orchestrator helper test monkeypatch signature changed
This change is needed because ensure_triage_started() now takes runner="codex" parameter. The monkeypatch was updated to accept any args. OK, but the test could be more specific.
Coherence Assessment
Overall coherence: HIGH
The changes are well-organized around a coherent theme: moving triage evidence from loose prose to structured, validated assessments, and hardening mid-cycle scan behavior to preserve triage state.
Strengths:
Unified validation framework — All stages now use the same _stage_evidence_parsing module
Backward compatibility — YAML template is preferred, but legacy bracket format still works
Clear field requirements — Evidence validation is explicit: verdict, reasoning, files, recommendation
Mid-cycle protection — Consistent across reconciliation, preflight, dimensions sync
Comprehensive tests — Both positive and negative cases covered
Potential issues:
confirmed_at field not found in real code — Tests use it, but need to verify actual stage handlers set it
Mid-cycle logic is distributed — Makes it harder to reason about, but not wrong
Test expectations slightly relaxed — Some tests now accept non-hex IDs to avoid evidence parsing; this is pragmatic but could mask issues
Missing pieces:
No docstring updates to explain new evidence structure to users (though --help will show the prompts)
No migration code if existing plans have triage stages without confirmed_at (may be OK if field is optional)
Summary
This is a solid, well-tested feature branch that:
Adds structured evidence parsing with YAML + legacy fallback
Hardens triage validation across all stages
Fixes a critical issue: mid-cycle scans now correctly skip destructive operations
Maintains backward compatibility for evidence formats
The only concern is confirming that confirmed_at is actually being set when stages are confirmed. Recommend a quick grep search for where confirmed_at is set in stage handlers.
confirmed_at
Based on my comprehensive search of the codebase, confirmed_at IS actively written by production code when a stage is confirmed. Here are the production code locations where it's being SET:
Direct Writes (utc_now() calls):
confirmations_shared.py:75 - Main confirmation handler
stages[stage]["confirmed_at"] = utc_now()
Called by finalize_stage_confirmation() for any stage confirmation
Used by: confirm_observe, confirm_reflect, confirm_organize, confirm_enrich, confirm_sense_check
_stage_validation.py:92 - Auto-confirm during fold-confirm operations
stage_record["confirmed_at"] = utc_now()
Called by _auto_confirm_stage() for inline attestation-based confirmations
Used when: --attestation flag is passed during stage recording (e.g., organize, enrich, sense-check)
All call: confirmations_shared.py:finalize_stage_confirmation()
Which calls: stages[stage]["confirmed_at"] = utc_now() at line 75
Alternatively, when using fold-confirm (--attestation inline with --stage):
User runs: desloppify plan triage --stage organize --report "..." --attestation "..."
Stage handler calls: _auto_confirm_stage() in _stage_validation.py
Which sets: stage_record["confirmed_at"] = utc_now() at line 92
Bottom line:confirmed_at is 100% written by production code during normal triage flows. It's not just in tests.
Perfect. Now I have all the information I need. Let me provide you with a comprehensive analysis of the three concerns:
Analysis of Uncommitted Changes
I've reviewed all four files and the git diffs. Here are my findings on your three concerns:
Concern 1: Preflight Behavior Change (Blocks ANY queue items, not just objective)
Status: INTENTIONAL and WELL-DOCUMENTED
The behavior change is explicit and properly commented:
Before:
python
if mode is not ScoreDisplayMode.FROZEN:
return # No objective work remains, scan allowed
remaining = breakdown.objective_actionable
After:
python
if mode is ScoreDisplayMode.LIVE:
return # Queue fully clear or no active cycle — scan allowed
remaining = breakdown.queue_total # Now blocks on ANY items
Key justification (lines 55-58):
python
# Count plan-aware remaining items. Block scan when ANY queue items
# remain (objective OR subjective). Mid-cycle scans regenerate issue
# IDs which wipes triage state and re-clusters the queue, undoing
# prioritisation work.
This is a principled change: Mid-cycle scans with subjective items in the queue would lose triage work because sync_triage_needed() and auto_cluster_issues() both regenerate queue structure. The gate now prevents this data loss.
Note: The force-rescan path was also refactored. The plan-start score clearing moved from preflight.py (temporary, lossy) to plan_reconcile.py → _reset_cycle_for_force_rescan() (comprehensive, durable). See next concern.
Status: DESIGN IS SOUND, but relies on orchestration
The new approach moved score clearing into _reset_cycle_for_force_rescan() (lines 39-68 of plan_reconcile.py), which runs before any other reconciliation:
python
# In reconcile_plan_post_scan (line 526):
dirty = _reset_cycle_for_force_rescan(plan) if force_rescan else False
# Then proceeds with other reconciliation steps
dirty = _sync_post_scan_without_policy(plan=plan, state=runtime.state) or dirty
Key guarantees:
Early execution: _reset_cycle_for_force_rescan() runs first, before any policy computation (which could fail)
Safe design: Returns a bool and modifies the plan dict directly (idempotent)
Potential weakness: If reconciliation's save_plan() call fails (lines 546-549), the cleared scores are still in the in-memory plan dict. However:
Clearing scores is not reversible anyway
The function logs a warning and returns
On next scan, the plan reloads from disk (scores would be restored from disk if save failed)
The preflight gate checks plan.get("plan_start_scores"), so even if save fails, the next scan would see empty scores from the failed attempt
Risk mitigation: The current design is sound because:
_reset_cycle_for_force_rescan() is idempotent
Reconciliation happens post-scan, so stale metadata is harmless if save fails
Next scan's preflight would allow rescanning anyway
Concern 3: Mid-cycle Logic Spread - Comments Linking It Together
Status: WELL-DOCUMENTED, with one central definition
You have a single source of truth: _sync_context.py
python
def is_mid_cycle(plan: PlanModel) -> bool:
"""True when a queue cycle is in progress.
A cycle is active when ``plan_start_scores`` is set to real score
values. The ``{"reset": True}`` sentinel (set by lifecycle reset)
does NOT count as mid-cycle — it means "seed real scores on next scan".
"""
scores = plan.get("plan_start_scores")
return bool(scores) and not (isinstance(scores, dict) and scores.get("reset"))
"auto-clustering and triage injection... regenerate queue structure and issue IDs, which wipes triage state and reorders the queue. They only run at cycle boundaries"
sync_triage.py lines 164-167 explains the deferred injection strategy:
"Triage injection itself is safe (appends to back of queue), but auto-clustering (guarded separately in plan_reconcile.py) would regenerate queue structure if triggered mid-cycle."
⚠️ Issue Found:_is_mid_cycle_scan() in plan_reconcile.py (lines 438-451) duplicates the logic from _sync_context.is_mid_cycle(). They're not identical:
python
# plan_reconcile.py version (EXTENDED):
def _is_mid_cycle_scan(plan: dict[str, object], state: state_mod.StateModel) -> bool:
if not plan.get("plan_start_scores"):
return False # No active cycle
order = plan.get("queue_order", [])
skipped = plan.get("skipped", {})
active_items = [item for item in order if item not in skipped]
return len(active_items) > 0 # Also checks queue is non-empty
# _sync_context.py version (STRICTER):
def is_mid_cycle(plan: PlanModel) -> bool:
scores = plan.get("plan_start_scores")
return bool(scores) and not (isinstance(scores, dict) and scores.get("reset"))
The plan_reconcile.py version adds an extra check for active queue items, while the _sync_context version only checks scores. This is intentional (prevents clustering when queue is non-empty) but introduces duplication risk. The cross-reference comment in sync_triage.py line 166 somewhat mitigates this by explicitly noting the dependency:
"auto-clustering (guarded separately in plan_reconcile.py)"
Summary Table
Concern
Finding
Risk Level
Preflight blocks ANY items
Intentional, well-commented, prevents triage/cluster data loss
Single source of truth (_sync_context.is_mid_cycle) with cross-file comments. ONE duplication in plan_reconcile.py
Low — duplication documented, but maintenance risk exists
Recommendation: The mid-cycle duplication in plan_reconcile.py lines 438-451 could be removed by importing is_mid_cycle from _sync_context and adding the extra queue check as a separate condition. This would reduce maintenance burden.