I need to understand how "planning mode" currently works in desloppify vs the regular work queue. Explore these areas thoroughly:
The planning system: desloppify/engine/planning/ - what are the stages/steps of planning mode? How does it flow?
The work queue system: desloppify/engine/_work_queue/ - how are items structured, ranked, and surfaced?
The plan system: desloppify/engine/_plan/ and desloppify/engine/plan.py - how does the plan (ordered queue, clusters, etc.) work?
How next command surfaces items: desloppify/app/commands/next.py and next_parts/
The cluster concept: how clusters work in the plan system
How the queue interacts with the plan
Key questions:
What are the distinct stages/steps of planning mode?
How is a work queue item structured (what fields)?
How do clusters group items?
Is there already any concept of "meta-tasks" or "workflow stages" in the queue?
How does next decide what to show?
Be very thorough - read the core files in full.
Assistant
I'll conduct a thorough exploration of the planning and work queue systems in desloppify. Let me start by examining the key directories and files.
Assistant
Now let me examine the work queue and plan systems:
Assistant
Now let me read the core files. I'll start with the planning system, work queue schema, and plan schema:
Assistant
Now let me read the planning core, render, select and scan modules:
Assistant
Now let me read the work queue core system:
Assistant
Now let me read the plan schema and main plan module:
Assistant
Let me continue with ranking, helpers, and the next command:
Assistant
Now let me read the next command and its rendering:
Assistant
Now let me explore the plan command structure and reconciliation system:
Assistant
Let me read more of the stale_dimensions module and then check the plan command:
Assistant
Now let me look at the auto_cluster and operations to understand how clusters are created and manipulated:
Assistant
Let me check the rendering of items in the next command:
Assistant
Let me check the synthesis-related features since they appear to be important meta-tasks:
Assistant
Let me check the synthesis item creation and the epic synthesis system:
Assistant
Now let me find and read the build_synthesis_item function:
Assistant
Let me read the full build_synthesis_item function:
Assistant
Perfect! Now let me create a comprehensive summary document by examining one more key area - how the queue items flow through and any documentation:
Assistant
User
I need to deeply understand how the current gate phases, synthesis workflow, and review cycle work in desloppify so we can migrate them to a unified queue system. Be VERY thorough — read files in full.
Focus areas:
Gate phases — How they're derived and used:
desloppify/engine/_work_queue/core.py — find _derive_gate_phase() and understand all gate logic, gate_phase field on WorkQueueResult, how gates interact with item filtering
How gates are consumed in desloppify/app/commands/next.py and
Assistant
I'll conduct a thorough analysis of the gate phases, synthesis workflow, and review cycle. Let me start by examining the core files systematically.
Assistant
Now let me read the next.py and status files to see how gates are consumed:
Assistant
Now let me examine the stale_dimensions and reconcile files to understand how synthesis and review items are created:
Assistant
Now let me look at the review command structure and synthesis workflow:
User
I need to deeply understand how queue items are rendered, resolved, and how the next/show/status commands consume them in desloppify. Read files in FULL.
Focus areas:
Item rendering in next command:
desloppify/app/commands/next.py — full file, understand the complete flow
desloppify/app/commands/next_parts/render.py — how different item kinds are rendered (findings, clusters, subjective, synthesis)
Let me read the full synthesize_handlers file and explore related files:
Assistant
I'll systematically read through all the files you've specified to give you a complete understanding of how queue items flow through the system. Let me start by reading these files in parallel.
Assistant
Let me read more critical files about the ranking and synthesis:
Assistant
Now let me continue reading the remaining files:
Assistant
Now let me examine plan operations and the operations module more closely:
Assistant
Now let me get more details on the operations module, particularly around gate and synthesis:
Assistant
Now let me continue with the work queue and plan-related files:
User
I need to understand the EXACT user-facing flow for synthesis and review in desloppify. Read files in FULL.
Synthesis stages — exact flow:
Read ALL files in desloppify/app/commands/plan/synthesis/ directory
No persistence of items — all synthetic items are ephemeral, regenerated per queue build from state + plan.
10. KEY CONFIGURATION & FLAGS
QueueBuildOptions:
python
@dataclass(frozen=True)
class QueueBuildOptions:
count: int | None = 1
scan_path: str | None = None
scope: str | None = None
status: str = "open" # Filter by status
include_subjective: bool = True # Include review items
subjective_threshold: float = 100.0 # Min score to include
chronic: bool = False # Only reopen_count >= 2
explain: bool = False # Ranking explanation
plan: dict | None = None # Living plan reference
include_skipped: bool = False # Show skipped items
cluster: str | None = None # Drill into specific cluster
collapse_clusters: bool = True # Collapse auto-clusters
WorkQueueResult (TypedDict):
python
{
"items": list[dict], # Final ranked items
"total": int, # Total before count limit
"grouped": dict[str, list[dict]], # By detector/kind
"suppressed_count": int, # Subjective items gated by backlog
"new_ids": set[str], # IDs added in latest scan
"gate_phase": str | None, # "needs_review" | "needs_plan" | None
"plan_dirty": bool, # Whether pending_plan_gate was set
}
SUMMARY FOR MIGRATION
To migrate to a unified queue system, key contracts to preserve:
Gate mechanism must run AFTER all items collected, BEFORE final ranking
Synthetic items (subjective, synthesis) must be ephemeral — regenerated per build
Cascade clear logic for synthesis stages when earlier stages re-edited
Hash-based synthesis trigger tied to review finding snapshot changes
Backlog-gated suppression of review-only items while objective work exists
Promoted-item barrier for unscored + stale dimension injection
Reconciliation must happen before any dimension sync
pending_plan_gate flag as single gate state marker (review→plan transition)
All ranking, interleaving, clustering, and filtering happens within the queue build, making it amenable to unified treatment.
Now I have enough information to provide a comprehensive answer. Let me compile the complete user-facing flow documentation based on all the files I've read.
Complete User-Facing Flow Documentation
Based on my thorough exploration of the codebase, here is the exact user-facing flow for synthesis, review, and scan workflows:
1. SYNTHESIS FLOW — Exact User Commands
The synthesis system uses a 4-stage workflow: OBSERVE → REFLECT → ORGANIZE → COMMIT with a fast-track CONFIRM-EXISTING skip path.
Synthesis enters the queue as synthesis::pending:
Auto-injected when first running --stage observe (if not already in queue)
Auto-injected by sync_synthesis_needed() when review finding snapshot hash changes
Never auto-pruned—only explicit completion removes it
T1 priority tier
Stage 1: OBSERVE
bash
desloppify plan synthesize --stage observe --report "analysis of themes and root causes..."
Validation: Report must be 50+ chars (≤3 findings) or 100+ chars (4+ findings)
No citation gate — just requires genuine analysis, not ID-stuffing
Auto-start: Injects synthesis::pending if not present
Jump-back: Reuses existing report if no --report provided (preserves confirmation if it existed)
Output: Stores in plan.epic_synthesis_meta.synthesis_stages.observe
Stage 2: REFLECT
bash
desloppify plan synthesize --stage reflect --report "comparison against completed work..."
Prerequisites: Must have observe stage complete
Validation: Report must be 50+ or 100+ chars; if recurring patterns detected, report MUST mention at least one recurring dimension name
Fold-confirm: Can pass --attestation (80+ chars min) to auto-confirm observe inline
Recurring patterns detection: Compares open findings against previously resolved ones
Output: Stores in synthesis_stages.reflect + recurring dimension list
Stage 3: ORGANIZE
bash
desloppify plan cluster create <name> --description "..."
desloppify plan cluster add <name> <finding-patterns>
desloppify plan cluster update <name> --description "..." --steps "step 1" "step 2"
desloppify plan synthesize --stage organize --report "summary of organization..."
Prerequisites: Must have reflect stage complete
Structural validation: Each manual (non-auto) cluster MUST have:
description (text)
action_steps (list of at least 1 step)
Report validation: Must be 100+ chars minimum
Fold-confirm: Can auto-confirm reflect if --attestation provided (80+ chars)
Output: Stores in synthesis_stages.organize
Stage 4: COMMIT/COMPLETE
bash
desloppify plan synthesize --complete --strategy "execution plan describing priorities..."
Prerequisites: Must have organize stage confirmed
Validation:
--strategy required (200+ chars OR special value "same" to reuse prior strategy)
Re-validates cluster enrichment at completion time
Checks that clusters exist and have findings
Fold-confirm: Can auto-confirm organize if --attestation provided
On completion:
Removes synthesis::pending from queue
Clears synthesis_stages dict (archives to last_synthesis)
Records finding_snapshot_hash (hash of open review finding IDs)
Records synthesized_ids (list of open review IDs at completion)
Stores strategy_summary
Records last_completed_at timestamp
Appends execution_log entry
Fast-track: CONFIRM-EXISTING (skip full flow)
bash
desloppify plan synthesize --confirm-existing \
--note "why plan is still valid..." \
--strategy "same" \
--confirmed "I validate this plan..."
Prerequisites: Prior synthesis must have completed (must have strategy_summary in meta)
Auto-path (light): If only additions since last synthesis (no resolved findings):
Skips observe + reflect requirement
Shows new findings for review
Defaults --strategy to "same"
Mixed-path (full): If findings resolved AND new findings added:
Requires observe + reflect stages
Validations:
--note must be 100+ chars minimum
--confirmed must be 80+ chars minimum
If new findings exist, --note must cite at least 1 new finding ID
Must have enriched clusters (same rules as full path)
Confirmation Workflow (attestation gates each stage)
bash
desloppify plan synthesize --confirm observe --attestation "I have reviewed..."
desloppify plan synthesize --confirm reflect --attestation "I have reviewed..."
desloppify plan synthesize --confirm organize --attestation "I have reviewed..."
Flow: Each stage must be confirmed before next stage can proceed
Attestation: 80+ chars minimum; must reference:
OBSERVE: at least one dimension name
REFLECT: at least one dimension OR cluster name
ORGANIZE: at least one cluster name
Cascade clear: When re-recording a stage, all confirmations on later stages are cleared
Jump-back: Can re-record earlier stages; report reused if no --report provided
Manual Start (Override)
bash
desloppify plan synthesize --start
Injects synthesis::pending at front of queue
Clears any existing stages (fresh start)
Useful for restarting synthesis from scratch
Dashboard View (No args)
bash
desloppify plan synthesize
Shows current synthesis state
Displays findings by dimension
Shows stage progress with enrichment gaps
Shows next command guidance based on current state
QueueBreakdown(
queue_total=1934,
plan_ordered=292, # Items in queue_order minus skipped
skipped=23, # In plan.skipped dict
subjective=15, # subjective::<slug> items
suppressed=8, # Hidden by noise budget
focus_cluster="fix-naming",
focus_cluster_count=10, # Remaining in cluster
focus_cluster_total=25, # Total in cluster
)
Frozen Score Display (when plan active)
plan_start_scores.strict frozen at queue start
Shown alongside queue breakdown
"Score will not update until queue is clear and you run desloppify scan"
Only shown when queue items remain
Show Commands
bash
desloppify plan queue # View plan order
desloppify plan queue --sort recent # Newest first
desloppify plan show # Summary metadata
desloppify plan focus --cluster <name> # Focus on one cluster
desloppify plan focus --clear # Clear focus
Confirmed-existing — Light path for additions only; full path for mixed changes
Artifact archival — Stages archived to last_synthesis on completion
This is the complete, exact user-facing contract for synthesis, review, and scan workflows. The unified queue must preserve these interfaces unchanged.
Perfect! Now I have a comprehensive understanding of the system. Let me create a detailed summary document of all the findings:
Summary: Queue Item Rendering, Resolution, and Consumption Flow in Desloppify
I've thoroughly read through all the key files you specified. Here's a comprehensive deep-dive covering how queue items flow through the system:
Cluster meta-items get kind="cluster", members, member_count, primary_command
Regular findings get all finding fields plus plan metadata (queue_position, plan_description, plan_cluster, plan_skipped, plan_skip_kind, plan_skip_reason)
Output modes: Terminal (rich), JSON, Markdown
2. SHOW COMMAND
File: show/cmd.py (dispatcher)
Entity resolution (resolve_entity()):
Check special views: "concerns", "subjective", "subjective_review"
Plan: purge_ids() removes from queue_order + all clusters
Execution log: Appends "done" or "resolve" entry
Query output: Updated via resolve command's _write_resolve_query_entry()
When a finding is skipped:
Plan: Added to plan.skipped[id] with kind + reason + attestation
State (permanent/false_positive): Also marks in findings
Queue: Skipped items shown last (or hidden if include_skipped=False)
Execution log: "skip" entry
When items are reordered (plan move):
Plan: queue_order list reordered
Queue: Next builds respect this order
New items: Sorted after existing remaining items
Execution log: "move" entry
When items are clustered:
Plan: clusters[name].finding_ids = members
Queue: If collapse_clusters=True and no drill-in, members replaced with meta-item
Meta-item sort: By action_type then member count
Execution log: "cluster" entry
9. ITEM LIFECYCLE SUMMARY
code
FINDING (raw from state)
↓ build_finding_items()
QUEUE ITEM (with computed fields: is_review, is_subjective, primary_command)
↓ sort by item_sort_key()
↓ apply_plan_order() [if plan active]
↓ _collapse_clusters() [if plan active & not drilling]
DISPLAY ITEM (with plan metadata: queue_position, plan_cluster, plan_description, plan_note)
↓ render_item() [terminal] or serialize_item() [JSON]
RENDERED (rich terminal UI / JSON payload / Markdown)
RESOLUTION FLOW:
user runs: plan done <id> / resolve <id> --status fixed
→ cmd_plan_done() / cmd_resolve()
→ state.findings[id].status = "fixed"
→ purge_ids(plan, [id])
→ append_log_entry("done" or "resolve")
→ save plan + state
→ next query omits this ID (not in state or marked complete)
10. CRITICAL INVARIANTS
Plan queue_order: Source of truth for ordering when plan active; new items sort after existing remaining items
Cluster collapse: Only happens if collapse_clusters=True AND plan active AND no explicit drill-in
Gate phases: "needs_review" blocks queue until reviews done; "needs_plan" blocks until plan runs
Skipped items: Hidden by default unless include_skipped=True
Synthesis item: Injected into queue_order if present; has kind="synthesis_needed"
Frozen scores: Captured at plan creation; displayed alongside live estimates to show progress
Plan purge: Removes IDs from queue_order + all cluster.finding_ids when items resolved
Execution log: Immutable audit trail; capped at config value (default 10k entries)
This comprehensive system ensures:
Visibility: Users see ranked, plan-aware queues with rich context
Directionality: Plan enforces work sequence; queue order guard prevents skipping items
Auditability: All mutations logged with actor/timestamp
Recovery: Rollback snapshots on transactional failures; superseded tracking for remapped IDs
I need to design a migration plan for unifying all workflow modes (review cycle, plan gate, synthesis stages, findings) into a single queue system in desloppify. The user wants "planning mode" (currently called synthesis) to just inject its 4 stages as queue items that flow through the same next → do → resolve → next loop as regular findings.
Current Architecture
Gate Phases (to be eliminated)
_derive_gate_phase() in _work_queue/core.py returns "needs_review", "needs_plan", or None
"needs_review": blocks queue, shows only review items (initial onboarding or stale end-of-cycle)
"needs_plan": blocks queue entirely until plan command runs (set via pending_plan_gate boolean on plan)
Gate logic runs AFTER all items collected but BEFORE final ranking
render_gate_banner() in next_parts/render.py renders the gate messages
Gates bypass when --scope or --cluster specified
Synthesis (to become individual queue items)
Currently ONE item: synthesis::pending (kind="synthesis_needed")
Has 4 hidden stages: observe → reflect → organize → commit
Stage progress tracked in plan.epic_synthesis_meta.synthesis_stages dict
Each stage has: report, confirmed_at, confirmed_text, finding_count, cited_ids, timestamp
Plan creation becomes a queue item: workflow::create-plan
Review dimensions remain individual items but lose their gate behavior (just sort high)
One loop: next → do → resolve → next for ALL item kinds
Users can see everything: show, status, plan display all items regardless of kind
Users can reorder/skip anything: plan move, plan skip work on workflow/synthesis items
Backward compatible commands: existing commands like plan synthesize --stage observe still work; they just also auto-resolve the corresponding queue item
Key Design Questions to Address
Synthesis stage dependencies: How to handle observe→reflect→organize→commit ordering in the queue? Options:
a) Inject all 4 upfront, but next skips blocked ones (shows them grayed out in show)
b) Inject one at a time — when observe completes, inject reflect
c) Inject all 4, use a blocked_by field, blocked items hidden from next but visible in show
Auto-resolution: When should queue items auto-resolve?
Review items: when review import covers that dimension
Plan creation item: when user runs plan command
Synthesis stages: when stage report is submitted
Should auto-resolution happen in reconciliation or in the command handler?
Tier assignments for new item types:
Workflow items (create-plan): what tier?
Synthesis stages: what tier?
Review items: what tier? (currently gated, not tiered)
The pending_plan_gate boolean: Can it be fully replaced by the workflow::create-plan item?
Synthesis meta storage: Currently synthesis stage data lives in epic_synthesis_meta.synthesis_stages. Should this change or stay?
What "completing" a synthesis stage means in queue terms: Currently it's stored in meta. In the new model, should the stage ID be removed from queue_order? Or marked in a new structure?
Rendering: How should next render workflow/synthesis items differently from findings?
Inner synthesis flow: The synthesis stages have complex validation (min chars, citations, cluster enrichment). How does this map? The primary_command points to the same plan synthesize --stage X commands. The stage handler validates and completes. The queue item auto-resolves when the stage handler succeeds.
Please design a comprehensive, concrete implementation plan addressing all of these. Be specific about which files change, what functions are added/modified/removed, and the migration path. Consider edge cases and backward compatibility.
I now have a comprehensive understanding of the entire codebase. Let me produce the implementation plan.
Unified Queue System -- Implementation Plan
Design Decisions
1. Synthesis Stage Dependencies: Option (c) -- All 4 injected upfront with blocked_by
I recommend injecting all 4 synthesis stage items upfront into queue_order and introducing a blocked_by field. Rationale:
Visibility: Users can see all work ahead of them via show, plan queue, and status. Grayed-out/blocked stages communicate the full scope.
Reorderability: plan move and plan skip can target any stage item. Want to skip reflect? Skip it. Want to move organize before reflect for some reason? The system shows you that it is blocked.
Simplicity: No conditional injection logic. sync_synthesis_needed() injects all 4 at once. next simply filters out blocked items from the "current next item" but shows them in show.
The blocked_by field is a list[str] of queue item IDs on the queue item dict itself (not persisted in plan -- computed at queue build time from the dependency graph).
2. Auto-resolution Strategy
Auto-resolution happens in the command handler (not reconciliation). Each command that performs real work checks if any queue items should auto-resolve:
Review items (subjective::*): Auto-resolve when review --import or review --prepare covers that dimension. The import handler calls purge_ids() for the matching subjective::* ID.
Plan creation item (workflow::create-plan): Auto-resolve when plan command runs (already happens via pending_plan_gate = False; we make it explicit by purging the queue item).
Synthesis stages (synthesis::observe, etc.): Auto-resolve when the stage handler (_cmd_stage_observe etc.) succeeds. The handler calls purge_ids() for that specific ID.
Reconciliation (reconcile_plan_after_scan) continues to handle finding-ID churn but does not auto-resolve workflow items.
3. Tier Assignments
All workflow/synthesis items sort before regular findings but are internally ordered:
Item kind
Sort tuple
Rationale
synthesis::observe
(-2, 0, ...)
Synthesis blocks everything, observe is first
synthesis::reflect
(-2, 1, ...)
Second stage
synthesis::organize
(-2, 2, ...)
Third stage
synthesis::commit
(-2, 3, ...)
Fourth stage
workflow::create-plan
(-1, 0, ...)
After synthesis, before findings
subjective::*
(1, 1, ...)
Keep current behavior (interleaved with findings)
findings
(1, 0, ...)
Keep current behavior
clusters
(0, ...)
Keep current behavior
4. pending_plan_gate Replacement
Yes, pending_plan_gate is fully replaced by the workflow::create-plan queue item. When reviews complete and plan is needed, instead of setting a boolean, inject workflow::create-plan into queue_order. When plan runs, purge it.
5. Synthesis Meta Storage
Keep epic_synthesis_meta.synthesis_stages as-is for stage data (reports, confirmations, citations). The queue items are ephemeral queue entries that point to the real data in meta. This is exactly how synthesis::pending works today -- the queue item is synthetic, the real data is in meta.
The old synthesis::pending constant is replaced by the 4 individual IDs. A SYNTHESIS_IDS tuple replaces the SYNTHESIS_ID constant. A helper SYNTHESIS_PREFIX = "synthesis::" is used for matching.
7. Completing a Synthesis Stage
When a stage handler succeeds:
Stage data is written to epic_synthesis_meta.synthesis_stages (already happens)
The corresponding queue ID is removed from queue_order via purge_ids()
On completion of the final stage (commit), all 4 IDs are purged (any remaining)
8. Rendering
_render_item() in next_parts/render.py gets a new branch for kind == "workflow_stage" (synthesis stages) and kind == "workflow_action" (create-plan). These render:
Stage number and name
What this stage requires
The command to execute it
Whether it's blocked and by what
9. Inner Synthesis Flow
The existing plan synthesize --stage observe commands continue to work exactly as-is. They also auto-resolve the corresponding queue item on success. The primary_command on each synthesis stage queue item points directly to the existing command. No behavioral change to the stage handlers except adding the auto-resolve call at the end.
SYNTHESIS_PREFIX = "synthesis::"
SYNTHESIS_STAGE_IDS = (
"synthesis::observe",
"synthesis::reflect",
"synthesis::organize",
"synthesis::commit",
)
SYNTHESIS_IDS = set(SYNTHESIS_STAGE_IDS)
WORKFLOW_CREATE_PLAN_ID = "workflow::create-plan"
WORKFLOW_PREFIX = "workflow::"
# All "synthetic" IDs that are not real findings
SYNTHETIC_PREFIXES = ("synthesis::", "workflow::", "subjective::")
Update sync_synthesis_needed() to inject all 4 stage IDs instead of one synthesis::pending:
python
def sync_synthesis_needed(plan, state) -> SynthesisSyncResult:
# ... existing hash logic ...
if current_hash and current_hash != last_hash and not already_present:
insert_at = _after_promoted(order, plan)
for stage_id in reversed(SYNTHESIS_STAGE_IDS):
if stage_id not in order:
order.insert(insert_at, stage_id)
result.injected = True
return result
Add sync_create_plan_needed():
python
def sync_create_plan_needed(plan, state) -> bool:
"""Inject workflow::create-plan when reviews complete and plan hasn't run."""
# This replaces the pending_plan_gate boolean logic
order = plan["queue_order"]
if WORKFLOW_CREATE_PLAN_ID in order:
return False
# Check: are there review items that just completed?
# (Logic from _derive_gate_phase "needs_plan" condition)
...
In build_work_queue(), replace the build_synthesis_item call with:
python
if resolved_options.plan and status in {"open", "all"}:
synth_items = build_synthesis_stage_items(resolved_options.plan, state)
for si in synth_items:
all_items.append(si)
create_plan_item = build_create_plan_item(resolved_options.plan)
if create_plan_item:
all_items.append(create_plan_item)
In _apply_plan_order(), exclude blocked items from the "next" position but keep them in the list for show:
No change here -- blocked items stay in the list. The filtering happens in build_work_queue based on count slicing.
After sorting and plan ordering, filter blocked items from the "available next" subset:
python
# Filter blocked items from the top of the queue for "next" command
# (they remain visible in show/plan queue with blocked indicator)
available_items = [item for item in all_items if not item.get("is_blocked")]
Actually, the cleaner approach: the count slicing in build_work_queue already takes the first N items. We just need blocked items to sort AFTER unblocked ones at the same priority. The sort key already handles this with the blocked_penalty term.
But there's a subtlety: next --count 1 should skip blocked items entirely. So we need:
python
# Before count slicing, move blocked items to the end
unblocked = [item for item in all_items if not item.get("is_blocked")]
blocked = [item for item in all_items if item.get("is_blocked")]
all_items = unblocked + blocked
Update the exclusion set to include new synthetic prefixes:
python
referenced_ids = {
fid for fid in referenced_ids
if not fid.startswith(SUBJECTIVE_PREFIX)
and not fid.startswith("synthesis::")
and not fid.startswith("workflow::")
}
Add migration function _migrate_synthesis_pending_to_stages():
python
def _migrate_synthesis_pending_to_stages(plan):
"""Migrate v5 synthesis::pending to v6 individual stage IDs."""
order = plan.get("queue_order", [])
if "synthesis::pending" in order:
idx = order.index("synthesis::pending")
order.remove("synthesis::pending")
# Insert stage IDs in reverse so they end up in correct order
for stage_id in reversed(SYNTHESIS_STAGE_IDS):
order.insert(idx, stage_id)
def _migrate_plan_gate_to_queue_item(plan):
"""Migrate pending_plan_gate boolean to workflow::create-plan queue item."""
if plan.pop("pending_plan_gate", False):
order = plan.get("queue_order", [])
if WORKFLOW_CREATE_PLAN_ID not in order:
order.insert(0, WORKFLOW_CREATE_PLAN_ID)
Add both migrations to ensure_plan_defaults()
Phase 11: Backward Compatibility
SYNTHESIS_ID constant stays exported but is deprecated (used by external consumers or tests)
plan synthesize --stage observe continues to work exactly as before; it just also resolves the queue item
plan done "synthesis::observe" also resolves the queue item (symmetric with findings)
plan skip "synthesis::reflect" skips the stage (user says: I don't need to reflect this time)
plan move "synthesis::commit" top reorders it (edge case, but works)
Phase 12: Tests
New test files:
test_unified_queue_synthesis_stages.py: Test that synthesis stages are injected as 4 items, blocked_by works, purging one unblocks the next
test_unified_queue_workflow_items.py: Test workflow::create-plan injection and auto-resolution
test_gate_removal.py: Test that gate_phase is no longer returned, review items sort normally
Updated test files:
/Users/user_c042661f/Documents/desloppify/desloppify/tests/plan/test_stale_dimensions.py: Update for 4-stage injection
Mid-synthesis migration: User has synthesis::pending in their plan mid-way through stages. Migration converts to 4 IDs. Completed stages (observe confirmed in meta) should auto-resolve their queue items on next queue build. Solution: in build_synthesis_stage_items(), if stage data shows confirmed_at, don't include it in the items list (it's already done).
Skip a synthesis stage: User runs plan skip synthesis::reflect. The organize stage becomes unblockable (its dependency is gone). Solution: blocked_by only counts IDs that are currently in the queue (not in skipped). If reflect is skipped, organize is no longer blocked.
Review items without gate: Initial reviews currently gate the entire queue. Without gating, initial reviews sort very high (sort key gives them priority) but don't block other work. The user CAN work on a finding before reviewing if they choose. This is intentional -- the unified model trusts the user. The sort ensures reviews are surfaced first.
workflow::create-plan timing: When should it be injected? After the last review item is resolved/imported. The _derive_gate_phase logic for "needs_plan" checked pending_plan_gate boolean after reviews finished. The new equivalent: sync_create_plan_needed() runs during post-scan reconciliation and checks if all initial-review subjective items have been resolved.
Concurrent synthesis + finding work: Previously impossible because synthesis::pending blocked everything. Now, synthesis stages sort first but don't technically block findings (they're just higher priority). If a user WANTS to fix a finding during synthesis, they can plan move <finding> top. This is a feature, not a bug.
Execution Order
The phases above are listed in dependency order. Phase 1 (constants) and Phase 2 (gate removal) can be done in parallel since they touch different code paths. Phase 3 depends on Phase 1. Phases 4-5 depend on Phase 3. Phase 6 depends on Phase 3. Phases 7-9 can proceed in parallel after Phase 3. Phase 10 should be done after Phase 1. Phase 11 and 12 are final.
Recommended sequencing for minimal breakage:
Phase 10 (schema migration) + Phase 1 (constants) -- foundation
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/stale_dimensions.py - New constants (SYNTHESIS_STAGE_IDS, WORKFLOW_CREATE_PLAN_ID), rewrite sync_synthesis_needed for 4-stage injection
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_work_queue/helpers.py - Replace build_synthesis_item with build_synthesis_stage_items and build_create_plan_item
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/synthesize_handlers.py - Add auto-resolution purge calls after each stage completes, update SYNTHESIS_ID references to stage IDs
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/schema.py - Bump plan version, add migration from synthesis::pending to 4 stage IDs, remove pending_plan_gate
Add build_create_plan_item():
python
def build_create_plan_item(plan: dict) -> dict | None:
"""Build a workflow item for plan creation."""
from desloppify.engine._plan.stale_dimensions import WORKFLOW_CREATE_PLAN_ID
if WORKFLOW_CREATE_PLAN_ID not in plan.get("queue_order", []):
return None
return {
"id": WORKFLOW_CREATE_PLAN_ID,
"kind": "workflow_action",
"confidence": "high",
"detector": "workflow",
"file": ".",
"summary": "Reviews complete -- run `desloppify plan` to build your prioritized queue",
"primary_command": "desloppify plan",
"blocked_by": [],
"is_blocked": False,
"detail": {},
}