Be very thorough - read each file and understand the flow.
Assistant
I'll systematically read through all the key files to understand plan staleness handling. Let me start by reading the core schema and reconciliation files in parallel.
Assistant
Good, I can see key files. Now let me read the stale_dimensions module (which is referenced heavily), the scan workflow, and the plan CLI command.
Assistant
Now let me read the scan workflow and review import files. Let me also check for the scan_workflow.py file and related review import modules.
Assistant
Now let me read the scan workflow and the review import files.
Assistant
Now let me check the review import flow to see if it does any plan reconciliation, and also look at the epic_synthesis module and the persistence layer.
Assistant
Now let me check if there's any "stale" concept in the state schema or if there's a last_scan timestamp, and also look at the scorecard_subjective_entries function that determines staleness.
Assistant
Let me read more of the scorecard_projection to understand the "stale" calculation, and also check how subjective assessments track staleness.
Assistant
Let me also read the _mark_stale_assessments_on_review_resolve and the merge module for staleness marking, plus the synthesize_handlers to see what happens during synthesis.
Assistant
Let me read the key completion part of the synthesize handlers.
Assistant
Now let me check one more thing -- whether the review import flow does ANY plan reconciliation.
Assistant
Now let me check the auto_cluster module for the auto/stale-review cluster, and the _mark_stale_on_mechanical_change function to complete the picture.
Assistant
Let me read the auto_cluster stale review cluster logic to complete the picture.
Assistant
Now I have a thorough understanding of the entire flow. Let me compile the analysis.
Here is a thorough analysis of how desloppify handles plan staleness after scans and review imports:
1. Does the plan track when it was last synthesized vs when the last scan happened?
Partially, but not directly. The PlanModel schema (/Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/schema.py) has:
created and updated timestamps (lines 76-77), where updated is bumped every time save_plan() is called (/Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/persistence.py, line 81).
epic_synthesis_meta dict (line 87) -- this is where synthesis metadata lives.
Inside epic_synthesis_meta (populated by apply_synthesis_to_plan in /Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/epic_synthesis.py, lines 601-609):
And from _apply_completion in /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/synthesize_handlers.py, line 194:
python
meta["last_completed_at"] = utc_now()
However, there is no field like last_scan_at_synthesis_time or scan_count_at_synthesis. The plan does NOT directly record which scan it was synthesized against. Instead, it uses a content-based hash approach: finding_snapshot_hash records a hash of the open review finding IDs at synthesis time, and this hash is compared against the current state to detect drift.
2. Is there any warning when a scan or review import happens that the plan may be stale?
Yes, but only for a specific type of staleness: synthesis staleness. In the scan workflow (/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/scan/scan_workflow.py, lines 200-209):
User
I need to understand the full picture of how plan staleness/invalidation currently works in desloppify, and all the places where a "forced" planning stage is triggered. Explore thoroughly:
scan_workflow.py - The _reconcile_plan_post_scan function and how it calls staleness checks after scan
plan.py facade (engine/plan.py) - synthesis_phase_banner and any other staleness-aware functions
app/commands/plan/cmd.py - How the CLI surfaces staleness warnings, any "gate" that blocks work until planning is done
app/commands/plan/synthesize_handlers.py - How synthesis completion clears the stale flag
The next command - Where is it? Does it check for synthesis::pending before returning work items? How does it gate?
The status command - Does it show plan staleness?
review/import_cmd.py - Confirm there's no plan interaction
Any existing pattern where users are "forced" to do something before proceeding (e.g., forced to run scan before plan, forced to synthesize before work)
For each file, note the key functions, line numbers, and how they interact. I need to understand the full control flow.
Assistant
I'll systematically explore all the files and patterns you've asked about. Let me start with parallel searches across the codebase.
Assistant
Now let me read all the primary source files in parallel.
User
I need to find ALL the places where the plan is loaded, created, or where users are directed to do planning. Search comprehensively for:
Every call to load_plan across the entire codebase - who loads plans and when?
Every call to save_plan - who modifies plans?
Every call to ensure_plan or any plan creation/initialization
Any reference to synthesis::pending or SYNTHESIS_ID
Any reference to synthesis_phase_banner
Every place that prints a message telling the user to run desloppify plan (search for "plan synthesize", "plan show", "desloppify plan")
The full flow of desloppify plan synthesize command - how does it start, what triggers it, how does --complete work?
Search for any "gate" or "guard" pattern where a command refuses to proceed unless some precondition is met (e.g., "scan first", "plan first")
Look at how _apply_plan_order in _work_queue/core.py works - does it skip synthesis::pending?
Find the next command implementation and trace how it picks the top item
Give me file paths and line numbers for everything.
Assistant
I'll conduct a comprehensive search across all these areas. Let me start with parallel searches for the key terms.
Assistant
Good, I have a large initial set of results. Now let me read the key files to trace the full flows.
Assistant
Now let me read the synthesize_handlers.py file fully and find the next command.
Assistant
Now let me read the remaining critical files.
Assistant
Now let me read more of the synthesize handlers and the scan preflight, plus search for more gate/guard patterns.
Assistant
Now let me read the remaining pieces: the synthesize command entrypoint, synthesis shared/reflect/organize handlers, and check where print_synthesis_guardrail_banner is called.
Assistant
Now let me look at a few more files to complete the picture - the show command, the plan_cmd.py shim, the needs_rescan pattern in config, and the queue_render.py to see if it also shows synthesis banners.
Assistant
Let me read a few more files to complete the picture: the resolve command, show command, and the rendering helper that mentions plans.
Assistant
Let me also check the resolve command and exclude command for the needs_rescan pattern, and look at the synthesize_handlers completion logic more carefully.
Assistant
Let me get the last pieces: the resolve queue_order guard, the scan_reporting files that reference plans, and the resolve apply module.
Assistant
Now let me read the _apply_completion in synthesize_handlers.py and the two call sites.
Assistant
Now I have a comprehensive picture. Here is the full analysis:
Complete Analysis: Plan Staleness, Invalidation, and Forced-Stage Gating in Desloppify
SYNTHESIS_ID = "synthesis::pending" (line 20) -- the sentinel queue item that gates work
Key Functions:
_current_stale_ids(state) (lines 55-73): Queries scorecard_subjective_entries() for entries where stale=True, returns a set of subjective::<slug> IDs. Staleness of individual subjective dimensions is determined upstream in the scorecard projection module, not here.
_current_unscored_ids(state) (lines 76-97): Looks directly at state["subjective_assessments"] for entries with placeholder=True. These are dimensions that have never been scored (e.g., after a scan reset). Returns subjective::<slug> IDs.
Prunes subjective::* IDs that are no longer stale AND not unscored.
Only injects stale IDs when no objective items remain in the queue (appended to the back). This is the "exhaustion trigger" -- stale dimensions only surface as work when the queue runs dry.
Returns StaleDimensionSyncResult.
review_finding_snapshot_hash(state) (lines 194-207): Hashes sorted IDs of all open findings where . Returns a 16-char hex digest. Returns when there are no open review findings. This is the core change-detection mechanism for synthesis invalidation.
Assistant
I now have comprehensive data. Here is the full report.
Synthesize (plan) → analyze all findings, set strategy + priorities via desloppify plan synthesize
Work queue → resolve items one by one via desloppify resolve / desloppify next
When queue drains → back to step 1
The problem: when users do step 1 or 2 again (re-scan or re-review), the plan from step 3 becomes stale and should be re-synthesized. Currently this is handled inconsistently.
Current State
What exists:
synthesis::pending sentinel ID gets inserted at position 0 of queue_order when review finding hash changes
sync_synthesis_needed(plan, state) in stale_dimensions.py — compares review_finding_snapshot_hash(state) against stored hash
Called ONLY from _reconcile_plan_post_scan() in scan_workflow.py — runs after every scan
synthesis_phase_banner(plan) in engine/plan.py — returns a display string when synthesis is needed
print_synthesis_guardrail_banner() in guardrails.py — prints the banner. Called ONLY by cmd_next()
build_synthesis_item() in work queue helpers — creates a T1 synthetic queue item so next shows synthesis as the top action
The gaps:
Review import is completely plan-unaware — do_import() in review/import_cmd.py saves state but never loads/reconciles the plan. After a review import, synthesis::pending is NOT injected until the next scan.
resolve has no synthesis check — users can keep resolving items from a stale plan
status and show don't display synthesis warnings — only next does
No pre-action warning — scan and review don't warn that they'll invalidate the plan before proceeding
Assistant
I'll start by thoroughly exploring the codebase to understand the existing patterns, then design the implementation plan.
Assistant
Now let me look at the scan preflight (model for hard gate), the review import more closely, and the rest of the resolve command.
Assistant
Now let me look at how the scan workflow handles the post-scan message to understand the messaging pattern, and the cmd_scan entry point to see where preflight is called.
Assistant
Let me look at the review import entry point and the work queue helpers for the synthesis item builder.
Assistant
Now let me check how scan invokes the preflight and what the scan entry point looks like.
Assistant
Now let me look at the full do_import function's tail end and the scan entry point.
Assistant
Now let me check the scan finding_snapshot_hash usage to understand what hashes are tracked (scan vs review), and look at the schema for how epic_synthesis_meta stores the hash.
Assistant
Now let me check if there's also a scan-findings hash concept (not just review findings), and understand the full set of places where synthesis staleness should be checked.
Assistant
Let me look at the plan done command to understand how synthesis::pending is removed, and the scan's post-output plan nudge.
Assistant
Now let me look at the review entrypoint more carefully for where plan reconciliation should happen, and understand the scan finding hash concept (not just review).
Assistant
Good - there's no scan finding hash, only the review finding hash. Now let me check how the has_living_plan() function works and the plan_path_for_state utility.
Assistant
Now I have a thorough understanding of the codebase. Let me also verify what the show_agent_plan function does in status_parts/render.py since that's where the synthesis banner should also appear.
Assistant
I now have complete understanding of all the relevant code. Let me design the implementation plan.
Implementation Plan: Standardized Plan Staleness/Invalidation System
1. Problem Summary
The plan staleness detection works via the synthesis::pending + review_finding_snapshot_hash mechanism, but has three gaps:
Review import is plan-unaware: do_import() saves state but never loads or reconciles the plan. After review import, synthesis::pending is NOT injected until the next scan runs _reconcile_plan_post_scan().
resolve has no synthesis check: Users can keep resolving items from a stale plan without any warning.
status and show don't display synthesis warnings: Only next calls print_synthesis_guardrail_banner().
2. Design Approach
The existing synthesis::pending + hash-comparison mechanism is solid. The design extends it with:
A single detection function (is_synthesis_stale()) that encapsulates the staleness check without side-effects.
A single guardrail function (check_synthesis_guardrail()) that replaces and subsumes print_synthesis_guardrail_banner() with configurable severity levels (info, warn, gate).
Plan reconciliation after review import by extracting the relevant sync logic from _reconcile_plan_post_scan() into a reusable helper.
Add a pure detection function that checks staleness without mutating anything.
python
User
I need to understand ALL the ways that review/subjective analysis results get submitted into state in desloppify. The user mentioned there's manual review and automated batches. Find every path:
Review import path — do_import() in review/import_cmd.py. What does the diff return value look like? It has new, auto_resolved, reopened counts.
Review run-batches path — how does --run-batches work? Does it eventually call do_import()? Or is there a separate path?
Any other review submission paths — manual review, direct assessment editing, etc.
The import_holistic_findings function — what does it return? What's in the diff? Can we use this to know exactly WHICH findings are new?
How scan results get merged — merge_scan_results in scan_workflow.py. Does it track new vs existing findings? What info is available about what changed?
The reconciliation diff — when reconcile_plan_after_scan runs, does it return info about what was superseded? Look at its return value.
Also look at:
desloppify/app/commands/review/ — all files, understand the full review command structure
desloppify/intelligence/review/ — the review engine internals
How --scan-after-import works (does it trigger a full scan after review import?)
I need to understand: at each submission point, what information do we have about what specifically changed (new findings, resolved findings, score changes)?
Assistant
I'll systematically trace all review/subjective analysis submission paths into state. Let me start by exploring the relevant directories and key files in parallel.
User
I need to understand how the plan synthesis workflow currently handles new/changed items, and what tools exist (or could be extended) to show users what's new. Explore:
desloppify plan synthesize stages — specifically the OBSERVE stage. Does it show new findings? How does it present what needs analysis?
desloppify plan show — what does it display? Does it have any concept of "new since last synthesis"?
desloppify plan queue — what does the queue view look like? Could it be extended to show "new" markers?
epic_synthesis_meta in the plan schema — what fields exist? Is there a synthesized_ids field that tracks which findings were included in the last synthesis?
The reconciliation result — reconcile_plan_after_scan returns a result. What's in it? Are there remapped or superseded entries that track what changed?
plan_start_scores — what does this track? Could it help show score impact of new findings?
Auto-clusters — auto_cluster_findings(). When new findings come in, do they automatically get added to existing clusters or create new ones?
The synthesis OBSERVE stage handler — what report does it generate? Does it have access to a "what's new" view?
Good, I have the lay of the land. Let me now read the core files in parallel.
Assistant
I'll explore all the files and components you've listed to build a comprehensive picture of the plan synthesis workflow, especially around new/changed item handling.
Assistant
Now let me read the remaining files mentioned in the request.
Assistant
Now let me read the remaining critical files: merge_scan in state.py, the batches.py orchestrator, the external review path, the scan_workflow merge, and the shared import utilities.
Assistant
Now let me read the synthesis stage handlers and the synthesis package files.
Assistant
Now let me read the merge_scan function in the state module and the scan_workflow to understand how scan results get merged and what diffs are returned.
Assistant
Now let me read the _build_merge_diff function and the upsert_findings function to understand what exactly is in the diff object.
Assistant
The synthesize_handlers file was truncated. Let me read it fully, along with the synthesis_playbook and the plan_start_scores usage.
Assistant
Let me also check the ScanDiff type definition and run_followup_scan to understand what --scan-after-import does.
Assistant
Now let me check one more thing -- the fix/review_flow.py to see if there's a fix-triggered review path.
Assistant
Now let me read the remaining part of synthesize_handlers.py and the [REDACTED] usage.
Assistant
Let me also check the stale_dimensions module (which contains the SYNTHESIS_ID and snapshot hash logic) and the last portion of synthesize_handlers.
Assistant
Now let me check the review_finding_snapshot_hash function and the sync_synthesis_needed function referenced in the scan workflow.
Assistant
Now I have a comprehensive understanding of the entire review/subjective analysis submission pipeline. Here is my complete analysis:
Complete Analysis: All Review/Subjective Analysis Submission Paths Into State
Overview of Submission Paths
There are 6 distinct paths that submit review/subjective analysis results into state, but they all funnel through one central merge function: import_holistic_findings() in /Users/user_c042661f/Documents/desloppify/desloppify/intelligence/review/importing/holistic.py, which itself calls merge_scan() from /Users/user_c042661f/Documents/desloppify/desloppify/engine/_state/merge.py. There is also one additional path (--merge) that directly mutates state without going through import_holistic_findings.
PATH 1: Manual --import (Direct CLI Import)
Entrypoint: cmd_review in /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/review/entrypoint.py (line 172-184)
The synthesis workflow is a 4-stage pipeline: OBSERVE -> REFLECT -> ORGANIZE -> COMMIT (with a fast-track CONFIRM-EXISTING skip path).
OBSERVE stage (_cmd_stage_observe, line 214):
Calls collect_synthesis_input(plan, state) to get a SynthesisInput object.
Does NOT explicitly show new findings in its output. It only reports the total finding count: "Observe stage recorded: {finding_count} findings analysed."
The report is a free-text analysis (minimum 100 chars) of themes, root causes, and contradictions. There is no citation gate -- finding ID citations are extracted for analytics but don't gate the stage.
After observe, there is a new confirmation step: desloppify plan synthesize --confirm observe with attestation.
Dashboard view (_cmd_synthesize_dashboard, line 888):
This IS the view that shows "what's new." On lines 904-907:
python
if si.new_since_last:
print(f" New since last synthesis: {len(si.new_since_last)}")
if si.resolved_since_last:
print(f" Resolved since last synthesis: {len(si.resolved_since_last)}")
But this only shows counts, not the actual new finding IDs or summaries.
The dashboard then shows all findings grouped by dimension (lines 984-1007), but does NOT mark which ones are new. Every finding is shown the same way.
Key gap: The dashboard knows the new_since_last set exists (from SynthesisInput) but only displays the count. No individual finding is marked as "NEW" in the dimension-grouped listing.
2. desloppify plan show
File:/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/cmd.py, function _cmd_plan_show (line 29)
python
synth_sync = sync_synthesis_needed(plan, runtime.state)
if synth_sync.changes:
dirty = True
if synth_sync.injected:
print(
colorize(
" Plan: synthesis needed -- review findings changed since last synthesis.",
"cyan",
)
)
This calls sync_synthesis_needed (/Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/stale_dimensions.py, lines 222-246), which:
Computes the current review_finding_snapshot_hash (SHA-256 of sorted open review/concerns finding IDs).
Compares it to epic_synthesis_meta.finding_snapshot_hash.
If different and synthesis::pending is not already in the queue, injects synthesis::pending at the front of the queue.
Then synthesis_phase_banner in /Users/user_c042661f/Documents/desloppify/desloppify/engine/plan.py (lines 79-95) renders a banner when synthesis::pending is in the queue:
code
"Synthesis needed -- review findings require analysis before fixing. Run: desloppify plan synthesize"
For review imports: NO plan reconciliation happens. Looking at do_import in /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/review/import_cmd.py -- it saves state (line 268) but never loads or reconciles the plan. There is zero load_plan, save_plan, reconcile, or sync_synthesis_needed call in the entire review/ command directory. This is a significant gap -- after a review import changes review findings, the plan is not notified until the next scan.
3. What does reconciliation do after a scan -- does it just add/remove items or does it re-prioritize?
Reconciliation does NOT re-prioritize. It only handles structural cleanup. Looking at reconcile_plan_after_scan in /Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/reconcile.py (lines 130-216), it does exactly three things:
a) Supersede dead findings (lines 144-167): Collects all finding IDs referenced by the plan (in queue_order, skipped, overrides, and cluster finding_ids). For each ID that is no longer alive (missing from state or status != "open"), it moves the ID to the superseded dict, removing it from queue_order, skipped, and all cluster membership lists. It also records remap candidates (other open findings from the same detector + file).
b) Clean up epic clusters (lines 169-184): For synthesis-clusters (names starting with epic/), removes dead finding IDs from finding_ids. If all findings in an epic are dead, deletes the entire epic cluster.
c) Resurface stale temporary skips (lines 187-193): Calls resurface_stale_skips to move temporary-skipped items back into the queue when their review_after scan count has been reached.
d) Prune old superseded entries (lines 195-198): Removes superseded entries older than 90 days (SUPERSEDED_TTL_DAYS).
The order within queue_order is never changed by reconciliation. Items just get removed (superseded) or added back (resurfaced). The relative priority of remaining items is preserved exactly.
4. Is there any concept of "plan is stale, needs re-synthesis" in the schema or state?
Yes, via a synthetic queue item, not a schema field. The concept is embodied by:
The synthesis::pending sentinel ID. This is defined in /Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/stale_dimensions.py (line 20):
python
SYNTHESIS_ID = "synthesis::pending"
When injected into the front of queue_order, it signals that synthesis is stale. The sync_synthesis_needed function (lines 222-246) handles injection:
It compares the current review_finding_snapshot_hash(state) against epic_synthesis_meta.finding_snapshot_hash.
If they differ and synthesis::pending is not already present, it inserts at position 0.
It never auto-prunes -- only explicit completion via _apply_completion in the synthesize handler removes it.
There are also stale subjective dimension sentinels (subjective::<slug> IDs) managed by sync_stale_dimensions and sync_unscored_dimensions. These are injected/pruned based on:
Whether subjective assessments have needs_review_refresh: true (set by _mark_stale_on_mechanical_change in merge.py when detectors that inform subjective dimensions have finding churn, or by _mark_stale_assessments_on_review_resolve when review findings are resolved).
Whether assessments have placeholder: true (unscored dimensions after scan reset).
But there is no first-class plan.is_stale boolean or plan.stale_reason field in PlanModel. Staleness is purely represented by the presence of synthetic IDs in the queue.
5. What happens in the scan workflow and review import flow related to the plan?
After merge_scan_results saves the updated state (line 576), it calls _reconcile_plan_post_scan (line 579). This function (lines 185-221) runs six reconciliation steps in sequence, inside a try/except that silently skips on errors:
_apply_plan_reconciliation -- calls reconcile_plan_after_scan (supersede dead findings, resurface skips, prune old superseded). Only runs if the plan has user content.
_sync_unscored_dimensions -- prepends subjective::* IDs for never-scored dimensions to the front of the queue.
_sync_stale_dimensions -- prunes no-longer-stale subjective IDs; appends newly-stale ones (only when no objective items remain).
_sync_auto_clusters -- regenerates automatic task clusters (including auto/stale-review for stale subjective dimensions, auto/initial-review for unscored ones).
sync_synthesis_needed -- injects synthesis::pending at front if review finding hash changed since last synthesis.
_seed_plan_start_scores / _clear_plan_start_scores_if_queue_empty -- manages the score snapshot for tracking progress across a queue cycle.
If any step modifies the plan, save_plan is called at the end.
Prints score updates, narratives, and query output
There is no call to load_plan, reconcile_plan_after_scan, sync_synthesis_needed, or any plan-related function. This means:
After a review import creates new review findings, the synthesis::pending injection will only happen on the NEXT scan.
After a review import resolves findings, those findings remain as references in the plan's queue_order and clusters until the next scan's reconciliation supersedes them.
The auto/stale-review cluster is not updated after review imports.
This is the most significant gap I found: the review import flow is completely plan-unaware.
The resolve command does interact with the plan (lines 200-218):
It calls purge_ids(plan, all_resolved) to remove resolved finding IDs from the queue.
It logs a "resolve" entry in the execution log.
It saves the plan.
But it does NOT trigger synthesis re-check or subjective dimension sync.
Summary of gaps
Scenario
Plan reconciliation?
Synthesis staleness check?
Subjective dimension sync?
After scan
Yes (full reconcile)
Yes (hash-based injection)
Yes (stale + unscored sync)
After review import
No
No
No
After resolve
Partial (purge IDs only)
No
No
The plan's staleness model is content-hash-based (comparing review finding snapshot hashes) rather than timestamp-based (comparing plan.updated vs state.last_scan). There is no single "plan is stale" flag -- instead, staleness is encoded as synthetic queue items (synthesis::pending, subjective::*). And critically, the review import flow does not trigger any plan synchronization, leaving the plan potentially stale until the next scan.
This is the main entry point for all post-scan plan mutations. Called from merge_scan_results() at line 579, after state is saved. It runs these steps in order:
Load plan (line 189): load_plan(plan_path)
_apply_plan_reconciliation (line 192): Calls reconcile_plan_after_scan(plan, state) -- only if the plan has user content (queue_order, overrides, clusters, or skipped). This resurfaces stale skipped items.
_sync_unscored_dimensions (line 194): Prepends never-scored dimensions to front.
_sync_stale_dimensions (line 196): Prunes refreshed + appends stale dimensions.
_sync_auto_clusters (line 198): Regenerates auto-clusters via auto_cluster_findings(plan, state).
sync_synthesis_needed (line 200): Checks if review findings have changed and injects synthesis::pending. Prints a cyan message: "Plan: synthesis needed -- review findings changed since last synthesis." (line 207).
_seed_plan_start_scores (line 210): Snapshots current scores when beginning a new queue cycle.
_clear_plan_start_scores_if_queue_empty (line 215): Clears the snapshot when queue drains (but not in the same pass that seeded it).
Save plan (line 219): Only if any step set dirty=True.
The entire block is wrapped in try/except PLAN_LOAD_EXCEPTIONS (line 220) -- failures are logged at debug level and swallowed. Plan reconciliation is best-effort.
cmd_plan(args) (lines 84-134): Pure dispatcher. Routes to subcommand handlers based on plan_action. No staleness checks here -- no synthesis banner, no require_completed_scan. The sub-handlers themselves do their own gating:
plan_action == "synthesize" routes to cmd_plan_synthesize (lazy import at line 129).
The default (no action) routes to _cmd_plan_generate which calls cmd_plan_output -- that function does call require_completed_scan(state) at line 26 of plan_cmd.py.
The cmd_plan dispatcher itself has no synthesis guardrail banner -- this is notably absent compared to next and show.
This is the only function that removes synthesis::pending from the queue. It:
Removes SYNTHESIS_ID from plan["queue_order"] (line 182-183).
Computes current review_finding_snapshot_hash(state) and stores it in meta["finding_snapshot_hash"] (line 190). This is the critical step -- it updates the hash so sync_synthesis_needed won't immediately re-inject it.
Calls require_completed_scan(state) (line 74) -- returns early if no scan exists. This is a soft gate: prints a yellow message and returns, doesn't sys.exit.
Prints tool/skill/config staleness warnings (lines 77-85).
Calls print_synthesis_guardrail_banner() (line 87) -- this is the synthesis warning banner.
Calls _get_items() to build and render the queue.
How synthesis::pending appears as a work item:
In _get_items (line 174), the work queue is built with plan=plan_data. Deep in build_work_queue() at /Users/user_c042661f/Documents/desloppify/desloppify/engine/_work_queue/core.py lines 337-340:
python
if resolved_options.plan and status in {"open", "all"}:
synth_item = build_synthesis_item(resolved_options.plan, state)
if synth_item is not None:
all_items.append(synth_item)
And build_synthesis_item() in /Users/user_c042661f/Documents/desloppify/desloppify/engine/_work_queue/helpers.py lines 171-209 creates a T1, high-confidence synthetic work item with:
kind: "synthesis_needed"
primary_command: "desloppify plan synthesize"
Summary describing how many review findings need synthesis.
Because it's T1 and because plan ordering puts synthesis::pending at position 0 in queue_order, it will always appear as the first item returned by next. The _apply_plan_order() function (core.py line 100) puts items from queue_order first, in that order.
Important: This is NOT a hard gate. The synthesis item appears as the top work item, but it doesn't block the user from requesting other items by tier, scope, or cluster filter. It's a "soft force" -- the highest-priority item is always the synthesis task.
Does NOT call print_synthesis_guardrail_banner() -- notable absence.
Loads plan at line 98 and passes it to compute_narrative() and to rendering helpers like show_agent_plan(narrative, plan=_plan_active) at line 152.
The show_agent_plan render function receives the plan but the synthesis banner is not explicitly shown by status. The narrative computation may include synthesis-related guidance if the plan is in a synthesis phase, but this is indirect.
Does not import from engine.plan, does not load plan, does not check synthesis status, does not interact with the living plan at all.
However, the import itself can trigger synthesis invalidation indirectly: when review findings are imported, the state's open finding set changes. The next scan will then detect the hash change in _reconcile_plan_post_scan -> sync_synthesis_needed and inject synthesis::pending.
9. All "Forced Action" Patterns
Here is a complete inventory of every pattern where the system forces or strongly encourages the user to do something before proceeding:
9a. require_completed_scan(state) -- Hard Gate (Soft Exit)
Loads plan, calls synthesis_phase_banner(), prints the result in yellow if non-empty. Never blocks.
Used by:next (line 87 of next.py).
NOT used by:status, show, plan, plan queue. This is a significant observation -- the synthesis banner only appears on the next command.
9e. synthesis::pending as T1 Queue Item -- Soft Force
When synthesis::pending is in the queue, build_synthesis_item() creates a T1 high-confidence item that gets positioned at the front of the queue by _apply_plan_order(). This means next will always show "run desloppify plan synthesize" as the top action. But users can filter by tier, scope, or cluster to bypass it.
9f. Synthesis Stage Dependencies -- Hard Gates Within Synthesis
Inside synthesize_handlers.py, each stage requires previous stages:
observe: no prereqs
reflect: requires observe
organize: requires reflect
commit: requires observe, reflect, organize
confirm-existing: requires observe, reflect, and at least one manual cluster
These are hard gates -- the stage handlers check and refuse to proceed without prerequisites. This is internal to the synthesis workflow, not a global gate.
Summary Control Flow Diagram
code
Review findings imported (review import)
|
v
Next scan runs -> merge_scan_results()
|
v
_reconcile_plan_post_scan():
1. reconcile_plan_after_scan() -- prune/resurface
2. sync_unscored_dimensions() -- prepend unscored to front
3. sync_stale_dimensions() -- append stale to back (only when queue empty)
4. auto_cluster_findings() -- rebuild auto-clusters
5. sync_synthesis_needed() -- compare hash, inject synthesis::pending at front
6. seed/clear plan_start_scores
|
v (if synthesis::pending injected)
User runs `next`:
1. require_completed_scan() -- soft gate
2. print_synthesis_guardrail_banner() -- yellow warning
3. build_work_queue() -> build_synthesis_item() -- T1 item at queue top
|
v
User runs `plan synthesize`:
observe -> reflect -> organize -> commit (staged, each gated)
OR: observe -> reflect -> confirm-existing (fast-track)
|
v
_apply_completion():
1. Remove synthesis::pending from queue_order
2. Update finding_snapshot_hash (prevents re-injection)
3. Clear synthesis_stages
|
v
Next `next` call: synthesis item gone, normal queue resumes
This is called in nearly every plan-touching function. The [REDACTED] points are:
empty_plan() -- /Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/schema.py (returns a freshly constructed PlanModel dict)
load_plan() -- /Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/persistence.py:27 -- Returns empty_plan() when no file exists or on corruption
save_plan() -- /Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/persistence.py:78 -- Calls ensure_plan_defaults() before writing
_reconcile_plan_post_scan() -- /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/scan/scan_workflow.py:185 -- Loads/creates/reconciles plan after every scan
The plan is auto-created implicitly the first time any scan runs (via reconciliation) or any plan subcommand loads a non-existent plan.json (load_plan returns empty_plan).
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/stale_dimensions.py:222-246 -- sync_synthesis_needed(): Injects synthesis::pending at position 0 of queue_order when the review-finding snapshot hash changes and it is not already present. Never auto-prunes -- only _apply_completion() removes it explicitly.
Called during post-scan reconciliation at /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/scan/scan_workflow.py:200-209
Reconcile exclusion:
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/reconcile.py:159 -- fid != SYNTHESIS_ID -- Reconcile skips synthesis::pending (it is a synthetic ID, not a real finding)
Epic synthesis handling:
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/epic_synthesis.py:583-587 -- When inserting epic items at front of queue, keeps synthesis::pending ahead of them
Work queue synthetic item:
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_work_queue/helpers.py:171-209 -- build_synthesis_item() creates a synthetic T1 work item for synthesis::pending with "primary_command": "desloppify plan synthesize"
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_work_queue/core.py:336-340 -- Injected into all_items when plan is provided and status is "open" or "all"
Removal (completion):
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/synthesize_handlers.py:178-183 -- _apply_completion() removes SYNTHESIS_ID from queue_order
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/synthesis/shared.py:244-250 -- Duplicate _apply_completion() in shared.py
Guard checks in synthesize handlers (all check SYNTHESIS_ID not in plan.get("queue_order", [])):
def synthesis_phase_banner(plan: PlanModel) -> str:
ensure_plan_defaults(plan)
if SYNTHESIS_ID not in plan.get("queue_order", []):
return ""
meta = plan.get("epic_synthesis_meta", {})
stages = meta.get("synthesis_stages", {})
completed = [s for s in ("observe", "reflect", "organize") if s in stages]
if completed:
return (f"Synthesis in progress ({len(completed)}/4 stages complete). "
"Run: desloppify plan synthesize")
return ("Synthesis needed -- review findings require analysis before fixing. "
"Run: desloppify plan synthesize")
Callsites:
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/helpers/guardrails.py:16 -- Called inside print_synthesis_guardrail_banner()
print_synthesis_guardrail_banner() is called from:
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/next.py:87 -- At the top of cmd_next(), before showing queue items
6. Messages directing users to desloppify plan
There are dozens of these. Key categories:
Post-scan nudges:
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/scan/scan_reporting_analysis.py:116 -- "Run 'desloppify plan' to see the updated living plan."
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/scan/scan_reporting_llm.py:315,333 -- "Use 'desloppify plan' to view and update it."
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/scan/reporting/agent_context.py:312,380 -- "'desloppify plan' to view the full queue."
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/scan/reporting/integrity_report.py:125 -- "Run 'desloppify plan' to see the updated living plan."
Synthesis banner (plan synthesize):
/Users/user_c042661f/Documents/desloppify/desloppify/engine/plan.py:90,94 -- "Run: desloppify plan synthesize"
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_work_queue/helpers.py:200 -- synthetic item "primary_command": "desloppify plan synthesize"
def _apply_plan_order(items, plan, *, include_skipped=False, cluster=None):
queue_order = plan.get("queue_order", [])
# ...
by_id = {item["id"]: item for item in items}
ordered = []
for fid in queue_order:
if fid in by_id and fid not in skipped_ids:
ordered.append(by_id[fid])
# ...
The function iterates queue_order and looks up each ID in by_id (a dict of all items). Since synthesis::pending is injected as a synthetic work item into all_items by build_synthesis_item() at line 338-340 of the same file, it will be present in by_id and thus will be placed at the position where it appears in queue_order (typically position 0, since sync_synthesis_needed inserts at front).
So _apply_plan_order does NOT skip synthesis::pending. It treats it like any other queue item. Because it is inserted at position 0 in queue_order, it becomes the first item shown by next.
Flow at queue build time (lines 336-351):
python
# Inject synthesis::pending synthetic item when plan requires it
if resolved_options.plan and status in {"open", "all"}:
synth_item = build_synthesis_item(resolved_options.plan, state)
if synth_item is not None:
all_items.append(synth_item)
all_items.sort(key=item_sort_key)
# Apply living plan ordering if provided
if resolved_options.plan:
all_items = _apply_plan_order(all_items, resolved_options.plan, ...)
10. The next command flow -- how it picks the top item
Line 87: print_synthesis_guardrail_banner() -- prints yellow banner if synthesis::pending in queue
Line 88: _get_items(args, state, config) -- main logic
Inside _get_items() (line 174):
5. Line 188: plan = load_plan() -- loads the living plan
6. Lines 190-195: Determines if plan is "active" (has queue_order, overrides, or clusters)
7. Lines 197-202: Resolves cluster focus (explicit --cluster, or plan's active_cluster, or none)
8. Lines 204-220: Calls build_work_queue() with plan data, passing:
plan=plan_data (so synthesis items get injected and plan ordering applies)
include_subjective=True
cluster=effective_cluster
include_skipped from args
Inside build_work_queue() (/Users/user_c042661f/Documents/desloppify/desloppify/engine/_work_queue/core.py:297):
9. Lines 313-319: Build finding items from state
10. Lines 322-334: Add subjective items if applicable
11. Lines 336-340: Inject synthesis::pending synthetic item if plan has it
12. Line 342: Sort all items by item_sort_key (tier -> confidence -> file)
13. Lines 345-351: _apply_plan_order() reorders according to queue_order
14. Lines 353-361: Collapse auto-clusters if applicable
15. Lines 363-372: Interleave subjective items
16. Lines 374-: Tier selection and count limiting
Back in _get_items():
17. Line 221: items = queue.get("items", []) -- gets the final ordered list
18. The first item in items is what gets rendered as "next"
Summary of priority resolution:
If synthesis::pending is at position 0 of queue_order (which is where sync_synthesis_needed puts it), and no cluster focus is active, it becomes the top item
Plan queue_order trumps mechanical tier sorting
Cluster focus filters everything to just that cluster's members
Skipped items are excluded unless --include-skipped
Existing gate patterns (to follow for consistency):
scan_queue_preflight() — hard gate: sys.exit(1) when queue is non-empty, bypass via --force-rescan --attest "I understand..."
require_completed_scan(state) — soft gate: prints message, returns False, callers return early
_check_queue_order_guard() — medium gate: blocks resolve --status fixed when items not at front of queue
print_synthesis_guardrail_banner() — info only: prints yellow text, never blocks
Design Requirements
Standardized — one unified mechanism, not more ad-hoc patterns
After scan/review: clearly communicate that plan needs re-synthesis
At work commands: force users to re-synthesize OR intentionally skip (with explicit acknowledgment)
Pre-action awareness: when running scan/review, note that this will require re-planning
Key Files
desloppify/app/commands/helpers/guardrails.py — current synthesis banner (29 lines)
desloppify/app/commands/review/import_cmd.py:132-268 — do_import() (no plan interaction)
desloppify/app/commands/next.py:69-88 — cmd_next() entry point
desloppify/app/commands/resolve/cmd.py:43-120,199-218 — queue order guard + plan purge
desloppify/app/commands/status_cmd.py:49-183 — status command
desloppify/app/commands/show/cmd.py:303-308 — show loads plan
desloppify/app/commands/scan/scan_preflight.py — model for hard gate with attest bypass
Design Constraints
Keep it simple — minimal new abstractions
Follow existing patterns (colorize output, PLAN_LOAD_EXCEPTIONS try/except, best-effort plan operations)
The synthesis::pending + hash approach works well — build on it, don't replace it
Don't over-engineer — the core problem is that review import doesn't sync the plan, and the warnings aren't shown consistently
Please design a concrete implementation plan with specific function signatures, where each function lives, and which existing functions get modified.
def is_synthesis_stale(plan: PlanModel, state: StateModel) -> bool:
"""Return True when plan needs re-synthesis.
Checks two conditions:
1. synthesis::pending is already in the queue (explicitly flagged stale).
2. The review finding snapshot hash has changed since last synthesis
(stale but not yet flagged).
"""
ensure_plan_defaults(plan)
order: list[str] = plan.get("queue_order", [])
if SYNTHESIS_ID in order:
return True
meta = plan.get("epic_synthesis_meta", {})
last_hash = meta.get("finding_snapshot_hash", "")
if not last_hash:
# No prior synthesis has been completed; not stale per se,
# but sync_synthesis_needed will handle injection if findings exist.
return False
current_hash = review_finding_snapshot_hash(state)
return bool(current_hash and current_hash != last_hash)
Add "is_synthesis_stale" to __all__.
3B. Facade: desloppify/engine/plan.py
Add re-export of is_synthesis_stale from stale_dimensions.
python
from desloppify.engine._plan.stale_dimensions import (
...
is_synthesis_stale,
...
)
Expand the module from a single print function to a two-level guardrail system.
Keep print_synthesis_guardrail_banner() for backward compatibility but have it delegate to the new function.
python
"""Shared synthesis guardrail helpers for command entrypoints."""
from __future__ import annotations
import sys
from typing import Literal
from desloppify.core.exception_sets import PLAN_LOAD_EXCEPTIONS
from desloppify.core.output_api import colorize
from desloppify.engine.plan import (
has_living_plan,
is_synthesis_stale,
load_plan,
synthesis_phase_banner,
SYNTHESIS_ID,
)
def check_synthesis_guardrail(
*,
plan: dict | None = None,
state: dict | None = None,
severity: Literal["info", "warn", "gate"] = "info",
command: str = "",
) -> bool:
"""Unified synthesis staleness guardrail.
Severity levels:
- "info": print yellow banner if stale (existing behavior). Returns True if stale.
- "warn": print yellow banner with stronger wording. Returns True if stale.
- "gate": print red error and sys.exit(1). Never returns True.
Returns False when plan is not stale or no plan exists.
"""
try:
if not has_living_plan():
return False
resolved_plan = plan if isinstance(plan, dict) else load_plan()
# Quick check: is synthesis::pending in queue?
banner = synthesis_phase_banner(resolved_plan)
if not banner:
# Check hash-level staleness (catches the review-import gap)
if state is not None and is_synthesis_stale(resolved_plan, state):
banner = (
"Synthesis needed -- data has changed since last synthesis. "
"Run: desloppify plan synthesize"
)
else:
return False
except PLAN_LOAD_EXCEPTIONS as exc:
print(
colorize(
" Warning: synthesis guardrail unavailable "
f"({exc.__class__.__name__}: {exc}).",
"yellow",
),
file=sys.stderr,
)
return False
if severity == "gate":
print(colorize(f"\n {banner}", "red"), file=sys.stderr)
print(
colorize(
" Re-synthesis is required before continuing to work the queue.",
"red",
),
file=sys.stderr,
)
print(
colorize(
" Run: desloppify plan synthesize",
"dim",
),
file=sys.stderr,
)
sys.exit(1)
color = "yellow"
print(colorize(f" {banner}", color))
return True
def print_synthesis_guardrail_banner(*, plan: dict | None = None) -> None:
"""Print synthesis phase guardrail banner (backward-compatible wrapper)."""
check_synthesis_guardrail(plan=plan, severity="info")
__all__ = [
"check_synthesis_guardrail",
"print_synthesis_guardrail_banner",
]
3D. Review Import Plan Sync: desloppify/app/commands/review/import_cmd.py
Add plan reconciliation at the end of do_import(), after state_mod.save_state(state, state_file) (line 268).
Insert the following block between lines 268 and 270:
python
# --- Reconcile plan: inject synthesis::pending if findings changed --------
try:
from desloppify.engine.plan import (
has_living_plan,
load_plan,
save_plan,
sync_synthesis_needed,
)
from desloppify.engine._plan.operations import append_log_entry
if has_living_plan():
plan = load_plan()
synth_sync = sync_synthesis_needed(plan, state)
if synth_sync.changes:
if synth_sync.injected:
print(
colorize(
" Plan: synthesis needed -- review findings changed since last synthesis.",
"cyan",
)
)
append_log_entry(
plan, "sync_synthesis", actor="system",
detail={"injected": True, "trigger": "review_import"},
)
save_plan(plan)
except PLAN_LOAD_EXCEPTIONS:
pass # best-effort, don't block import
Note: PLAN_LOAD_EXCEPTIONS needs to be imported at the top of import_cmd.py:
python
from desloppify.core.exception_sets import PLAN_LOAD_EXCEPTIONS
The message text ("Plan: synthesis needed -- review findings changed since last synthesis.") intentionally mirrors the identical message in _reconcile_plan_post_scan() (line 221 of scan_workflow.py) for consistency.
Add a synthesis staleness gate in cmd_resolve(), after the queue-order guard (line 170-171) and before _enforce_batch_wontfix_confirmation.
python
# Warn when plan needs re-synthesis — stale plan means priorities may be wrong
from desloppify.app.commands.helpers.guardrails import check_synthesis_guardrail
check_synthesis_guardrail(state=state, severity="warn", command="resolve")
The "warn" severity prints the banner text but does NOT block. This is the right default for resolve because:
A hard gate would be annoying during partial-synthesis workflows.
The queue-order guard already provides a structural gate.
Users see the warning and can choose to continue or re-synthesize first.
If you want to make this a hard gate instead, change to severity="gate". I recommend starting with "warn" and upgrading to "gate" later if users ignore it.
3F. status Command: desloppify/app/commands/status_cmd.py
Add synthesis banner to cmd_status(), after the config staleness warning block (after line 88) and before the scores rendering:
python
from desloppify.app.commands.helpers.guardrails import check_synthesis_guardrail
check_synthesis_guardrail(plan=_plan, state=state, severity="info")
Note: The plan is loaded later in the function (line 98). We need to move the plan load earlier or pass it after. The simplest approach: the guardrail already has has_living_plan() check internally, so call it without plan and let it load internally. But this means a double load. Better: move the call to after _plan is loaded (after line 101):
python
# After line 101 (plan load)
check_synthesis_guardrail(plan=_plan, state=state, severity="info")
3G. show Command: desloppify/app/commands/show/cmd.py
Add synthesis banner after the plan load (after line 307):
python
from desloppify.app.commands.helpers.guardrails import check_synthesis_guardrail
check_synthesis_guardrail(plan=_plan_active, severity="info")
3H. next Command: desloppify/app/commands/next.py
Update the existing print_synthesis_guardrail_banner() call (line 87) to use the new function with state context for better detection:
python
# Replace line 87:
# print_synthesis_guardrail_banner()
# With:
from desloppify.app.commands.helpers.guardrails import check_synthesis_guardrail
check_synthesis_guardrail(state=state, severity="info")
The import of print_synthesis_guardrail_banner at line 16 can be removed.
No change needed here. The existing _reconcile_plan_post_scan() already calls sync_synthesis_needed() and prints the cyan message. This is working correctly.
4. Implementation Sequence
desloppify/engine/_plan/stale_dimensions.py - Add is_synthesis_stale() (pure function, no side effects, easy to test)
desloppify/app/commands/next.py - Migrate to new guardrail function
5. Tests
New test file: desloppify/tests/plan/test_synthesis_staleness.py
Tests for is_synthesis_stale():
Returns False when no plan or empty plan
Returns True when synthesis::pending in queue
Returns True when hash changed (review findings differ from stored hash)
Returns False when hash matches
Returns False when no prior synthesis (empty last_hash)
Tests for check_synthesis_guardrail():
Severity "info" prints banner, returns True when stale
Severity "warn" prints banner, returns True when stale
Severity "gate" calls sys.exit(1) when stale
Returns False when plan is not stale
Returns False when no living plan exists
Handles PLAN_LOAD_EXCEPTIONS gracefully
Tests for review import plan sync:
After do_import(), synthesis::pending is injected into plan queue when review findings change
After do_import(), plan is not modified when findings haven't changed
Plan sync failure doesn't block the import
6. Design Tradeoffs
Why "warn" not "gate" for resolve? A gate would be safer but more disruptive. The queue-order guard already provides structural protection. Starting with warn lets us observe if users actually ignore the warning before escalating to a gate.
Why not add a scan-findings hash? The current system only tracks review-finding hashes because scan results are directly reconciled by reconcile_plan_after_scan() (which runs inline during scan). The gap is specifically about review imports, which bypass the reconciliation path. Adding a scan-findings hash would be over-engineering.
Why function-level imports in cmd files? This follows the existing pattern (see _reconcile_plan_post_scan in scan_workflow.py) and avoids import cycles in the command layer.
Why not a new module for the reconciliation helper? The sync logic is only 15 lines. Extracting it to a shared module would be premature abstraction. If future commands also need post-mutation plan sync, it would be time to extract a reconcile_plan_after_mutation(state) helper.
Critical Files for Implementation
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/helpers/guardrails.py - Core file to expand with check_synthesis_guardrail(), the unified entry point
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/stale_dimensions.py - Add is_synthesis_stale() pure detection function
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/review/import_cmd.py - Add plan reconciliation after state save (the primary bug fix)
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/resolve/cmd.py - Add warn-level guardrail to prevent working a stale plan
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/scan/scan_preflight.py - Reference pattern for hard gate with attest bypass (read-only reference)
--import FILE alone: findings_only (assessments stripped if present)
--import FILE --manual-override --attest "...": manual_override (provisional scores, expire on next scan)
What do_import() returns: None (void). But the internal diff dict from import_holistic_findings() is printed to the user and written to query.json.
PATH 2: --run-batches (Automated Batch Review)
Entrypoint: cmd_review -> _do_run_batches() in /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/review/batch.py (line 181)
Flow:
code
entrypoint.py: cmd_review()
-> batch.py: _do_run_batches(args, state, lang, state_file, config)
-> batches.py: do_run_batches(...) # the orchestrator
-> _load_or_prepare_packet() # builds holistic review packet with investigation_batches
-> execute_batches_fn() # runs codex subagent(s) in parallel or serial
-> collect_batch_results_fn() # parses raw batch outputs
-> _merge_batch_results() # deterministic merge of batch outputs -> single merged dict
-> batch.py line 267: do_import_fn = _do_import # <-- CALLS do_import() from import_cmd.py!
-> do_import(str(merged_path), state, lang, state_file,
trusted_assessment_source=True, # <-- KEY: marked as trusted
trusted_assessment_label="trusted internal run-batches import")
-> if --scan-after-import: run_followup_scan() # spawns subprocess: `python -m desloppify scan`
Key insight: --run-batches eventually calls the same do_import() with trusted_assessment_source=True. This means assessment scores are durable (not provisional). The merged findings are written to holistic_findings_merged.json in the run directory, then imported as if the user had done --import holistic_findings_merged.json with trusted provenance.
PATH 3: --import-run (Re-import from Completed Run Directory)
Entrypoint: cmd_review -> do_import_run() in /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/review/batch.py (line 327-433)
Flow:
code
entrypoint.py: cmd_review()
-> batch.py: do_import_run(run_dir_path, state, lang, state_file, ...)
-> _validate_run_dir() # validates run_summary.json, loads blind packet
-> collect_batch_results() # re-parses raw batch outputs from results/ dir
-> _merge_batch_results() # re-merge
-> build_batch_import_provenance() # reconstruct provenance
-> do_import(merged_path, ..., trusted_assessment_source=True) # <-- same do_import
-> if scan_after_import: run_followup_scan()
Purpose: Replay an interrupted --run-batches pipeline when batch results completed but the import step failed (e.g., broken pipe). Same final path as PATH 2.
Entrypoint: cmd_review -> do_external_start() and do_external_submit() in /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/review/external.py
Key difference from PATH 2: Uses attested_external=True instead of trusted_assessment_source=True. This triggers the attested_external policy path in import_helpers.py, which requires:
Attestation text containing "without awareness" and "unbiased"
PATH 5: --merge (Duplicate Finding Merge)
Entrypoint: cmd_review -> do_merge() in /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/review/merge.py
Flow:
code
entrypoint.py: cmd_review()
-> merge.py: do_merge(args)
-> list_open_review_findings(state) # gets all open review findings
-> _same_issue_concept() comparisons # Jaccard similarity + file overlap
-> For each merge group:
-> _merge_finding_details(primary, duplicate) # combines related_files, evidence
-> duplicate["status"] = "auto_resolved" # DIRECT state mutation
-> save_state(state, state_file)
Key difference: This does NOT go through import_holistic_findings() or merge_scan(). It directly mutates the findings dict in state, marking duplicates as auto_resolved and merging their details into the primary finding.
Change info available: The function prints merge group count and duplicate count, and writes to query.json:
python
{"command": "review", "action": "merge", "groups": N, "duplicates_merged": M}
PATH 6: fix review (Per-File Review Preparation)
Entrypoint: _cmd_fix_review() in /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/fix/review_flow.py
This is preparation only, not import. It calls review_mod.prepare_review() (per-file mode) and writes the review packet to query.json. The actual import would happen when the agent calls --import separately. So this is not a direct submission path -- it feeds into PATH 1.
THE CORE: import_holistic_findings() Return Value (The diff)
File: /Users/user_c042661f/Documents/desloppify/desloppify/intelligence/review/importing/holistic.py, line 256-388
The function returns a dict[str, Any] which is a ScanDiff (TypedDict from /Users/user_c042661f/Documents/desloppify/desloppify/engine/_state/schema.py, line 164-178).
The diff contains:
python
class ScanDiff(TypedDict):
new: int # count of genuinely new findings
auto_resolved: int # count of auto-resolved findings
reopened: int # count of reopened (previously resolved) findings
total_current: int # total current finding IDs in this batch
suspect_detectors: list[str] # detectors that may not have run
chronic_reopeners: list[dict] # findings reopened 2+ times
skipped_other_lang: int # findings skipped due to language mismatch
skipped_out_of_scope: int # findings skipped due to scope mismatch
ignored: int # findings matching ignore patterns
ignore_patterns: int # count of active ignore patterns
raw_findings: int # total raw findings before filtering
suppressed_pct: float # percentage of findings suppressed
# Added after merge_scan returns:
skipped: NotRequired[int] # validation-skipped findings count
skipped_details: NotRequired[list[dict]] # per-finding skip reasons
Critical limitation: The diff tells you counts but NOT which specific findings are new, resolved, or reopened. The new count comes from upsert_findings() in /Users/user_c042661f/Documents/desloppify/desloppify/engine/_state/merge_findings.py (line 153), but the actual finding IDs are not returned in the diff.
However, import_holistic_findings() DOES build new_ids = {finding["id"] for finding in review_findings} (line 346) -- this set contains ALL finding IDs that were submitted (not just the new ones). This is used internally for auto-resolve logic but is NOT returned in the diff.
What import_holistic_findings additionally does beyond returning the diff:
Stores assessments in state["subjective_assessments"] via store_assessments()
Stores dismissed concerns in state["concern_dismissals"]
Updates state["potentials"] for review/concerns detectors
Auto-resolves stale holistic findings not in the new import (_auto_resolve_stale_holistic)
Auto-resolves subjective_review coverage findings for reviewed files
_merge_scan_inputs: writes potentials and codebase_metrics into state
upsert_findings (merge_findings.py line 117-204):
For each finding in current_findings:
If ID is new: inserts into state["findings"], increments new_count
If ID exists but was fixed/auto_resolved: reopens it (increments reopened_count)
If ID exists and is open: updates last_seen, tier, confidence, summary, detail
Returns current_ids (all IDs in this batch), new_count, reopened_count, by_detector, ignored_count, changed_detectors
auto_resolve_disappeared: resolves findings that existed before but are NOT in current_ids (unless detector is suspect)
Critical for review: The review detector is always marked suspect (line 30 of merge_findings.py), so review findings are NEVER auto-resolved by a scan. They can only be auto-resolved by the holistic import's _auto_resolve_stale_holistic().
_mark_stale_on_mechanical_change: when mechanical detector findings change, marks corresponding subjective assessments as stale (needs_review_refresh = True)
_recompute_stats: recalculates score metrics
_append_scan_history: logs the scan result to state["scan_history"] (max 20 entries)
THE RECONCILIATION: reconcile_plan_after_scan()
File: /Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/reconcile.py, line 130-216
Return value: ReconcileResult dataclass:
python
@dataclass
class ReconcileResult:
superseded: list[str] # finding IDs that disappeared and were moved to plan["superseded"]
pruned: list[str] # old superseded entries removed (>90 days TTL)
resurfaced: list[str] # temporarily skipped items re-surfaced after review period
changes: int # total change count
What it does: Iterates all finding IDs referenced by the plan (queue_order, skipped, overrides, cluster finding_ids), checks if each is still alive in state. Dead findings get moved to plan["superseded"] with:
Yes, you can know exactly which findings were superseded -- they're in result.superseded. The function also reconciles epic clusters (removing dead finding IDs, deleting empty epics) and resurfaces stale temporary skips.
When it runs: Called from _reconcile_plan_post_scan() in /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/scan/scan_workflow.py (line 186-243) after every merge_scan_results(). It is best-effort (caught by PLAN_LOAD_EXCEPTIONS).
--scan-after-import Behavior
File: /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/review/runner_helpers.py, line 638-668
run_followup_scan() literally spawns a subprocess:
This is a full independent scan -- it runs the entire detector pipeline, calls merge_scan() again (this time for mechanical findings), saves state, and runs plan reconciliation. The review findings from the just-completed import are NOT auto-resolved by this scan because the review detector is always marked suspect.
Summary: What Change Information Is Available At Each Point
Submission Point
New Findings (count)
New Findings (IDs)
Resolved (count)
Resolved (IDs)
Score Changes
Assessment Changes
do_import()
Yes (diff["new"])
No (not in diff)
Yes (diff["auto_resolved"])
No
Yes (before/after score_snapshot)
Yes (in _imported_assessment_keys)
import_holistic_findings()
Yes
Partially (new_ids exists internally but = all submitted IDs, not just new)
Yes
No
No (caller must snapshot)
Yes (via store_assessments)
merge_scan()
Yes (new_count)
No (only current_ids = all current)
Yes
No
Recomputed in state
Via _mark_stale_on_mechanical_change
upsert_findings()
Yes
Yes (the new ones are those where finding_id not in existing)
N/A (done by auto_resolve_disappeared)
N/A
N/A
N/A
reconcile_plan_after_scan()
N/A
N/A
N/A
Yes (result.superseded)
N/A
N/A
do_merge()
N/A
N/A
Yes (count)
Yes (explicitly marked)
Yes (before/after snapshot)
N/A
The key gap: At the import_holistic_findings level, you get new_ids which is the set of ALL submitted finding IDs (line 346: new_ids = {finding["id"] for finding in review_findings}). To determine which are genuinely NEW vs. updates to existing, you would need to check new_ids against what was in state["findings"] before the merge -- but this comparison happens inside upsert_findings() and the individual IDs are not bubbled up. Only the count (new_count) makes it into the diff.
This is a metadata-only summary showing:
Queue item count
Skipped breakdown (temp/wontfix/fp counts)
Cluster list with member counts and descriptions
Annotations count (described/noted)
Active focus cluster
Superseded count ("Disappeared: N")
No concept of "new since last synthesis" whatsoever. It does not reference epic_synthesis_meta, synthesized_ids, or new_since_last. It is purely structural metadata.
The queue table renders columns: #, Tier, Detector, Summary, Cluster. There are currently two item markers:
[skip] suffix for skipped items (line 107)
[N items] prefix for collapsed cluster rows (line 97)
No "new" marker exists. The _build_rows function (line 87) builds rows from queue items but has no access to epic_synthesis_meta.synthesized_ids or any "new since" data. However, it would be straightforward to extend:
The plan dict is loaded (line 125) and available
Each item has an id field
A [NEW] suffix could be added in _build_rows by checking item["id"] not in plan.get("epic_synthesis_meta", {}).get("synthesized_ids", [])
4. epic_synthesis_meta in the Plan Schema
File:/Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/schema.py, line 87
In the schema it is typed as dict with no further structure: epic_synthesis_meta: dict # synthesis engine metadata
The actual structure is populated in two places:
After LLM-based synthesis (apply_synthesis_to_plan in /Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/epic_synthesis.py, line 601):
python
plan["epic_synthesis_meta"] = {
"synthesized_ids": open_review_ids, # list[str] -- ALL open review IDs at time of synthesis
"last_run": now,
"version": version,
"dismissed_ids": dismissed_ids,
"finding_snapshot_hash": current_hash,
"strategy_summary": synthesis.strategy_summary,
"trigger": trigger,
}
After manual staged synthesis (_apply_completion in synthesize_handlers.py, line 178):
meta["stage_snapshot_hash"] -- set by refresh_stage_snapshot(), used to detect if review findings changed mid-synthesis
meta["stage_refresh_required"] -- set when snapshot hash diverges
Critical finding: synthesized_ids is only written by the LLM-based path (apply_synthesis_to_plan). The manual staged synthesis path (_apply_completion) does NOT write synthesized_ids. This means after a manual synthesis, the next collect_synthesis_input call would compute new_since_last as current_review_ids - set(meta.get("synthesized_ids", [])), which would be ALL current IDs (everything looks "new").
@dataclass
class ReconcileResult:
superseded: list[str] # IDs moved to superseded (disappeared findings)
pruned: list[str] # Old superseded entries cleaned up (>90 day TTL)
resurfaced: list[str] # Stale temporary skips brought back
changes: int = 0 # Total mutation count
The reconciliation focuses on removals -- what disappeared. It does NOT track "new" findings. There is no added or new field.
_supersede_id (line 47) creates a SupersededEntry with:
superseded_at, remapped_to, candidates (up to 5 potential remaps from same detector/file)
note (preserved from override if one existed)
The candidates field (line 75) is interesting -- it finds open findings with the same detector+file, which could be used to suggest remapping. But there is no actual remapping logic; it just records the candidates.
No remapped entries are tracked in the result -- only superseded. The remapped_to field on SupersededEntry exists in the schema but is always set to None by the current reconciliation code.
6. plan_start_scores
File:/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/scan/scan_workflow.py (line 149) and /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/helpers/queue_progress.py
plan_start_scores implements a frozen score lifecycle:
Seeded (_seed_plan_start_scores, line 149): When a plan has queue items but no plan_start_scores, snapshot the current scores:
Display while active (print_frozen_score_with_queue_context, queue_progress.py line 33): Shows the frozen score and queue remaining count: "Score (frozen at plan start): strict 85.0/100" with a note that the score won't update until queue is clear.
Cleared when queue empties (_clear_plan_start_scores_if_queue_empty, line 165): When queue count reaches 0, stashes the old scores on state["_plan_start_scores_for_reveal"] and clears the plan field.
Revealed on next scan (_show_score_reveal in scan_reporting_summary.py): Compares frozen start scores against new live scores to show the improvement delta.
Could it help show score impact of new findings? Yes, conceptually. The frozen score establishes a "before" baseline. If new findings come in (raising the queue), comparing current live dimension scores against the frozen snapshot would show degradation. However, the current code only reveals the comparison when the queue is drained (a success moment). There is no mid-cycle comparison showing "these 5 new findings would move your strict score from X to Y."
When new findings come in after a scan, auto-clustering handles them as follows (line 241, auto_cluster_findings):
For existing auto-clusters:
If user_modified: merge new findings in, don't remove user's edits (line 314-319):
python
new_ids = [fid for fid in member_ids if fid not in existing_ids]
if new_ids:
cluster["finding_ids"].extend(new_ids)
If NOT user_modified: replace membership wholesale (line 322-329). The entire finding_ids list is rebuilt from the current grouping key match.
For new grouping keys: Creates a new auto/ cluster (line 337-348).
Singleton suppression: Groups with fewer than 2 members are dropped (line 279: _MIN_CLUSTER_SIZE = 2), except for _UNSCORED_NAME = "auto/initial-review" which has _MIN_UNSCORED_CLUSTER_SIZE = 1.
Stale cluster cleanup: Auto-clusters whose grouping key is no longer active (no matching findings) are deleted (line 461-489), unless user_modified and still has alive members.
Key observation: Auto-clustering does NOT annotate which findings are "new" to a cluster. It simply rebuilds memberships. There is no added_since_last tracking on clusters.
8. The Synthesis OBSERVE Stage Handler -- "What's New" View
The OBSERVE handler itself (_cmd_stage_observe, line 214) does NOT generate a "what's new" view. It simply accepts a text report and saves it.
The dashboard (_cmd_synthesize_dashboard, line 888) is the only place that shows new/resolved counts:
python
if si.new_since_last:
print(f" New since last synthesis: {len(si.new_since_last)}")
if si.resolved_since_last:
print(f" Resolved since last synthesis: {len(si.resolved_since_last)}")
The SynthesisInput dataclass (in epic_synthesis.py, line 123) has the fields:
python
new_since_last: set[str] # finding IDs new since last synthesis
resolved_since_last: set[str] # finding IDs resolved since last
These are computed in collect_synthesis_input (line 184):
The LLM prompt (build_synthesis_prompt, line 300) DOES include a clear "what's new" section:
python
if si.new_since_last:
parts.append(f"## New findings since last synthesis ({len(si.new_since_last)})")
for fid in sorted(si.new_since_last):
f = si.open_findings.get(fid, {})
parts.append(f"- {fid}: {f.get('summary', '(no summary)')}")
But this prompt is only used in the LLM-driven path (not the manual staged workflow).
The reflect dashboard (_print_reflect_dashboard, line 832) shows completed clusters, resolved findings, and recurring patterns -- but not new findings specifically.
Summary of Gaps and Extension Points
Area
Current State
Gap
Extension Opportunity
Synthesize dashboard
Shows new_since_last count only
Does not list new findings or mark them in the dimension listing
Add [NEW] markers in the dimension-grouped listing; show new findings in their own section
plan show
Pure metadata summary
No synthesis awareness at all
Add "N new since last synthesis" line when epic_synthesis_meta exists
plan queue
No new markers
No access to synthesis meta in row building
Pass synthesized_ids to _build_rows; add [NEW] suffix
epic_synthesis_meta
synthesized_ids only written by LLM path
Manual synthesis does not write synthesized_ids
_apply_completion should also write synthesized_ids (list of current open review IDs)
Reconcile result
Tracks superseded, pruned, resurfaced
No added/new field
Could add new_findings: list[str] by diffing current state IDs vs plan queue
plan_start_scores
Frozen score with queue-drained reveal
No mid-cycle "impact of new findings"
Compare current dimension scores against frozen snapshot when new findings arrive
Auto-clusters
Rebuilds memberships wholesale
No per-cluster "added since last" tracking
Add added_at timestamps per finding in cluster, or a new_members transient field
OBSERVE handler
Accepts free-text, no structured "new" view
The new findings data exists in SynthesisInput.new_since_last but isn't surfaced to the CLI user
Print new findings with summaries before asking for the observe report