Consolidate lifecycle phase derivation into a single canonical pure function and add explicit marker lifecycle documentation. Currently phase is determined independently by current_lifecycle_phase() (scan-count markers) and _resolve_reconcile_display_phase() (queue contents) with no structural guarantee they agree. current_lifecycle_phase() also mutates on read (legacy migration). The goal: (1) Create a single derive_lifecycle_state() pure function that returns both persisted mode and display phase, used by all consumers. (2) Remove the mutation side-effect from the getter. (3) Document marker invariants explicitly. Key files: engine/_plan/refresh_lifecycle.py, engine/_plan/sync/pipeline.py, engine/_plan/sync/workflow.py, engine/_plan/sync/context.py, engine/_work_queue/synthetic.py, app/commands/scan/plan_reconcile.py.
Currently, lifecycle phase is determined by three independent code paths that can disagree:
current_lifecycle_phase() (refresh_lifecycle.py:100) — returns persisted mode ("plan" / "execute") from refresh_state["lifecycle_phase"]. Also performs legacy migration with mutation on read (line 131: refresh_state[_LIFECYCLE_PHASE_KEY] = migrated). Falls back to heuristics based on postflight_scan_pending() and plan_start_scores.
_resolve_reconcile_display_phase() (pipeline.py:99) — derives display phase (review, assessment, workflow, triage, execute, scan) from queue contents during reconciliation. Used only in reconcile_plan().
_derive_display_phase() (snapshot.py:313) — derives display phase from materialized queue item partitions. Has a comment "Keep this equivalent to pipeline._resolve_reconcile_display_phase" but uses completely different inputs (item lists vs queue IDs). Called by _phase_for_snapshot() which also reads .
Assistant
User
Assistant
The revised plan fixes the first-round gaps. I’m checking whether the new load_plan() migration strategy and shared signal function still match the repo’s actual load paths and phase ordering.
Assistant
The repo has a few subtle phase-ordering rules beyond the earlier caller-coverage issue. I’m checking whether the new shared priority chain preserves those exact rules or quietly changes behavior.
Assistant
{"flags":[{"id":"migration-coverage-incomplete","concern":"Moving legacy lifecycle migration only into load_plan() still leaves real repository paths uncovered. Several read-only entry points do not call load_plan(); they go through resolve_plan_load_status() and then build queue/snapshot state from the returned plan. If becomes a pure reader, those paths can still observe unmigrated legacy phase values.","category":"completeness","severity_hint":"likely-significant","evidence":" returns directly, and feeds that plan into . also calls directly. Step 1 only patches (), so the plan's claim that this covers read-only paths automatically is not true."},{"id":"shared-phase-priority-order-regresses-current-behavior","concern":"The proposed shared priority chain does not match the repository’s current behavior. It puts workflow ahead of initial review and assessment, but the existing snapshot behavior and tests require initial-review items and postflight assessment to preempt queued workflow items when both are present. Implementing the plan as written would change visible queue phase/output.","category":"correctness","severity_hint":"likely-significant","evidence":"Current snapshot ordering is in . The proposed Step 3 starts with before and before . Existing tests show these overlaps are real, not hypothetical: expects initial review to hide queued workflow/triage items, and expects assessment to beat queued workflow."}],"verified_flag_ids":["canonical-derivation-not-actually-canonical","unset-mode-behavior-unspecified"],"disputed_flag_ids":[]}
User
Assistant
I’m down to one question: whether the plan now actually delivers the user’s requested “single derive_lifecycle_state() used by all consumers,” or only centralizes the display-phase half of the problem.
Assistant
I found one more place where the proposed signal mapping may still diverge from current pipeline behavior: it collapses open_review_ids(state) into has_review_postflight, which could make review beat execute in cases the current pipeline still treats as execute. I’m checking whether the repo allows that overlap.
Assistant
{"flags":[{"id":"pipeline-review-signal-overstates-postflight-review","concern":"The plan’s Step 4 signal mapping is still too coarse for the actual repository. It treats open_review_ids(state) as equivalent to has_review_postflight, but snapshot only enters review-postflight when review findings are actually executable after triage gating. In mixed states with real execute work plus non-executable review findings, the proposed mapping would incorrectly make review beat execute.","category":"correctness","severity_hint":"likely-significant","evidence":"Step 4 defines has_review_postflight as ... or bool(open_review_ids(state)). In the current code, pipeline.py:145-156 checks real work before the fallback open_review_ids(state) review case, and snapshot applies stricter gating in desloppify/engine/_work_queue/snapshot.py:196-212 and :156-193. The repo has an explicit regression test for this mixed state: desloppify/tests/plan/test_reconcile_pipeline.py:457-490 expects LIFECYCLE_PHASE_EXECUTE when objective work is queued alongside an unpromoted review finding."}],"verified_flag_ids":["migration-coverage-incomplete","shared-phase-priority-order-regresses-current-behavior"],"disputed_flag_ids":[]}
User
Assistant
I’m checking the force-rescan carry-forward path and whether load-time migration can change behavior for read-only operations in the current repo, rather than just on paper.
Assistant
{"flags":[{"id":"pipeline-review-signal-overstates-postflight-review","concern":"The unresolved review-postflight signal problem is still present. Step 4 maps directly into , but in the actual repository review-postflight is narrower than “any open review issue exists”. Snapshot only surfaces review findings after triage/currentness gating, and mixed states with executable objective work must remain execute, not review.","category":"correctness","severity_hint":"likely-significant","evidence":"Step 4 sets . In the current code, checks real work before the fallback review case, while snapshot gates review visibility in . The repository has an explicit mixed-state regression test: expects when objective work is queued alongside an unpromoted review finding."},{"id":"scan-vs-workflow-signal-collapsed-in-pipeline-mapping","concern":"The proposed boolean signal mapping still does not preserve snapshot’s scan/workflow distinction. Step 4 collapses all into , but snapshot treats and as scan-phase inputs while remains workflow. That means the new shared function still would not make pipeline and snapshot structurally agree on these cases.","category":"correctness","severity_hint":"likely-significant","evidence":" defines as . Snapshot splits these differently in : / are , while is part of . Existing tests lock in that behavior: expects to yield , expects to yield , and expects to yield ."}],"verified_flag_ids":[],"disputed_flag_ids":[]}
User
Assistant
I’m checking one last signal edge case: in snapshot, prefer_scan only turns on when the persisted mode is execute, but the plan’s Step 4 turns it on whenever scan-phase workflow IDs are present. If those overlap with assessment/review work, that could still diverge.
Assistant
{"flags":[{"id":"edge-case-signal-mapping-tests-missing","concern":"The plan updates Step 4 pseudocode to fix the two open signal-mapping bugs, but Step 7 still does not add direct regression tests for those exact pipeline-vs-snapshot edge cases. The existing equivalence matrix does not cover either review_postflight fallback gating or the run-scan/deferred-disposition scan-phase split, so the riskiest part of the refactor would still rely on indirect coverage.","category":"completeness","severity_hint":"likely-significant","evidence":"Step 7 only proposes tests for derive_display_phase() priority and re-running the existing equivalence matrix. The current matrix in desloppify/tests/plan/test_reconcile_pipeline.py:294-357 does not include a workflow::run-scan/workflow::deferred-disposition case or the mixed objective-plus-review case from desloppify/tests/plan/test_reconcile_pipeline.py:457-490. The scan-phase expectations currently live in snapshot-focused tests at desloppify/tests/engine/test_sync_split_modules_direct.py:998-1004 and , not in a pipeline/snapshot equivalence assertion."}],"verified_flag_ids":["pipeline-review-signal-overstates-postflight-review","scan-vs-workflow-signal-collapsed-in-pipeline-mapping"],"disputed_flag_ids":[]}
current_lifecycle_phase()
Key problems:
current_lifecycle_phase() mutates plan data on read (legacy migration writes, heuristic fallbacks)
No single function takes (plan, state) → (persisted_mode, display_phase)
snapshot._derive_display_phase and pipeline._resolve_reconcile_display_phase must be kept in sync manually
Marker invariants (postflight_scan_completed_at, subjective_review_completed_at, lifecycle_phase) are undocumented
Constraints:
Data migration code must be preserved (backward compat policy)
_set_lifecycle_phase is already single-writer via pipeline.py (enforced by prior refactor)
Display phase constants are never persisted — only "plan" / "execute" are persisted
snapshot.py's _derive_display_phase takes materialized item lists, not raw queue IDs, so full unification into one function requires either (a) always materializing items first, or (b) a shared interface that both paths can call
Step 1: Extract migration into a separate pure function
Scope: Small Files:engine/_plan/refresh_lifecycle.py
Createmigrate_legacy_phase(plan: PlanModel) -> bool — a standalone function that migrates legacy phase values exactly once. Extracts lines 106-132 from current_lifecycle_phase(). Returns True if migration occurred.
Createpersisted_lifecycle_mode(plan: PlanModel) -> str — pure reader that returns "plan" or "execute" from refresh_state["lifecycle_phase"]. No mutation, no fallback heuristics. Returns the raw persisted value or raises if not set.
Modifycurrent_lifecycle_phase() to call migrate_legacy_phase() first, then delegate to persisted_lifecycle_mode(). The heuristic fallback (lines 133-137) becomes the only remaining "guess" path for plans that have never had a phase set.
Add docstring block at module top documenting marker invariants:
lifecycle_phase: "plan" | "execute", set only by _set_lifecycle_phase via reconcile_plan()
postflight_scan_completed_at_scan_count: int, set by mark_postflight_scan_completed(), cleared by invalidate_postflight_scan()
subjective_review_completed_at_scan_count: int, set by mark_subjective_review_completed()
Step 2: Create derive_lifecycle_state() pure function
Scope: Medium Files:engine/_plan/refresh_lifecycle.py
Createderive_lifecycle_state(plan, state, *, queue_order, policy=None, triage_snapshot=None) -> LifecycleState where LifecycleState is a NamedTuple(mode=str, display_phase=str).
mode: the persisted mode ("plan" / "execute") — derived from the current refresh_state["lifecycle_phase"] value
display_phase: derived from queue contents using the logic currently in _resolve_reconcile_display_phase()
Move the display-phase derivation logic from pipeline._resolve_reconcile_display_phase() into this function. The pipeline version becomes a thin wrapper calling derive_lifecycle_state().display_phase.
The function is pure — it reads plan/state but writes nothing. Migration must have already run.
python
class LifecycleState(NamedTuple):
mode: str # "plan" or "execute"
display_phase: str # one of LIFECYCLE_PHASE_* constants
Step 3: Wire pipeline.py to use derive_lifecycle_state()
Scope: Medium Files:engine/_plan/sync/pipeline.py, engine/_plan/refresh_lifecycle.py
Replace_resolve_reconcile_display_phase() body in pipeline.py with a call to derive_lifecycle_state(). The function signature changes minimally — it still receives plan, state, result, policy but delegates the phase logic.
Updatereconcile_plan() to call migration upfront (if needed for legacy plans) before entering the reconcile pipeline, so the pure function never encounters unmigrated data.
Keep the ReconcileResult dataclass unchanged — lifecycle_phase continues to hold the display phase string, lifecycle_phase_changed continues to track mode persistence.
Step 4: Wire snapshot.py to use derive_lifecycle_state()
Scope: Medium Files:engine/_work_queue/snapshot.py
Evaluate whether snapshot._derive_display_phase can delegate to the same derive_lifecycle_state(). The challenge: snapshot works with materialized WorkQueueItem lists, not raw queue IDs. The two derivation paths use different input representations.
If feasible: replace _derive_display_phase in snapshot.py with a call to the shared function, mapping item lists → queue IDs + policy signals.
If not feasible (likely — the snapshot path uses item-level properties like initial_review flags that aren't in raw queue IDs): keep _derive_display_phase in snapshot.py but add a cross-reference comment and ensure the existing test_phase_derivation_equivalence_matrix test validates both paths produce the same result for the same inputs. Document the intentional divergence.
Remove the mutation from current_lifecycle_phase()'s fallback path — the migration is now explicit.
Step 5: Remove mutation side-effect from current_lifecycle_phase()
Scope: Small Files:engine/_plan/refresh_lifecycle.py, callers in plan_reconcile.py, snapshot.py, synthetic.py
Ensure all entry points that call current_lifecycle_phase() have already run migration. The main entry points:
reconcile_plan_post_scan() in plan_reconcile.py:366 — add explicit migration call at top
_phase_for_snapshot() in snapshot.py:294 — this is a read-only path; migration should have been done by the last scan/save
build_subjective_items() in synthetic.py:240 — also read-only
Remove the mutation from current_lifecycle_phase(): the legacy migration block (lines 111-132) becomes a pure read that returns the migrated mode without writing it back. Move the actual write to migrate_legacy_phase().
Update the fallback heuristic (lines 133-137) to be deterministic: if lifecycle_phase is not set, return "plan" if postflight_scan_pending(), else "execute". No write-back.
Step 6: Add marker lifecycle documentation
Scope: Small Files:engine/_plan/refresh_lifecycle.py
Add a module-level docstring section titled "Marker invariants" documenting:
The three markers in refresh_state: lifecycle_phase, postflight_scan_completed_at_scan_count, subjective_review_completed_at_scan_count
Valid values and transitions for each
Which functions write each marker (single-writer enforcement)
The relationship between persisted mode and display phase
Add a brief state machine description: plan → execute happens when planning work drains from queue; execute → plan happens when invalidate_postflight_scan() or new review items trigger re-planning.
Step 7: Update tests
Scope: Medium Files:tests/plan/test_refresh_lifecycle.py, tests/plan/test_reconcile_pipeline.py, tests/commands/scan/test_plan_reconcile_postflight_and_reconcile.py
Add unit tests for derive_lifecycle_state():
Pure function with known plan/state → expected (mode, display_phase) pairs
No mutation assertion: plan dict unchanged after call
Add test for migrate_legacy_phase():
Migrates old phase names correctly
Idempotent on already-migrated plans
Handles the stuck-in-plan edge case (line 118-129)
Update existing test_current_lifecycle_phase_falls_back_for_legacy_plans to verify no mutation occurs
Verifytest_phase_derivation_equivalence_matrix still passes — this is the [REDACTED] test
Run full test suite: python -m pytest desloppify/tests/ -q
Execution Order
Step 1 first — extract migration, no callers change behavior
Step 6 alongside Step 1 — documentation is independent
"version": 1,
"timestamp": "2026-03-23T20:12:14Z",
"hash": "sha256:96064a90e5d11bd865762660e9d2c87e726c05c5ddbd253d1136f9a96c244760",
"questions": [
"Step 4 divergence: snapshot.py's _derive_display_phase uses materialized WorkQueueItem lists with item-level flags (e.g. initial_review), while pipeline's version uses raw queue IDs. Should we (a) force both through one function by extracting shared signals, (b) keep them separate but add stronger cross-validation tests, or (c) collapse the snapshot path to also work from queue IDs? Option (b) is lowest risk.",
"Migration timing: should migrate_legacy_phase() be called eagerly at plan load time (in load_plan()), or lazily at first access? Eager means the migration always persists on next save; lazy means read-only paths never trigger migration writes.",
"The heuristic fallback in current_lifecycle_phase() (lines 133-137) returns 'execute' for plans with no refresh_state and no postflight_scan_pending. Is this the correct default for brand-new plans, or should new plans default to 'plan'?"
],
"success_criteria": [
"derive_lifecycle_state() is a pure function: given the same (plan, state) it returns the same (mode, display_phase) and mutates nothing",
"current_lifecycle_phase() no longer writes to refresh_state \u2014 mutation is isolated in migrate_legacy_phase()",
"All existing tests pass with no behavioral changes (especially test_phase_derivation_equivalence_matrix)",
"pipeline.py's reconcile_plan() delegates display-phase derivation to the shared derive_lifecycle_state()",
"Marker invariants (lifecycle_phase, postflight_scan_completed_at_scan_count, subjective_review_completed_at_scan_count) are documented with valid values, transitions, and single-writer functions",
"Self-scan succeeds: python -m desloppify --lang python scan --path desloppify produces no errors"
],
"assumptions": [
"snapshot.py's _derive_display_phase will likely remain a separate implementation due to different input representations (item lists vs queue IDs) \u2014 Step 4 evaluates this and falls back to stronger cross-validation if unification isn't clean",
"Legacy migration code is preserved per backward compat policy (data migration for .desloppify/ state formats must be kept)",
"The LifecycleState return type is a NamedTuple rather than a dataclass to keep it lightweight and immutable",
"migrate_legacy_phase() will be called explicitly by entry points (reconcile_plan_post_scan, etc.) rather than at load_plan() time, to keep the persistence layer mutation-free",
"The heuristic fallback for plans without any lifecycle_phase marker continues to return 'execute' for plans with plan_start_scores and 'plan' otherwise \u2014 matching current behavior exactly"
],
"structure_warnings": []
}
code
Plan structure warnings from validator:
[]
Existing flags:
[]
Requirements:
- Consider whether the plan is at the right level of abstraction.
- Reuse existing flag IDs when the same concern is still open.
- `verified_flag_ids` should list previously addressed flags that now appear resolved.
- Focus on concrete issues that would cause real problems.
- Robustness level: standard. Use balanced judgment. Flag significant risks, but do not spend flags on minor polish or executor-obvious boilerplate.
- Verify that the plan remains aligned with the user's original intent.
- Verify that the plan follows the expected structure: one H1 title, `## Overview`, numbered `## Step N:` sections with file references and numbered substeps, plus `## Execution Order` or `## Validation Order`. Missing structure should be flagged as category `completeness` with severity_hint `likely-significant`.
- Flag scope creep explicitly when the plan grows beyond the original idea or recorded user notes. Use the phrase "Scope creep:" in the concern.
- Assign severity_hint carefully. Implementation details the executor will naturally resolve should usually be `likely-minor`.
{"flags":[{"id":"migration-coverage-incomplete","concern":"The plan removes mutation from current_lifecycle_phase() but only adds explicit migration to a subset of entry points. The repository has several other load-modify-save paths that call current_lifecycle_phase() and then save the plan, so legacy refresh_state[\"lifecycle_phase\"] values could remain stranded unless those paths also normalize or reconcile.","category":"completeness","severity_hint":"likely-significant","evidence":"current_lifecycle_phase() is read in save flows at desloppify/app/commands/resolve/living_plan.py:88-135, desloppify/app/commands/review/importing/plan_sync.py:443-475, desloppify/app/commands/plan/override/resolve_workflow.py:474-482, and desloppify/app/commands/plan/triage/completion_flow.py:198-229. The proposed Step 5 only names app/commands/scan/plan_reconcile.py, engine/_work_queue/snapshot.py, and engine/_work_queue/synthetic.py."},{"id":"canonical-derivation-not-actually-canonical","concern":"The plan does not fully solve the duplication it identifies. Snapshot phase derivation uses richer signals than raw queue IDs, and Step 4 explicitly allows keeping snapshot._derive_display_phase() separate with only a comment/test. That leaves the main cross-module sync problem in place, even though the goal says a single canonical pure function should be used by all consumers.","category":"correctness","severity_hint":"likely-significant","evidence":"desloppify/engine/_work_queue/snapshot.py:102-109 derives fresh_boundary; :215-226 splits subjective items into initial vs postflight using initial_review; :489-497 builds assessment/review partitions from materialized items; and :313-350 derives the display phase from those partitions. The plan's Step 4 says to keep this separate if unification is not feasible, which would preserve the current two-implementation contract noted in desloppify/engine/_plan/sync/pipeline.py:111-113 and desloppify/engine/_work_queue/snapshot.py:328-329."},{"id":"unset-mode-behavior-unspecified","concern":"The proposed persisted_lifecycle_mode()/derive_lifecycle_state() design does not account for normal plans where no persisted lifecycle marker exists yet. In this repository, empty and partially initialized plans are valid, and current behavior intentionally falls back instead of raising. Without an explicit defaulting rule in the shared function, fresh-plan and read-only paths can break or force a wider migration than the idea calls for.","category":"correctness","severity_hint":"likely-significant","evidence":"Current fallback logic is in desloppify/engine/_plan/refresh_lifecycle.py:133-137, and desloppify/tests/plan/test_refresh_lifecycle.py:106-114 asserts that an empty plan returns \"plan\". Read-only consumers call current_lifecycle_phase() on normal plans at desloppify/engine/_work_queue/snapshot.py:294, desloppify/engine/_work_queue/synthetic.py:240, desloppify/app/commands/scan/preflight.py:49, and desloppify/engine/_state/progression.py:324."}],"verified_flag_ids":[],"disputed_flag_ids":[]}
You are an independent reviewer. Critique the plan against the actual repository.
Consolidate lifecycle phase derivation into a single canonical pure function and add explicit marker lifecycle documentation. Currently phase is determined independently by current_lifecycle_phase() (scan-count markers) and _resolve_reconcile_display_phase() (queue contents) with no structural guarantee they agree. current_lifecycle_phase() also mutates on read (legacy migration). The goal: (1) Create a single derive_lifecycle_state() pure function that returns both persisted mode and display phase, used by all consumers. (2) Remove the mutation side-effect from the getter. (3) Document marker invariants explicitly. Key files: engine/_plan/refresh_lifecycle.py, engine/_plan/sync/pipeline.py, engine/_plan/sync/workflow.py, engine/_plan/sync/context.py, engine/_work_queue/synthetic.py, app/commands/scan/plan_reconcile.py.
Currently, lifecycle phase is determined by three independent code paths that can disagree:
current_lifecycle_phase() (refresh_lifecycle.py:100) — returns persisted mode ("plan" / "execute") from refresh_state["lifecycle_phase"]. Also performs legacy migration with mutation on read (line 131: writes back migrated value). Falls back to heuristics based on postflight_scan_pending() and plan_start_scores.
_resolve_reconcile_display_phase() (pipeline.py:99) — derives display phase from queue contents during reconciliation.
_derive_display_phase() (snapshot.py:313) — derives display phase from materialized queue item partitions. Must be kept manually in sync with #2.
Key problems:
current_lifecycle_phase() mutates plan data on read (legacy migration writes)
No single function takes (plan, state) → (persisted_mode, display_phase)
Display-phase derivation rules are duplicated between pipeline.py and snapshot.py with no shared code
Marker invariants (postflight_scan_completed_at, subjective_review_completed_at, lifecycle_phase) are undocumented
Constraints:
Data migration code must be preserved (backward compat policy)
_set_lifecycle_phase is already single-writer via pipeline.reconcile_plan() (enforced by prior refactor)
Display phase constants are never persisted — only "plan" / "execute" are persisted
Complete caller inventory for current_lifecycle_phase():
All load-modify-save paths go through load_plan() (persistence.py:164). Read-only paths receive an already-loaded plan dict.
Step 1: Move legacy migration into load_plan() (engine/_plan/persistence.py, engine/_plan/refresh_lifecycle.py)
Scope: Small
Extractmigrate_legacy_phase(plan: PlanModel) -> bool into refresh_lifecycle.py. This is the mutation logic from current_lifecycle_phase() lines 106-132: reads the raw lifecycle_phase value, maps legacy names via _LEGACY_PHASE_TO_MODE, handles the stuck-in-plan edge case (lines 118-129), and writes back the canonical mode. Returns True if a write occurred.
Callmigrate_legacy_phase(plan) inside load_plan() (persistence.py:164-167) after ensure_plan_defaults(). This ensures every loaded plan has a canonical lifecycle_phase marker before any consumer reads it. The mutation persists on the next save_plan() call, which every load-modify-save path performs.
Exportmigrate_legacy_phase in refresh_lifecycle.__all__ — this is data migration, which the backward compat policy requires keeping.
python
# persistence.py:164
def load_plan(path: Path | None = None) -> PlanModel:
"""Load plan from disk, or return empty plan on missing/corruption."""
status = resolve_plan_load_status(path)
plan = status.plan or empty_plan()
migrate_legacy_phase(plan) # one-shot data migration
return plan
This single change covers all 5 load-modify-save callers without touching any of them individually.
Step 2: Make current_lifecycle_phase() a pure reader (engine/_plan/refresh_lifecycle.py)
Scope: Small
Remove the mutation block (lines 106-132) from current_lifecycle_phase(). Replace with a pure read: check refresh_state["lifecycle_phase"], return if valid.
Preserve the heuristic fallback (lines 133-137) for plans that have never had a phase set (fresh/empty plans). Explicit default rule:
If postflight_scan_pending(plan) → return "plan"
If plan.get("plan_start_scores") → return "execute"
Else → return "execute"
This matches the existing behavior tested in test_refresh_lifecycle.py:106-121: empty plan returns "plan", plan with plan_start_scores returns "execute".
No callers change — they all still call current_lifecycle_phase() with the same semantics. The only difference: no mutation occurs on read.
python
def current_lifecycle_phase(plan: PlanModel) -> str:
"""Return the persisted lifecycle mode: 'plan' or 'execute'.
Pure reader — never mutates plan. Legacy migration runs at load_plan() time.
For fresh plans without a persisted marker, falls back to heuristics.
"""
refresh_state = plan.get("refresh_state")
if isinstance(refresh_state, dict):
phase = refresh_state.get(_LIFECYCLE_PHASE_KEY)
if isinstance(phase, str) and phase in _VALID_PHASES:
return phase
# Fallback for plans that haven't been through reconcile yet.
if postflight_scan_pending(plan):
return "plan"
if plan.get("plan_start_scores"):
return "execute"
return "execute"
Step 3: Create derive_display_phase() shared pure function (engine/_plan/refresh_lifecycle.py)
Scope: Medium
Createderive_display_phase() — a pure function that takes boolean phase signals and returns a display phase string. This is the single canonical priority chain for display-phase derivation, used by both pipeline.py and snapshot.py.
python
def derive_display_phase(
*,
has_initial_review: bool,
has_postflight_assessment: bool,
has_workflow: bool,
has_triage: bool,
has_review_postflight: bool,
has_execution: bool,
fresh_boundary: bool,
prefer_scan: bool,
) -> str:
"""Canonical display-phase derivation from abstract signals.
Both pipeline._resolve_reconcile_display_phase (queue IDs) and
snapshot._derive_display_phase (materialized items) compute boolean
signals from their respective inputs and call this function.
"""
if has_workflow:
return LIFECYCLE_PHASE_WORKFLOW_POSTFLIGHT
if fresh_boundary and has_initial_review:
return LIFECYCLE_PHASE_REVIEW_INITIAL
if has_postflight_assessment:
return LIFECYCLE_PHASE_ASSESSMENT_POSTFLIGHT
if has_triage:
return LIFECYCLE_PHASE_TRIAGE_POSTFLIGHT
if prefer_scan:
return LIFECYCLE_PHASE_SCAN
if has_review_postflight:
return LIFECYCLE_PHASE_REVIEW_POSTFLIGHT
if has_execution:
return LIFECYCLE_PHASE_EXECUTE
return LIFECYCLE_PHASE_SCAN
Createderive_lifecycle_state() — combines current_lifecycle_phase() (pure reader) with derive_display_phase() into one call. Returns a LifecycleState NamedTuple.
python
class LifecycleState(NamedTuple):
mode: str # "plan" or "execute"
display_phase: str # one of LIFECYCLE_PHASE_* constants
Export both derive_display_phase and derive_lifecycle_state in __all__.
Why boolean signals instead of queue IDs or item lists: The pipeline path computes signals from raw queue IDs + reconcile results. The snapshot path computes signals from materialized WorkQueueItem lists. Both produce the same boolean answers; the shared function doesn't care how they were computed. This makes the priority chain canonical without forcing either caller to change its data representation.
Step 4: Wire pipeline.py to use shared derivation (engine/_plan/sync/pipeline.py)
Scope: Medium
Rewrite_resolve_reconcile_display_phase() to compute boolean signals from queue IDs and call derive_display_phase():
python
def _resolve_reconcile_display_phase(plan, state, *, result, policy) -> str:
order = [item for item in plan.get("queue_order", []) if isinstance(item, str)]
subjective_ids = [item for item in order if item.startswith("subjective::")]
unscored_ids = set(getattr(policy, "unscored_ids", ()) or ())
skipped = plan.get("skipped") or {}
triage_snapshot = build_triage_snapshot(plan, state)
has_review_postflight = (
(triage_snapshot.triage_has_run
and not triage_snapshot.has_triage_in_queue
and not triage_snapshot.is_triage_stale
and bool(triage_snapshot.live_open_ids))
or bool(open_review_ids(state))
)
return derive_display_phase(
has_initial_review=any(sid in unscored_ids for sid in subjective_ids),
has_postflight_assessment=bool(subjective_ids) and not any(sid in unscored_ids for sid in subjective_ids),
has_workflow=(
any(item in PRE_REVIEW_WORKFLOW_IDS for item in order)
or bool(result.workflow_injected_ids)
or any(item.startswith("workflow::") for item in order)
),
has_triage=(
(result.triage is not None and bool(result.triage.injected or result.triage.deferred))
or any(item.startswith("triage::") for item in order)
),
has_review_postflight=has_review_postflight,
has_execution=any(
not item.startswith(("subjective::", "workflow::", "triage::"))
for item in order if item not in skipped
),
fresh_boundary=not bool(plan.get("plan_start_scores")),
prefer_scan=False,
)
Wirereconcile_plan() to use derive_lifecycle_state() for the combined mode + display phase lookup (replacing the separate _resolve_reconcile_display_phase + _display_phase_to_mode calls at lines 282-289).
Step 5: Wire snapshot.py to use shared derivation (engine/_work_queue/snapshot.py)
Scope: Medium
Rewrite_derive_display_phase() in snapshot.py to compute boolean signals from its item-list parameters and delegate to derive_display_phase():
Preserve the early-return in _phase_for_snapshot() at line 296 (if raw_phase == "execute" and (anchored_execution_items or explicit_queue_items): return LIFECYCLE_PHASE_EXECUTE) as a pre-signal override — this forces execute mode when the persisted phase says execute and there's real work. This stays in _phase_for_snapshot, not in the shared function.
Remove the duplicated priority-chain logic that previously lived in _derive_display_phase. The function becomes a thin signal-computation wrapper.
Replace the module docstring with a comprehensive "Marker invariants" section:
python
"""Helpers for the persisted queue lifecycle phase.
Marker invariants
-----------------
Three markers live in ``plan["refresh_state"]``:
``lifecycle_phase`` : ``"plan"`` | ``"execute"``
The persisted lifecycle mode. Written ONLY by ``_set_lifecycle_phase()``
(called from ``reconcile_plan()`` in pipeline.py). Legacy values are
migrated at ``load_plan()`` time by ``migrate_legacy_phase()``.
Transitions:
- plan → execute: planning work drains from queue (no workflow/triage items remain)
- execute → plan: ``invalidate_postflight_scan()`` clears the scan marker,
or new review items trigger re-planning via reconcile
``postflight_scan_completed_at_scan_count`` : int
Set by ``mark_postflight_scan_completed()``.
Cleared by ``invalidate_postflight_scan()`` (when objective queue work changes).
``subjective_review_completed_at_scan_count`` : int
Set by ``mark_subjective_review_completed()``.
Carried forward by ``carry_forward_subjective_review()`` across cycle boundaries.
Display phase (never persisted)
-------------------------------
Display phases (review_initial, assessment, workflow, triage, execute, scan)
are derived from queue contents by ``derive_display_phase()`` — a shared pure
function called by both ``pipeline._resolve_reconcile_display_phase()`` and
``snapshot._derive_display_phase()``. The ``user_facing_mode()`` function
collapses display phases back to ``"plan"`` or ``"execute"`` for user output.
"""
Step 7: Update and add tests (tests/plan/test_refresh_lifecycle.py, tests/plan/test_reconcile_pipeline.py)
Scope: Medium
Add unit tests for derive_display_phase():
Pure function: each signal combination → expected display phase
Priority chain: when multiple signals are true, higher-priority wins
No mutation: function is stateless (no plan/state args to mutate)
Add unit tests for migrate_legacy_phase():
Migrates old phase names correctly (each _LEGACY_PHASE_TO_MODE entry)
Idempotent on already-migrated plans
Handles stuck-in-plan edge case (legacy "plan" + no plan work → migrates to "execute")
Returns False on fresh plans with no legacy marker
Updatetest_current_lifecycle_phase_falls_back_for_legacy_plans (test_refresh_lifecycle.py:106): verify current_lifecycle_phase() does NOT mutate refresh_state — assert plan dict unchanged after call.
Verifytest_phase_derivation_equivalence_matrix (test_reconcile_pipeline.py) still passes — this validates that pipeline and snapshot produce identical results for the same inputs, now both delegating to the shared function.
Run full test suite: python -m pytest desloppify/tests/ -q
Execution Order
Step 1 — migration into load_plan() (safe: adds a call, no behavior change for callers)
Step 2 — pure reader (safe: behavior identical since migration already ran)
Step 6 — documentation (independent, no code changes)
Step 3 — shared derive_display_phase() function (new code, no callers yet)
Step 4 — wire pipeline.py (first consumer of shared function)
Step 5 — wire snapshot.py (second consumer)
Step 7 — tests throughout, full suite at end
Validation Order
After Step 2: python -m pytest desloppify/tests/plan/test_refresh_lifecycle.py -q — existing behavior preserved, no mutations on read
After Step 4: python -m pytest desloppify/tests/plan/test_reconcile_pipeline.py -q — equivalence matrix still passes
"version": 2,
"timestamp": "2026-03-23T20:20:50Z",
"hash": "sha256:efff1591124ca121e540d0d22e759d01dce05a8f867acc12d360e79f5ad543a0",
"changes_summary": "Key revisions from v1:\n\n1. Migration coverage (flag: migration-coverage-incomplete): Moved migration into load_plan() instead of patching individual entry points. This covers ALL 5 load-modify-save callers (plan_reconcile, living_plan, plan_sync, resolve_workflow, completion_flow) plus read-only paths automatically. Complete caller inventory added to Overview.\n\n2. Canonical derivation (flag: canonical-derivation-not-actually-canonical): Replaced the "keep separate with a comment" fallback with a shared derive_display_phase() function that takes boolean signals. Both pipeline.py (computes signals from queue IDs) and snapshot.py (computes signals from item lists) delegate to the same priority chain. The decision rules are now in one place \u2014 only signal computation differs.\n\n3. Unset mode behavior (flag: unset-mode-behavior-unspecified): Dropped the persisted_lifecycle_mode() that "raises if not set". Instead, current_lifecycle_phase() remains the reader with an explicit documented fallback: postflight_scan_pending \u2192 \"plan\", plan_start_scores \u2192 \"execute\", else \"execute\". This preserves the existing test assertions for empty plans.",
"flags_addressed": [
"migration-coverage-incomplete",
"canonical-derivation-not-actually-canonical",
"unset-mode-behavior-unspecified"
],
"questions": [
"The shared derive_display_phase() priority chain unifies two orderings that were previously slightly different (pipeline checks PRE_REVIEW_WORKFLOW before subjective; snapshot checks initial_review before workflow). These signals should be mutually exclusive by construction (pre-review workflow items are injected only after initial reviews complete). Should we add a defensive assertion/test that these signals never overlap, or trust the existing invariant?"
],
"success_criteria": [
"derive_display_phase() is a pure function with boolean inputs: given the same signals it returns the same display phase, with no plan/state arguments to mutate",
"current_lifecycle_phase() no longer writes to refresh_state \u2014 migration is isolated in migrate_legacy_phase() called from load_plan()",
"All existing tests pass with no behavioral changes (especially test_phase_derivation_equivalence_matrix and test_current_lifecycle_phase_falls_back_for_legacy_plans)",
"Both pipeline._resolve_reconcile_display_phase and snapshot._derive_display_phase delegate to the shared derive_display_phase() for their priority chain",
"Marker invariants (lifecycle_phase, postflight_scan_completed_at_scan_count, subjective_review_completed_at_scan_count) are documented with valid values, transitions, and single-writer functions in the module docstring",
"Self-scan succeeds: python -m desloppify --lang python scan --path desloppify produces no errors",
"Fresh/empty plans continue to return 'plan' from current_lifecycle_phase() without requiring a persisted marker"
],
"assumptions": [
"All load-modify-save paths go through load_plan() (persistence.py:164) \u2014 verified by reading all 5 callers: plan_reconcile.py:361, living_plan.py:88, plan_sync.py:443, resolve_workflow.py:425, completion_flow.py calls load_plan via services",
"The boolean signal mapping between pipeline (queue IDs) and snapshot (item lists) produces equivalent results \u2014 enforced by the existing test_phase_derivation_equivalence_matrix test",
"Legacy migration code is preserved per backward compat policy (data migration for .desloppify/ state formats must be kept)",
"The LifecycleState return type is a NamedTuple to keep it lightweight and immutable",
"The heuristic fallback for plans without a persisted lifecycle_phase marker preserves exact current behavior: postflight_scan_pending \u2192 'plan', plan_start_scores \u2192 'execute', else \u2192 'execute'",
"snapshot._phase_for_snapshot's early-return for execute+real-work (line 296) stays as a pre-signal override outside the shared function \u2014 it's a snapshot-specific optimization that doesn't belong in the canonical derivation"
],
"structure_warnings": [],
"delta_from_previous_percent": 94.22
}
code
Plan structure warnings from validator:
[]
Existing flags:
[
{
"id": "migration-coverage-incomplete",
"concern": "The plan removes mutation from current_lifecycle_phase() but only adds explicit migration to a subset of entry points. The repository has several other load-modify-save paths that call current_lifecycle_phase() and then save the plan, so legacy refresh_state[\"lifecycle_phase\"] values could remain stranded unless those paths also normalize or reconcile.",
"status": "addressed",
"severity": "significant"
},
{
"id": "canonical-derivation-not-actually-canonical",
"concern": "The plan does not fully solve the duplication it identifies. Snapshot phase derivation uses richer signals than raw queue IDs, and Step 4 explicitly allows keeping snapshot._derive_display_phase() separate with only a comment/test. That leaves the main cross-module sync problem in place, even though the goal says a single canonical pure function should be used by all consumers.",
"status": "addressed",
"severity": "significant"
},
{
"id": "unset-mode-behavior-unspecified",
"concern": "The proposed persisted_lifecycle_mode()/derive_lifecycle_state() design does not account for normal plans where no persisted lifecycle marker exists yet. In this repository, empty and partially initialized plans are valid, and current behavior intentionally falls back instead of raising. Without an explicit defaulting rule in the shared function, fresh-plan and read-only paths can break or force a wider migration than the idea calls for.",
"status": "addressed",
"severity": "significant"
}
]
code
Requirements:
- Consider whether the plan is at the right level of abstraction.
- Reuse existing flag IDs when the same concern is still open.
- `verified_flag_ids` should list previously addressed flags that now appear resolved.
- Focus on concrete issues that would cause real problems.
- Robustness level: standard. Use balanced judgment. Flag significant risks, but do not spend flags on minor polish or executor-obvious boilerplate.
- Verify that the plan remains aligned with the user's original intent.
- Verify that the plan follows the expected structure: one H1 title, `## Overview`, numbered `## Step N:` sections with file references and numbered substeps, plus `## Execution Order` or `## Validation Order`. Missing structure should be flagged as category `completeness` with severity_hint `likely-significant`.
- Flag scope creep explicitly when the plan grows beyond the original idea or recorded user notes. Use the phrase "Scope creep:" in the concern.
- Assign severity_hint carefully. Implementation details the executor will naturally resolve should usually be `likely-minor`.
Consolidate lifecycle phase derivation into a single canonical pure function and add explicit marker lifecycle documentation. Currently phase is determined independently by current_lifecycle_phase() (scan-count markers) and _resolve_reconcile_display_phase() (queue contents) with no structural guarantee they agree. current_lifecycle_phase() also mutates on read (legacy migration). The goal: (1) Create a single derive_lifecycle_state() pure function that returns both persisted mode and display phase, used by all consumers. (2) Remove the mutation side-effect from the getter. (3) Document marker invariants explicitly. Key files: engine/_plan/refresh_lifecycle.py, engine/_plan/sync/pipeline.py, engine/_plan/sync/workflow.py, engine/_plan/sync/context.py, engine/_work_queue/synthetic.py, app/commands/scan/plan_reconcile.py.
Currently, lifecycle phase is determined by three independent code paths that can disagree:
current_lifecycle_phase() (refresh_lifecycle.py:100) — returns persisted mode ("plan" / "execute") from refresh_state["lifecycle_phase"]. Also performs legacy migration with mutation on read (line 131: writes back migrated value). Falls back to heuristics based on postflight_scan_pending() and plan_start_scores.
_resolve_reconcile_display_phase() (pipeline.py:99) — derives display phase from queue contents during reconciliation.
_derive_display_phase() (snapshot.py:313) — derives display phase from materialized queue item partitions. Must be kept manually in sync with #2.
Key problems:
current_lifecycle_phase() mutates plan data on read (legacy migration writes)
No single function takes (plan, state) → (persisted_mode, display_phase)
Display-phase derivation rules are duplicated between pipeline.py and snapshot.py with no shared code
Marker invariants (postflight_scan_completed_at, subjective_review_completed_at, lifecycle_phase) are undocumented
Constraints:
Data migration code must be preserved (backward compat policy)
_set_lifecycle_phase is already single-writer via pipeline.reconcile_plan() (enforced by prior refactor)
Display phase constants are never persisted — only "plan" / "execute" are persisted
Complete caller inventory for current_lifecycle_phase():
Plan loading bottleneck: Both load_plan() (persistence.py:164) and resolve_plan_load_status() (persistence.py:113) load plans through _load_validated_plan() (persistence.py:88). Placing migration in _load_validated_plan() covers all paths.
Canonical display-phase priority order (from snapshot.py:331-350, verified by tests):
The shared function must match this exact order. Tests explicitly assert: initial review hides queued workflow/triage items (test_work_queue_plan_order_and_triage.py:743-757), and assessment beats queued workflow (test_sync_split_modules_direct.py:1123-1139).
Step 1: Move legacy migration into _load_validated_plan() (engine/_plan/persistence.py, engine/_plan/refresh_lifecycle.py)
Scope: Small
Extractmigrate_legacy_phase(plan: PlanModel) -> bool into refresh_lifecycle.py. This is the mutation logic from current_lifecycle_phase() lines 106-132: reads the raw lifecycle_phase value, maps legacy names via _LEGACY_PHASE_TO_MODE, handles the stuck-in-plan edge case (lines 118-129), and writes back the canonical mode. Returns True if a write occurred.
Callmigrate_legacy_phase(plan) inside _load_validated_plan() (persistence.py:88-110) after ensure_plan_defaults(data) (line 108). This is the shared loading bottleneck for bothload_plan() and resolve_plan_load_status(), covering all entry points:
Also handles the backup-recovery path at persistence.py:129 (which also calls _load_validated_plan).
Step 2: Make current_lifecycle_phase() a pure reader (engine/_plan/refresh_lifecycle.py)
Scope: Small
Remove the mutation block (lines 106-132) from current_lifecycle_phase(). Replace with a pure read: check refresh_state["lifecycle_phase"], return if valid.
Preserve the heuristic fallback (lines 133-137) for plans that have never had a phase set (fresh/empty plans). Explicit default rule:
If postflight_scan_pending(plan) → return "plan"
If plan.get("plan_start_scores") → return "execute"
Else → return "execute"
This matches the existing behavior tested in test_refresh_lifecycle.py:106-121: empty plan returns "plan", plan with plan_start_scores returns "execute".
No callers change — they all still call current_lifecycle_phase() with the same semantics. The only difference: no mutation occurs on read.
python
def current_lifecycle_phase(plan: PlanModel) -> str:
"""Return the persisted lifecycle mode: 'plan' or 'execute'.
Pure reader — never mutates plan. Legacy migration runs at
_load_validated_plan() time via migrate_legacy_phase().
For fresh plans without a persisted marker, falls back to heuristics.
"""
refresh_state = plan.get("refresh_state")
if isinstance(refresh_state, dict):
phase = refresh_state.get(_LIFECYCLE_PHASE_KEY)
if isinstance(phase, str) and phase in _VALID_PHASES:
return phase
# Fallback for plans that haven't been through reconcile yet.
if postflight_scan_pending(plan):
return "plan"
if plan.get("plan_start_scores"):
return "execute"
return "execute"
Step 3: Create derive_display_phase() shared pure function (engine/_plan/refresh_lifecycle.py)
Scope: Medium
Createderive_display_phase() — a pure function that takes boolean phase signals and returns a display phase string. The priority chain matches the existing snapshot ordering (snapshot.py:331-350):
python
def derive_display_phase(
*,
has_initial_review: bool,
has_postflight_assessment: bool,
has_workflow: bool,
has_triage: bool,
has_review_postflight: bool,
has_execution: bool,
fresh_boundary: bool,
prefer_scan: bool,
) -> str:
"""Canonical display-phase derivation from abstract signals.
Priority order matches snapshot._derive_display_phase (the user-visible
path). Both pipeline and snapshot compute boolean signals from their
respective inputs and call this function.
Priority chain:
initial_review > prefer_scan > assessment > workflow > triage
> review_postflight > execute > scan (default)
"""
if fresh_boundary and has_initial_review:
return LIFECYCLE_PHASE_REVIEW_INITIAL
if prefer_scan:
return LIFECYCLE_PHASE_SCAN
if has_postflight_assessment:
return LIFECYCLE_PHASE_ASSESSMENT_POSTFLIGHT
if has_workflow:
return LIFECYCLE_PHASE_WORKFLOW_POSTFLIGHT
if has_triage:
return LIFECYCLE_PHASE_TRIAGE_POSTFLIGHT
if has_review_postflight:
return LIFECYCLE_PHASE_REVIEW_POSTFLIGHT
if has_execution:
return LIFECYCLE_PHASE_EXECUTE
return LIFECYCLE_PHASE_SCAN
Createderive_lifecycle_state() — combines current_lifecycle_phase() (pure reader) with derive_display_phase() into one call. Returns a LifecycleState NamedTuple.
python
class LifecycleState(NamedTuple):
mode: str # "plan" or "execute"
display_phase: str # one of LIFECYCLE_PHASE_* constants
Export both derive_display_phase and derive_lifecycle_state in __all__.
Why this priority order: The snapshot path (snapshot.py:331-350) is the user-visible display path and has explicit test coverage asserting this order:
The pipeline's current PRE_REVIEW_WORKFLOW_IDS-first check (line 116) is a reconciliation shortcut whose output mode ("plan") is identical to what initial_review or assessment would produce. Aligning pipeline with this order changes only the display phase string in rare overlap cases (e.g., from "workflow" to "assessment"), making it more correct.
Step 4: Wire pipeline.py to use shared derivation (engine/_plan/sync/pipeline.py)
Scope: Medium
Rewrite_resolve_reconcile_display_phase() to compute boolean signals from queue IDs and call derive_display_phase(). The signal computation preserves pipeline-specific knowledge (ReconcileResult, policy unscored_ids, triage_snapshot):
python
def _resolve_reconcile_display_phase(plan, state, *, result, policy) -> str:
order = [item for item in plan.get("queue_order", []) if isinstance(item, str)]
subjective_ids = [item for item in order if item.startswith("subjective::")]
unscored_ids = set(getattr(policy, "unscored_ids", ()) or ())
skipped = plan.get("skipped") or {}
triage_snapshot = build_triage_snapshot(plan, state)
has_review_postflight = (
(triage_snapshot.triage_has_run
and not triage_snapshot.has_triage_in_queue
and not triage_snapshot.is_triage_stale
and bool(triage_snapshot.live_open_ids))
or bool(open_review_ids(state))
)
return derive_display_phase(
has_initial_review=any(sid in unscored_ids for sid in subjective_ids),
has_postflight_assessment=(
bool(subjective_ids)
and not any(sid in unscored_ids for sid in subjective_ids)
),
has_workflow=(
any(item in PRE_REVIEW_WORKFLOW_IDS for item in order)
or bool(result.workflow_injected_ids)
or any(item.startswith("workflow::") for item in order)
),
has_triage=(
bool(result.triage and (result.triage.injected or result.triage.deferred))
or any(item.startswith("triage::") for item in order)
),
has_review_postflight=has_review_postflight,
has_execution=any(
not item.startswith(("subjective::", "workflow::", "triage::"))
for item in order if item not in skipped
),
fresh_boundary=not bool(plan.get("plan_start_scores")),
prefer_scan=False,
)
Remove_display_phase_to_mode() wrapper (pipeline.py:159-161). Replace the _resolve_reconcile_display_phase + _display_phase_to_mode call sequence at lines 282-289 with a single derive_lifecycle_state() call, or inline the equivalent: derive display phase, then user_facing_mode(display_phase) for the mode.
Step 5: Wire snapshot.py to use shared derivation (engine/_work_queue/snapshot.py)
Scope: Medium
Rewrite_derive_display_phase() in snapshot.py to compute boolean signals from its item-list parameters and delegate to derive_display_phase():
Preserve the early-return in _phase_for_snapshot() at line 296 (if raw_phase == "execute" and (anchored_execution_items or explicit_queue_items): return LIFECYCLE_PHASE_EXECUTE) as a pre-signal override — this forces execute mode when the persisted phase says execute and there's real work. This stays in _phase_for_snapshot, not in the shared function.
Remove the duplicated priority-chain logic that previously lived in _derive_display_phase. The function becomes a thin signal-computation wrapper.
Replace the module docstring with a comprehensive "Marker invariants" section:
python
"""Helpers for the persisted queue lifecycle phase.
Marker invariants
-----------------
Three markers live in ``plan["refresh_state"]``:
``lifecycle_phase`` : ``"plan"`` | ``"execute"``
The persisted lifecycle mode. Written ONLY by ``_set_lifecycle_phase()``
(called from ``reconcile_plan()`` in pipeline.py). Legacy values are
migrated at ``_load_validated_plan()`` time by ``migrate_legacy_phase()``.
Transitions:
- plan → execute: planning work drains from queue
(no workflow/triage items remain)
- execute → plan: ``invalidate_postflight_scan()`` clears the scan marker,
or new review items trigger re-planning via reconcile
``postflight_scan_completed_at_scan_count`` : int
Set by ``mark_postflight_scan_completed()``.
Cleared by ``invalidate_postflight_scan()``
(when objective queue work changes).
``subjective_review_completed_at_scan_count`` : int
Set by ``mark_subjective_review_completed()``.
Carried forward by ``carry_forward_subjective_review()``
across cycle boundaries.
Display phase (never persisted)
-------------------------------
Display phases (review_initial, assessment, workflow, triage, execute, scan)
are derived from queue contents by ``derive_display_phase()`` — a shared pure
function called by both ``pipeline._resolve_reconcile_display_phase()`` and
``snapshot._derive_display_phase()``. Priority order::
initial_review > prefer_scan > assessment > workflow > triage
> review_postflight > execute > scan
``user_facing_mode()`` collapses display phases back to ``"plan"``
or ``"execute"`` for user output.
"""
Step 7: Update and add tests (tests/plan/test_refresh_lifecycle.py, tests/plan/test_reconcile_pipeline.py)
Scope: Medium
Add unit tests for derive_display_phase():
Each signal in isolation → expected display phase
Priority chain: when multiple signals are true, higher-priority wins (specifically: initial_review > workflow, assessment > workflow — matching the assertions in test_sync_split_modules_direct.py:1123-1139)
No mutation: function is stateless (no plan/state args to mutate)
Add unit tests for migrate_legacy_phase():
Migrates old phase names correctly (each _LEGACY_PHASE_TO_MODE entry)
Idempotent on already-migrated plans
Handles stuck-in-plan edge case (legacy "plan" + no plan work → migrates to "execute")
Returns False on fresh plans with no legacy marker
Updatetest_current_lifecycle_phase_falls_back_for_legacy_plans (test_refresh_lifecycle.py:106): verify current_lifecycle_phase() does NOT mutate refresh_state — assert plan dict unchanged after call.
Verifytest_phase_derivation_equivalence_matrix (test_reconcile_pipeline.py) still passes — this validates that pipeline and snapshot produce identical results for the same inputs, now both delegating to the shared function.
Run full test suite: python -m pytest desloppify/tests/ -q
Execution Order
Step 1 — migration into _load_validated_plan() (safe: adds a call, no behavior change for callers)
Step 2 — pure reader (safe: behavior identical since migration already ran at load time)
Step 6 — documentation (independent, no code changes)
Step 3 — shared derive_display_phase() function (new code, no callers yet)
Step 4 — wire pipeline.py (first consumer of shared function)
Step 5 — wire snapshot.py (second consumer)
Step 7 — tests throughout, full suite at end
Validation Order
After Step 2: python -m pytest desloppify/tests/plan/test_refresh_lifecycle.py -q — existing behavior preserved, no mutations on read
After Step 4: python -m pytest desloppify/tests/plan/test_reconcile_pipeline.py -q — equivalence matrix still passes
After Step 5: python -m pytest desloppify/tests/commands/scan/test_plan_reconcile_postflight_and_reconcile.py -q and python -m pytest desloppify/tests/engine/test_sync_split_modules_direct.py -q — assessment-beats-workflow test passes
After Step 7: python -m pytest desloppify/tests/ -q — full suite
"version": 3,
"timestamp": "2026-03-23T20:27:10Z",
"hash": "sha256:dab4a53e2613b1fe80233206875dc249ce38714110236ca4af932399e47b1c9c",
"changes_summary": "Key revisions from v2:\n\n1. Migration coverage (flag: migration-coverage-incomplete, recurring): Moved migration from load_plan() to _load_validated_plan() (persistence.py:88-110) \u2014 the shared bottleneck that both load_plan() AND resolve_plan_load_status() call. This covers the two previously-missed read-only paths: context.py:56 (resolve_persisted_plan_load_status() \u2192 resolve_plan_load_status() \u2192 _load_validated_plan()) and preflight.py:88 (resolve_plan_load_status() \u2192 _load_validated_plan()). Also covers the backup-recovery path. Complete call graph documented in Step 1.\n\n2. Priority order regression (flag: shared-phase-priority-order-regresses-current-behavior): Fixed derive_display_phase() priority chain to match the existing snapshot ordering: initial_review \u2192 prefer_scan \u2192 assessment \u2192 workflow \u2192 triage \u2192 review_postflight \u2192 execute \u2192 scan. The v2 plan incorrectly put has_workflow first. The corrected order is verified by existing tests: test_work_queue_plan_order_and_triage.py:743-757 (initial_review hides workflow) and test_sync_split_modules_direct.py:1123-1139 (assessment beats workflow). Added the priority chain as explicit documentation in both the shared function docstring and the module-level marker invariants.",
"flags_addressed": [
"migration-coverage-incomplete",
"shared-phase-priority-order-regresses-current-behavior"
],
"questions": [],
"success_criteria": [
"derive_display_phase() is a pure function with boolean inputs whose priority chain matches snapshot.py:331-350 exactly: initial_review > prefer_scan > assessment > workflow > triage > review_postflight > execute > scan",
"current_lifecycle_phase() no longer writes to refresh_state \u2014 migration is isolated in migrate_legacy_phase() called from _load_validated_plan()",
"All existing tests pass with no behavioral changes (especially test_phase_derivation_equivalence_matrix, test_current_lifecycle_phase_falls_back_for_legacy_plans, and the assessment-beats-workflow assertion in test_sync_split_modules_direct.py:1123-1139)",
"Both pipeline._resolve_reconcile_display_phase and snapshot._derive_display_phase delegate to the shared derive_display_phase() for their priority chain",
"Migration runs for ALL plan-loading paths: load_plan(), resolve_plan_load_status() (including context.py and preflight.py callers), and backup recovery",
"Marker invariants (lifecycle_phase, postflight_scan_completed_at_scan_count, subjective_review_completed_at_scan_count) are documented with valid values, transitions, and single-writer functions in the module docstring",
"Self-scan succeeds: python -m desloppify --lang python scan --path desloppify produces no errors",
"Fresh/empty plans continue to return 'plan' from current_lifecycle_phase() without requiring a persisted marker"
],
"assumptions": [
"_load_validated_plan() is the single bottleneck for all plan loading \u2014 verified by reading persistence.py: load_plan() \u2192 resolve_plan_load_status() \u2192 _load_validated_plan(), and the backup recovery path also calls _load_validated_plan()",
"The boolean signal mapping between pipeline (queue IDs) and snapshot (item lists) produces equivalent results \u2014 enforced by the existing test_phase_derivation_equivalence_matrix test",
"Legacy migration code is preserved per backward compat policy (data migration for .desloppify/ state formats must be kept)",
"The LifecycleState return type is a NamedTuple to keep it lightweight and immutable",
"The heuristic fallback for plans without a persisted lifecycle_phase marker preserves exact current behavior: postflight_scan_pending \u2192 'plan', plan_start_scores \u2192 'execute', else \u2192 'execute'",
"snapshot._phase_for_snapshot's early-return for execute+real-work (line 296) stays as a pre-signal override outside the shared function \u2014 it's a snapshot-specific optimization",
"Pipeline's PRE_REVIEW_WORKFLOW_IDS-first check being reordered behind initial_review/assessment is safe: (a) the persisted mode ('plan') is identical either way since all these phases map to 'plan', and (b) if both exist, assessment/initial_review is the more correct display phase since review should complete before scan/import"
],
"structure_warnings": [],
"delta_from_previous_percent": 26.51
}
code
Plan structure warnings from validator:
[]
Existing flags:
[
{
"id": "migration-coverage-incomplete",
"concern": "Moving legacy lifecycle migration only into load_plan() still leaves real repository paths uncovered. Several read-only entry points do not call load_plan(); they go through resolve_plan_load_status() and then build queue/snapshot state from the returned plan. If current_lifecycle_phase() becomes a pure reader, those paths can still observe unmigrated legacy phase values.",
"status": "addressed",
"severity": "significant"
},
{
"id": "shared-phase-priority-order-regresses-current-behavior",
"concern": "The proposed shared derive_display_phase() priority chain does not match the repository\u2019s current behavior. It puts workflow ahead of initial review and assessment, but the existing snapshot behavior and tests require initial-review items and postflight assessment to preempt queued workflow items when both are present. Implementing the plan as written would change visible queue phase/output.",
"status": "addressed",
"severity": "significant"
}
]
code
Requirements:
- Consider whether the plan is at the right level of abstraction.
- Reuse existing flag IDs when the same concern is still open.
- `verified_flag_ids` should list previously addressed flags that now appear resolved.
- Focus on concrete issues that would cause real problems.
- Robustness level: standard. Use balanced judgment. Flag significant risks, but do not spend flags on minor polish or executor-obvious boilerplate.
- Verify that the plan remains aligned with the user's original intent.
- Verify that the plan follows the expected structure: one H1 title, `## Overview`, numbered `## Step N:` sections with file references and numbered substeps, plus `## Execution Order` or `## Validation Order`. Missing structure should be flagged as category `completeness` with severity_hint `likely-significant`.
- Flag scope creep explicitly when the plan grows beyond the original idea or recorded user notes. Use the phrase "Scope creep:" in the concern.
- Assign severity_hint carefully. Implementation details the executor will naturally resolve should usually be `likely-minor`.
You are an independent reviewer. Critique the plan against the actual repository.
Consolidate lifecycle phase derivation into a single canonical pure function and add explicit marker lifecycle documentation. Currently phase is determined independently by current_lifecycle_phase() (scan-count markers) and _resolve_reconcile_display_phase() (queue contents) with no structural guarantee they agree. current_lifecycle_phase() also mutates on read (legacy migration). The goal: (1) Create a single derive_lifecycle_state() pure function that returns both persisted mode and display phase, used by all consumers. (2) Remove the mutation side-effect from the getter. (3) Document marker invariants explicitly. Key files: engine/_plan/refresh_lifecycle.py, engine/_plan/sync/pipeline.py, engine/_plan/sync/workflow.py, engine/_plan/sync/context.py, engine/_work_queue/synthetic.py, app/commands/scan/plan_reconcile.py.
User notes and answers:
Focus critique on: (1) the unresolved pipeline-review-signal flag, (2) any edge cases in the boolean signal mapping between pipeline and snapshot, (3) whether the migration in _load_validated_plan could have side effects on read-only paths that don't save, (4) interaction with the force-rescan carry-forward fix we just landed
Currently, lifecycle phase is determined by three independent code paths that can disagree:
current_lifecycle_phase() (refresh_lifecycle.py:100) — returns persisted mode ("plan" / "execute") from refresh_state["lifecycle_phase"]. Also performs legacy migration with mutation on read (line 131: writes back migrated value). Falls back to heuristics based on postflight_scan_pending() and plan_start_scores.
_resolve_reconcile_display_phase() (pipeline.py:99) — derives display phase from queue contents during reconciliation.
_derive_display_phase() (snapshot.py:313) — derives display phase from materialized queue item partitions. Must be kept manually in sync with #2.
Key problems:
current_lifecycle_phase() mutates plan data on read (legacy migration writes)
No single function takes (plan, state) → (persisted_mode, display_phase)
Display-phase derivation rules are duplicated between pipeline.py and snapshot.py with no shared code
Marker invariants (postflight_scan_completed_at, subjective_review_completed_at, lifecycle_phase) are undocumented
Constraints:
Data migration code must be preserved (backward compat policy)
_set_lifecycle_phase is already single-writer via pipeline.reconcile_plan() (enforced by prior refactor)
Display phase constants are never persisted — only "plan" / "execute" are persisted
Complete caller inventory for current_lifecycle_phase():
Plan loading bottleneck: Both load_plan() (persistence.py:164) and resolve_plan_load_status() (persistence.py:113) load plans through _load_validated_plan() (persistence.py:88). Placing migration in _load_validated_plan() covers all paths.
Canonical display-phase priority order (from snapshot.py:331-350, verified by tests):
The shared function must match this exact order. Tests explicitly assert: initial review hides queued workflow/triage items (test_work_queue_plan_order_and_triage.py:743-757), and assessment beats queued workflow (test_sync_split_modules_direct.py:1123-1139).
Step 1: Move legacy migration into _load_validated_plan() (engine/_plan/persistence.py, engine/_plan/refresh_lifecycle.py)
Scope: Small
Extractmigrate_legacy_phase(plan: PlanModel) -> bool into refresh_lifecycle.py. This is the mutation logic from current_lifecycle_phase() lines 106-132: reads the raw lifecycle_phase value, maps legacy names via _LEGACY_PHASE_TO_MODE, handles the stuck-in-plan edge case (lines 118-129), and writes back the canonical mode. Returns True if a write occurred.
Callmigrate_legacy_phase(plan) inside _load_validated_plan() (persistence.py:88-110) after ensure_plan_defaults(data) (line 108). This is the shared loading bottleneck for bothload_plan() and resolve_plan_load_status(), covering all entry points:
Also handles the backup-recovery path at persistence.py:129 (which also calls _load_validated_plan).
Step 2: Make current_lifecycle_phase() a pure reader (engine/_plan/refresh_lifecycle.py)
Scope: Small
Remove the mutation block (lines 106-132) from current_lifecycle_phase(). Replace with a pure read: check refresh_state["lifecycle_phase"], return if valid.
Preserve the heuristic fallback (lines 133-137) for plans that have never had a phase set (fresh/empty plans). Explicit default rule:
If postflight_scan_pending(plan) → return "plan"
If plan.get("plan_start_scores") → return "execute"
Else → return "execute"
This matches the existing behavior tested in test_refresh_lifecycle.py:106-121: empty plan returns "plan", plan with plan_start_scores returns "execute".
No callers change — they all still call current_lifecycle_phase() with the same semantics. The only difference: no mutation occurs on read.
python
def current_lifecycle_phase(plan: PlanModel) -> str:
"""Return the persisted lifecycle mode: 'plan' or 'execute'.
Pure reader — never mutates plan. Legacy migration runs at
_load_validated_plan() time via migrate_legacy_phase().
For fresh plans without a persisted marker, falls back to heuristics.
"""
refresh_state = plan.get("refresh_state")
if isinstance(refresh_state, dict):
phase = refresh_state.get(_LIFECYCLE_PHASE_KEY)
if isinstance(phase, str) and phase in _VALID_PHASES:
return phase
# Fallback for plans that haven't been through reconcile yet.
if postflight_scan_pending(plan):
return "plan"
if plan.get("plan_start_scores"):
return "execute"
return "execute"
Step 3: Create derive_display_phase() shared pure function (engine/_plan/refresh_lifecycle.py)
Scope: Medium
Createderive_display_phase() — a pure function that takes boolean phase signals and returns a display phase string. The priority chain matches the existing snapshot ordering (snapshot.py:331-350):
python
def derive_display_phase(
*,
has_initial_review: bool,
has_postflight_assessment: bool,
has_workflow: bool,
has_triage: bool,
has_review_postflight: bool,
has_execution: bool,
fresh_boundary: bool,
prefer_scan: bool,
) -> str:
"""Canonical display-phase derivation from abstract signals.
Priority order matches snapshot._derive_display_phase (the user-visible
path). Both pipeline and snapshot compute boolean signals from their
respective inputs and call this function.
Priority chain:
initial_review > prefer_scan > assessment > workflow > triage
> review_postflight > execute > scan (default)
"""
if fresh_boundary and has_initial_review:
return LIFECYCLE_PHASE_REVIEW_INITIAL
if prefer_scan:
return LIFECYCLE_PHASE_SCAN
if has_postflight_assessment:
return LIFECYCLE_PHASE_ASSESSMENT_POSTFLIGHT
if has_workflow:
return LIFECYCLE_PHASE_WORKFLOW_POSTFLIGHT
if has_triage:
return LIFECYCLE_PHASE_TRIAGE_POSTFLIGHT
if has_review_postflight:
return LIFECYCLE_PHASE_REVIEW_POSTFLIGHT
if has_execution:
return LIFECYCLE_PHASE_EXECUTE
return LIFECYCLE_PHASE_SCAN
Createderive_lifecycle_state() — combines current_lifecycle_phase() (pure reader) with derive_display_phase() into one call. Returns a LifecycleState NamedTuple.
python
class LifecycleState(NamedTuple):
mode: str # "plan" or "execute"
display_phase: str # one of LIFECYCLE_PHASE_* constants
Export both derive_display_phase and derive_lifecycle_state in __all__.
Why this priority order: The snapshot path (snapshot.py:331-350) is the user-visible display path and has explicit test coverage asserting this order:
The pipeline's current PRE_REVIEW_WORKFLOW_IDS-first check (line 116) is a reconciliation shortcut whose output mode ("plan") is identical to what initial_review or assessment would produce. Aligning pipeline with this order changes only the display phase string in rare overlap cases (e.g., from "workflow" to "assessment"), making it more correct.
Step 4: Wire pipeline.py to use shared derivation (engine/_plan/sync/pipeline.py)
Scope: Medium
Rewrite_resolve_reconcile_display_phase() to compute boolean signals from queue IDs and call derive_display_phase(). The signal computation preserves pipeline-specific knowledge (ReconcileResult, policy unscored_ids, triage_snapshot):
python
def _resolve_reconcile_display_phase(plan, state, *, result, policy) -> str:
order = [item for item in plan.get("queue_order", []) if isinstance(item, str)]
subjective_ids = [item for item in order if item.startswith("subjective::")]
unscored_ids = set(getattr(policy, "unscored_ids", ()) or ())
skipped = plan.get("skipped") or {}
triage_snapshot = build_triage_snapshot(plan, state)
has_review_postflight = (
(triage_snapshot.triage_has_run
and not triage_snapshot.has_triage_in_queue
and not triage_snapshot.is_triage_stale
and bool(triage_snapshot.live_open_ids))
or bool(open_review_ids(state))
)
return derive_display_phase(
has_initial_review=any(sid in unscored_ids for sid in subjective_ids),
has_postflight_assessment=(
bool(subjective_ids)
and not any(sid in unscored_ids for sid in subjective_ids)
),
has_workflow=(
any(item in PRE_REVIEW_WORKFLOW_IDS for item in order)
or bool(result.workflow_injected_ids)
or any(item.startswith("workflow::") for item in order)
),
has_triage=(
bool(result.triage and (result.triage.injected or result.triage.deferred))
or any(item.startswith("triage::") for item in order)
),
has_review_postflight=has_review_postflight,
has_execution=any(
not item.startswith(("subjective::", "workflow::", "triage::"))
for item in order if item not in skipped
),
fresh_boundary=not bool(plan.get("plan_start_scores")),
prefer_scan=False,
)
Remove_display_phase_to_mode() wrapper (pipeline.py:159-161). Replace the _resolve_reconcile_display_phase + _display_phase_to_mode call sequence at lines 282-289 with a single derive_lifecycle_state() call, or inline the equivalent: derive display phase, then user_facing_mode(display_phase) for the mode.
Step 5: Wire snapshot.py to use shared derivation (engine/_work_queue/snapshot.py)
Scope: Medium
Rewrite_derive_display_phase() in snapshot.py to compute boolean signals from its item-list parameters and delegate to derive_display_phase():
Preserve the early-return in _phase_for_snapshot() at line 296 (if raw_phase == "execute" and (anchored_execution_items or explicit_queue_items): return LIFECYCLE_PHASE_EXECUTE) as a pre-signal override — this forces execute mode when the persisted phase says execute and there's real work. This stays in _phase_for_snapshot, not in the shared function.
Remove the duplicated priority-chain logic that previously lived in _derive_display_phase. The function becomes a thin signal-computation wrapper.
Replace the module docstring with a comprehensive "Marker invariants" section:
python
"""Helpers for the persisted queue lifecycle phase.
Marker invariants
-----------------
Three markers live in ``plan["refresh_state"]``:
``lifecycle_phase`` : ``"plan"`` | ``"execute"``
The persisted lifecycle mode. Written ONLY by ``_set_lifecycle_phase()``
(called from ``reconcile_plan()`` in pipeline.py). Legacy values are
migrated at ``_load_validated_plan()`` time by ``migrate_legacy_phase()``.
Transitions:
- plan → execute: planning work drains from queue
(no workflow/triage items remain)
- execute → plan: ``invalidate_postflight_scan()`` clears the scan marker,
or new review items trigger re-planning via reconcile
``postflight_scan_completed_at_scan_count`` : int
Set by ``mark_postflight_scan_completed()``.
Cleared by ``invalidate_postflight_scan()``
(when objective queue work changes).
``subjective_review_completed_at_scan_count`` : int
Set by ``mark_subjective_review_completed()``.
Carried forward by ``carry_forward_subjective_review()``
across cycle boundaries.
Display phase (never persisted)
-------------------------------
Display phases (review_initial, assessment, workflow, triage, execute, scan)
are derived from queue contents by ``derive_display_phase()`` — a shared pure
function called by both ``pipeline._resolve_reconcile_display_phase()`` and
``snapshot._derive_display_phase()``. Priority order::
initial_review > prefer_scan > assessment > workflow > triage
> review_postflight > execute > scan
``user_facing_mode()`` collapses display phases back to ``"plan"``
or ``"execute"`` for user output.
"""
Step 7: Update and add tests (tests/plan/test_refresh_lifecycle.py, tests/plan/test_reconcile_pipeline.py)
Scope: Medium
Add unit tests for derive_display_phase():
Each signal in isolation → expected display phase
Priority chain: when multiple signals are true, higher-priority wins (specifically: initial_review > workflow, assessment > workflow — matching the assertions in test_sync_split_modules_direct.py:1123-1139)
No mutation: function is stateless (no plan/state args to mutate)
Add unit tests for migrate_legacy_phase():
Migrates old phase names correctly (each _LEGACY_PHASE_TO_MODE entry)
Idempotent on already-migrated plans
Handles stuck-in-plan edge case (legacy "plan" + no plan work → migrates to "execute")
Returns False on fresh plans with no legacy marker
Updatetest_current_lifecycle_phase_falls_back_for_legacy_plans (test_refresh_lifecycle.py:106): verify current_lifecycle_phase() does NOT mutate refresh_state — assert plan dict unchanged after call.
Verifytest_phase_derivation_equivalence_matrix (test_reconcile_pipeline.py) still passes — this validates that pipeline and snapshot produce identical results for the same inputs, now both delegating to the shared function.
Run full test suite: python -m pytest desloppify/tests/ -q
Execution Order
Step 1 — migration into _load_validated_plan() (safe: adds a call, no behavior change for callers)
Step 2 — pure reader (safe: behavior identical since migration already ran at load time)
Step 6 — documentation (independent, no code changes)
Step 3 — shared derive_display_phase() function (new code, no callers yet)
Step 4 — wire pipeline.py (first consumer of shared function)
Step 5 — wire snapshot.py (second consumer)
Step 7 — tests throughout, full suite at end
Validation Order
After Step 2: python -m pytest desloppify/tests/plan/test_refresh_lifecycle.py -q — existing behavior preserved, no mutations on read
After Step 4: python -m pytest desloppify/tests/plan/test_reconcile_pipeline.py -q — equivalence matrix still passes
After Step 5: python -m pytest desloppify/tests/commands/scan/test_plan_reconcile_postflight_and_reconcile.py -q and python -m pytest desloppify/tests/engine/test_sync_split_modules_direct.py -q — assessment-beats-workflow test passes
After Step 7: python -m pytest desloppify/tests/ -q — full suite
"version": 3,
"timestamp": "2026-03-23T20:27:10Z",
"hash": "sha256:dab4a53e2613b1fe80233206875dc249ce38714110236ca4af932399e47b1c9c",
"changes_summary": "Key revisions from v2:\n\n1. Migration coverage (flag: migration-coverage-incomplete, recurring): Moved migration from load_plan() to _load_validated_plan() (persistence.py:88-110) \u2014 the shared bottleneck that both load_plan() AND resolve_plan_load_status() call. This covers the two previously-missed read-only paths: context.py:56 (resolve_persisted_plan_load_status() \u2192 resolve_plan_load_status() \u2192 _load_validated_plan()) and preflight.py:88 (resolve_plan_load_status() \u2192 _load_validated_plan()). Also covers the backup-recovery path. Complete call graph documented in Step 1.\n\n2. Priority order regression (flag: shared-phase-priority-order-regresses-current-behavior): Fixed derive_display_phase() priority chain to match the existing snapshot ordering: initial_review \u2192 prefer_scan \u2192 assessment \u2192 workflow \u2192 triage \u2192 review_postflight \u2192 execute \u2192 scan. The v2 plan incorrectly put has_workflow first. The corrected order is verified by existing tests: test_work_queue_plan_order_and_triage.py:743-757 (initial_review hides workflow) and test_sync_split_modules_direct.py:1123-1139 (assessment beats workflow). Added the priority chain as explicit documentation in both the shared function docstring and the module-level marker invariants.",
"flags_addressed": [
"migration-coverage-incomplete",
"shared-phase-priority-order-regresses-current-behavior"
],
"questions": [],
"success_criteria": [
"derive_display_phase() is a pure function with boolean inputs whose priority chain matches snapshot.py:331-350 exactly: initial_review > prefer_scan > assessment > workflow > triage > review_postflight > execute > scan",
"current_lifecycle_phase() no longer writes to refresh_state \u2014 migration is isolated in migrate_legacy_phase() called from _load_validated_plan()",
"All existing tests pass with no behavioral changes (especially test_phase_derivation_equivalence_matrix, test_current_lifecycle_phase_falls_back_for_legacy_plans, and the assessment-beats-workflow assertion in test_sync_split_modules_direct.py:1123-1139)",
"Both pipeline._resolve_reconcile_display_phase and snapshot._derive_display_phase delegate to the shared derive_display_phase() for their priority chain",
"Migration runs for ALL plan-loading paths: load_plan(), resolve_plan_load_status() (including context.py and preflight.py callers), and backup recovery",
"Marker invariants (lifecycle_phase, postflight_scan_completed_at_scan_count, subjective_review_completed_at_scan_count) are documented with valid values, transitions, and single-writer functions in the module docstring",
"Self-scan succeeds: python -m desloppify --lang python scan --path desloppify produces no errors",
"Fresh/empty plans continue to return 'plan' from current_lifecycle_phase() without requiring a persisted marker"
],
"assumptions": [
"_load_validated_plan() is the single bottleneck for all plan loading \u2014 verified by reading persistence.py: load_plan() \u2192 resolve_plan_load_status() \u2192 _load_validated_plan(), and the backup recovery path also calls _load_validated_plan()",
"The boolean signal mapping between pipeline (queue IDs) and snapshot (item lists) produces equivalent results \u2014 enforced by the existing test_phase_derivation_equivalence_matrix test",
"Legacy migration code is preserved per backward compat policy (data migration for .desloppify/ state formats must be kept)",
"The LifecycleState return type is a NamedTuple to keep it lightweight and immutable",
"The heuristic fallback for plans without a persisted lifecycle_phase marker preserves exact current behavior: postflight_scan_pending \u2192 'plan', plan_start_scores \u2192 'execute', else \u2192 'execute'",
"snapshot._phase_for_snapshot's early-return for execute+real-work (line 296) stays as a pre-signal override outside the shared function \u2014 it's a snapshot-specific optimization",
"Pipeline's PRE_REVIEW_WORKFLOW_IDS-first check being reordered behind initial_review/assessment is safe: (a) the persisted mode ('plan') is identical either way since all these phases map to 'plan', and (b) if both exist, assessment/initial_review is the more correct display phase since review should complete before scan/import"
],
"structure_warnings": [],
"delta_from_previous_percent": 26.51
}
code
Plan structure warnings from validator:
[]
Existing flags:
[
{
"id": "pipeline-review-signal-overstates-postflight-review",
"concern": "The plan\u2019s Step 4 signal mapping is still too coarse for the actual repository. It treats open_review_ids(state) as equivalent to has_review_postflight, but snapshot only enters review-postflight when review findings are actually executable after triage gating. In mixed states with real execute work plus non-executable review findings, the proposed mapping would incorrectly make review beat execute.",
"status": "open",
"severity": "significant"
}
]
code
Requirements:
- Consider whether the plan is at the right level of abstraction.
- Reuse existing flag IDs when the same concern is still open.
- `verified_flag_ids` should list previously addressed flags that now appear resolved.
- Focus on concrete issues that would cause real problems.
- Robustness level: standard. Use balanced judgment. Flag significant risks, but do not spend flags on minor polish or executor-obvious boilerplate.
- Verify that the plan remains aligned with the user's original intent.
- Verify that the plan follows the expected structure: one H1 title, `## Overview`, numbered `## Step N:` sections with file references and numbered substeps, plus `## Execution Order` or `## Validation Order`. Missing structure should be flagged as category `completeness` with severity_hint `likely-significant`.
- Flag scope creep explicitly when the plan grows beyond the original idea or recorded user notes. Use the phrase "Scope creep:" in the concern.
- Assign severity_hint carefully. Implementation details the executor will naturally resolve should usually be `likely-minor`.
bool(open_review_ids(state))
has_review_postflight
has_review_postflight = (...) or bool(open_review_ids(state))
Consolidate lifecycle phase derivation into a single canonical pure function and add explicit marker lifecycle documentation. Currently phase is determined independently by current_lifecycle_phase() (scan-count markers) and _resolve_reconcile_display_phase() (queue contents) with no structural guarantee they agree. current_lifecycle_phase() also mutates on read (legacy migration). The goal: (1) Create a single derive_lifecycle_state() pure function that returns both persisted mode and display phase, used by all consumers. (2) Remove the mutation side-effect from the getter. (3) Document marker invariants explicitly. Key files: engine/_plan/refresh_lifecycle.py, engine/_plan/sync/pipeline.py, engine/_plan/sync/workflow.py, engine/_plan/sync/context.py, engine/_work_queue/synthetic.py, app/commands/scan/plan_reconcile.py.
User notes and answers:
Focus critique on: (1) the unresolved pipeline-review-signal flag, (2) any edge cases in the boolean signal mapping between pipeline and snapshot, (3) whether the migration in _load_validated_plan could have side effects on read-only paths that don't save, (4) interaction with the force-rescan carry-forward fix we just landed
Fix the two open flags: (1) pipeline-review-signal-overstates-postflight-review: has_review_postflight must preserve pipeline.py:145-156 gating, not use bare open_review_ids(). (2) scan-vs-workflow-signal-collapsed-in-pipeline-mapping: workflow::run-scan and workflow::deferred-disposition must feed prefer_scan=True, only workflow::import-scores feeds has_workflow=True. Both fixes are to Step 4 pseudocode only.
Currently, lifecycle phase is determined by three independent code paths that can disagree:
current_lifecycle_phase() (refresh_lifecycle.py:100) — returns persisted mode ("plan" / "execute") from refresh_state["lifecycle_phase"]. Also performs legacy migration with mutation on read (line 131: writes back migrated value). Falls back to heuristics based on postflight_scan_pending() and plan_start_scores.
_resolve_reconcile_display_phase() (pipeline.py:99) — derives display phase from queue contents during reconciliation.
_derive_display_phase() (snapshot.py:313) — derives display phase from materialized queue item partitions. Must be kept manually in sync with #2.
Key problems:
current_lifecycle_phase() mutates plan data on read (legacy migration writes)
No single function takes (plan, state) → (persisted_mode, display_phase)
Display-phase derivation rules are duplicated between pipeline.py and snapshot.py with no shared code
Marker invariants (postflight_scan_completed_at, subjective_review_completed_at, lifecycle_phase) are undocumented
Constraints:
Data migration code must be preserved (backward compat policy)
_set_lifecycle_phase is already single-writer via pipeline.reconcile_plan() (enforced by prior refactor)
Display phase constants are never persisted — only "plan" / "execute" are persisted
Complete caller inventory for current_lifecycle_phase():
Plan loading bottleneck: Both load_plan() (persistence.py:164) and resolve_plan_load_status() (persistence.py:113) load plans through _load_validated_plan() (persistence.py:88). Placing migration in _load_validated_plan() covers all paths.
Canonical display-phase priority order (from snapshot.py:331-350, verified by tests):
The shared function must match this exact order. Tests explicitly assert: initial review hides queued workflow/triage items (test_work_queue_plan_order_and_triage.py:743-757), and assessment beats queued workflow (test_sync_split_modules_direct.py:1123-1139).
Step 1: Move legacy migration into _load_validated_plan() (engine/_plan/persistence.py, engine/_plan/refresh_lifecycle.py)
Scope: Small
Extractmigrate_legacy_phase(plan: PlanModel) -> bool into refresh_lifecycle.py. This is the mutation logic from current_lifecycle_phase() lines 106-132: reads the raw lifecycle_phase value, maps legacy names via _LEGACY_PHASE_TO_MODE, handles the stuck-in-plan edge case (lines 118-129), and writes back the canonical mode. Returns True if a write occurred.
Callmigrate_legacy_phase(plan) inside _load_validated_plan() (persistence.py:88-110) after ensure_plan_defaults(data) (line 108). This is the shared loading bottleneck for bothload_plan() and resolve_plan_load_status(), covering all entry points:
Also handles the backup-recovery path at persistence.py:129 (which also calls _load_validated_plan).
Step 2: Make current_lifecycle_phase() a pure reader (engine/_plan/refresh_lifecycle.py)
Scope: Small
Remove the mutation block (lines 106-132) from current_lifecycle_phase(). Replace with a pure read: check refresh_state["lifecycle_phase"], return if valid.
Preserve the heuristic fallback (lines 133-137) for plans that have never had a phase set (fresh/empty plans). Explicit default rule:
If postflight_scan_pending(plan) → return "plan"
If plan.get("plan_start_scores") → return "execute"
Else → return "execute"
This matches the existing behavior tested in test_refresh_lifecycle.py:106-121: empty plan returns "plan", plan with plan_start_scores returns "execute".
No callers change — they all still call current_lifecycle_phase() with the same semantics. The only difference: no mutation occurs on read.
python
def current_lifecycle_phase(plan: PlanModel) -> str:
"""Return the persisted lifecycle mode: 'plan' or 'execute'.
Pure reader — never mutates plan. Legacy migration runs at
_load_validated_plan() time via migrate_legacy_phase().
For fresh plans without a persisted marker, falls back to heuristics.
"""
refresh_state = plan.get("refresh_state")
if isinstance(refresh_state, dict):
phase = refresh_state.get(_LIFECYCLE_PHASE_KEY)
if isinstance(phase, str) and phase in _VALID_PHASES:
return phase
# Fallback for plans that haven't been through reconcile yet.
if postflight_scan_pending(plan):
return "plan"
if plan.get("plan_start_scores"):
return "execute"
return "execute"
Step 3: Create derive_display_phase() shared pure function (engine/_plan/refresh_lifecycle.py)
Scope: Medium
Createderive_display_phase() — a pure function that takes boolean phase signals and returns a display phase string. The priority chain matches the existing snapshot ordering (snapshot.py:331-350):
python
def derive_display_phase(
*,
has_initial_review: bool,
has_postflight_assessment: bool,
has_workflow: bool,
has_triage: bool,
has_review_postflight: bool,
has_execution: bool,
fresh_boundary: bool,
prefer_scan: bool,
) -> str:
"""Canonical display-phase derivation from abstract signals.
Priority order matches snapshot._derive_display_phase (the user-visible
path). Both pipeline and snapshot compute boolean signals from their
respective inputs and call this function.
Priority chain:
initial_review > prefer_scan > assessment > workflow > triage
> review_postflight > execute > scan (default)
"""
if fresh_boundary and has_initial_review:
return LIFECYCLE_PHASE_REVIEW_INITIAL
if prefer_scan:
return LIFECYCLE_PHASE_SCAN
if has_postflight_assessment:
return LIFECYCLE_PHASE_ASSESSMENT_POSTFLIGHT
if has_workflow:
return LIFECYCLE_PHASE_WORKFLOW_POSTFLIGHT
if has_triage:
return LIFECYCLE_PHASE_TRIAGE_POSTFLIGHT
if has_review_postflight:
return LIFECYCLE_PHASE_REVIEW_POSTFLIGHT
if has_execution:
return LIFECYCLE_PHASE_EXECUTE
return LIFECYCLE_PHASE_SCAN
Createderive_lifecycle_state() — combines current_lifecycle_phase() (pure reader) with derive_display_phase() into one call. Returns a LifecycleState NamedTuple.
python
class LifecycleState(NamedTuple):
mode: str # "plan" or "execute"
display_phase: str # one of LIFECYCLE_PHASE_* constants
Export both derive_display_phase and derive_lifecycle_state in __all__.
Why this priority order: The snapshot path (snapshot.py:331-350) is the user-visible display path and has explicit test coverage asserting this order:
The pipeline's current PRE_REVIEW_WORKFLOW_IDS-first check (line 116) is a reconciliation shortcut whose output mode ("plan") is identical to what initial_review or assessment would produce. Aligning pipeline with this order changes only the display phase string in rare overlap cases (e.g., from "workflow" to "assessment"), making it more correct.
Step 4: Wire pipeline.py to use shared derivation (engine/_plan/sync/pipeline.py)
Scope: Medium
Rewrite_resolve_reconcile_display_phase() to compute boolean signals from queue IDs and call derive_display_phase(). The signal computation preserves pipeline-specific knowledge (ReconcileResult, policy unscored_ids, triage_snapshot).
Critical signal-mapping rules (derived from snapshot.py:230-255 and existing test assertions):
workflow::run-scan and workflow::deferred-disposition → prefer_scan=True (NOT has_workflow). These are scan-phase items. Tests: test_sync_split_modules_direct.py:998-1004 and :1201-1203 assert LIFECYCLE_PHASE_SCAN.
has_review_postflight must NOT use bare open_review_ids(state) — it's a fallback only when no real execution work exists. Test: test_reconcile_pipeline.py:457-490 expects LIFECYCLE_PHASE_EXECUTE when objective work coexists with review findings.
Note: The current pipeline code (line 116) incorrectly collapses ALL PRE_REVIEW_WORKFLOW_IDS into workflow phase, which disagrees with snapshot's scan/workflow split. This refactor fixes that pre-existing disagreement by aligning pipeline with snapshot's signal semantics.
python
# Constants for scan-phase workflow items (snapshot treats these as scan_items)
_SCAN_PHASE_WORKFLOW_IDS = {
WORKFLOW_DEFERRED_DISPOSITION_ID,
WORKFLOW_RUN_SCAN_ID,
}
def _resolve_reconcile_display_phase(plan, state, *, result, policy) -> str:
order = [item for item in plan.get("queue_order", []) if isinstance(item, str)]
subjective_ids = [item for item in order if item.startswith("subjective::")]
unscored_ids = set(getattr(policy, "unscored_ids", ()) or ())
skipped = plan.get("skipped") or {}
# Split workflow IDs: scan-phase vs true workflow
has_scan_workflow = any(item in _SCAN_PHASE_WORKFLOW_IDS for item in order)
has_true_workflow = (
any(
item.startswith("workflow::") and item not in _SCAN_PHASE_WORKFLOW_IDS
for item in order
)
or bool(result.workflow_injected_ids)
)
# Review-postflight: triage-gated review findings first, bare open_review_ids
# ONLY as fallback when no real execution work exists (see priority chain below)
triage_snapshot = build_triage_snapshot(plan, state)
triage_gated_review = (
triage_snapshot.triage_has_run
and not triage_snapshot.has_triage_in_queue
and not triage_snapshot.is_triage_stale
and bool(triage_snapshot.live_open_ids)
)
has_real_work = any(
not item.startswith(("subjective::", "workflow::", "triage::"))
for item in order if item not in skipped
)
# open_review_ids fallback: only when no real execution work exists
has_review_postflight = triage_gated_review or (
not has_real_work and bool(open_review_ids(state))
)
return derive_display_phase(
has_initial_review=any(sid in unscored_ids for sid in subjective_ids),
has_postflight_assessment=(
bool(subjective_ids)
and not any(sid in unscored_ids for sid in subjective_ids)
),
has_workflow=has_true_workflow,
has_triage=(
bool(result.triage and (result.triage.injected or result.triage.deferred))
or any(item.startswith("triage::") for item in order)
),
has_review_postflight=has_review_postflight,
has_execution=has_real_work,
fresh_boundary=not bool(plan.get("plan_start_scores")),
prefer_scan=has_scan_workflow,
)
Remove_display_phase_to_mode() wrapper (pipeline.py:159-161). Replace the _resolve_reconcile_display_phase + _display_phase_to_mode call sequence at lines 282-289 with a single derive_lifecycle_state() call, or inline the equivalent: derive display phase, then user_facing_mode(display_phase) for the mode.
Step 5: Wire snapshot.py to use shared derivation (engine/_work_queue/snapshot.py)
Scope: Medium
Rewrite_derive_display_phase() in snapshot.py to compute boolean signals from its item-list parameters and delegate to derive_display_phase():
Preserve the early-return in _phase_for_snapshot() at line 296 (if raw_phase == "execute" and (anchored_execution_items or explicit_queue_items): return LIFECYCLE_PHASE_EXECUTE) as a pre-signal override — this forces execute mode when the persisted phase says execute and there's real work. This stays in _phase_for_snapshot, not in the shared function.
Remove the duplicated priority-chain logic that previously lived in _derive_display_phase. The function becomes a thin signal-computation wrapper.
Replace the module docstring with a comprehensive "Marker invariants" section:
python
"""Helpers for the persisted queue lifecycle phase.
Marker invariants
-----------------
Three markers live in ``plan["refresh_state"]``:
``lifecycle_phase`` : ``"plan"`` | ``"execute"``
The persisted lifecycle mode. Written ONLY by ``_set_lifecycle_phase()``
(called from ``reconcile_plan()`` in pipeline.py). Legacy values are
migrated at ``_load_validated_plan()`` time by ``migrate_legacy_phase()``.
Transitions:
- plan → execute: planning work drains from queue
(no workflow/triage items remain)
- execute → plan: ``invalidate_postflight_scan()`` clears the scan marker,
or new review items trigger re-planning via reconcile
``postflight_scan_completed_at_scan_count`` : int
Set by ``mark_postflight_scan_completed()``.
Cleared by ``invalidate_postflight_scan()``
(when objective queue work changes).
``subjective_review_completed_at_scan_count`` : int
Set by ``mark_subjective_review_completed()``.
Carried forward by ``carry_forward_subjective_review()``
across cycle boundaries.
Display phase (never persisted)
-------------------------------
Display phases (review_initial, assessment, workflow, triage, execute, scan)
are derived from queue contents by ``derive_display_phase()`` — a shared pure
function called by both ``pipeline._resolve_reconcile_display_phase()`` and
``snapshot._derive_display_phase()``. Priority order::
initial_review > prefer_scan > assessment > workflow > triage
> review_postflight > execute > scan
``user_facing_mode()`` collapses display phases back to ``"plan"``
or ``"execute"`` for user output.
"""
Step 7: Update and add tests (tests/plan/test_refresh_lifecycle.py, tests/plan/test_reconcile_pipeline.py)
Scope: Medium
Add unit tests for derive_display_phase():
Each signal in isolation → expected display phase
Priority chain: when multiple signals are true, higher-priority wins (specifically: initial_review > workflow, assessment > workflow — matching the assertions in test_sync_split_modules_direct.py:1123-1139)
No mutation: function is stateless (no plan/state args to mutate)
Add unit tests for migrate_legacy_phase():
Migrates old phase names correctly (each _LEGACY_PHASE_TO_MODE entry)
Idempotent on already-migrated plans
Handles stuck-in-plan edge case (legacy "plan" + no plan work → migrates to "execute")
Returns False on fresh plans with no legacy marker
Updatetest_current_lifecycle_phase_falls_back_for_legacy_plans (test_refresh_lifecycle.py:106): verify current_lifecycle_phase() does NOT mutate refresh_state — assert plan dict unchanged after call.
Verifytest_phase_derivation_equivalence_matrix (test_reconcile_pipeline.py) still passes — this validates that pipeline and snapshot produce identical results for the same inputs, now both delegating to the shared function.
Run full test suite: python -m pytest desloppify/tests/ -q
Execution Order
Step 1 — migration into _load_validated_plan() (safe: adds a call, no behavior change for callers)
Step 2 — pure reader (safe: behavior identical since migration already ran at load time)
Step 6 — documentation (independent, no code changes)
Step 3 — shared derive_display_phase() function (new code, no callers yet)
Step 4 — wire pipeline.py (first consumer of shared function)
Step 5 — wire snapshot.py (second consumer)
Step 7 — tests throughout, full suite at end
Validation Order
After Step 2: python -m pytest desloppify/tests/plan/test_refresh_lifecycle.py -q — existing behavior preserved, no mutations on read
After Step 4: python -m pytest desloppify/tests/plan/test_reconcile_pipeline.py -q — equivalence matrix still passes
After Step 5: python -m pytest desloppify/tests/commands/scan/test_plan_reconcile_postflight_and_reconcile.py -q and python -m pytest desloppify/tests/engine/test_sync_split_modules_direct.py -q — assessment-beats-workflow test passes
After Step 7: python -m pytest desloppify/tests/ -q — full suite
"version": 3,
"timestamp": "2026-03-23T20:27:10Z",
"hash": "sha256:dab4a53e2613b1fe80233206875dc249ce38714110236ca4af932399e47b1c9c",
"changes_summary": "Key revisions from v2:\n\n1. Migration coverage (flag: migration-coverage-incomplete, recurring): Moved migration from load_plan() to _load_validated_plan() (persistence.py:88-110) \u2014 the shared bottleneck that both load_plan() AND resolve_plan_load_status() call. This covers the two previously-missed read-only paths: context.py:56 (resolve_persisted_plan_load_status() \u2192 resolve_plan_load_status() \u2192 _load_validated_plan()) and preflight.py:88 (resolve_plan_load_status() \u2192 _load_validated_plan()). Also covers the backup-recovery path. Complete call graph documented in Step 1.\n\n2. Priority order regression (flag: shared-phase-priority-order-regresses-current-behavior): Fixed derive_display_phase() priority chain to match the existing snapshot ordering: initial_review \u2192 prefer_scan \u2192 assessment \u2192 workflow \u2192 triage \u2192 review_postflight \u2192 execute \u2192 scan. The v2 plan incorrectly put has_workflow first. The corrected order is verified by existing tests: test_work_queue_plan_order_and_triage.py:743-757 (initial_review hides workflow) and test_sync_split_modules_direct.py:1123-1139 (assessment beats workflow). Added the priority chain as explicit documentation in both the shared function docstring and the module-level marker invariants.",
"flags_addressed": [
"migration-coverage-incomplete",
"shared-phase-priority-order-regresses-current-behavior"
],
"questions": [],
"success_criteria": [
"derive_display_phase() is a pure function with boolean inputs whose priority chain matches snapshot.py:331-350 exactly: initial_review > prefer_scan > assessment > workflow > triage > review_postflight > execute > scan",
"current_lifecycle_phase() no longer writes to refresh_state \u2014 migration is isolated in migrate_legacy_phase() called from _load_validated_plan()",
"All existing tests pass with no behavioral changes (especially test_phase_derivation_equivalence_matrix, test_current_lifecycle_phase_falls_back_for_legacy_plans, and the assessment-beats-workflow assertion in test_sync_split_modules_direct.py:1123-1139)",
"Both pipeline._resolve_reconcile_display_phase and snapshot._derive_display_phase delegate to the shared derive_display_phase() for their priority chain",
"Migration runs for ALL plan-loading paths: load_plan(), resolve_plan_load_status() (including context.py and preflight.py callers), and backup recovery",
"Marker invariants (lifecycle_phase, postflight_scan_completed_at_scan_count, subjective_review_completed_at_scan_count) are documented with valid values, transitions, and single-writer functions in the module docstring",
"Self-scan succeeds: python -m desloppify --lang python scan --path desloppify produces no errors",
"Fresh/empty plans continue to return 'plan' from current_lifecycle_phase() without requiring a persisted marker"
],
"assumptions": [
"_load_validated_plan() is the single bottleneck for all plan loading \u2014 verified by reading persistence.py: load_plan() \u2192 resolve_plan_load_status() \u2192 _load_validated_plan(), and the backup recovery path also calls _load_validated_plan()",
"The boolean signal mapping between pipeline (queue IDs) and snapshot (item lists) produces equivalent results \u2014 enforced by the existing test_phase_derivation_equivalence_matrix test",
"Legacy migration code is preserved per backward compat policy (data migration for .desloppify/ state formats must be kept)",
"The LifecycleState return type is a NamedTuple to keep it lightweight and immutable",
"The heuristic fallback for plans without a persisted lifecycle_phase marker preserves exact current behavior: postflight_scan_pending \u2192 'plan', plan_start_scores \u2192 'execute', else \u2192 'execute'",
"snapshot._phase_for_snapshot's early-return for execute+real-work (line 296) stays as a pre-signal override outside the shared function \u2014 it's a snapshot-specific optimization",
"Pipeline's PRE_REVIEW_WORKFLOW_IDS-first check being reordered behind initial_review/assessment is safe: (a) the persisted mode ('plan') is identical either way since all these phases map to 'plan', and (b) if both exist, assessment/initial_review is the more correct display phase since review should complete before scan/import"
],
"structure_warnings": [],
"delta_from_previous_percent": 26.51
}
code
Plan structure warnings from validator:
[]
Existing flags:
[
{
"id": "pipeline-review-signal-overstates-postflight-review",
"concern": "The unresolved review-postflight signal problem is still present. Step 4 maps bool(open_review_ids(state)) directly into has_review_postflight, but in the actual repository review-postflight is narrower than \u201cany open review issue exists\u201d. Snapshot only surfaces review findings after triage/currentness gating, and mixed states with executable objective work must remain execute, not review.",
"status": "open",
"severity": "significant"
},
{
"id": "scan-vs-workflow-signal-collapsed-in-pipeline-mapping",
"concern": "The proposed boolean signal mapping still does not preserve snapshot\u2019s scan/workflow distinction. Step 4 collapses all PRE_REVIEW_WORKFLOW_IDS into has_workflow, but snapshot treats workflow::run-scan and workflow::deferred-disposition as scan-phase inputs while workflow::import-scores remains workflow. That means the new shared function still would not make pipeline and snapshot structurally agree on these cases.",
"status": "open",
"severity": "significant"
}
]
code
Requirements:
- Consider whether the plan is at the right level of abstraction.
- Reuse existing flag IDs when the same concern is still open.
- `verified_flag_ids` should list previously addressed flags that now appear resolved.
- Focus on concrete issues that would cause real problems.
- Robustness level: standard. Use balanced judgment. Flag significant risks, but do not spend flags on minor polish or executor-obvious boilerplate.
- Verify that the plan remains aligned with the user's original intent.
- Verify that the plan follows the expected structure: one H1 title, `## Overview`, numbered `## Step N:` sections with file references and numbered substeps, plus `## Execution Order` or `## Validation Order`. Missing structure should be flagged as category `completeness` with severity_hint `likely-significant`.
- Flag scope creep explicitly when the plan grows beyond the original idea or recorded user notes. Use the phrase "Scope creep:" in the concern.
- Assign severity_hint carefully. Implementation details the executor will naturally resolve should usually be `likely-minor`.