diff --git a/apps/marketing/src/content/blog/continuously-improve-claude-code-plans.md b/apps/marketing/src/content/blog/continuously-improve-claude-code-plans.md new file mode 100644 index 0000000..ab8ed0a --- /dev/null +++ b/apps/marketing/src/content/blog/continuously-improve-claude-code-plans.md @@ -0,0 +1,55 @@ +--- +title: "Continuously Improve Claude Code Plans" +description: "Use your denial history to find feedback patterns, generate a personalized report, and automatically improve every future plan." +date: 2026-04-01 +author: "backnotprop" +tags: ["compound-planning", "plan-mode", "claude-code"] +--- + +**Compound Planning.** If you've been actively using plan mode in Claude Code, there's an opportunity to improve how your agents plan for you. Here is a skill that analyzes your plan denial history, surfaces your own feedback patterns, and creates an automated loop that refines planning over time (at your request). The point is to consistently optimize what works best for you. + + + +If you use plan mode and deny plans, you already have the data. The skill reads it and puts it to work. It works day one for any Claude Code user who has been actively using plan mode. [Plannotator](https://github.com/backnotprop/plannotator) users get an even richer analysis since Plannotator captures full plan text and inline annotations with every denial. Plannotator is [open source](https://github.com/backnotprop/plannotator) and free. + +[Install Plannotator](https://github.com/backnotprop/plannotator?tab=readme-ov-file#install-for-claude-code), then run: + +``` +/plannotator-compound +``` + +## How it works + +When you deny a plan in Claude Code, that interaction gets logged. If you're a Plannotator user, it's even better. The more you use it, the richer your archive gets. Full plan text, inline annotations, structural feedback, all saved as markdown files that build up over time. + +Compound Planning reads that archive in three steps: + +1. **Analyze** all your plan denials and approvals, surfacing insight patterns +2. **Report** generates a personalized report so you can view your own findings and insights +3. **Hook** creates an improvement hook that gets injected on plan enter mode, carrying forward the insights from the last time you ran the skill + +The report is personalized. Every quote is pulled from your actual feedback. Every percentage is calculated from your real data. The corrective instructions at the end trace directly back to your most frequent denial reasons. + + + +## Works for all Claude Code users + +Plannotator users get the richest analysis since the archive contains full plan text and inline annotations. But you don't need Plannotator. + +If you use Claude Code with plan mode, your denial reasons live in `~/.claude/projects/`. The skill includes a Python parser that extracts your `ExitPlanMode` outcomes, filters out boilerplate, and produces clean records of your human-authored feedback. The same analysis pipeline runs on this data and produces the same report. + +## The feedback loop + +The real value is the improvement hook. The corrective instructions from your report can be saved to a file that gets injected into every future planning session automatically. Claude sees your feedback patterns before writing any plan. + +Your denied plans aren't wasted work. They're the specification for better plans going forward. + +## Try it + +If you have [Plannotator](https://github.com/backnotprop/plannotator) installed, it works out of the box. If you're using Claude Code without Plannotator, the skill works with your existing session logs, no additional setup. + +The more denial history you have, the richer the analysis. Start with the [installation guide](/docs/getting-started/installation/) or check out the [repo](https://github.com/backnotprop/plannotator). diff --git a/apps/marketing/src/styles/global.css b/apps/marketing/src/styles/global.css index 29b2f02..15aef53 100644 --- a/apps/marketing/src/styles/global.css +++ b/apps/marketing/src/styles/global.css @@ -37,6 +37,13 @@ color: var(--foreground); } +@media (min-width: 768px) { + .prose { + font-size: 0.95rem; + line-height: 1.6; + } +} + .prose h1 { font-size: 1.5rem; font-weight: 700; diff --git a/apps/skills/plannotator-compound/SKILL.md b/apps/skills/plannotator-compound/SKILL.md index fa9cc2b..5ac8421 100644 --- a/apps/skills/plannotator-compound/SKILL.md +++ b/apps/skills/plannotator-compound/SKILL.md @@ -4,7 +4,8 @@ disable-model-invocation: true description: > Analyze a user's Plannotator plan archive to extract denial patterns, feedback taxonomy, evolution over time, and actionable prompt improvements — then produce - a polished HTML dashboard report. + a polished HTML dashboard report. Falls back to Claude Code ExitPlanMode denial + reasons when Plannotator data is unavailable. --- # Compound Planning Analysis @@ -16,15 +17,37 @@ them into actionable insights, and produce an elegant HTML dashboard report. This is a multi-phase process. Each phase must complete fully before the next begins. Research integrity is paramount — every file must be read, no skipping. +## Source Selection + +Before starting the analysis, determine which data source is available. + +1. **Plannotator mode (first-class)** — Check `~/.plannotator/plans/`. If it + exists and contains `*-denied.md` files, use this mode. The entire workflow + below is written for Plannotator data. + +2. **Claude Code fallback mode** — If the Plannotator archive is absent or + contains no denied plans, check `~/.claude/projects/`. If present, read + [references/claude-code-fallback.md](references/claude-code-fallback.md) + before continuing. That reference explains how to use the bundled parser at + [scripts/extract_exit_plan_mode_outcomes.py](scripts/extract_exit_plan_mode_outcomes.py) + to extract denial reasons from Claude Code JSONL transcripts. Every phase + below has a short note explaining what changes in fallback mode — the + reference file has the details. + +3. **Neither available** — Ask the user for their Plannotator plans directory or + Claude Code projects directory. Do not guess. + ## Phase 0: Locate Plans & Check for Previous Reports -Check for `~/.plannotator/plans/`. If it exists and contains `.md` files, proceed. +Use the mode chosen in Source Selection above. -If not found, ask the user: -> "I couldn't find plans at ~/.plannotator/plans/. Where is your plans directory?" +**Plannotator mode:** Verify the plans directory contains `*-denied.md` files. If +none exist, fall back to Claude Code mode before stopping. -Once you have the path, verify it contains files matching `*-denied.md`. If none -exist, inform the user there's no denial data to analyze and stop. +**Claude Code fallback mode:** Run the bundled parser per the fallback reference to +build the denial-reason dataset. Create `/tmp/compound-planning/` if needed. + +In either mode, proceed to Previous Report Detection below. ### Previous Report Detection @@ -112,6 +135,11 @@ Extract dates from all filenames. Tell the user what you found and that you're beginning the extraction. +**Claude Code fallback mode:** The Plannotator inventory fields above do not apply. +Follow the inventory instructions in +[references/claude-code-fallback.md](references/claude-code-fallback.md) instead — +report the denial-reason dataset assembled by the parser. + ## Phase 2: Map — Parallel Extraction This is the most time-intensive phase. You must read EVERY `*-denied.md` file @@ -121,6 +149,11 @@ This is the most time-intensive phase. You must read EVERY `*-denied.md` file files dated after the cutoff date if running incrementally. In incremental mode, only process files whose embedded YYYY-MM-DD date is strictly after the cutoff. +**Claude Code fallback mode:** The parser output is the clean source dataset. Read +the fallback reference for the extraction prompt and batching strategy specific to +JSON part files. Do not go back to raw `.jsonl` logs unless the parser fails or the +user asks for audit-level verification. + **Important:** Only read `*-denied.md` files. Do NOT read approved plans, annotation files, or diff files. Each denied file contains the full plan text followed by a `---` separator and the reviewer's feedback — everything needed @@ -248,6 +281,10 @@ extraction files and produce the full analysis. This covers most datasets. merges taxonomies, combines counts, deduplicates patterns, and reconciles any conflicting categorizations across partials. +**Claude Code fallback mode:** The reduction phase is the same. The only upstream +difference is that extraction files were derived from normalized denial-reason JSON +instead of Plannotator markdown files. + ### Reduction Prompt Give each reduction agent this prompt (adapt file paths for single vs multi-stage): @@ -427,6 +464,10 @@ one — the flow moves from "what happened" through "why" to "what to do about i - If the user has < 3 months of data, reduce the evolution section to fewer cards - If most denied files lack feedback below the `---` (bare denials with no annotations), note this in the narrative — the analysis will be thinner +- **Claude Code fallback mode:** Explicitly label the report source as Claude Code + `ExitPlanMode` denial reasons. Do not fabricate Plannotator-only fields such as + annotation counts or approved-plan line counts. See the fallback reference for + KPI substitutes and footer/provenance guidance. - If fewer than 5 denial categories emerge, combine the taxonomy and patterns sections into one - If the dataset is very small (< 20 files), the narrative should acknowledge the @@ -457,6 +498,10 @@ Tell the user: - Where the report was saved (including version number) - If incremental: remind the user that earlier findings are in the previous report +**Claude Code fallback mode:** Adapt the summary per the fallback reference — +report human denial reasons analyzed and total `ExitPlanMode` attempts scanned +instead of Plannotator file counts. + ## Phase 6: Improvement Hook After presenting the summary, ask the user if they want to enable an **improvement @@ -510,6 +555,8 @@ Read the existing file and present the user with a choice: ## Important Notes +- **Data source priority:** Plannotator is the first-class path. Claude Code log + analysis is the secondary path for users without Plannotator archives. - **Research integrity:** Every file must be read. The value of this analysis comes from completeness. Sampling or skipping undermines the findings. - **Real data only:** Never fabricate quotes, percentages, or patterns. If the data diff --git a/apps/skills/plannotator-compound/references/claude-code-fallback.md b/apps/skills/plannotator-compound/references/claude-code-fallback.md new file mode 100644 index 0000000..7551456 --- /dev/null +++ b/apps/skills/plannotator-compound/references/claude-code-fallback.md @@ -0,0 +1,282 @@ +# Claude Code Fallback + +Read this file only when the user does **not** have a usable Plannotator archive. + +This is the secondary path for ordinary Claude Code users whose denial history +exists in `~/.claude/projects/` rather than `~/.plannotator/plans/`. + +The goal is the same as the main skill: + +- extract the user's real denial reasons +- reduce them into a taxonomy and prompt corrections +- produce the same HTML report design and section flow + +## Source of Truth + +Use the bundled parser at: + +- [scripts/extract_exit_plan_mode_outcomes.py](../scripts/extract_exit_plan_mode_outcomes.py) + +Resolve that script path relative to this skill directory before running it. + +This script normalizes `ExitPlanMode` outcomes from Claude Code JSONL transcripts +and emits clean JSON parts containing only human-authored denial reasons by default. + +Do **not** read raw `~/.claude/projects/**/*.jsonl` directly unless: + +- the parser fails +- the user asks for audit-level verification +- you need to inspect one or two suspicious records by hand + +The parser exists specifically to strip transcript noise such as generic native +reject strings and wrapper boilerplate. + +## Run the Parser + +Create the working directory first: + +```bash +mkdir -p /tmp/compound-planning +``` + +Then run the bundled parser. Prefer `python3`; if unavailable, use `python`. + +Use a resolved absolute script path, not a repo-local copy. + +```bash +python3 [RESOLVED SKILL PATH]/scripts/extract_exit_plan_mode_outcomes.py \ + --projects-dir ~/.claude/projects \ + --json-out /tmp/compound-planning/claude-code-human-reasons.json \ + --show-samples 0 +``` + +Expected output: + +- manifest: + `/tmp/compound-planning/claude-code-human-reasons/claude-code-human-reasons.manifest.json` +- part files: + `/tmp/compound-planning/claude-code-human-reasons/claude-code-human-reasons.part-XXXX-of-XXXX.json` + +The script prints how many records were detected and how many JSON part files were emitted. + +## What To Read First + +Read the manifest before reading any part file. + +The manifest gives you: + +- total filtered record count +- total `ExitPlanMode` attempts +- native approval / denial counts +- non-native denial counts +- part file list + +Use the part files only after you understand the overall dataset shape. + +## Inventory In Fallback Mode + +In Claude Code fallback mode, report this dataset instead of the Plannotator file counts: + +- human denial reasons found +- total `ExitPlanMode` attempts scanned +- native approvals +- native denials with extractable inline reason +- native denials without recoverable reason +- non-native denials with recoverable payload +- number of emitted JSON parts +- date range from the records +- total days spanned +- distinct sessions +- distinct project roots / `cwd` values + +Also calculate: + +- average `plan_length_chars` where present +- percentage of all denials that contain a recoverable human reason + +Do **not** fabricate Plannotator-only inventory fields in fallback mode: + +- no `*-approved.md` counts +- no `*.annotations.md` counts +- no `*.diff.md` counts +- no approved-plan line-count analysis + +If the user asks for those specifically, state that Claude Code log fallback mode +does not contain those artifacts. + +### Previous Report Detection In Fallback Mode + +Previous report detection still applies. Check the user's home directory or +`~/.plannotator/plans/` for existing `compound-planning-report*.html` files. If +found, offer the same incremental vs full choice as Plannotator mode. In +incremental mode, filter the parser output by timestamp rather than by filename +date — use the `timestamp` field in each JSON record. + +If no previous report exists, use the first-report naming convention +(`compound-planning-report.html`). Otherwise use the next version number. + +## Extraction In Fallback Mode + +Treat the emitted JSON part files as the clean source dataset. + +### Batching + +- **Small datasets (< 200 records):** read the part files directly without extra agents +- **Medium datasets (200-800 records):** split by part file or time range into 2-4 agents +- **Large datasets (800+ records):** split by part file groups or balanced time ranges + +All extraction agents should use `model: "haiku"` — they're doing straightforward +file reading and structured extraction, not reasoning. + +Each extraction agent should read every record in its assigned part files and write +clean markdown output to: + +```text +/tmp/compound-planning/extraction-{batch-name}.md +``` + +### Extraction Prompt For Claude Code Denial Records + +Use this prompt for each fallback extraction batch (adapt the part files and output path): + +```text +You are extracting structured data from Claude Code ExitPlanMode denial records. + +Files to read: [JSON PART FILES] +Output: Write your complete results to [OUTPUT FILE PATH] + +Read EVERY record in the assigned files. Each record already contains a cleaned +human_reason field. Use that as the primary source text. + +For EACH record, extract: +- Date +- Session ID +- Project / cwd +- Topic (only if inferable from the reason or plan path; otherwise say "Unknown from logs") +- Human denial reason +- What was specifically asked to change +- Feedback type (let the content determine the category) +- Notable phrases +- Reason source (`native_inline_reason`, `non_native_freeform_payload`, or `structured_quote_extraction`) +- Plan path if present +- Plan length in chars if present + +Do NOT skip any records. One entry per record. + +Format each entry as: +**[session_id :: tool_use_id]** +- Date: ... +- Project: ... +- Topic: ... +- Human denial reason: ... +- Feedback type: ... +- Specific asks: ... +- Notable phrases: ... +- Reason source: ... +- Plan path: ... +- Plan length chars: ... +--- + +After processing all records, write the complete results to [OUTPUT FILE PATH]. +State the total record count at the end of the file. +``` + +## Reduction In Fallback Mode + +The reduction step stays conceptually the same: + +- taxonomy +- top patterns +- recurring phrases +- reviewer values +- recurring agent mistakes +- structural requests +- evolution over time +- corrective prompt instructions + +Use `model: "sonnet"` for reduction agents, same as Plannotator mode. The +two-stage reduce (partial reduces for 21+ extraction files) also applies when +there are many part files. + +But interpret the dataset correctly: + +- this is denial-reason evidence from Claude Code logs +- not every denial has a recoverable human reason +- annotations may be absent entirely +- success traits are often inferred from the inverse of repeated denial feedback + +If the evidence for "what works" is weaker than the evidence for "what fails", +say that explicitly. + +## HTML Report Adaptation + +Use the same template and the same section order as the main skill. + +In fallback mode: + +- explicitly state in the header/meta that the source is Claude Code `ExitPlanMode` + denial reasons +- keep the same narrative-first editorial style +- keep the same 7 major sections +- use real denial-reason counts, dates, phrases, and percentages only + +### KPI Sidebar Substitutes + +The Plannotator version uses a revision-rate KPI that may not exist here. + +In fallback mode, prefer this KPI trio: + +1. top denial category percentage +2. total human denial reasons recovered +3. number of distinct denial categories + +If a better third metric emerges from the data, use it, but do not invent one. + +### Footer / Provenance + +The footer tagline should mention that the report was derived from Claude Code +denial reasons rather than Plannotator markdown archives. + +### Important Limitation To State + +If `human_reasons_total < total denials`, mention in the narrative or footer note +that some denials in the transcript did not contain recoverable human-authored +feedback and therefore could not contribute to the pattern analysis. + +### Versioned Report Naming + +Versioned naming (`v2`, `v3`, etc.) applies to fallback mode too. Save reports +to `~/.plannotator/plans/` (create the directory if it doesn't exist) so that +all compound planning reports live in the same location regardless of data source. + +## Summary In Fallback Mode + +At the end, tell the user: + +- how many human denial reasons were analyzed +- how many total `ExitPlanMode` attempts were scanned +- the top 3 denial patterns found +- the estimated percentage of denial reasons the corrective instructions address +- the single most impactful prompt improvement +- where the report was saved (including version number) +- if incremental: note that earlier findings are in the previous report + +## Improvement Hook In Fallback Mode + +The Phase 6 improvement hook applies to fallback mode too. The corrective prompt +instructions derived from Claude Code denial reasons are just as useful for +injection into future planning sessions. Follow the same flow as the main skill. + +## Audit Mode + +Only if the user asks for raw denial records or transcript noise: + +```bash +python3 [RESOLVED SKILL PATH]/scripts/extract_exit_plan_mode_outcomes.py \ + --projects-dir ~/.claude/projects \ + --records-filter denials \ + --json-out /tmp/compound-planning/claude-code-all-denials.json \ + --show-samples 0 +``` + +Do not use this audit-mode output for the normal report unless the user asks for it. diff --git a/apps/skills/plannotator-compound/scripts/extract_exit_plan_mode_outcomes.py b/apps/skills/plannotator-compound/scripts/extract_exit_plan_mode_outcomes.py new file mode 100644 index 0000000..68df55c --- /dev/null +++ b/apps/skills/plannotator-compound/scripts/extract_exit_plan_mode_outcomes.py @@ -0,0 +1,820 @@ +#!/usr/bin/env python3 +"""Extract ExitPlanMode outcomes from Claude Code JSONL session logs. + +This parser keeps three views of the same data: + +1. Strict native Claude Code classification + - native approval: + "User has approved your plan." + - native denial: + "The user doesn't want to proceed with this tool use. The tool use was rejected" + +2. General denial capture + - any matching ExitPlanMode tool_result with is_error=true and non-empty text + is captured as a denial/error payload, even when it is custom hook output + or some other non-native integration. + +3. Human-reason extraction + - native inline reasons are preserved as-is + - freeform non-native error payloads are treated as human reasons + - structured non-native payloads are reduced to quoted feedback where possible + +This means the script does not depend on hook-specific strings to capture custom +denials, but it also does not dump wrapper boilerplate into the human-reason +output. + +The script streams JSONL line-by-line and uses only the Python standard library. +""" + +from __future__ import annotations + +import argparse +import json +import os +import sys +from dataclasses import asdict, dataclass +from pathlib import Path +from typing import Dict, Iterable, Iterator, List, Optional, Tuple + + +APPROVE_PREFIX = "User has approved your plan." +REJECT_PREFIX = ( + "The user doesn't want to proceed with this tool use. " + "The tool use was rejected" +) +REASON_MARKER = "To tell you how to proceed, the user said:\n" +NOTE_MARKER = ( + "\n\nNote: The user's next message may contain a correction or preference." +) + + +@dataclass +class AttemptRecord: + session_id: str + tool_use_id: str + file_path: str + line_number: int + timestamp: Optional[str] + cwd: Optional[str] + plan_file_path: Optional[str] + plan_length_chars: Optional[int] + outcome: str = "pending" + native_reason: Optional[str] = None + native_reason_style: Optional[str] = None + captured_reason: Optional[str] = None + captured_reason_style: Optional[str] = None + captured_reason_source: Optional[str] = None + human_reason: Optional[str] = None + human_reason_style: Optional[str] = None + human_reason_source: Optional[str] = None + result_is_error: Optional[bool] = None + result_file_path: Optional[str] = None + result_line_number: Optional[int] = None + result_timestamp: Optional[str] = None + result_preview: Optional[str] = None + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Extract ExitPlanMode approvals/denials from Claude Code logs." + ) + parser.add_argument( + "--projects-dir", + default="~/.claude/projects", + help="Root Claude projects directory. Default: %(default)s", + ) + parser.add_argument( + "--include-subagents", + action="store_true", + help="Include /subagents/ JSONL files. Default is to skip them.", + ) + parser.add_argument( + "--records-filter", + choices=("all", "native", "native-denials", "denials", "human-reasons"), + default="human-reasons", + help=( + "Which records to write to JSON/CSV outputs. " + "Default: %(default)s" + ), + ) + parser.add_argument( + "--include-non-native-denials", + action="store_true", + help=( + "Include non-native denial/error payloads in sample output. " + "Default sample output shows only native denials." + ), + ) + parser.add_argument( + "--show-samples", + type=int, + default=5, + help="How many denial samples to print in the text summary.", + ) + parser.add_argument( + "--json-out", + help="Optional path to write a JSON report.", + ) + parser.add_argument( + "--max-output-tokens-per-file", + type=int, + default=50000, + help=( + "Approximate max token budget per JSON file when writing --json-out. " + "Default: %(default)s" + ), + ) + return parser.parse_args() + + +def iter_jsonl_files(root: Path, include_subagents: bool) -> Iterator[Path]: + for dirpath, dirnames, filenames in os.walk(root): + if not include_subagents and "subagents" in dirnames: + dirnames.remove("subagents") + dirnames.sort() + for filename in sorted(filenames): + if filename.endswith(".jsonl"): + yield Path(dirpath) / filename + + +def make_attempt_key(session_id: str, tool_use_id: str) -> str: + return session_id + "::" + tool_use_id + + +def preview(text: str, limit: int = 220) -> str: + compact = " ".join(text.split()) + if len(compact) <= limit: + return compact + return compact[: limit - 3] + "..." + + +def estimate_tokens(text: str) -> int: + # Rough enough for output chunking. We intentionally bias slightly high. + return max(1, (len(text) + 3) // 4) + + +def iter_blocks(message_content: object) -> Iterator[dict]: + if not isinstance(message_content, list): + return + for block in message_content: + if isinstance(block, dict): + yield block + + +def extract_text(content: object) -> str: + if isinstance(content, str): + return content + if not isinstance(content, list): + return "" + + parts: List[str] = [] + for item in content: + if isinstance(item, str): + parts.append(item) + continue + if not isinstance(item, dict): + continue + if isinstance(item.get("text"), str): + parts.append(item["text"]) + elif isinstance(item.get("content"), str): + parts.append(item["content"]) + return "\n".join(part for part in parts if part) + + +def classify_reason_style(reason: Optional[str]) -> Optional[str]: + if not reason: + return None + + stripped = reason.lstrip() + if ( + stripped.startswith("#") + or stripped.startswith("YOUR PLAN WAS NOT APPROVED.") + or "\n## " in reason + or "\n---" in reason + ): + return "structured" + return "freeform" + + +def extract_blockquote_feedback(text: str) -> List[str]: + quotes: List[str] = [] + current: List[str] = [] + + for raw_line in text.splitlines(): + stripped = raw_line.strip() + if stripped.startswith(">"): + current.append(stripped[1:].lstrip()) + continue + + if current: + if not stripped or stripped.startswith("## ") or stripped == "---": + quote = "\n".join(line for line in current if line).strip() + if quote: + quotes.append(quote) + current = [] + continue + + # Preserve wrapped continuation lines that belong to the same quote. + current.append(stripped) + + if current: + quote = "\n".join(line for line in current if line).strip() + if quote: + quotes.append(quote) + + return quotes + + +def extract_human_reason( + native_reason: Optional[str], + captured_reason: Optional[str], + captured_reason_style: Optional[str], +) -> Tuple[Optional[str], Optional[str], Optional[str]]: + if native_reason: + return ( + native_reason, + classify_reason_style(native_reason), + "native_inline_reason", + ) + + if not captured_reason: + return (None, None, None) + + if captured_reason_style == "freeform": + return ( + captured_reason, + classify_reason_style(captured_reason), + "non_native_freeform_payload", + ) + + quote_feedback = extract_blockquote_feedback(captured_reason) + if quote_feedback: + reason = "\n\n".join(quote_feedback) + return ( + reason, + classify_reason_style(reason), + "structured_quote_extraction", + ) + + return (None, None, None) + + +def classify_result( + text: str, + is_error: bool, +) -> Tuple[str, Optional[str], Optional[str], Optional[str], Optional[str]]: + stripped = text.strip() + if not stripped: + if is_error: + return ( + "denied_non_native_no_payload", + None, + None, + None, + None, + ) + return ("pending", None, None, None, None) + + if stripped.startswith(APPROVE_PREFIX): + return ("approved_native", None, None, None, None) + + if stripped.startswith(REJECT_PREFIX): + marker_index = stripped.find(REASON_MARKER) + if marker_index < 0: + return ("denied_native_no_reason", None, None, None, None) + + reason = stripped[marker_index + len(REASON_MARKER) :] + note_index = reason.find(NOTE_MARKER) + if note_index >= 0: + reason = reason[:note_index] + reason = reason.strip() + if reason: + style = classify_reason_style(reason) + return ( + "denied_native_with_reason", + reason, + reason, + "native_inline_reason", + style, + ) + return ("denied_native_no_reason", None, None, None, None) + + if is_error: + style = classify_reason_style(stripped) + return ( + "denied_non_native_with_payload", + None, + stripped, + "non_native_error_payload", + style, + ) + + return ("non_native_other", None, None, None, None) + + +def outcome_rank(outcome: str) -> int: + ranks = { + "pending": 0, + "non_native_other": 1, + "approved_native": 2, + "denied_native_no_reason": 3, + "denied_native_with_reason": 4, + "denied_non_native_no_payload": 5, + "denied_non_native_with_payload": 6, + } + return ranks.get(outcome, 0) + + +def update_attempt_from_result( + attempt: AttemptRecord, + file_path: Path, + line_number: int, + timestamp: Optional[str], + text: str, + is_error: bool, +) -> None: + ( + outcome, + native_reason, + captured_reason, + captured_reason_source, + captured_reason_style, + ) = classify_result(text=text, is_error=is_error) + if outcome_rank(outcome) < outcome_rank(attempt.outcome): + return + + attempt.outcome = outcome + attempt.native_reason = native_reason + attempt.native_reason_style = classify_reason_style(native_reason) + attempt.captured_reason = captured_reason + attempt.captured_reason_source = captured_reason_source + attempt.captured_reason_style = captured_reason_style + ( + attempt.human_reason, + attempt.human_reason_style, + attempt.human_reason_source, + ) = extract_human_reason( + native_reason=native_reason, + captured_reason=captured_reason, + captured_reason_style=captured_reason_style, + ) + attempt.result_is_error = is_error + attempt.result_file_path = str(file_path) + attempt.result_line_number = line_number + attempt.result_timestamp = timestamp + attempt.result_preview = preview(text) + + +def scan_projects( + projects_dir: Path, + include_subagents: bool, +) -> Tuple[Dict[str, int], List[AttemptRecord]]: + stats = { + "files_scanned": 0, + "lines_scanned": 0, + "json_errors": 0, + } + attempts: Dict[str, AttemptRecord] = {} + + for file_path in iter_jsonl_files(projects_dir, include_subagents): + stats["files_scanned"] += 1 + try: + handle = file_path.open("r", encoding="utf-8", errors="replace") + except OSError: + continue + + with handle: + for line_number, raw_line in enumerate(handle, start=1): + if not raw_line.strip(): + continue + stats["lines_scanned"] += 1 + try: + obj = json.loads(raw_line) + except json.JSONDecodeError: + stats["json_errors"] += 1 + continue + + session_id = str(obj.get("sessionId") or str(file_path)) + timestamp = obj.get("timestamp") + cwd = obj.get("cwd") + message = obj.get("message") + if not isinstance(message, dict): + continue + + content = message.get("content") + + for block in iter_blocks(content): + if ( + block.get("type") == "tool_use" + and block.get("name") == "ExitPlanMode" + and isinstance(block.get("id"), str) + ): + tool_use_id = block["id"] + key = make_attempt_key(session_id, tool_use_id) + if key in attempts: + continue + input_data = block.get("input") + plan = None + plan_file_path = None + if isinstance(input_data, dict): + if isinstance(input_data.get("plan"), str): + plan = input_data["plan"] + if isinstance(input_data.get("planFilePath"), str): + plan_file_path = input_data["planFilePath"] + + attempts[key] = AttemptRecord( + session_id=session_id, + tool_use_id=tool_use_id, + file_path=str(file_path), + line_number=line_number, + timestamp=timestamp if isinstance(timestamp, str) else None, + cwd=cwd if isinstance(cwd, str) else None, + plan_file_path=plan_file_path, + plan_length_chars=len(plan) if isinstance(plan, str) else None, + ) + + if message.get("role") != "user": + continue + + for block in iter_blocks(content): + if ( + block.get("type") != "tool_result" + or not isinstance(block.get("tool_use_id"), str) + ): + continue + + key = make_attempt_key(session_id, block["tool_use_id"]) + attempt = attempts.get(key) + if attempt is None: + continue + + text = extract_text(block.get("content")) + update_attempt_from_result( + attempt=attempt, + file_path=file_path, + line_number=line_number, + timestamp=timestamp if isinstance(timestamp, str) else None, + text=text, + is_error=bool(block.get("is_error")), + ) + + return stats, list(attempts.values()) + + +def summarize(attempts: Iterable[AttemptRecord]) -> Dict[str, int]: + summary = { + "total_exit_plan_attempts": 0, + "approved_native": 0, + "denied_native_with_reason": 0, + "denied_native_no_reason": 0, + "denied_native_with_freeform_reason": 0, + "denied_native_with_structured_reason": 0, + "denied_non_native_with_payload": 0, + "denied_non_native_no_payload": 0, + "captured_denial_reasons_total": 0, + "captured_freeform_reasons": 0, + "captured_structured_reasons": 0, + "human_reasons_total": 0, + "human_reasons_native": 0, + "human_reasons_non_native": 0, + "human_reasons_freeform": 0, + "human_reasons_structured": 0, + "non_native_other": 0, + "pending": 0, + } + for attempt in attempts: + summary["total_exit_plan_attempts"] += 1 + summary[attempt.outcome] = summary.get(attempt.outcome, 0) + 1 + if attempt.outcome == "denied_native_with_reason": + if attempt.native_reason_style == "freeform": + summary["denied_native_with_freeform_reason"] += 1 + elif attempt.native_reason_style == "structured": + summary["denied_native_with_structured_reason"] += 1 + if attempt.captured_reason: + summary["captured_denial_reasons_total"] += 1 + if attempt.captured_reason_style == "freeform": + summary["captured_freeform_reasons"] += 1 + elif attempt.captured_reason_style == "structured": + summary["captured_structured_reasons"] += 1 + if attempt.human_reason: + summary["human_reasons_total"] += 1 + if attempt.human_reason_source == "native_inline_reason": + summary["human_reasons_native"] += 1 + else: + summary["human_reasons_non_native"] += 1 + if attempt.human_reason_style == "freeform": + summary["human_reasons_freeform"] += 1 + elif attempt.human_reason_style == "structured": + summary["human_reasons_structured"] += 1 + return summary + + +def filter_records( + attempts: List[AttemptRecord], + records_filter: str, +) -> List[AttemptRecord]: + if records_filter == "all": + return attempts + if records_filter == "native": + return [ + attempt + for attempt in attempts + if attempt.outcome.startswith("approved_native") + or attempt.outcome.startswith("denied_native") + ] + if records_filter == "native-denials": + return [ + attempt + for attempt in attempts + if attempt.outcome.startswith("denied_native") + ] + if records_filter == "human-reasons": + return [attempt for attempt in attempts if attempt.human_reason] + return [ + attempt + for attempt in attempts + if attempt.outcome.startswith("denied_native") + or attempt.outcome.startswith("denied_non_native") + ] + + +def build_json_chunks( + records: List[AttemptRecord], + max_output_tokens_per_file: int, +) -> List[List[AttemptRecord]]: + if not records: + return [[]] + + chunks: List[List[AttemptRecord]] = [] + current_chunk: List[AttemptRecord] = [] + current_tokens = 0 + + for record in records: + record_dict = asdict(record) + record_json = json.dumps(record_dict, ensure_ascii=False) + record_tokens = estimate_tokens(record_json) + + if current_chunk and current_tokens + record_tokens > max_output_tokens_per_file: + chunks.append(current_chunk) + current_chunk = [] + current_tokens = 0 + + current_chunk.append(record) + current_tokens += record_tokens + + if current_chunk: + chunks.append(current_chunk) + + return chunks + + +def print_summary( + projects_dir: Path, + include_subagents: bool, + stats: Dict[str, int], + attempts: List[AttemptRecord], + summary: Dict[str, int], + show_samples: int, + include_non_native_denials: bool, +) -> None: + native_denials = ( + summary["denied_native_with_reason"] + summary["denied_native_no_reason"] + ) + total_denials = ( + native_denials + + summary["denied_non_native_with_payload"] + + summary["denied_non_native_no_payload"] + ) + native_extractable_ratio = ( + (summary["denied_native_with_reason"] / native_denials) * 100.0 + if native_denials + else 0.0 + ) + all_capture_ratio = ( + (summary["captured_denial_reasons_total"] / total_denials) * 100.0 + if total_denials + else 0.0 + ) + + print(f"Projects dir: {projects_dir}") + print(f"Included subagents: {'yes' if include_subagents else 'no'}") + print(f"JSONL files scanned: {stats['files_scanned']}") + print(f"JSON lines scanned: {stats['lines_scanned']}") + print(f"JSON parse errors: {stats['json_errors']}") + print() + print(f"ExitPlanMode attempts: {summary['total_exit_plan_attempts']}") + print(f"Native approvals: {summary['approved_native']}") + print( + "Native denials with extractable reason: " + f"{summary['denied_native_with_reason']}" + ) + print( + "Native denials without reason: " + f"{summary['denied_native_no_reason']}" + ) + print( + "Freeform native reasons: " + f"{summary['denied_native_with_freeform_reason']}" + ) + print( + "Structured native reasons: " + f"{summary['denied_native_with_structured_reason']}" + ) + print( + "Non-native denials with payload: " + f"{summary['denied_non_native_with_payload']}" + ) + print( + "Non-native denials without payload: " + f"{summary['denied_non_native_no_payload']}" + ) + print( + "Captured denial reasons total: " + f"{summary['captured_denial_reasons_total']}" + ) + print( + "Captured freeform reasons: " + f"{summary['captured_freeform_reasons']}" + ) + print( + "Captured structured reasons: " + f"{summary['captured_structured_reasons']}" + ) + print(f"Human reasons total: {summary['human_reasons_total']}") + print(f"Human reasons from native denials: {summary['human_reasons_native']}") + print( + "Human reasons from non-native denials: " + f"{summary['human_reasons_non_native']}" + ) + print( + "Non-native / non-denial outcomes: " + f"{summary['non_native_other']}" + ) + print(f"Pending / unmatched attempts: {summary['pending']}") + print() + print( + "Extractable native denial reasons: " + f"{summary['denied_native_with_reason']}/{native_denials} " + f"({native_extractable_ratio:.1f}%)" + ) + print( + "Captured denial payloads across all denial types: " + f"{summary['captured_denial_reasons_total']}/{total_denials} " + f"({all_capture_ratio:.1f}%)" + ) + print( + "Human reasons across all denial types: " + f"{summary['human_reasons_total']}/{total_denials} " + f"({((summary['human_reasons_total'] / total_denials) * 100.0 if total_denials else 0.0):.1f}%)" + ) + + if include_non_native_denials: + samples = [attempt for attempt in attempts if attempt.human_reason] + else: + samples = [ + attempt + for attempt in attempts + if attempt.outcome == "denied_native_with_reason" and attempt.human_reason + ] + samples = samples[: max(show_samples, 0)] + if not samples: + return + + print() + print( + "Sample denial reasons:" + if include_non_native_denials + else "Sample native denial reasons:" + ) + for attempt in samples: + style = attempt.human_reason_style or "unknown" + source = attempt.human_reason_source or "unknown" + reason = attempt.human_reason or "" + print( + "- " + f"[{attempt.outcome} / {source} / {style}] " + f"{reason!r} " + f"({attempt.file_path}:{attempt.result_line_number})" + ) + + +def write_json_report( + output_path: Path, + projects_dir: Path, + include_subagents: bool, + stats: Dict[str, int], + summary: Dict[str, int], + records: List[AttemptRecord], + max_output_tokens_per_file: int, +) -> List[Path]: + output_path.parent.mkdir(parents=True, exist_ok=True) + + chunks = build_json_chunks(records, max_output_tokens_per_file) + base_name = output_path.stem + output_dir = output_path.with_suffix("") + output_dir.mkdir(parents=True, exist_ok=True) + + written_files: List[Path] = [] + part_summaries = [] + + for index, chunk in enumerate(chunks, start=1): + chunk_records = [asdict(record) for record in chunk] + chunk_payload = { + "projects_dir": str(projects_dir), + "include_subagents": include_subagents, + "stats": stats, + "summary": summary, + "part_index": index, + "part_count": len(chunks), + "record_count": len(chunk_records), + "records": chunk_records, + } + part_name = f"{base_name}.part-{index:04d}-of-{len(chunks):04d}.json" + part_path = output_dir / part_name + part_path.write_text( + json.dumps(chunk_payload, indent=2, ensure_ascii=False), + encoding="utf-8", + ) + written_files.append(part_path) + part_summaries.append( + { + "part_index": index, + "file_name": part_name, + "record_count": len(chunk_records), + } + ) + + manifest_payload = { + "projects_dir": str(projects_dir), + "include_subagents": include_subagents, + "stats": stats, + "summary": summary, + "records_filter_record_count": len(records), + "part_count": len(chunks), + "max_output_tokens_per_file": max_output_tokens_per_file, + "parts": part_summaries, + } + manifest_path = output_dir / f"{base_name}.manifest.json" + manifest_path.write_text( + json.dumps(manifest_payload, indent=2, ensure_ascii=False), + encoding="utf-8", + ) + written_files.insert(0, manifest_path) + + return written_files + + +def main() -> int: + args = parse_args() + projects_dir = Path(args.projects_dir).expanduser() + if not projects_dir.exists(): + print(f"Projects dir does not exist: {projects_dir}", file=sys.stderr) + return 1 + + stats, attempts = scan_projects( + projects_dir=projects_dir, + include_subagents=args.include_subagents, + ) + attempts.sort( + key=lambda attempt: ( + attempt.file_path, + attempt.line_number, + attempt.tool_use_id, + ) + ) + summary = summarize(attempts) + records = filter_records(attempts, args.records_filter) + + print_summary( + projects_dir=projects_dir, + include_subagents=args.include_subagents, + stats=stats, + attempts=attempts, + summary=summary, + show_samples=args.show_samples, + include_non_native_denials=args.include_non_native_denials, + ) + + if args.json_out: + written_files = write_json_report( + output_path=Path(args.json_out).expanduser(), + projects_dir=projects_dir, + include_subagents=args.include_subagents, + stats=stats, + summary=summary, + records=records, + max_output_tokens_per_file=args.max_output_tokens_per_file, + ) + part_count = max(len(written_files) - 1, 0) + print() + print( + "Wrote JSON output: " + f"detected {len(records)} records for filter '{args.records_filter}' " + f"and emitted {part_count} part file(s) plus a manifest." + ) + + return 0 + + +if __name__ == "__main__": + sys.exit(main())