I need to understand the key files for implementing a lifecycle integration test suite. Read these files and summarize the important patterns, function signatures, data structures, and constants I need:
desloppify/tests/commands/scan/test_plan_reconcile.py - existing test patterns, mocking approach, _runtime helper
desloppify/app/commands/scan/plan_reconcile.py - reconcile_plan_post_scan signature and behavior
desloppify/base/subjective_dimensions.py - DISPLAY_NAMES or dimension key mapping
desloppify/tests/review/work_queue_cases.py - any useful patterns for building test state
For each file, provide:
Full function signatures with parameters
Key constants and their values
Data structure shapes (state dict, plan dict, etc.)
Mocking patterns used in tests
Be thorough - I need exact details to write the test file.
Assistant
I'll read these files systematically to extract the key patterns, signatures, and data structures you need.
Assistant
User
I need to understand how work queue items get marked as completed/resolved in the desloppify CLI. Search for:
How plan resolve works - the command that marks queue items as done
How subjective reviews get completed (what changes in state when a review finishes)
How workflow items like workflow::communicate-score get resolved
How triage stages get confirmed/completed
Any helper functions that "complete" or "resolve" a queue item programmatically
Look in:
desloppify/app/commands/plan/ for resolve commands
desloppify/app/commands/review/ for review completion
desloppify/engine/_plan/ for plan operations that mark things done
Any resolve, complete, confirm, skip functions
I need exact function signatures and what state mutations they perform, so I can call them from tests to walk through the lifecycle properly.
Assistant
I'll search for how work queue items get marked as completed/resolved in the desloppify CLI.
Assistant
Now let me read the key files for understanding completion/resolution workflows:
Assistant
Now let me look at operations_queue to find how items get removed from queue and what functions complete items:
Assistant
Let me check the apply_completion function and look more broadly for item completion:
Assistant
Now let me check the review completion and look at the next command to see what handles queue item movement:
Assistant
Let me try again:
Assistant
Now let me check the next cmd and review workflow handlers:
Assistant
Now let me look at how the plan resolve command works and review item handling:
Assistant
Now let me look at the cmd_plan_resolve function:
Assistant
Perfect! Now let me look at cmd_resolve to see the full flow:
Assistant
Let me look at the resolve apply module:
Assistant
Now let me get more of the resolve command to understand the full lifecycle:
Assistant
Perfect! Now let me look at synthetic workflow and subjective policy to understand those item types:
Assistant
Now let me check stale_dimensions for the subjective item IDs and look at the plan operations more broadly:
Assistant
Perfect! Now let me get the engine plan facade to see the full API:
Assistant
Great! Now let me gather the test file information to see how testing works:
Assistant
Perfect! Now I have enough information. Let me create a comprehensive summary document:
Assistant
Perfect! Now let me create one more supplemental document with exact file locations and imports:
Assistant
Perfect! Now let me create one final document with code examples:
Assistant
User
I need to understand how desloppify reads/writes state and plan files so I can write a script that creates spoofed state files on disk.
Find:
How state_path is determined — what file name, what directory (.desloppify/)
How plan.json is located relative to state
The exact format of state JSON files — what top-level keys are required
How next and plan commands load state — do they need a --path arg?
How scan --path determines the .desloppify/ directory location
Any save_state/load_state functions and their file paths
Look in:
desloppify/state.py for load/save
desloppify/cli.py for how --path works
desloppify/engine/plan.py for load_plan/save_plan
desloppify/base/file_paths.py for path resolution
I need exact file paths and the minimum viable state dict to write to disk.
Assistant
I'll help you understand how desloppify reads and writes state and plan files. Let me search through the codebase systematically.
Assistant
Let me try with absolute paths:
Assistant
Now let me read these files:
Assistant
Now let me find the actual state path and schema definitions:
Assistant
Now let me check the plan persistence:
Assistant
Now let me check how the plan and next commands determine paths, and look at more of the plan schema:
Assistant
Let me read more of the plan schema to see the full structure:
Assistant
Perfect! Now let me check how load_plan() is called (with or without arguments) and how paths are resolved:
Assistant
Good! Now let me check how scan determines the .desloppify directory:
Assistant
Let me check the scan command entry point:
Assistant
Let me search for where state_path is used in scan context:
Assistant
Excellent! Now let me get a summary by looking at a test to see real examples of state files:
Assistant
Now let me look at test fixtures to see actual state structures:
Assistant
Perfect! Now let me create a comprehensive summary. Let me also quickly check what happens when --path is passed to the scan command:
Assistant
Excellent! I have all the files. Let me now provide you with a comprehensive summary of the key patterns, signatures, and data structures needed for your lifecycle integration test suite.
Summary: Key Patterns, Function Signatures, and Data Structures
1. Test Patterns & Mocking Approach (test_plan_reconcile.py)
_runtime() Helper
python
def _runtime(*, state=None, config=None) -> SimpleNamespace:
return SimpleNamespace(
state=state or {},
state_path=Path("/tmp/fake-state.json"),
config=config or {},
)
Used to mock the CLI runtime object passed to commands
Must include: state (dict), state_path (Path), config (dict)
def sync_unscored_dimensions(
plan: PlanModel,
state: StateModel,
) -> UnscoredDimensionSyncResult:
"""Prepend unscored IDs unconditionally (onboarding priority)."""
def sync_stale_dimensions(
plan: PlanModel,
state: StateModel,
*,
policy: SubjectiveVisibility | None = None,
cycle_just_completed: bool = False,
) -> StaleDimensionSyncResult:
"""Inject stale/under-target dimensions when no objective backlog or cycle just completed."""
def sync_triage_needed(
plan: PlanModel,
state: StateModel,
) -> TriageSyncResult:
"""Inject 4 triage stage IDs when review issues change."""
def review_issue_snapshot_hash(state: StateModel) -> str:
"""Hash open review issue IDs to detect changes. Empty string if no open review issues."""
ID Discovery Functions
python
def current_unscored_ids(state: StateModel) -> set[str]:
"""subjective::<slug> IDs that are placeholder (never scored)."""
def current_under_target_ids(
state: StateModel,
*,
target_strict: float = DEFAULT_TARGET_STRICT_SCORE,
) -> set[str]:
"""subjective::<slug> IDs under target but not stale/unscored."""
def _current_stale_ids(state: StateModel) -> set[str]:
"""subjective::<slug> IDs that are currently stale."""
def _open_review_issue_ids(state: StateModel) -> set[str]:
"""Set of open issue IDs with detector 'review' or 'concerns'."""
class WorkQueueResult(TypedDict):
items: list[WorkQueueItem] # sorted queue items
total: int # count before limiting
grouped: dict[str, list[WorkQueueItem]]
new_ids: set[str] # IDs new since last triage
DEFAULT_TARGET_STRICT_SCORE = 85.0 # from base/config.py
9. Key Assertions Patterns
From test examples:
python
# Superseding
assert "issue-1" in plan["superseded"]
assert "issue-1" not in plan["queue_order"]
# Syncing dimensions
assert "subjective::naming" in plan["queue_order"]
assert "subjective::naming" in result.injected
# Scoring
assert plan["plan_start_scores"]["strict"] == 85.0
# Execution log
log_actions = [e["action"] for e in plan["execution_log"]]
assert "reconcile" in log_actions
assert "seed_start_scores" in log_actions
# Queue building
ids = {item["id"] for item in queue["items"]}
assert "issue-1" in ids
# Lifecycle filtering
subj_ids = [i for i in ids if i.startswith("subjective::")]
assert len(subj_ids) == 0 # blocked when objective work remains
This gives you all the exact function signatures, data structures, constants, and test patterns you need to write comprehensive lifecycle integration tests. The key insight is that tests use monkeypatching for I/O boundaries, real orchestration logic, and capture changes to validate behavior.
Perfect! Now let me create a final summary to share with the user:
Summary
I've completed a comprehensive search of the desloppify CLI codebase to understand how work queue items get marked as completed/resolved. Here are the key findings:
Returns count unskipped + IDs needing state reopen (permanent/false_positive)
Key Mutation Functions for Tests
python
# Import all these for test helpers
from desloppify import state as state_mod
from desloppify.engine import plan as plan_mod
from desloppify.engine._state.resolution import resolve_issues
from desloppify.engine._plan.operations_lifecycle import purge_ids
from desloppify.engine._plan.operations_meta import append_log_entry
from desloppify.engine._plan.operations_skip import skip_items, unskip_items
from desloppify.engine._plan.stale_dimensions import TRIAGE_IDS, WORKFLOW_*
# Mark issue complete
state_mod.resolve_issues(state, "pattern", "fixed", "note", attestation="...")
plan_mod.purge_ids(plan, ["issue-id"])
# Log completion
plan_mod.append_log_entry(plan, "done", issue_ids=["..."], actor="user", note="...")
# Skip/resurface
plan_mod.skip_items(plan, ["id"], kind="temporary", review_after=3, scan_count=state["scan_count"])
count, reopen_ids = plan_mod.unskip_items(plan, ["id"])
I've created three detailed reference documents in /tmp/ that contain:
completion_lifecycle_summary.txt - Complete workflow overview with state structures
completion_reference.txt - Exact function signatures, imports, and constants
Minimum viable plan (using empty_plan() function):
python
from desloppify.engine.plan import empty_plan
plan = empty_plan()
# Already has all required keys populated
5. How next and plan Commands Load State/Plan
Both commands:
Do NOT require --path argument
Auto-resolve state path using state_path(args) in cli.py
Auto-resolve plan path as .desloppify/plan.json
Load sequence:
python
# From cli.py main():
_load_shared_runtime(args) # Called once
# Inside _load_shared_runtime():
state_file = state_path(args) # → Path | None
state = load_state(state_file) # load from state_file or use default
# state_file can be None (no language detected)
# load_state(None) returns empty_state()
# Later in command handler:
plan = load_plan() # No args needed
# Defaults to PLAN_FILE = .desloppify/plan.json
6. How scan --path Determines .desloppify Directory
Critical detail: The --path argument to scan is the source code directory, NOT the state directory.
.desloppify location is always:
code
<PROJECT_ROOT>/.desloppify/
Where PROJECT_ROOT is:
From get_project_root() in base/discovery/paths.py
First directory containing .git/ going upward from CWD
Falls back to CWD if no .git/ found
Example:
bash
# Regardless of where you run this:
desloppify --lang python scan --path ./src
# State is ALWAYS saved to:
<PROJECT_ROOT>/.desloppify/state-python.json
7. Save/Load Functions
State persistence:
python
# From engine/_state/persistence.py
load_state(path: Path | None = None) -> StateModel
# If path is None, defaults to STATE_FILE = .desloppify/state.json
# Returns empty_state() if file missing or corrupted
# Tries backup (.json.bak) if primary corrupted
save_state(
state: StateModel,
path: Path | None = None,
*,
subjective_integrity_target: float | None = None,
) -> None
# If path is None, defaults to STATE_FILE
# Atomically writes via safe_write_text()
# Creates backup .json.bak before overwriting
# Recomputes stats before saving
Plan persistence:
python
# From engine/_plan/persistence.py
load_plan(path: Path | None = None) -> PlanModel
# If path is None, defaults to PLAN_FILE = .desloppify/plan.json
# Returns empty_plan() if missing or corrupted
# Tries backup (.json.bak) if primary corrupted
save_plan(plan: PlanModel | dict, path: Path | None = None) -> None
# If path is None, defaults to PLAN_FILE
# Atomically writes via safe_write_text()
# Creates backup .json.bak before overwriting
# Auto-updates "updated" timestamp
8. Safe File Writing Pattern
Used by both state and plan persistence:
python
# From base/discovery/file_paths.py
def safe_write_text(filepath: str | Path, content: str) -> None:
"""Atomically write text using temp+rename."""
p = Path(filepath)
p.parent.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=p.parent, suffix=".tmp")
try:
with os.fdopen(fd, "w") as f:
f.write(content)
os.replace(tmp, str(p)) # Atomic on POSIX
except OSError:
if os.path.exists(tmp):
os.unlink(tmp)
raise