Explore the desloppify codebase to understand the task resolution flow. Specifically:
How does a user mark a task as "resolved" or "done"? Look at desloppify/app/commands/resolve/ — understand the full flow from CLI input to state update.
What happens after resolution? Does it show a next task? Does it prompt anything?
Look at desloppify/app/commands/resolve/cmd.py, selection.py, render.py and any other files in that directory.
Look at desloppify/engine/_state/resolution.py to understand state changes on resolution.
How does the next command work? Look at desloppify/app/commands/next.py and next_parts/.
What is the user experience flow: scan → plan → next → resolve → next → ...?
Be very thorough - read the actual code in these files.
Assistant
I'll help you explore the task resolution flow in the desloppify codebase. Let me start by examining the key files you mentioned.
Assistant
Now let me read the main resolve command file and related files:
User
Explore the desloppify codebase to understand the plan/state data structures and persistence. Specifically:
Read desloppify/engine/_plan/schema.py — what is the full data model for the plan? What fields exist?
Read desloppify/engine/_plan/operations.py — what operations can be performed on plan items?
Read desloppify/engine/_state/schema.py — what is tracked per-finding in state?
Read desloppify/engine/plan.py — the facade for plan operations.
How are clusters represented? Look at cluster-related code in _plan/ and app/commands/plan/cluster_handlers.py.
What does .desloppify/plan.json look like in terms of structure?
Is there any existing git-related tracking in the codebase?
Be very thorough - read the actual code.
Assistant
Now let me examine the state resolution logic and the next command:
Assistant
I'll help you explore the desloppify codebase to understand the plan/state data structures and persistence. Let me start by reading the key files systematically.
Assistant
Let me look at more files to understand the complete flow:
Assistant
Now let me read the cluster-related code and check the persistence/plan.json structure:
Assistant
Let me continue examining the resolve files and the plan integration:
Assistant
Now let me check for any git-related code in the codebase:
Assistant
Let me look at the queue_guard file and understand how the plan is updated:
User
Explore the desloppify codebase to understand configuration, settings, and user interaction patterns. Specifically:
Read desloppify/core/config.py — how are settings stored and loaded? Is there a user config file?
Read desloppify/core/file_paths.py — what files does the tool use for persistence?
Look at how the CLI prompts users for input — search for input(, click.confirm, click.prompt, Prompt.ask, Confirm.ask or any rich/click prompt patterns across the codebase.
Look at desloppify/app/commands/plan/cmd.py to understand how plan subcommands work.
Search for any existing git integration — look for subprocess calls with git, or imports of git modules.
Look at how the tool handles the work queue — desloppify/engine/_work_queue/ and desloppify/engine/work_queue.py.
Check desloppify/engine/_plan/stale_dimensions.py and reconcile.py to understand how the plan stays in sync.
Be very thorough.
Assistant
I'll conduct a comprehensive exploration of the desloppify codebase focusing on configuration, file persistence, user interaction patterns, git integration, and the work queue system. Let me start with parallel searches to cover these areas efficiently.
Assistant
Now let me look at the plan.py facade file to understand the plan API:
Assistant
Let me look at an example plan.json file to understand the structure:
Assistant
Let me look at the purge_ids and understand the work queue building:
Assistant
Let me continue searching for more information on user interaction patterns, git integration, and the work queue system.
Assistant
Now let me read the purge_ids function:
Assistant
Perfect! Now let me read a bit more to see the clusters and other sections:
Assistant
Let me check the narrative context and understand the full post-resolve flow:
Assistant
Let me search for the individual work queue files and explore the system more methodically.
Assistant
Let me search for cluster and superseded information:
Assistant
Let me check how triage guardrails work and examine a test to understand the flow better:
Assistant
Perfect! Now let me check the superseded section and skipped section:
Assistant
Let me look at one more important piece - how the CLI is structured and how the commands flow together:
Assistant
Excellent! Now let me check for any git-related code more comprehensively:
Assistant
Now let me read the key files for work queue and plan, plus examine input patterns more deeply.
Assistant
Now let me search for more information on CLI prompts, triage handlers, and the plan operations.
Assistant
Let me continue exploring with more targeted searches for CLI interaction patterns and plan persistence.
Assistant
Let me search for CLI input patterns with more specific approaches and examine override handlers.
Assistant
Let me continue exploring, focusing on epic_triage.py to understand the user input collection mechanism.
Assistant
Let me continue gathering information on the complete CLI structure and check for any git integration.
Assistant
Let me refocus and search for more specific patterns and files.
Assistant
Let me check the fix/apply_flow.py for git integration patterns.
Assistant
Let me check that subprocess.run call in apply_flow.py and continue with other important files.
Assistant
Excellent! I found git integration. Let me check for more user interaction patterns and gather the remaining information.
Assistant
Let me check the state module and plan persistence more thoroughly.
Assistant
Assistant
Assistant
User
Assistant
I'll start by thoroughly exploring the codebase to understand the existing patterns, data models, and flows before designing the implementation plan.
Assistant
Now let me explore the remaining key files to understand the full picture.
Assistant
No existing git usage in the codebase at all. Let me now look at the existing fix/apply flow that the requirements mentioned has git status --porcelain.
Assistant
Now let me look at the resolve command's argparse setup and the _add_resolve_parser function to understand CLI arg patterns.
Assistant
Now let me look at the plan done subcommand and the resolve parser in parser_groups_admin.py to understand how resolve is invoked.
Assistant
Now let me look at the plan done handler to understand the parallel resolution flow.
Assistant
Now let me look at the discovery_api for safe_write_text and the core module structure.
Assistant
I now have a thorough understanding of the codebase. Let me look at one more critical area -- how query.json is built and the status command, since those surfaces need to show commit info too.
Assistant
Now I have gathered comprehensive information. Let me create a thorough summary document:
Task Resolution Flow in Desloppify - Comprehensive Exploration Report
Based on my thorough exploration of the desloppify codebase, here's the complete task resolution flow:
wontfix - Finding is intentional debt (requires 50+ char note)
open - Reopening a previously resolved finding (no extra requirements)
Key Validation Checks (from selection.py):
Note Length (line 69-80): For fixed status, minimum 50 characters required - describes what was actually done
Attestation Keywords (line 14-47): For fixed status, must contain "i have actually" and "not gaming" to prove human verification
Wontfix Note Requirement (line 83-88): Wontfix requires a note to explain reasoning
Batch Wontfix Confirmation (line 136-164): Resolving >10 items as wontfix requires --confirm-batch-wontfix flag; estimates strict-score debt and warns user
Queue Order Guard (from queue_guard.py): If a living plan exists with queue_order, items being resolved as fixed must be at the front of the queue - prevents out-of-order resolution
2. What Happens After Resolution
State Layer Changes (from engine/_state/resolution.py)
When resolve_findings() is called:
Status Update (line 143-157): Sets finding status, clears suppression, records resolution timestamp and attestation
Wontfix Snapshot (line 116-125): For wontfix status, captures current scan count, tier, confidence, and detail as a snapshot
Reopening Logic (line 126-141): For reopening as open, increments reopen_count, clears wontfix metadata, records manual reopen attestation
Subjective Assessment Staling (line 40-80): When review findings are resolved, their related subjective dimensions are marked with needs_review_refresh=True and stale_since timestamp - signals to re-run review
Plan Integration (from resolve/cmd.py lines 84-102)
If a living plan exists:
purge_ids() (from engine/_plan/operations.py line 540): Removes resolved IDs from:
queue_order list
skipped dict
All cluster memberships
Clears stale cluster references in overrides (preserves notes/descriptions)
append_log_entry() (line 87-95): Records structured execution log entry with:
Finding IDs resolved
Status (fixed/wontfix/open)
Note and attestation text
Timestamp and actor ("user")
save_plan(): Persists plan changes
Scoring Recomputation (from resolution.py line 169)**
After resolution state updates, _recompute_stats() is called to update:
Total finding counts
Dimension scores
Overall/objective/strict scores
Query Output Update (from apply.py line 70-91)
A resolve query entry is written to .desloppify/query.json recording:
Patterns matched
Resolution status
Count of IDs resolved
Score deltas (before/after)
Narrative context
3. Post-Resolution User Feedback
Display Summary (from render.py)
Resolution Summary (line 16-22): Green banner showing "Resolved N finding(s) as {status}" with first 20 IDs listed
Wontfix Debt Warning (line 25-54): Yellow warning if batch wontfix, shows wontfix count and percentage of actionable findings
Score Movement Display (from queue_progress.py - called line 110): Shows:
Overall/objective/strict/verified scores with deltas
Strict target nudge if gap remains
Strict gap note: "wontfix items still count against strict score"
Subjective Reset Hint (line 103-149): If review findings resolved, suggests re-running review for updated dimension scores:
code
Subjective scores unchanged — re-run review for updated scores: <dims>
Milestone Banner (line 124-125): Green milestone message if narrative detects phase progression (computed by narrative_mod.compute_narrative())
Next Command Hint (line 152-171): Tells user what to do next:
This architecture creates a cohesive workflow where users are guided from scan → planning → task-by-task resolution, with the system preventing common mistakes (out-of-order resolution, undocumented decisions, gaming the score system) while maintaining an audit trail of all actions.
Perfect! Now I have a comprehensive understanding. Let me create a detailed summary document:
Summary
Based on my thorough exploration of the desloppify codebase, here is the comprehensive analysis of the plan/state data structures and persistence:
1. Plan Data Model (schema.py)
The plan data model is defined in /Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/schema.py as a PlanModel TypedDict with the following structure:
python
class PlanModel(TypedDict, total=False):
version: int # Current: PLAN_VERSION = 7
created: str # UTC timestamp when plan created
updated: str # UTC timestamp of last update
queue_order: list[str] # Primary queue of finding IDs in priority order
deferred: list[str] # Kept empty for migration compat
skipped: dict[str, SkipEntry] # Findings marked temporary/permanent/false_positive
active_cluster: str | None # Currently focused cluster name
overrides: dict[str, ItemOverride] # Custom descriptions, notes, cluster assignments
clusters: dict[str, Cluster] # Named groupings of findings
superseded: dict[str, SupersededEntry] # Findings that disappeared/were remapped
promoted_ids: list[str] # IDs user moved to top (for barrier logic)
plan_start_scores: dict # Frozen score snapshot from plan creation
execution_log: list[ExecutionLogEntry] # Audit trail of all operations
epic_triage_meta: dict # Triage engine metadata
Key Sub-Types:
SkipEntry (for skipped findings):
finding_id: Required[str]
kind: Required[str] — one of "temporary", "permanent", "false_positive", "triaged_out"
reason: Optional description
note: Required for permanent (wontfix note)
attestation: Required for permanent/false_positive
created_at: UTC timestamp
review_after: N scans before auto-resurface (temporary only)
skipped_at_scan: State.scan_count when skipped
ItemOverride (augmentations applied to findings):
finding_id: Required[str]
description: Custom description
note: Custom note
cluster: Cluster name the finding belongs to
created_at: UTC timestamp
updated_at: UTC timestamp
Cluster (grouped findings for bulk action):
name: Required[str]
description: Human-readable cluster purpose
finding_ids: list[str] — members of this cluster
created_at: UTC timestamp
updated_at: UTC timestamp
auto: bool — True for auto-generated clusters (auto/*)
cluster_key: Deterministic grouping key for regeneration (e.g., "typed::dict_keys::phantom_read")
action: Primary resolution command/guidance text
user_modified: True when user manually edits membership
optional: True for optional clusters (under-target review)
Singleton groups filtered out (min_cluster_size=2, except unscored=1)
Stale cluster deletion (unless user_modified)
Ghost ref repair (overrides pointing to non-existent clusters)
Version Control:
PLAN_VERSION = 7 with migrations for v1→v2 (deferred→skipped), v2→v3 (epics), v3→v4 (unified), v5→v6 (gates), v6→v7 (synthesis→triage naming)
ensure_plan_defaults() normalizes on load
validate_plan() checks invariants (no ID in both queue_order and skipped, skip kinds)
Atomic Writes:
safe_write_text() used for atomicity
.json.bak created before overwrite
Corruption handled gracefully (load from backup or empty plan)
This is a comprehensive, production-grade plan management system with full audit trails, deterministic clustering, finding lifecycle management, and atomic persistence—but zero git integration.
Perfect! I now have enough information to provide a comprehensive report. Let me compile my findings.
/Users/user_c042661f/Documents/desloppify/desloppify/cli.py — entry point
You are designing a new "commit integration" feature for the desloppify CLI tool. Based on the codebase exploration below, design a detailed implementation plan.
Current State
Python CLI tool using argparse (no click/typer)
No interactive prompts currently — all input via CLI args
Plan data model: PlanModel TypedDict in engine/_plan/schema.py with fields: version, queue_order, skipped, clusters, overrides, execution_log, etc.
Config: .desloppify/config.json managed by core/config.py with typed settings
Resolution flow: resolve command → state update → plan purge + execution_log entry → render score delta + "run next" hint
Atomic persistence (temp + os.replace + .bak) for all JSON files
Only existing git usage: git status --porcelain in fix/apply_flow.py for a warning
Clusters group findings; active_cluster focuses the queue
purge_ids() removes resolved findings from queue/clusters
Requirements
Post-resolution commit prompt: When user resolves task(s) via resolve, show commit guidance
Commit tracking: Record which findings were committed, to which git SHA, on which branch
Bundling logic: Show uncommitted previous resolved tasks and upcoming next tasks, help user decide commit grouping
Branch config: Store default branch name in config, allow overriding
Commit rationale: Encourage including resolution notes/attestation in commit messages
Goal: Keep users thinking about committing throughout the process
Design Constraints
The tool doesn't currently do interactive stdin prompts. Consider whether to add them or keep the CLI-arg pattern.
Must work when git is not available (graceful degradation)
Must not break existing workflows
Must store commit metadata durably in plan data (not just execution_log)
Should feel natural in the scan → plan → next → resolve → next loop
Things to Design
A. Data Model Changes
Where to store commit metadata? Options:
New top-level field on PlanModel (e.g., commit_log)
On execution_log entry detail dict
New field per-finding in state
Think about: what needs to be queryable? We need "which findings are uncommitted?" and "what commit did finding X go to?"
B. Config Changes
What settings to add to config.json? Think about:
Default branch name
Whether commit prompts are enabled/disabled
Commit message template
C. CLI Interface
How does the user interact? Think about:
Post-resolve output: what exactly is shown?
New commit subcommand? Or integrated into resolve?
How to bundle: resolve --commit flag? Or separate desloppify commit command?
How to specify "commit this with the next task too" (deferring commit)
D. Git Operations
What git operations does the tool perform?
Just suggestions? Or actual git add/commit?
Branch creation/switching?
How to handle uncommitted changes detection?
E. Render Changes
What changes to the resolve/next output to encourage committing?
F. The "bundle" concept
How do we handle:
"Commit just this task"
"Bundle with previously-resolved-but-uncommitted tasks"
"Wait and bundle with the next task"
The user needs to see what's uncommitted and what's coming up.
Please provide a concrete, detailed implementation plan with specific file paths, data structures, and function signatures. Consider trade-offs and recommend the best approach.
I have now thoroughly explored the codebase. Let me compile the full implementation plan.
Commit Integration Feature -- Implementation Plan
1. Design Philosophy and Key Decisions
After thorough exploration of the codebase, here are the recommended approaches for each design question:
A. Data Model: Hybrid approach -- new top-level commit_log on PlanModel + back-references on execution_log entries
The commit_log is the right primary home because:
It needs to be independently queryable ("which findings are uncommitted?")
Execution log entries are append-only and capped at 10,000; they are not designed for reverse lookups
Findings in state already have resolved_at and resolution_attestation -- adding git metadata there would couple state (per-language) to plan (cross-language), breaking the clean separation
The execution_log detail dict gets a commit_sha back-reference when a commit is recorded, linking the two systems.
B. CLI Interface: No new subcommand. Post-resolve output only, plus a plan commit-status query subcommand.
Rationale: The tool should NOT perform git add/commit operations. It is a health tracker, not a git workflow manager. Instead:
After resolve, print a commit guidance block showing uncommitted findings
Add desloppify plan commit-log to mark findings as committed (recording the SHA) or to view uncommitted findings
The information output keeps the tool non-interactive (matching the existing pattern of all input via CLI args)
C. Git Operations: Observation only, never mutation.
The tool should:
Detect the current git branch (for recording in commit_log)
Detect the current HEAD SHA (after user commits externally)
Check for uncommitted changes via git status --porcelain
NEVER run git add, git commit, git checkout, or any mutation
This is consistent with the tool's philosophy (advisor/tracker, not actor) and avoids the enormous complexity of managing git state.
D. The "bundle" concept: Implicit bundling via uncommitted-findings accumulation
Findings accumulate in an "uncommitted" state after resolve. The user sees them listed together in the post-resolve guidance. When they run desloppify plan commit-log record, all uncommitted findings (or a subset) get tagged with the current HEAD SHA. This naturally handles:
"Commit just this task" -- resolve one, then record
"Bundle with previous" -- resolve several, then record once
"Wait and bundle with next" -- just keep resolving; the uncommitted list grows
2. Detailed Data Model Changes
2a. New TypedDict: CommitRecord in /Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/schema.py
python
class CommitRecord(TypedDict, total=False):
sha: Required[str] # git commit SHA (short or full)
branch: str | None # branch name at commit time
finding_ids: list[str] # findings included in this commit
recorded_at: str # ISO timestamp when record was created
note: str | None # user-provided commit rationale
cluster_name: str | None # if these findings were from a focused cluster
2b. New field on PlanModel
python
class PlanModel(TypedDict, total=False):
# ... existing fields ...
commit_log: list[CommitRecord] # ordered list of commit records
uncommitted_findings: list[str] # finding IDs resolved but not yet committed
2c. empty_plan() update
Add defaults:
python
"commit_log": [],
"uncommitted_findings": [],
2d. ensure_container_types() in schema_migrations.py
Add:
python
if not isinstance(plan.get("commit_log"), list):
plan["commit_log"] = []
if not isinstance(plan.get("uncommitted_findings"), list):
plan["uncommitted_findings"] = []
2e. No PLAN_VERSION bump needed
These are additive fields with list defaults. ensure_plan_defaults already handles missing keys via setdefault. A version bump would only be needed if we changed the semantics of existing fields.
3. Config Changes
New keys in CONFIG_SCHEMA in /Users/user_c042661f/Documents/desloppify/desloppify/core/config.py:
python
"commit_tracking_enabled": ConfigKey(
bool, True, "Show commit guidance after resolve and track uncommitted findings"
),
"commit_default_branch": ConfigKey(
str, "", "Default branch name for commit context (empty = auto-detect from git)"
),
"commit_message_template": ConfigKey(
str,
"desloppify: {status} {count} finding(s) — {summary}",
"Template for suggested commit messages ({status}, {count}, {summary}, {ids} available)",
),
The commit_tracking_enabled key allows users to opt out entirely (e.g., in CI pipelines or when not using git). The commit_default_branch stores the target branch -- empty means auto-detect. The commit_message_template provides a customizable commit message suggestion.
4. New Module: Git Observation Layer
New file: /Users/user_c042661f/Documents/desloppify/desloppify/core/git_context.py
This module provides read-only git introspection with graceful degradation. It is the single place where subprocess is invoked for git operations.
python
"""Read-only git context detection with graceful degradation."""
from __future__ import annotations
import logging
import shutil
import subprocess
from dataclasses import dataclass
logger = logging.getLogger(__name__)
@dataclass(frozen=True)
class GitContext:
"""Snapshot of the current git state. All fields None when git is unavailable."""
available: bool
branch: str | None # current branch name
head_sha: str | None # current HEAD short SHA
has_uncommitted: bool | None # True if working tree has changes
root: str | None # git repo root path
def detect_git_context() -> GitContext:
"""Detect current git context. Returns a GitContext with available=False
when git is not installed or not in a repo."""
if not shutil.which("git"):
return GitContext(available=False, branch=None, head_sha=None,
has_uncommitted=None, root=None)
try:
root = _run_git("rev-parse", "--show-toplevel")
branch = _run_git("rev-parse", "--abbrev-ref", "HEAD")
head_sha = _run_git("rev-parse", "--short", "HEAD")
status_output = _run_git("status", "--porcelain")
has_uncommitted = bool(status_output.strip())
return GitContext(
available=True,
branch=branch.strip() if branch else None,
head_sha=head_sha.strip() if head_sha else None,
has_uncommitted=has_uncommitted,
root=root.strip() if root else None,
)
except (subprocess.SubprocessError, OSError, FileNotFoundError) as exc:
logger.debug("Git context detection failed: %s", exc)
return GitContext(available=False, branch=None, head_sha=None,
has_uncommitted=None, root=None)
def _run_git(*args: str) -> str:
"""Run a git command and return stdout. Raises on failure."""
result = subprocess.run(
["git", *args],
capture_output=True,
text=True,
timeout=5,
)
if result.returncode != 0:
raise subprocess.SubprocessError(
f"git {' '.join(args)} failed: {result.stderr.strip()}"
)
return result.stdout
5. New Module: Commit Tracking Operations
New file: /Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/commit_tracking.py
python
"""Commit tracking operations on the plan model."""
from __future__ import annotations
from desloppify.engine._plan.schema import (
CommitRecord,
PlanModel,
ensure_plan_defaults,
)
from desloppify.engine._state.schema import utc_now
def add_uncommitted_findings(plan: PlanModel, finding_ids: list[str]) -> int:
"""Mark finding IDs as resolved-but-uncommitted. Returns count added."""
ensure_plan_defaults(plan)
uncommitted: list[str] = plan.get("uncommitted_findings", [])
existing = set(uncommitted)
added = 0
for fid in finding_ids:
if fid not in existing:
uncommitted.append(fid)
existing.add(fid)
added += 1
plan["uncommitted_findings"] = uncommitted
return added
def record_commit(
plan: PlanModel,
*,
sha: str,
branch: str | None = None,
finding_ids: list[str] | None = None,
note: str | None = None,
cluster_name: str | None = None,
) -> CommitRecord:
"""Record a commit against uncommitted findings.
If *finding_ids* is None, records all uncommitted findings.
Removes recorded IDs from uncommitted_findings.
"""
ensure_plan_defaults(plan)
uncommitted: list[str] = plan.get("uncommitted_findings", [])
if finding_ids is None:
# Record all uncommitted
ids_to_record = list(uncommitted)
else:
ids_to_record = [fid for fid in finding_ids if fid in set(uncommitted)]
record: CommitRecord = {
"sha": sha,
"branch": branch,
"finding_ids": ids_to_record,
"recorded_at": utc_now(),
"note": note,
"cluster_name": cluster_name,
}
plan.setdefault("commit_log", []).append(record)
# Remove from uncommitted
recorded_set = set(ids_to_record)
plan["uncommitted_findings"] = [
fid for fid in uncommitted if fid not in recorded_set
]
return record
def get_uncommitted_findings(plan: PlanModel) -> list[str]:
"""Return list of resolved-but-uncommitted finding IDs."""
ensure_plan_defaults(plan)
return list(plan.get("uncommitted_findings", []))
def find_commit_for_finding(plan: PlanModel, finding_id: str) -> CommitRecord | None:
"""Find the commit record that includes a given finding ID."""
for record in plan.get("commit_log", []):
if finding_id in record.get("finding_ids", []):
return record
return None
def purge_uncommitted_ids(plan: PlanModel, finding_ids: list[str]) -> int:
"""Remove finding IDs from uncommitted list (e.g., when reopened). Returns count removed."""
ensure_plan_defaults(plan)
uncommitted: list[str] = plan.get("uncommitted_findings", [])
purge_set = set(finding_ids)
before = len(uncommitted)
plan["uncommitted_findings"] = [fid for fid in uncommitted if fid not in purge_set]
return before - len(plan["uncommitted_findings"])
6. Integration Points
6a. Hook into cmd_resolve in /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/resolve/cmd.py
After the existing plan update block (lines 84-102), add commit tracking:
python
# After purge_ids and append_log_entry, within the same try block:
if args.status == "fixed":
from desloppify.engine._plan.commit_tracking import add_uncommitted_findings
add_uncommitted_findings(plan, all_resolved)
# save_plan already happens below
After show_score_with_plan_context (line 110), add the commit guidance render:
The new _print_commit_guidance function goes in /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/resolve/render.py:
python
def _print_commit_guidance(
state: dict,
just_resolved: list[str],
status: str,
) -> None:
"""Show post-resolve commit guidance block."""
if status != "fixed":
return # Only prompt for fixed status, not wontfix/reopen
from desloppify.core.config import load_config
config = load_config()
if not config.get("commit_tracking_enabled", True):
return
from desloppify.core.git_context import detect_git_context
git = detect_git_context()
if not git.available:
return # Graceful degradation: no git, no guidance
from desloppify.engine.plan import load_plan
from desloppify.engine._plan.commit_tracking import get_uncommitted_findings
try:
plan = load_plan()
uncommitted = get_uncommitted_findings(plan)
except (OSError, ValueError, KeyError, TypeError):
return
if not uncommitted:
return
# Render the commit guidance block
print(colorize("\n Commit Guidance", "bold"))
print(colorize(" " + "-" * 40, "dim"))
if git.has_uncommitted:
print(colorize(" Working tree has uncommitted changes.", "yellow"))
if git.branch:
print(colorize(f" Branch: {git.branch}", "dim"))
just_set = set(just_resolved)
previous = [fid for fid in uncommitted if fid not in just_set]
if previous:
print(colorize(f" {len(previous)} previously resolved finding(s) also uncommitted:", "yellow"))
for fid in previous[:5]:
summary = _finding_summary(state, fid)
print(f" {fid} {summary}")
if len(previous) > 5:
print(colorize(f" ... and {len(previous) - 5} more", "dim"))
total = len(uncommitted)
print(colorize(f"\n Total uncommitted: {total} finding(s)", "cyan"))
# Suggest commit message
template = config.get("commit_message_template", "desloppify: fixed {count} finding(s)")
suggested = template.format(
status="fixed",
count=total,
summary=_brief_summary(state, uncommitted[:3]),
ids=", ".join(uncommitted[:5]),
)
print(colorize(f" Suggested commit message:", "dim"))
print(colorize(f' "{suggested}"', "dim"))
print(colorize(
f"\n After committing, record it: "
f"`desloppify plan commit-log record`",
"dim",
))
def _finding_summary(state: dict, finding_id: str) -> str:
"""Get a short summary for a finding ID."""
finding = state.get("findings", {}).get(finding_id, {})
return finding.get("summary", "(resolved)")[:60]
def _brief_summary(state: dict, finding_ids: list[str]) -> str:
"""Build a brief summary string from a list of finding IDs."""
findings = state.get("findings", {})
detectors = set()
for fid in finding_ids:
f = findings.get(fid, {})
d = f.get("detector", "")
if d:
detectors.add(d)
if detectors:
return ", ".join(sorted(detectors)[:3])
return "resolved findings"
6b. Hook into cmd_plan_done in /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/override_handlers.py
cmd_plan_done delegates to cmd_resolve, so the commit tracking in resolve will fire automatically. No separate change needed here for the normal flow.
For synthetic IDs (triage::, workflow::), these are not code changes, so they should NOT be added to uncommitted_findings. The existing code handles synthetic IDs before delegating to resolve, so no change needed.
6c. New CLI subcommand: plan commit-log
Add to the plan subparser in /Users/user_c042661f/Documents/desloppify/desloppify/app/cli_support/parser_groups_admin.py:
python
# plan commit-log
p_commit_log = plan_sub.add_parser(
"commit-log",
help="View and manage commit tracking for resolved findings",
epilog="""\
examples:
desloppify plan commit-log # show uncommitted findings
desloppify plan commit-log record # record current HEAD for all uncommitted
desloppify plan commit-log record --sha abc123 # record specific SHA
desloppify plan commit-log record --note "..." # add rationale
desloppify plan commit-log history # show commit history""",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
commit_log_sub = p_commit_log.add_subparsers(dest="commit_log_action")
# plan commit-log record
p_cl_record = commit_log_sub.add_parser(
"record", help="Record that uncommitted findings have been committed"
)
p_cl_record.add_argument(
"--sha", type=str, default=None,
help="Git commit SHA (default: current HEAD)",
)
p_cl_record.add_argument(
"--branch", type=str, default=None,
help="Branch name (default: auto-detect)",
)
p_cl_record.add_argument(
"--note", type=str, default=None,
help="Commit rationale or description",
)
p_cl_record.add_argument(
"--only", nargs="+", default=None, metavar="PATTERN",
help="Record only specific finding IDs (default: all uncommitted)",
)
# plan commit-log history
p_cl_history = commit_log_sub.add_parser(
"history", help="Show commit history for resolved findings"
)
p_cl_history.add_argument(
"--top", type=int, default=10,
help="Number of recent commits to show (default: 10)",
)
6d. New handler: /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/commit_log_handlers.py
python
6e. Wire into plan dispatcher in /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/cmd.py
Add import and dispatch case:
python
from desloppify.app.commands.plan.commit_log_handlers import cmd_commit_log_dispatch
# In the dispatch logic:
if plan_action == "commit-log":
cmd_commit_log_dispatch(args)
return
7. Render Changes for Next Command
In /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/next_parts/render.py, add a small uncommitted-findings reminder in render_followup_nudges:
python
# At the end of render_followup_nudges, add:
def _render_uncommitted_reminder(plan: dict | None) -> None:
"""Show a subtle reminder if there are uncommitted findings."""
if not plan:
return
uncommitted = plan.get("uncommitted_findings", [])
if not uncommitted:
return
count = len(uncommitted)
print(colorize(
f" {count} resolved finding(s) uncommitted — "
f"run `desloppify plan commit-log` to review",
"dim",
))
8. Integration with purge_ids for Cleanup
When findings are reopened (status changed back to "open"), they should be removed from uncommitted_findings. Modify the existing purge_ids in /Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/operations.py is NOT the right place since purge_ids removes resolved findings. Instead, hook into the reopen flow:
In cmd_plan_reopen (override_handlers.py), after reopening findings, call:
python
from desloppify.engine._plan.commit_tracking import purge_uncommitted_ids
purge_uncommitted_ids(plan, reopened)
Similarly in cmd_resolve when status == "open" (reopening), clean up uncommitted:
python
if args.status == "open":
from desloppify.engine._plan.commit_tracking import purge_uncommitted_ids
purge_uncommitted_ids(plan, all_resolved)
9. Status Command Integration
In /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/status_parts/render.py, add a one-line uncommitted count to the existing status output:
python
def show_uncommitted_summary(plan: dict | None) -> None:
"""Show uncommitted findings count in status dashboard."""
if not plan:
return
uncommitted = plan.get("uncommitted_findings", [])
if not uncommitted:
return
print(colorize(
f" Uncommitted: {len(uncommitted)} resolved finding(s) pending commit",
"yellow",
))
10. Query.json Integration
The resolve query payload (in _write_resolve_query_entry in apply.py) should include uncommitted count so agents can see it:
python
# Add to the payload dict:
"uncommitted_count": len(plan.get("uncommitted_findings", [])) if plan else 0,
Add CommitRecord TypedDict and new fields to PlanModel in schema.py
Update empty_plan() and ensure_container_types() with defaults
Create engine/_plan/commit_tracking.py -- pure operations
Phase 2: Core integration
5. Hook add_uncommitted_findings into cmd_resolve (resolve/cmd.py)
6. Hook purge_uncommitted_ids into reopen flows (resolve/cmd.py, override_handlers.py)
7. Add _print_commit_guidance to resolve/render.py
Phase 3: CLI subcommand
8. Add plan commit-log parser group in parser_groups_admin.py
9. Create plan/commit_log_handlers.py with show/record/history handlers
10. Wire into plan dispatcher in plan/cmd.py
11. Add "commit-log" to plan's __all__ and the command registry
Phase 4: Polish
12. Add config keys to CONFIG_SCHEMA
13. Add uncommitted reminder to next render output
14. Add uncommitted line to status dashboard
15. Include uncommitted_count in query.json resolve payload
16. Update SKILL.md to document the new workflow
Phase 5: Tests
17. Unit tests for git_context.py (mock subprocess)
18. Unit tests for commit_tracking.py operations
19. Integration tests for resolve + commit guidance flow
20. CLI parser tests for new subcommands
12. Trade-offs Considered
Why not a top-level desloppify commit command?
A separate top-level command would suggest the tool manages git, which it does not. Nesting under plan commit-log keeps it clearly associated with the plan lifecycle and avoids confusion. The post-resolve guidance block provides the primary user-facing nudge.
Why not store commit data per-finding in state?
State is per-language and the tool carefully separates state (findings, scores) from plan (prioritization, workflow). Commit metadata is workflow data, not detection data. Putting it in plan keeps the clean separation.
Why not use interactive prompts?
The tool currently uses zero interactive prompts (all via CLI args). Adding input() calls would break agent workflows, piped commands, and CI usage. The information-push model (show guidance, let user act externally) is more composable.
Why observation-only for git?
Running git add/commit introduces enormous complexity: handling merge conflicts, staged vs unstaged, .gitignore, submodules, worktrees, and all the edge cases. The tool is a health tracker, not a VCS manager. Observation-only means it can never corrupt a user's repo.
Critical Files for Implementation
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/schema.py - Add CommitRecord TypedDict and new PlanModel fields (commit_log, uncommitted_findings)
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/resolve/cmd.py - Primary integration point: hook commit tracking into the resolve flow
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/resolve/render.py - Add _print_commit_guidance for post-resolve output
/Users/user_c042661f/Documents/desloppify/desloppify/app/cli_support/parser_groups_admin.py - Add plan commit-log subparser group
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/cmd.py - Wire commit-log dispatch into plan command router
"""Plan commit-log subcommand handlers."""
from __future__ import annotations
import argparse
from desloppify.app.commands.helpers.runtime import command_runtime
from desloppify.core.git_context import detect_git_context
from desloppify.core.output_api import colorize
from desloppify.engine._plan.commit_tracking import (
get_uncommitted_findings,
record_commit,
)
from desloppify.engine.plan import append_log_entry, load_plan, save_plan
def cmd_commit_log_dispatch(args: argparse.Namespace) -> None:
"""Dispatch plan commit-log subcommands."""
action = getattr(args, "commit_log_action", None)
if action == "record":
_cmd_commit_log_record(args)
elif action == "history":
_cmd_commit_log_history(args)
else:
_cmd_commit_log_show(args)
def _cmd_commit_log_show(args: argparse.Namespace) -> None:
"""Show uncommitted findings (default action)."""
runtime = command_runtime(args)
state = runtime.state
plan = load_plan()
uncommitted = get_uncommitted_findings(plan)
if not uncommitted:
print(colorize(" All resolved findings have been committed.", "green"))
return
print(colorize(f" {len(uncommitted)} uncommitted finding(s):", "bold"))
findings = state.get("findings", {})
for fid in uncommitted:
f = findings.get(fid, {})
summary = f.get("summary", "(resolved)")[:70]
detector = f.get("detector", "?")
print(f" {fid} [{detector}] {summary}")
git = detect_git_context()
if git.available and git.branch:
print(colorize(f"\n Branch: {git.branch}", "dim"))
if git.available and git.has_uncommitted:
print(colorize(" Working tree has uncommitted changes.", "yellow"))
print(colorize(
"\n Record after committing: `desloppify plan commit-log record`",
"dim",
))
def _cmd_commit_log_record(args: argparse.Namespace) -> None:
"""Record that uncommitted findings have been committed."""
plan = load_plan()
uncommitted = get_uncommitted_findings(plan)
if not uncommitted:
print(colorize(" Nothing to record — all findings are committed.", "green"))
return
sha = getattr(args, "sha", None)
branch = getattr(args, "branch", None)
note = getattr(args, "note", None)
only_patterns = getattr(args, "only", None)
# Auto-detect from git if not provided
if sha is None or branch is None:
git = detect_git_context()
if git.available:
if sha is None:
sha = git.head_sha
if branch is None:
branch = git.branch
elif sha is None:
print(colorize(
" Git not available. Provide --sha manually.",
"red",
))
return
finding_ids = None
if only_patterns:
finding_ids = [fid for fid in uncommitted if fid in set(only_patterns)]
if not finding_ids:
print(colorize(" No uncommitted findings match the provided IDs.", "yellow"))
return
record = record_commit(
plan,
sha=sha,
branch=branch,
finding_ids=finding_ids,
note=note,
)
append_log_entry(
plan,
"commit_record",
finding_ids=record["finding_ids"],
actor="user",
note=note,
detail={"sha": sha, "branch": branch},
)
save_plan(plan)
count = len(record["finding_ids"])
print(colorize(f" Recorded {count} finding(s) to commit {sha}.", "green"))
if branch:
print(colorize(f" Branch: {branch}", "dim"))
remaining = get_uncommitted_findings(plan)
if remaining:
print(colorize(f" {len(remaining)} finding(s) still uncommitted.", "yellow"))
def _cmd_commit_log_history(args: argparse.Namespace) -> None:
"""Show commit history."""
plan = load_plan()
commit_log = plan.get("commit_log", [])
top = getattr(args, "top", 10)
if not commit_log:
print(colorize(" No commit records yet.", "dim"))
return
recent = commit_log[-top:] if top else commit_log
recent.reverse() # Most recent first
print(colorize(f" Commit History ({len(recent)}/{len(commit_log)})", "bold"))
print(colorize(" " + "-" * 50, "dim"))
for record in recent:
sha = record.get("sha", "?")[:8]
branch = record.get("branch", "")
count = len(record.get("finding_ids", []))
timestamp = record.get("recorded_at", "?")[:10]
note_str = f" — {record['note'][:40]}" if record.get("note") else ""
branch_str = f" ({branch})" if branch else ""
print(f" {sha}{branch_str} {count} finding(s) {timestamp}{note_str}")