I need to understand the current postflight lifecycle architecture in desloppify. Thoroughly explore these areas:
Work queue system: Read all files in desloppify/engine/_work_queue/ — especially snapshot.py, synthetic.py, synthetic_workflow.py, types.py, ranking.py, finalize.py
Plan sync/triage: Read desloppify/engine/_plan/sync/pipeline.py, desloppify/engine/_plan/sync/triage.py, desloppify/engine/_plan/sync/workflow.py
Based on my thorough exploration of the codebase, here's the complete picture of how queue contents flow from scan through review, score, triage, and execute:
_seed_plan_start_scores() — Freeze baseline when cycle begins (objective work exists)
_clear_plan_start_scores_if_queue_empty() — Unfreeze when queue drains (all work done)
_mark_postflight_scan_completed_if_ready() — Record completion once import scores are trusted
Key insight: Plan-start scores freeze only when an objective cycle is detected. Once the cycle drains and communicate-score has been resolved, the baseline is cleared and score unfreezes for reveal.
Frozen score semantics: Baseline is frozen only when objective work exists AND communicate-score hasn't run. Score unfreezes once queue drains completely.
Triage gating: Triage stages only inject when objective backlog is empty OR deferral escalates after repeated failures to drain.
Review import integration: Review imports trigger boundary reconciliation, ensuring workflow items (score gates, triage stages) surface at the right time.
Plan atomicity: All mutations are collected and saved in one atomic save, with execution_log entries for audit.
Files (absolute paths) documenting this architecture:
Perfect! Now I have a comprehensive view of the existing test patterns. Let me create a detailed summary document.
Key Test Patterns Summary: Postflight Queue Lifecycle
Based on reading the three test files and related fixtures, here are the established patterns and helper functions for testing postflight queue lifecycle:
from desloppify.engine._plan.operations.lifecycle import purge_ids
purge_ids(plan, [fid1, fid2, ...])
Purpose: Remove completed items from queue_order (simulates plan resolve)
Pattern: Mutates plan in place; no return value
Note: Not a test helper, but core operation used in integration tests
Reuse this: For marking items as done between queue queries
7. Assertion Patterns
From test_lifecycle_transitions.py:
python
# Check queue is only initial reviews
assert all(fid.startswith("subjective::") for fid in ids)
assert len(ids) == len(DIM_KEYS)
# Check queue ordering invariants
assert ids.index(WORKFLOW_COMMUNICATE_SCORE_ID) < ids.index(WORKFLOW_CREATE_PLAN_ID)
# Check triage injection
assert all(sid in plan["queue_order"] for sid in TRIAGE_STAGE_IDS)
assert not any(fid.startswith("triage::") for fid in ids) # hidden during execute
# Check plan completion markers
assert plan["epic_triage_meta"]["triaged_ids"] == sorted([...])
assert not plan["epic_triage_meta"].get("triage_recommended")
# Workflow item ordering
workflow_ids = [fid for fid in ids if fid.startswith("workflow::")]
assert len(workflow_ids) > 0
In sync_plan_after_import() (line 233), the flow is:
_sync_review_delta() — appends review::xxx IDs to plan["queue_order"]
sync_import_scores_needed() — may inject workflow items
live_planned_queue_empty(plan) check — BUG: now returns False because review IDs were appended
reconcile_plan() is skipped
Fix: Capture was_boundary_ready = live_planned_queue_empty(plan) BEFORE step 1. Use was_boundary_ready and trusted as the gate for reconcile instead of post-mutation check.
Bug 2: Covered subjective placeholders not pruned after import
When a trusted review import covers dimensions (e.g., naming_quality), the matching subjective::naming-quality IDs should be removed from plan["queue_order"]. Currently they're not.
The _build_import_sync_inputs() function (line 154) already computes covered_ids as subjective::<dim_key> for each assessment key. We just need to actually remove them from queue_order and auto-cluster membership.
Fix: Add a pruning step that removes sync_inputs.covered_ids from queue_order and auto-cluster issue_ids. Create a shared helper for this.
Trusted import updates state, marking some dims with needs_review_refresh=True (because open review findings exist for that dimension)
all_subjective_entries() in scorecard_projection.py (line 116-120) computes stale=True when assessments[dim_key].get("needs_review_refresh") is True
current_stale_ids() includes these dims
sync_subjective_dimensions() injects subjective::xxx for these stale dims during reconcile
_phase_for_snapshot() sees postflight_assessment_items and picks PHASE_ASSESSMENT_POSTFLIGHT over PHASE_WORKFLOW_POSTFLIGHT
This is a layered bug fixed by a combination of:
Fix 4 (persisted phase wins) prevents the rendering layer from showing assessment items during workflow
Fix 5 (phase transition cleanup) prevents stale subjective items from remaining in queue_order after workflow items are injected
But we also need a guard in build_subjective_items() or _subjective_partitions(): when lifecycle phase is "workflow" or "triage", suppress postflight assessment items from the execution view. The data stays available in backlog.
The simplest approach: in _subjective_partitions() in snapshot.py, check the persisted lifecycle phase. If it's "workflow" or "triage", return empty postflight list (initial review items pass through since they override everything).
Bug 4: Phase selection overrides persisted lifecycle too aggressively
File: desloppify/engine/_work_queue/snapshot.py
In _phase_for_snapshot() (line 258), the postflight_sticky block checks items in this order:
python
if postflight_assessment_items: return PHASE_ASSESSMENT_POSTFLIGHT
if postflight_workflow_items: return PHASE_WORKFLOW_POSTFLIGHT
if triage_items: return PHASE_TRIAGE_POSTFLIGHT
Assessment ALWAYS wins over workflow, even when the persisted phase says "workflow". The persisted phase (from current_lifecycle_phase(plan)) is computed but only used to gate postflight_sticky, not to prioritize phases.
Fix: When postflight_sticky is True and persisted_phase is valid:
If persisted_phase is "workflow" and postflight_workflow_items exist → PHASE_WORKFLOW_POSTFLIGHT
If persisted_phase is "triage" and triage_items exist → PHASE_TRIAGE_POSTFLIGHT
Fall through to partition-based inference only when persisted phase doesn't match available items
The persisted phase values are coarse: "review", "workflow", "triage", "execute", "scan"
The snapshot phases are fine-grained: PHASE_REVIEW_INITIAL, PHASE_ASSESSMENT_POSTFLIGHT, etc.
For "review" persisted phase, keep existing partition-based inference (initial vs assessment vs review-postflight).
Fix 5: Normalize synthetic cleanup at phase transitions
File: desloppify/engine/_plan/sync/pipeline.py
After _persist_lifecycle() runs in reconcile_plan(), add a cleanup step:
If phase is "workflow": remove subjective::... IDs from queue_order (they were assessment work, now superseded)
If phase is "triage": remove remaining subjective::... IDs + completed workflow IDs
If phase is "execute": remove triage::... IDs + workflow::... IDs
This uses the same pruning logic as fix #2 but triggered by phase transition instead of import.
Create a shared function like prune_synthetic_for_phase(plan, phase) that can be called from both the reconcile pipeline and import sync.
PHASE_ASSESSMENT_POSTFLIGHT, PHASE_WORKFLOW_POSTFLIGHT, PHASE_TRIAGE_POSTFLIGHT, etc.
Plan model: dict with keys queue_order (list[str]), skipped (dict), clusters (dict), refresh_state (dict), etc.
Design questions
Where should prune_synthetic_for_phase() live? Options: constants.py (already has synthetic helpers), pipeline.py (where it's primarily used), or a new cleanup.py in the sync package.
For fix 3's rendering guard: should it be in _subjective_partitions() (filters items before phase selection), build_queue_snapshot() (has plan access), or _phase_for_snapshot() (already makes phase decisions)?
Should fix 5's cleanup prune ALL subjective IDs or only the ones that correspond to "covered" dimensions? The plan says "entering workflow prunes covered subjective IDs" but the reconcile pipeline doesn't have the import's covered-dimension info. It would need to derive it (e.g., prune all non-unscored subjective IDs).
Please design a concrete implementation plan with specific code changes for each file, considering these design questions.
Now I have a complete picture of the codebase. Let me provide the implementation plan.
Implementation Plan: 5 Postflight Queue Bug Fixes
Design Decisions (answers to the 3 questions)
Q1: Where should prune_synthetic_for_phase() live?
It should live in a new file desloppify/engine/_plan/sync/phase_cleanup.py. Rationale: constants.py is for data constants and simple predicate functions; pipeline.py orchestrates the reconcile flow and should call cleanup but not define it; a dedicated module in the sync package follows the existing pattern (there is already auto_prune.py, dimensions.py, etc.). The import sync in plan_sync.py can also import from this module for the shared pruning helper.
Q2: Where should Fix 3's rendering guard go?
In _subjective_partitions() in snapshot.py. This is the right layer because: (a) it filters items before phase selection, preventing the cascade where stale items cause wrong phase inference; (b) _subjective_partitions already has access to state and can accept the plan as an additional parameter; (c) it keeps _phase_for_snapshot clean -- that function reasons about what phase to pick given items, not about which items should exist.
Q3: Should Fix 5 prune ALL subjective IDs or only covered ones?
Prune ALL subjective IDs when entering workflow phase. At the reconcile pipeline level, we don't have import-specific "covered" info. But entering workflow means the scoring/workflow gates have been injected, which means assessment is done. Any remaining subjective:: IDs are leftover artifacts. The phase transition is the semantic boundary. This is both simpler and more correct than trying to derive coverage.
Fix 1: Boundary check captured before mutation (already fixed)
Looking at the current code in plan_sync.py (lines 318, 337), this is already fixed in the working tree. Line 318 captures was_boundary_ready = live_planned_queue_empty(plan) before _sync_review_delta on line 320, and line 337 uses was_boundary_ready as the gate. No further work needed.
Fix 2: Covered subjective placeholders pruned after import (already fixed)
Looking at lines 200-240 and 321-325 in plan_sync.py, the _prune_covered_subjective_ids_from_plan() function already exists and is called at line 321-325. It removes covered IDs from queue_order, overrides, and cluster issue_ids. This is already implemented. No further work needed.
Fix 3: Suppress same-cycle stale re-request in rendering
Current state of the code: build_subjective_items() in synthetic.py already has a _suppressed_same_cycle_refresh() inner function (lines 230-245) that does exactly this guard. It checks if current_phase is workflow or triage, and if the dimension's assessed_at timestamp is >= the latest trusted audit timestamp, it suppresses the item (line 279: if _suppressed_same_cycle_refresh(dim_key, stale=is_stale): continue).
However, build_subjective_items() receives plan as an optional kwarg, and the call site in _subjective_partitions() (snapshot.py line 224) does not pass plan:
The plan is never forwarded, so current_phase in build_subjective_items() resolves to None, and the suppression check is dead code in the snapshot path.
Looking at _phase_for_snapshot() lines 287-320, the postflight_sticky block already branches on persisted_phase:
Lines 288-298: persisted_phase == LIFECYCLE_PHASE_WORKFLOW -- workflow items checked first, then triage, then assessment
Lines 299-309: persisted_phase == LIFECYCLE_PHASE_TRIAGE -- triage items checked first, then workflow, then assessment
Lines 310-320: else (review) -- assessment first, then review, then workflow, then triage
This is already fixed in the working tree. The persisted phase correctly prioritizes the matching phase's items. No further work needed.
Fix 5: Phase-transition synthetic cleanup
This is the one remaining substantial change needed. After _persist_lifecycle() runs in reconcile_plan(), stale synthetic IDs from prior phases should be pruned.
New file: /Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/sync/phase_cleanup.py
python
"""Prune synthetic queue IDs that belong to prior lifecycle phases."""
from desloppify.engine._plan.constants import (
SUBJECTIVE_PREFIX,
TRIAGE_PREFIX,
WORKFLOW_PREFIX,
)
from desloppify.engine._plan.refresh_lifecycle import (
LIFECYCLE_PHASE_EXECUTE,
LIFECYCLE_PHASE_TRIAGE,
LIFECYCLE_PHASE_WORKFLOW,
)
def prune_synthetic_for_phase(plan: dict, phase: str) -> list[str]:
"""Remove synthetic IDs from queue_order that are superseded by *phase*.
Returns list of pruned IDs (empty if nothing changed).
"""
order = plan.get("queue_order")
if not isinstance(order, list):
return []
remove_prefixes: tuple[str, ...] = ()
if phase == LIFECYCLE_PHASE_WORKFLOW:
remove_prefixes = (SUBJECTIVE_PREFIX,)
elif phase == LIFECYCLE_PHASE_TRIAGE:
remove_prefixes = (SUBJECTIVE_PREFIX, WORKFLOW_PREFIX)
elif phase == LIFECYCLE_PHASE_EXECUTE:
remove_prefixes = (SUBJECTIVE_PREFIX, WORKFLOW_PREFIX, TRIAGE_PREFIX)
if not remove_prefixes:
return []
pruned = [
issue_id for issue_id in order
if isinstance(issue_id, str) and issue_id.startswith(remove_prefixes)
]
if not pruned:
return []
pruned_set = set(pruned)
order[:] = [issue_id for issue_id in order if issue_id not in pruned_set]
# Also prune from cluster issue_ids
for cluster in plan.get("clusters", {}).values():
if not isinstance(cluster, dict):
continue
issue_ids = cluster.get("issue_ids")
if not isinstance(issue_ids, list):
continue
cluster["issue_ids"] = [
issue_id for issue_id in issue_ids
if issue_id not in pruned_set
]
return pruned
In reconcile_plan(), after the _persist_lifecycle() call (line 163), add the cleanup step:
python
from desloppify.engine._plan.sync.phase_cleanup import prune_synthetic_for_phase
# After line 167 (lifecycle_phase_changed logging):
phase_pruned = prune_synthetic_for_phase(plan, result.lifecycle_phase)
if phase_pruned:
_log_gate_changes(
plan,
"phase_transition_cleanup",
{"phase": result.lifecycle_phase, "pruned": phase_pruned},
)
The ReconcileResult dataclass does not need a new field for this; the pruned IDs are logged, and dirty will already be True because lifecycle_phase_changed would be True (phase transitions only prune when the phase actually changed -- if the phase stays the same, no pruning happens since it was already cleaned up on the prior transition).
Wait -- there is an edge case: prune_synthetic_for_phase should also run when the phase did NOT change (e.g., if cleanup was missed in a prior cycle). But dirty needs to reflect this. Let me revise:
Add a phase_cleanup_pruned: list[str] field to ReconcileResult:
python
@dataclass
class ReconcileResult:
subjective: QueueSyncResult | None = None
auto_cluster_changes: int = 0
communicate_score: QueueSyncResult | None = None
create_plan: QueueSyncResult | None = None
triage: QueueSyncResult | None = None
lifecycle_phase: str = ""
lifecycle_phase_changed: bool = False
phase_cleanup_pruned: list[str] | None = None # NEW
@property
def dirty(self) -> bool:
return any(
(
self.subjective is not None and bool(self.subjective.changes),
self.auto_cluster_changes > 0,
self.communicate_score is not None
and bool(self.communicate_score.changes),
self.create_plan is not None
and bool(self.create_plan.changes),
self.triage is not None
and bool(
self.triage.changes
or getattr(self.triage, "deferred", False)
),
self.lifecycle_phase_changed,
bool(self.phase_cleanup_pruned), # NEW
)
)
And in reconcile_plan(), always run cleanup after lifecycle persist:
Update __init__.py: Add phase_cleanup to the __all__ list in /Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/sync/__init__.py.
Summary of actual changes needed
Only 2 bugs remain unfixed in the working tree. Bugs 1, 2, and 4 are already resolved.
Fix
Status
Files to change
Bug 1 (boundary check timing)
Already fixed
None
Bug 2 (covered subjective pruning)
Already fixed
None
Bug 3 (stale re-request)
Needs fix
snapshot.py (2-line change: add plan param, forward it)
Bug 4 (phase priority)
Already fixed
None
Fix 5 (phase transition cleanup)
Needs fix
New phase_cleanup.py, modify pipeline.py (add call + result field), update __init__.py
Testing approach
Fix 3 test: In the existing test files for snapshot/queue behavior, create a test that:
Builds state with a dimension that has needs_review_refresh=True and a recent assessed_at
Sets plan lifecycle phase to "workflow"
Calls build_queue_snapshot() with that plan
Asserts that the stale dimension does NOT appear in postflight_assessment_items
Fix 5 test:
Build a plan with subjective:: IDs in queue_order
Call prune_synthetic_for_phase(plan, "workflow")
Assert all subjective:: IDs removed, non-subjective IDs preserved
Repeat for "triage" (removes subjective + workflow) and "execute" (removes all synthetic)
Test that cluster issue_ids are also cleaned
Critical Files for Implementation
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_work_queue/snapshot.py - Fix 3: forward plan to _subjective_partitions() so lifecycle-aware suppression works
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/sync/phase_cleanup.py - Fix 5: new module with prune_synthetic_for_phase() shared helper
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_work_queue/synthetic.py - Reference: contains the _suppressed_same_cycle_refresh guard that Fix 3 activates
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/constants.py - Reference: synthetic prefix constants used by Fix 5