I need to audit the current implementation for code elegance issues. The feature "Standardized Plan Staleness & Re-Synthesis System" was just implemented across ~13 files. The self-assessment identified these problems:
_short_id() is copy-pasted in 4 files — find all copies and determine the best home for a single shared version
check_synthesis_guardrail() in guardrails.py calls sys.exit(1) directly — assess whether other guardrail/gate patterns in the codebase use sys.exit or return results
_sync_plan_after_review_change() in import_cmd.py mixes data mutation with presentation — assess the pattern used by other plan sync functions (like reconcile_plan_after_scan)
Two _apply_completion() functions exist (synthesize_handlers.py and synthesis/shared.py) — assess whether they can be unified
The guardrail is sprinkled into 5 command files individually — assess whether the codebase has any middleware/decorator pattern for cross-cutting concerns
For each issue, read the relevant files and report:
The exact file paths and line numbers of each problem
What existing patterns in the codebase suggest as the right solution
Whether there are existing shared utils that could be reused
Files to check:
desloppify/app/commands/helpers/guardrails.py (check_synthesis_guardrail with sys.exit)
Also check: does _short_id already exist in a shared location? Search for "short_id" across the codebase.
Assistant
I'll systematically audit these files to identify the code elegance issues. Let me start by searching for existing patterns and then examining each problem area.
Assistant
Now let me read the key files to understand the issues:
Assistant
Now let me examine more files to understand the patterns used elsewhere:
Assistant
Now let me look at the command files that call the guardrail to understand how it's being used:
Assistant
Now let me search for more context on how other patterns handle error conditions and middleware:
Assistant
Now let me check the synthesize_handlers file for the full _apply_completion function and look at batch_prompt_template to see if it has _short_id too:
Assistant
Let me check the batch_prompt_template more carefully and look at stale_dimensions:
Assistant
Now let me look at the complete _apply_completion functions in synthesize_handlers to understand the second one:
Assistant
Let me verify the exact locations and check for middleware patterns:
Assistant
Now let me find all the file locations and exact line numbers:
Assistant
Perfect! Now let me get more detail on those usage contexts:
Assistant
Now let me check what file paths are being used and check the reconcile function for how it handles plan state:
Assistant
Now let me verify the usage context of the two functions in the resolve cmd more carefully:
Assistant
Perfect! Now I have all the information I need. Let me create a comprehensive audit report:
Code Elegance Audit Report: Standardized Plan Staleness & Re-Synthesis System
def _short_id(fid: str) -> str:
if "::" in fid:
suffix = fid.rsplit("::", 1)[-1]
if len(suffix) >= 8:
return suffix[:8]
return fid
Usage Pattern:
guardrails.py line 102: displays new findings in guardrail banner
synthesize_handlers.py line 169: displays findings during synthesis stages
synthesis/shared.py line 199: displays unclustered findings in progress
import_cmd.py line 198: displays newly imported findings summary
Recommended Solution:
Move to desloppify/app/commands/helpers/ as a utility function (guardrails.py is the most appropriate home since it's already a public guardrail module) or create a new display_helpers.py module in desloppify/app/commands/helpers/. The guardrails.py location makes sense because:
It already exports public functions (print_synthesis_guardrail_banner, check_synthesis_guardrail)
Display/rendering concerns are closely related to output presentation
def check_synthesis_guardrail(
*,
plan: dict | None = None,
state: dict | None = None,
severity: Literal["info", "gate"] = "info",
bypass: bool = False,
attest: str = "",
) -> bool:
"""Unified synthesis guardrail.
- ``"info"`` — yellow banner (for status, show, next, plan queue)
- ``"gate"`` — red block + sys.exit(1) unless bypassed (for resolve --status fixed)
Returns True if the guardrail fired (stale/pending), False if clean.
"""
# ... logic ...
if severity == "info":
# Yellow informational banner
# ... prints but returns True/False
return True
# severity == "gate"
if bypass and attest and len(attest.strip()) >= 30:
# ... returns False (allowed to proceed)
return False
# BLOCKED
# ... prints error details ...
sys.exit(1) # LINE 118 — exits process directly
Contrast with Other Patterns:
In desloppify/app/commands/helpers/state.py (line 53-58), the codebase has established a "guard" pattern:
python
def require_completed_scan(state: dict) -> bool:
"""Return True when the state contains at least one completed scan."""
has_completed_scan = bool(state.get("last_scan"))
if not has_completed_scan:
print(colorize("No scans yet. Run: desloppify scan", "yellow"))
return has_completed_scan # Caller decides what to do
In desloppify/app/commands/resolve/cmd.py (lines 137-143), helper functions return and let the caller decide:
python
def _save_state_or_exit(state: dict, state_file: str) -> None:
"""Persist state with a consistent CLI error boundary."""
try:
state_mod.save_state(state, state_file)
except OSError as exc:
print_error(f"could not save state: {exc}")
sys.exit(1) # Named `_or_exit` to signal this behavior
Problem:check_synthesis_guardrail() doesn't signal in its name that it may exit. The function has a dual personality:
When severity="info" → returns bool (non-blocking)
When severity="gate" → may call sys.exit(1) without explicit control
Actual Call Site Handling (resolve/cmd.py, lines 175-181):
python
if args.status == "fixed":
check_synthesis_guardrail(
state=state,
severity="gate",
bypass=bool(getattr(args, "force_resolve", False)),
attest=getattr(args, "attest", "") or "",
)
# Code AFTER this call assumes check_synthesis_guardrail didn't exit
# But it might have!
Recommended Solution:
Rename to check_synthesis_guardrail_or_exit() to explicitly signal the exit behavior, matching the pattern used for _save_state_or_exit() and _save_config_or_exit(). Alternatively, refactor to return a result that the caller can handle, but the _or_exit naming convention is already established in the codebase for functions that may terminate.
Issue 3: _sync_plan_after_review_change() Mixes Data Mutation with Presentation
def _sync_plan_after_review_change(state: dict, diff: dict) -> None:
"""Best-effort: sync living plan after review import introduces new findings."""
try:
from desloppify.engine.plan import (
append_log_entry,
compute_new_finding_ids,
ensure_plan_defaults,
has_living_plan,
load_plan,
save_plan,
sync_synthesis_needed,
)
# DATA MUTATION PHASE (lines 154-188)
if not has_living_plan():
return
plan = load_plan()
ensure_plan_defaults(plan)
new_ids = compute_new_finding_ids(plan, state)
if not new_ids:
return
order: list[str] = plan["queue_order"]
existing = set(order)
added: list[str] = []
for fid in sorted(new_ids):
if fid not in existing:
order.append(fid)
added.append(fid)
sync_synthesis_needed(plan, state)
append_log_entry(plan, "review_import_sync", actor="system", detail={...})
save_plan(plan) # ← MUTATION COMMITTED
# PRESENTATION PHASE (lines 190-211)
print(colorize(f"\n Plan updated: {len(new_ids)} new review finding(s) added to queue.", "bold"))
findings = state.get("findings", {})
for fid in sorted(new_ids)[:10]:
f = findings.get(fid, {})
print(f" * [{_short_id(fid)}] {f.get('summary', '')}")
# ... more prints ...
except PLAN_LOAD_EXCEPTIONS:
pass # best-effort — don't break import on plan errors
Contrast with reconcile_plan_after_scan() (engine/_plan/reconcile.py, lines 132-170):
python
def reconcile_plan_after_scan(
plan: PlanModel,
state: StateModel,
) -> ReconcileResult: # ← Returns summary, no side effects
"""Reconcile plan against current state after a scan.
Finds IDs referenced in the plan that no longer exist or are no longer
open, moves them to superseded, and prunes old superseded entries.
"""
ensure_plan_defaults(plan)
result = ReconcileResult() # ← Builds result dataclass
# ... performs all mutations ...
return result # ← Caller decides how to present/log
How reconciliation is called (scan_workflow.py):
python
if _apply_plan_reconciliation(plan, runtime.state, reconcile_plan_after_scan):
dirty = True
The reconciliation function returns data, and the caller controls presentation.
Problem:_sync_plan_after_review_change() is opinionated about:
What to print (lines 191-211 are hardcoded output)
How many items to show (first 10)
The exact phrasing of messages
This makes it harder to reuse in different contexts (e.g., if the review command wanted different output formatting) and violates separation of concerns.
Recommended Solution:
Extract a pure _sync_plan_after_review_change_data() function that returns a structured result (e.g., dict with new_ids, added, existing) and move presentation to the caller. Model it after reconcile_plan_after_scan():
python
def _sync_plan_after_review_change_data(state: dict) -> dict:
"""Return plan sync result or empty dict if no changes."""
# Pure data function, no printing
def _sync_plan_after_review_change(state: dict, diff: dict) -> None:
"""Wrapper: sync plan and present results."""
result = _sync_plan_after_review_change_data(state)
if not result:
return
# Presentation logic here
Issue 4: Two _apply_completion() Functions (Potential Duplication)
Function 1 (synthesize_handlers.py, lines 178-212):
python
def _apply_completion(args: argparse.Namespace, plan: dict, strategy: str) -> None:
"""Shared completion logic: update meta, remove synthesis::pending, save."""
organized, total, clusters = _synthesis_coverage(plan)
order: list[str] = plan.get("queue_order", [])
if SYNTHESIS_ID in order:
order.remove(SYNTHESIS_ID)
runtime = command_runtime(args)
state = runtime.state
current_hash = review_finding_snapshot_hash(state)
meta = plan.setdefault("epic_synthesis_meta", {})
meta["finding_snapshot_hash"] = current_hash
open_review_ids = sorted(
fid for fid, f in state.get("findings", {}).items()
if f.get("status") == "open" and f.get("detector") in ("review", "concerns")
)
meta["synthesized_ids"] = open_review_ids
if strategy.strip().lower() != "same":
meta["strategy_summary"] = strategy
meta["trigger"] = "manual_synthesis"
meta["last_completed_at"] = utc_now()
meta["synthesis_stages"] = {} # clear stages on completion
meta.pop("stage_refresh_required", None)
meta.pop("stage_snapshot_hash", None)
save_plan(plan)
cluster_count = len([c for c in clusters.values() if c.get("finding_ids")])
print(colorize(f" Synthesis complete: {organized}/{total} findings in {cluster_count} cluster(s).", "green"))
effective_strategy = strategy if strategy.strip().lower() != "same" else meta.get("strategy_summary", "")
if effective_strategy:
print(colorize(f" Strategy: {effective_strategy}", "cyan"))
print(colorize(" Run `desloppify next` to start implementation.", "green"))
Function 2 (synthesis/shared.py, lines 244-286):
python
def _apply_completion(args: argparse.Namespace, plan: dict, strategy: str) -> None:
"""Shared completion logic: update meta, remove synthesis::pending, save."""
organized, total, clusters = _synthesis_coverage(plan)
order: list[str] = plan.get("queue_order", [])
if SYNTHESIS_ID in order:
order.remove(SYNTHESIS_ID)
runtime = command_runtime(args)
state = runtime.state
current_hash = review_finding_snapshot_hash(state)
meta = plan.setdefault("epic_synthesis_meta", {})
meta["finding_snapshot_hash"] = current_hash
open_review_ids = sorted(
fid for fid, f in state.get("findings", {}).items()
if f.get("status") == "open" and f.get("detector") in ("review", "concerns")
)
meta["synthesized_ids"] = open_review_ids
if strategy.strip().lower() != "same":
meta["strategy_summary"] = strategy
meta["trigger"] = "manual_synthesis"
meta["last_completed_at"] = utc_now()
meta["synthesis_stages"] = {}
meta.pop("stage_refresh_required", None)
meta.pop("stage_snapshot_hash", None)
save_plan(plan)
cluster_count = len([c for c in clusters.values() if c.get("finding_ids")])
print(
colorize(
f" Synthesis complete: {organized}/{total} findings in {cluster_count} cluster(s).",
"green",
)
)
effective_strategy = (
strategy if strategy.strip().lower() != "same" else meta.get("strategy_summary", "")
)
if effective_strategy:
print(colorize(f" Strategy: {effective_strategy}", "cyan"))
print(colorize(" Run `desloppify next` to start implementation.", "green"))
Difference:
The functions are 98% identical. The only difference is line wrapping/formatting in the final print statement. They should be unified.
Usage:
synthesize_handlers.py: lines 712, 842 call it
synthesis/shared.py: not called anywhere visible in the grep results
Assessment:
It appears synthesis/shared.py contains a shared module, but the _apply_completion is being used locally in synthesize_handlers.py. The copy in synthesis/shared.py may be a helper that was duplicated or leftover.
Recommended Solution:
Keep the version in synthesis/shared.py as the canonical shared implementation (it's in a "shared" module)
Remove the duplicate from synthesize_handlers.py
Import from synthesis/shared.py in synthesize_handlers.py
Issue 5: Guardrail Check Sprinkled into 5 Command Files Individually
Call Pattern:
All calls are explicit imports and manual calls within command logic. Example (next.py):
python
from desloppify.app.commands.helpers.guardrails import check_synthesis_guardrail
def cmd_next(args: argparse.Namespace) -> None:
"""Show next highest-priority queue items."""
runtime = command_runtime(args)
state = runtime.state
# ... other setup ...
check_synthesis_guardrail(state=state, severity="info") # ← Manual call
_get_items(args, state, config)
Existing Middleware/Decorator Patterns in Codebase:
The codebase uses helper functions rather than decorators:
require_completed_scan(state) in helpers/state.py — guards before state usage
_save_state_or_exit() in resolve/cmd.py — safety wrapper
There is no decorator pattern found in desloppify/app/commands/. All command logic is sequential (non-decorated).
Assessment:
The guardrail is not truly "sprinkled" — it's strategically placed at 5 guard points where different severity levels are needed:
1 gate (resolve) for blocking behavior
4 info (next, status, show, plan queue) for informational notices
These are deliberate placements, not random duplication. However, the pattern could be cleaner.
Recommended Solution:
Given the codebase's architectural style, there are two reasonable approaches:
Option A (Minimal Change):
Keep as-is. The pattern is explicit and clear, and each call site has good reason (different severity levels + different contexts). This aligns with the codebase's preference for explicit helper function calls over implicit decorators.
Option B (Centralize Info Banners):
Create a helper wrapper for the "info" case since 4 out of 5 calls are identical:
This reduces duplication while keeping the gate case explicit in resolve/cmd.py.
Option C (Middleware Pattern):
Create a command wrapper (not a decorator, but a pre-flight check function) that all info-level commands call. This isn't idiomatic to the codebase though.