Skip to content

100+ AI Agents, Agent Skills and RAG Apps - Free and Open Source.

Add scope-creep-detector skill: flag where a diff grew past its stated intent

Matt Van Horn78473c2c2673
diff --git a/README.md b/README.md
index 2969b872..ca84a3aa 100644
--- a/README.md
+++ b/README.md
@@ -84,6 +84,7 @@ streamlit run travel_agent.py
*Give your coding agent new abilities. One command to install, plain English to use. Every skill ships real code and passes a security + eval CI gate. Works with Claude Code, Codex, Cursor, and other coding agents. [Browse all skills →](agent_skills/)*
* [⚰️ Project Graveyard](agent_skills/project-graveyard/) - Finds every side project you abandoned, tells you why each one died, and helps you finish the one worth going back to
+* [🔭 Scope Creep Detector](agent_skills/scope-creep-detector/) - Checks whether a diff grew beyond its stated intent and recommends what to keep, split, or justify
* [🧠 Advisor Orchestrator Worker](agent_skills/advisor-orchestrator-worker/) - Meta Loop with Claude Flabe 5 as advisor, GPT-5.6 as orchestrator, and Gemini 3.5 Flash as worker
* [♾️ Self-Improving Agent Skills](agent_skills/self-improving-agent-skills/) - Automatically optimize agent skills using Gemini and ADK
diff --git a/agent_skills/README.md b/agent_skills/README.md
index c2e0c0a9..4d45262a 100644
--- a/agent_skills/README.md
+++ b/agent_skills/README.md
@@ -20,6 +20,7 @@ Most "skills" on registries are text-only prompt dumps — advice the model alre
|---|---|
| [🧠 advisor-orchestrator-worker](advisor-orchestrator-worker/) | Turns your agent into the orchestrator of a three-tier model team: cheap stateless workers in parallel, expensive advisor consulted only at commitment boundaries, verification gates between every step — budgeted so a run can't burn a hole in your API bill |
| [⚰️ project-graveyard](project-graveyard/) | Scans your machine for dead side projects, autopsies why each one died from its git history (deploy fear, payments wall, killed by a newer project), shows your personal death patterns, and resurrects the one with a pulse — with relapse tracking on every resurrection it prescribes |
+| [🔭 scope-creep-detector](scope-creep-detector/) | Checks a diff against its stated intent, flags unrelated files and scope signals, and recommends what to keep, split, or justify |
| [♾️ self-improving-agent-skills](self-improving-agent-skills/) | Automatically optimizes agent skills using Gemini and ADK |
More coming, released one at a time.
diff --git a/agent_skills/evals/scope-creep-detector/evals.json b/agent_skills/evals/scope-creep-detector/evals.json
new file mode 100644
index 00000000..50722d88
--- /dev/null
+++ b/agent_skills/evals/scope-creep-detector/evals.json
@@ -0,0 +1,36 @@
+{
+ "skill_name": "scope-creep-detector",
+ "evals": [
+ {
+ "id": 1,
+ "prompt": "Did my change grow beyond the parser fix I intended?",
+ "expected_output": "A local scope report that separates the parser fix from unrelated diff content and recommends keep, split, or justify.",
+ "expectations": [
+ "The skill asks for or derives a one-line intent before classifying the diff",
+ "The skill runs scripts/scope_creep.py against the requested working, staged, or branch diff",
+ "The report distinguishes in-scope files from likely creep using evidence from the JSON",
+ "Every likely-creep item receives a keep, split, or justify recommendation"
+ ]
+ },
+ {
+ "id": 2,
+ "prompt": "Is my PR too broad? Check the staged changes before I open it.",
+ "expected_output": "A staged-diff scope report with subsystem counts, dependency and API signals, and concrete split advice.",
+ "expectations": [
+ "The skill uses --staged and does not modify the index or working tree",
+ "The report names touched subsystems and high-risk scope signals",
+ "Suggested splits group related files or hunks without changing them"
+ ]
+ },
+ {
+ "id": 3,
+ "prompt": "What unrelated stuff did I touch while fixing this null dereference?",
+ "expected_output": "A concise explanation of unrelated files, new dependencies, renames, config edits, and oversized or formatting-only changes.",
+ "expectations": [
+ "The answer does not call keyword relatedness proof of intent",
+ "The answer cites file paths and classifier reasons",
+ "The agent asks before making any split or revert edits"
+ ]
+ }
+ ]
+}
diff --git a/agent_skills/evals/scope-creep-detector/test_scope_creep.py b/agent_skills/evals/scope-creep-detector/test_scope_creep.py
new file mode 100644
index 00000000..0c6c9980
--- /dev/null
+++ b/agent_skills/evals/scope-creep-detector/test_scope_creep.py
@@ -0,0 +1,306 @@
+#!/usr/bin/env python3
+"""
+Executable eval for scope-creep-detector. Builds a temporary git repository,
+creates a deliberately mixed diff, and checks the deterministic classifier.
+
+ python3 agent_skills/evals/scope-creep-detector/test_scope_creep.py
+
+The fixture contains an in-scope parser fix plus an unrelated CI edit, a new
+dependency, and a public API rename. It uses only git and the Python stdlib.
+"""
+
+import json
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+
+
+SCRIPT = os.path.join(
+ os.path.dirname(os.path.abspath(__file__)),
+ "..",
+ "..",
+ "scope-creep-detector",
+ "scripts",
+ "scope_creep.py",
+)
+
+checks = []
+
+
+def check(name, ok, detail=""):
+ checks.append(ok)
+ suffix = ": %s" % detail if detail and not ok else ""
+ print(" %s %s%s" % ("PASS" if ok else "FAIL", name, suffix))
+
+
+def write(root, path, content):
+ target = os.path.join(root, path)
+ os.makedirs(os.path.dirname(target), exist_ok=True)
+ with open(target, "w", encoding="utf-8") as handle:
+ handle.write(content)
+
+
+def build_repo(root):
+ subprocess.run(["git", "init", "-q"], cwd=root, check=True)
+ subprocess.run(["git", "config", "user.email", "[email protected]"], cwd=root, check=True)
+ subprocess.run(["git", "config", "user.name", "scope eval"], cwd=root, check=True)
+
+ write(
+ root,
+ "src/parser.py",
+ "def parse_payload(payload):\n"
+ " return payload[\"value\"]\n",
+ )
+ write(
+ root,
+ "src/public_api.py",
+ "def load_record(record):\n"
+ " return record\n"
+ "\n"
+ "def _normalize_record(record):\n"
+ " return record\n",
+ )
+ write(root, "requirements.txt", "click==8.1.7\n")
+ write(
+ root,
+ "package.json",
+ "{\n"
+ " \"dependencies\": {\n"
+ " \"chalk\": \"5.3.0\"\n"
+ " }\n"
+ "}\n",
+ )
+ write(
+ root,
+ "pyproject.toml",
+ "[project]\n"
+ "dependencies = [\n"
+ " \"click==8.1.7\",\n"
+ "]\n",
+ )
+ write(root, ".gitattributes", "*.bin diff=scope-eval-textconv\n")
+ write(root, "assets/sample.bin", "before\x00data\n")
+ write(root, "src/format_only.py", "answer=42\n")
+ write(
+ root,
+ "src/bulk_change.py",
+ "".join("old_%03d = %d\n" % (index, index) for index in range(45)),
+ )
+ write(
+ root,
+ ".github/workflows/ci.yml",
+ "name: CI\n"
+ "on: [push]\n"
+ "jobs:\n"
+ " test:\n"
+ " runs-on: ubuntu-latest\n",
+ )
+ subprocess.run(["git", "add", "-A"], cwd=root, check=True)
+ subprocess.run(["git", "commit", "-qm", "baseline"], cwd=root, check=True)
+
+ write(
+ root,
+ "src/parser.py",
+ "def parse_payload(payload):\n"
+ " if payload is None:\n"
+ " return None\n"
+ " return payload[\"value\"]\n",
+ )
+ write(
+ root,
+ "src/public_api.py",
+ "def fetch_record(record):\n"
+ " return record\n"
+ "\n"
+ "def _coerce_record(record):\n"
+ " return record\n",
+ )
+ write(root, "requirements.txt", "click==8.1.7\nhttpx==0.27.0\n")
+ write(
+ root,
+ "package.json",
+ "{\n"
+ " \"dependencies\": {\n"
+ " \"chalk\": \"5.3.0\",\n"
+ " \"ora\": \"8.0.1\"\n"
+ " }\n"
+ "}\n",
+ )
+ write(
+ root,
+ "pyproject.toml",
+ "[project]\n"
+ "dependencies = [\n"
+ " \"click==8.1.7\",\n"
+ " \"rich==13.7.1\",\n"
+ "]\n",
+ )
+ write(root, "assets/sample.bin", "after\x00data\n")
+ marker = os.path.join(root, "textconv-ran")
+ helper = os.path.join(root, "textconv.py")
+ write(
+ root,
+ "textconv.py",
+ "import pathlib\n"
+ "import sys\n"
+ "pathlib.Path(sys.argv[1]).write_text('ran', encoding='utf-8')\n"
+ "print(pathlib.Path(sys.argv[2]).read_bytes().hex())\n",
+ )
+ subprocess.run(
+ [
+ "git",
+ "config",
+ "diff.scope-eval-textconv.textconv",
+ "%s %s %s" % (sys.executable, helper, marker),
+ ],
+ cwd=root,
+ check=True,
+ )
+ write(root, "src/format_only.py", "answer = 42\n")
+ write(
+ root,
+ "src/bulk_change.py",
+ "".join("new_%03d = %d\n" % (index, index) for index in range(45)),
+ )
+ write(
+ root,
+ ".github/workflows/ci.yml",
+ "name: CI\n"
+ "on: [push, pull_request]\n"
+ "jobs:\n"
+ " test:\n"
+ " runs-on: ubuntu-latest\n",
+ )
+
+
+def main():
+ root = tempfile.mkdtemp(prefix="scope-creep-eval-")
+ try:
+ build_repo(root)
+ marker = os.path.join(root, "textconv-ran")
+ result = subprocess.run(
+ [
+ sys.executable,
+ SCRIPT,
+ "--repo",
+ root,
+ "--intent",
+ "fix null dereference in parser",
+ "--json",
+ ],
+ capture_output=True,
+ text=True,
+ )
+
+ print("scope classification:")
+ check("script exits successfully", result.returncode == 0, result.stderr.strip())
+ try:
+ report = json.loads(result.stdout)
+ except json.JSONDecodeError as error:
+ report = {}
+ check("stdout is valid JSON", False, str(error))
+ else:
+ check("stdout is valid JSON", True)
+
+ in_scope = {item["path"] for item in report.get("in_scope", [])}
+ creep = {item["path"] for item in report.get("likely_creep", [])}
+ deps = report.get("new_deps", [])
+ renames = report.get("api_renames", [])
+ config = {item["path"] for item in report.get("config_edits", [])}
+ stats = report.get("stats", {})
+
+ check("parser fix is in scope", "src/parser.py" in in_scope, sorted(in_scope))
+ check("CI edit is likely creep", ".github/workflows/ci.yml" in creep, sorted(creep))
+ check("CI edit is classified as config", ".github/workflows/ci.yml" in config, sorted(config))
+ check(
+ "new dependency is detected",
+ any(item.get("name") == "httpx" and item.get("path") == "requirements.txt" for item in deps),
+ deps,
+ )
+ check(
+ "package.json dependency is detected",
+ any(item.get("name") == "ora" and item.get("path") == "package.json" for item in deps),
+ deps,
+ )
+ check(
+ "pyproject dependency is detected",
+ any(item.get("name") == "rich" and item.get("path") == "pyproject.toml" for item in deps),
+ deps,
+ )
+ check("git textconv command is not executed", not os.path.exists(marker), marker)
+ check("dependency file is likely creep", "requirements.txt" in creep, sorted(creep))
+ check(
+ "public API rename is detected",
+ any(
+ item.get("path") == "src/public_api.py"
+ and item.get("from") == "load_record"
+ and item.get("to") == "fetch_record"
+ for item in renames
+ ),
+ renames,
+ )
+ check(
+ "private helper rename is ignored",
+ not any(item.get("from", "").startswith("_") for item in renames),
+ renames,
+ )
+ check(
+ "formatting-only file is detected",
+ "src/format_only.py" in stats.get("formatting_only_files", []),
+ stats.get("formatting_only_files", []),
+ )
+ check(
+ "oversized hunk is detected",
+ any(item.get("path") == "src/bulk_change.py" for item in stats.get("oversized_hunks", [])),
+ stats.get("oversized_hunks", []),
+ )
+
+ plain_diff = os.path.join(root, "plain.diff")
+ write(
+ root,
+ "plain.diff",
+ "--- a/src/parser.py\n"
+ "+++ b/src/parser.py\n"
+ "@@ -1 +1,2 @@\n"
+ " def parse_payload(payload):\n"
+ "+ return payload\n",
+ )
+ plain_result = subprocess.run(
+ [
+ sys.executable,
+ SCRIPT,
+ "--diff",
+ plain_diff,
+ "--intent",
+ "parser change",
+ "--json",
+ ],
+ capture_output=True,
+ text=True,
+ )
+ try:
+ plain_report = json.loads(plain_result.stdout)
+ except json.JSONDecodeError:
+ plain_report = {}
+ check(
+ "plain unified diff without git headers is parsed",
+ plain_result.returncode == 0
+ and plain_report.get("stats", {}).get("files_touched") == 1
+ and plain_report.get("in_scope", [{}])[0].get("path") == "src/parser.py",
+ plain_result.stderr.strip() or plain_result.stdout.strip(),
+ )
+
+ print()
+ if all(checks):
+ print("PASS: %d/%d checks" % (len(checks), len(checks)))
+ return 0
+ print("FAIL: %d/%d checks passed" % (sum(checks), len(checks)))
+ return 1
+ finally:
+ shutil.rmtree(root, ignore_errors=True)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/agent_skills/evals/scope-creep-detector/trigger-cases.json b/agent_skills/evals/scope-creep-detector/trigger-cases.json
new file mode 100644
index 00000000..d80bc7b6
--- /dev/null
+++ b/agent_skills/evals/scope-creep-detector/trigger-cases.json
@@ -0,0 +1,42 @@
+{
+ "skill": "scope-creep-detector",
+ "purpose": "Trigger-behavior spec for deterministic lexical routing and manual behavior checks.",
+ "cases": [
+ {
+ "id": "change-grew-beyond-fix",
+ "prompt": "did my change grow beyond the fix",
+ "should_trigger": true,
+ "assert": "Analyzes the diff against the stated fix and reports likely scope creep."
+ },
+ {
+ "id": "pr-too-broad",
+ "prompt": "is my PR too broad",
+ "should_trigger": true,
+ "assert": "Produces a scope report and recommends what to keep, split, or justify."
+ },
+ {
+ "id": "unrelated-files-touched",
+ "prompt": "what unrelated stuff did I touch",
+ "should_trigger": true,
+ "assert": "Flags unrelated files and explains the deterministic signals."
+ },
+ {
+ "id": "near-miss-format",
+ "prompt": "format my code",
+ "should_trigger": false,
+ "assert": "Does not trigger for a direct formatting request."
+ },
+ {
+ "id": "near-miss-linter",
+ "prompt": "run the linter",
+ "should_trigger": false,
+ "assert": "Does not trigger for routine lint execution."
+ },
+ {
+ "id": "near-miss-commit-message",
+ "prompt": "write my commit message",
+ "should_trigger": false,
+ "assert": "Does not trigger for commit message drafting alone."
+ }
+ ]
+}
diff --git a/agent_skills/scope-creep-detector/README.md b/agent_skills/scope-creep-detector/README.md
new file mode 100644
index 00000000..803121cd
--- /dev/null
+++ b/agent_skills/scope-creep-detector/README.md
@@ -0,0 +1,29 @@
+# Scope Creep Detector
+
+Checks a working, staged, saved, or branch diff against a one-line intent. It
+flags unrelated paths, new dependencies, public API renames, config or CI
+edits, oversized hunks, formatting-only files, and subsystem spread. The output
+is a local JSON report for keep, split, or justify decisions.
+
+## Install
+
+```bash
+npx skills add https://github.com/Shubhamsaboo/awesome-llm-apps/tree/main/agent_skills/scope-creep-detector
+```
+
+## Run
+
+Ask the agent:
+
+> Did my change grow beyond the parser fix I intended?
+
+Or run the deterministic core directly:
+
+```bash
+python3 scripts/scope_creep.py --repo /path/to/repo \
+ --intent "fix null dereference in parser" --json
+```
+
+Use `--staged` for the index, `--base main` for a branch diff, or `--diff -`
+for unified diff input on stdin. The script uses only the Python standard
+library, makes no network calls, and does not modify the repository.
diff --git a/agent_skills/scope-creep-detector/SKILL.md b/agent_skills/scope-creep-detector/SKILL.md
new file mode 100644
index 00000000..cb1d3e0f
--- /dev/null
+++ b/agent_skills/scope-creep-detector/SKILL.md
@@ -0,0 +1,136 @@
+---
+name: scope-creep-detector
+description: >-
+ Analyzes git diffs against a stated intent to detect scope creep, unrelated
+ files, broad pull requests, changes that grew beyond a fix, dependency
+ additions, public API renames, config or CI edits, oversized hunks, and
+ formatting-only files. Use when the user asks whether a change grew beyond
+ the fix, a PR is too broad, or what unrelated stuff they touched, and wants
+ keep, split, or justify guidance. Operates locally and offline.
+license: Apache-2.0
+metadata:
+ author: "Shubham Saboo"
+ version: "1.0.0"
+ source: "https://github.com/Shubhamsaboo/awesome-llm-apps"
+---
+
+# Scope Creep Detector
+
+A one-line fix should not require a reviewer to reverse-engineer fourteen files
+across three subsystems. This skill compares a git diff with its stated intent,
+surfaces scope signals, and turns them into keep, split, or justify decisions.
+
+Everything runs locally. The script makes no network calls and does not change
+the working tree, index, commits, or branches.
+
+## When to use
+
+- Before opening a pull request whose diff may have grown beyond its intent
+- When a bug fix touches unexpected files or subsystems
+- When the user asks whether staged changes are too broad
+- When a diff includes dependency, public API, config, CI, or build changes
+- When the user wants a concrete split plan for a mixed change
+
+## When not to use
+
+- Formatting code, running a linter, or writing a commit message
+- Reviewing correctness, security, or test quality inside an agreed scope
+- Measuring historical project growth across many commits
+- Editing or reverting files without the user's approval
+
+## Establish the intent
+
+Use the user's one-line intent when available. Keep it concrete, such as
+`fix null dereference in parser` or `add retry limit to webhook delivery`.
+
+If no intent was given, the script falls back to the current branch name. If
+that name is generic, detached, or unrelated to the work, ask for one line of
+intent before treating relatedness as meaningful.
+
+## Run the classifier
+
+Run from this skill directory and point `--repo` at the target repository.
+
+Working tree diff:
+
+```bash
+python3 scripts/scope_creep.py --repo /path/to/repo \
+ --intent "fix null dereference in parser" --json
+```
+
+Staged diff:
+
+```bash
+python3 scripts/scope_creep.py --repo /path/to/repo --staged \
+ --intent "fix null dereference in parser" --json
+```
+
+Branch diff against a merge base:
+
+```bash
+python3 scripts/scope_creep.py --repo /path/to/repo --base main \
+ --intent "fix null dereference in parser" --json
+```
+
+Saved diff or stdin:
+
+```bash
+python3 scripts/scope_creep.py --diff change.diff --intent "parser fix" --json
+git diff --staged | python3 scripts/scope_creep.py --diff - \
+ --intent "parser fix" --json
+```
+
+Use `--hunk-threshold` only when the repository has a documented reason to
+change the default churn threshold. Do not tune the threshold merely to make a
+warning disappear.
+
+## Interpret the JSON
+
+Read [references/scope-signals.md](references/scope-signals.md) before making a
+recommendation. Treat the classifier as triage evidence, not proof of authorial
+intent.
+
+- `in_scope`: file paths with at least one intent/path keyword overlap
+- `likely_creep`: paths without overlap, with the reason and detected signals
+- `new_deps`: dependencies introduced in supported manifest formats
+- `api_renames`: nearby removed and added public function or class declarations
+- `config_edits`: CI, container, build, YAML, and TOML changes
+- `stats`: churn, subsystem counts, oversized hunks, and formatting-only files
+
+Empty arrays are evidence too. Say that no signal was detected, not that the
+diff is guaranteed to be in scope.
+
+## Recommend keep, split, or justify
+
+Give every item in `likely_creep` one disposition:
+
+1. **Keep** when the path is necessary for the stated intent and the connection
+ is direct. Explain the connection in one sentence.
+2. **Split** when it can land independently, belongs to another subsystem, or
+ introduces a dependency, API rename, config edit, or large hunk that is not
+ required for the intent. Name the files or hunks for the follow-up change.
+3. **Justify** when a cross-cutting edit cannot be separated safely. State the
+ invariant or build constraint that requires it and call out reviewer risk.
+
+Prefer split when evidence is ambiguous. Never claim that a zero overlap score
+proves a file is unrelated. Path vocabulary is a cheap, deterministic proxy.
+
+## Write the scope report
+
+Use this compact structure:
+
+1. Intent and diff source
+2. Files and subsystems touched, with total additions and deletions
+3. In-scope changes
+4. Likely creep with signal evidence
+5. Keep, split, or justify table
+6. Proposed follow-up grouping, if any
+
+Name file paths and hunk headers. For an oversized mixed hunk, explain that the
+script cannot split it automatically and describe the smallest coherent edit.
+Ask before applying any split, revert, staging, or commit operation.
+
+## Files
+
+- `scripts/scope_creep.py`: deterministic unified-diff parser and classifier
+- `references/scope-signals.md`: signal definitions, thresholds, and limits
diff --git a/agent_skills/scope-creep-detector/references/scope-signals.md b/agent_skills/scope-creep-detector/references/scope-signals.md
new file mode 100644
index 00000000..92a6cfcf
--- /dev/null
+++ b/agent_skills/scope-creep-detector/references/scope-signals.md
@@ -0,0 +1,83 @@
+# Scope signals
+
+The classifier uses cheap, deterministic signals. They are review prompts, not
+proof that a change is wrong or unrelated.
+
+## Relatedness
+
+The script tokenizes the stated intent and each changed path. It removes common
+branch words such as `fix`, `feat`, and `change`, then computes:
+
+`relatedness = shared intent/path tokens / usable intent tokens`
+
+A file with at least one shared token enters `in_scope`. A file with no shared
+tokens enters `likely_creep`. This deliberately favors recall. A zero score can
+mean a vague intent or an indirect but necessary file, so verify the connection
+before recommending a split.
+
+## Subsystems
+
+The first path component is the subsystem. Root files use `(root)`. Three or
+more subsystems are worth naming in the report even if every path is justified.
+Subsystem count is context, not a failure threshold.
+
+## Added dependencies
+
+The detector reads added lines in these formats:
+
+- `requirements*.txt`
+- dependency sections in `package.json`
+- PEP 621 and Poetry dependency sections in `pyproject.toml`
+
+If the same normalized package name is removed in the diff, the change is
+treated as a version or constraint edit, not a new dependency. Lockfiles are
+not parsed because generated transitive changes obscure the direct addition.
+
+## Public API renames
+
+A rename is a removed `def`, `async def`, or `class` declaration paired with a
+nearby added declaration of the same kind in one hunk. The declarations must be
+within 12 diff lines. This catches common renames but can confuse a deletion and
+addition that happen to be adjacent. Confirm call sites before describing an
+API break.
+
+## Config, CI, and build edits
+
+The signal covers:
+
+- `.github/` paths as CI
+- `Dockerfile`, Docker Compose, Make, CMake, Meson, and Procfile paths as build
+- `.toml`, `.yml`, and `.yaml` files as config
+
+These files often have legitimate cross-cutting reasons. Prefer `justify` when
+the feature cannot pass tests, package, or deploy without the edit. Prefer
+`split` when the edit changes infrastructure policy independently.
+
+## Oversized hunks
+
+Hunk churn is added lines plus removed lines. The default threshold is more
+than 80 changed lines in one hunk. Context lines do not count. The threshold is
+intended to expose mixed or hard-to-review edits, not enforce a PR size limit.
+
+## Formatting-only files
+
+A file is formatting-only when it has the same number of removed and added
+lines and each pair becomes identical after all whitespace is removed. This is
+intentionally narrow. Reordered imports, quote changes, and formatter rewrites
+that move lines may not qualify.
+
+## Recommendation matrix
+
+| Evidence | Default action |
+|---|---|
+| Path overlaps intent and has no independent signal | Keep |
+| No path overlap and a separate subsystem | Split |
+| New dependency unrelated to intent | Split |
+| Public API rename not required by intent | Split |
+| CI or build edit required for the change to work | Justify |
+| Formatting-only file mixed into a behavior change | Split |
+| Oversized hunk containing one coherent algorithm | Keep or justify |
+| Oversized hunk containing separable concerns | Split by hunk or file |
+
+Always name the evidence. Do not turn a heuristic label into a claim about the
+author's motivation.
diff --git a/agent_skills/scope-creep-detector/scripts/scope_creep.py b/agent_skills/scope-creep-detector/scripts/scope_creep.py
new file mode 100644
index 00000000..34c022a4
--- /dev/null
+++ b/agent_skills/scope-creep-detector/scripts/scope_creep.py
@@ -0,0 +1,523 @@
+#!/usr/bin/env python3
+"""
+Classify scope signals in a unified diff.
+
+Usage:
+ python3 scope_creep.py --repo . --intent "fix parser crash" --json
+ python3 scope_creep.py --repo . --staged --json
+ python3 scope_creep.py --repo . --base main --json
+ python3 scope_creep.py --diff change.diff --intent "fix parser crash" --json
+
+Python 3.11 stdlib only. Runs locally and never changes the target repository.
+"""
+
+import argparse
+import collections
+import json
+import os
+import re
+import shlex
+import subprocess
+import sys
+
+
+DEFAULT_HUNK_THRESHOLD = 80
+STOP_WORDS = {
+ "add", "branch", "bug", "change", "changes", "chore", "develop",
+ "development", "feat", "feature", "fix", "fixed", "main", "master",
+ "the", "this", "to", "update", "with",
+}
+CONFIG_EXTENSIONS = {".toml", ".yaml", ".yml"}
+BUILD_FILES = {
+ "cmakelists.txt", "docker-compose.yaml", "docker-compose.yml",
+ "dockerfile", "makefile", "meson.build", "procfile",
+}
+SYMBOL_RE = re.compile(
+ r"^\s*(?:(?:async\s+)?def\s+([A-Za-z_]\w*)|class\s+([A-Za-z_]\w*))"
+)
+HUNK_RE = re.compile(
+ r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$"
+)
+REQUIREMENTS_RE = re.compile(r"^\s*([A-Za-z0-9][A-Za-z0-9_.-]*)")
+JSON_PROPERTY_RE = re.compile(r'^\s*"([A-Za-z0-9@/_.-]+)"\s*:\s*(.+?)[,]?\s*$')
+PYPROJECT_STRING_RE = re.compile(r'^\s*["\']([A-Za-z0-9][A-Za-z0-9_.-]*)[^"\']*["\']\s*,?\s*$')
+PYPROJECT_ASSIGN_RE = re.compile(r"^\s*([A-Za-z0-9][A-Za-z0-9_.-]*)\s*=\s*(.+)$")
+
+
+def clean_path(value):
+ """Normalize a git header path without touching the filesystem."""
+ value = value.strip()
+ if "\t" in value:
+ value = value.split("\t", 1)[0].rstrip()
+ if value.startswith('"') and value.endswith('"'):
+ try:
+ value = json.loads(value)
+ except json.JSONDecodeError:
+ value = value[1:-1]
+ if value in {"/dev/null", "dev/null"}:
+ return None
+ if value.startswith(("a/", "b/")):
+ value = value[2:]
+ return value
+
+
+def new_file(old_path=None, new_path=None):
+ return {
+ "old_path": old_path,
+ "new_path": new_path,
+ "path": new_path or old_path or "unknown",
+ "hunks": [],
+ }
+
+
+def parse_diff(text):
+ """Parse the file and hunk structure needed by the classifiers."""
+ files = []
+ current = None
+ hunk = None
+ old_remaining = new_remaining = 0
+
+ for raw in text.splitlines():
+ if raw.startswith("diff --git "):
+ try:
+ parts = shlex.split(raw)
+ except ValueError:
+ parts = raw.split()
+ old_path = clean_path(parts[2]) if len(parts) > 2 else None
+ new_path = clean_path(parts[3]) if len(parts) > 3 else None
+ current = new_file(old_path, new_path)
+ files.append(current)
+ hunk = None
+ continue
+
+ if current is None:
+ if not raw.startswith("--- "):
+ continue
+ current = new_file()
+ files.append(current)
+
+ match = HUNK_RE.match(raw)
+ if match:
+ old_remaining = int(match.group(2) or "1")
+ new_remaining = int(match.group(4) or "1")
+ hunk = {"header": raw, "lines": []}
+ current["hunks"].append(hunk)
+ continue
+
+ if hunk is not None:
+ if not raw:
+ continue
+ marker = raw[0]
+ if marker not in {" ", "+", "-"}:
+ continue
+ entry = {
+ "marker": marker,
+ "text": raw[1:],
+ "index": len(hunk["lines"]),
+ }
+ hunk["lines"].append(entry)
+ if marker != "+":
+ old_remaining -= 1
+ if marker != "-":
+ new_remaining -= 1
+ if old_remaining <= 0 and new_remaining <= 0:
+ hunk = None
+ continue
+
+ if raw.startswith("--- ") and current["hunks"]:
+ current = new_file()
+ files.append(current)
+ if raw.startswith("rename from "):
+ current["old_path"] = clean_path(raw[len("rename from "):])
+ current["path"] = current["new_path"] or current["old_path"]
+ continue
+ if raw.startswith("rename to "):
+ current["new_path"] = clean_path(raw[len("rename to "):])
+ current["path"] = current["new_path"] or current["old_path"]
+ continue
+ if raw.startswith("--- "):
+ current["old_path"] = clean_path(raw[4:])
+ current["path"] = current["new_path"] or current["old_path"] or "unknown"
+ continue
+ if raw.startswith("+++ "):
+ current["new_path"] = clean_path(raw[4:])
+ current["path"] = current["new_path"] or current["old_path"] or "unknown"
+ continue
+
+ return files
+
+
+def changed_lines(file_change, marker):
+ return [
+ entry["text"]
+ for hunk in file_change["hunks"]
+ for entry in hunk["lines"]
+ if entry["marker"] == marker
+ ]
+
+
+def tokenize(value):
+ value = re.sub(r"([a-z0-9])([A-Z])", r"\1 \2", value)
+ value = re.sub(r"[^A-Za-z0-9]+", " ", value).lower()
+ return {
+ token for token in value.split()
+ if len(token) >= 3 and token not in STOP_WORDS
+ }
+
+
+def subsystem(path):
+ parts = path.split("/")
+ return parts[0] if len(parts) > 1 else "(root)"
+
+
+def config_kind(path):
+ normalized = path.lower()
+ name = os.path.basename(normalized)
+ extension = os.path.splitext(name)[1]
+ if normalized.startswith(".github/"):
+ return "ci"
+ if name in BUILD_FILES or name.startswith("dockerfile."):
+ return "build"
+ if extension in CONFIG_EXTENSIONS:
+ return "config"
+ return None
+
+
+def requirement_dependency(line):
+ stripped = line.strip()
+ if not stripped or stripped.startswith(("#", "-", ".")):
+ return None
+ match = REQUIREMENTS_RE.match(stripped)
+ if not match:
+ return None
+ return match.group(1).lower().replace("_", "-"), stripped
+
+
+def package_json_dependencies(file_change, marker):
+ dependencies = []
+ for hunk in file_change["hunks"]:
+ in_dependencies = False
+ for entry in hunk["lines"]:
+ line = entry["text"]
+ top_key = re.match(r'^\s{0,2}"([^"]+)"\s*:', line)
+ if top_key:
+ in_dependencies = top_key.group(1) in {
+ "dependencies", "devDependencies", "optionalDependencies",
+ "peerDependencies",
+ }
+ continue
+ if entry["marker"] != marker or not in_dependencies:
+ continue
+ match = JSON_PROPERTY_RE.match(line)
+ if match:
+ dependencies.append((match.group(1).lower(), line.strip()))
+ return dependencies
+
+
+def pyproject_dependencies(file_change, marker):
+ dependencies = []
+ section = None
+ in_project_list = False
+ for hunk in file_change["hunks"]:
+ for entry in hunk["lines"]:
+ line = entry["text"]
+ section_match = re.match(r"^\s*\[([^]]+)\]\s*$", line)
+ if section_match:
+ section = section_match.group(1).lower()
+ in_project_list = False
+ continue
+ if section == "project" and re.match(r"^\s*dependencies\s*=\s*\[", line):
+ in_project_list = True
+ continue
+ if in_project_list and "]" in line:
+ in_project_list = False
+ if entry["marker"] != marker:
+ continue
+ if in_project_list:
+ match = PYPROJECT_STRING_RE.match(line)
+ if match:
+ dependencies.append((match.group(1).lower().replace("_", "-"), line.strip()))
+ elif section in {"tool.poetry.dependencies", "tool.poetry.group.dev.dependencies"}:
+ match = PYPROJECT_ASSIGN_RE.match(line)
+ if match and match.group(1).lower() != "python":
+ dependencies.append((match.group(1).lower().replace("_", "-"), line.strip()))
+ return dependencies
+
+
+def dependency_lines(file_change, marker):
+ path = file_change["path"].lower()
+ name = os.path.basename(path)
+ if name.startswith("requirements") and name.endswith(".txt"):
+ found = []
+ for line in changed_lines(file_change, marker):
+ parsed = requirement_dependency(line)
+ if parsed:
+ found.append(parsed)
+ return found
+ if name == "package.json":
+ return package_json_dependencies(file_change, marker)
+ if name == "pyproject.toml":
+ return pyproject_dependencies(file_change, marker)
+ return []
+
+
+def find_new_dependencies(files):
+ found = []
+ for file_change in files:
+ removed = {name for name, _line in dependency_lines(file_change, "-")}
+ for name, line in dependency_lines(file_change, "+"):
+ if name not in removed:
+ found.append({"path": file_change["path"], "name": name, "line": line})
+ unique = {(item["path"], item["name"]): item for item in found}
+ return [unique[key] for key in sorted(unique)]
+
+
+def declaration(entry):
+ match = SYMBOL_RE.match(entry["text"])
+ if not match:
+ return None
+ name = match.group(1) or match.group(2)
+ if name.startswith("_"):
+ return None
+ kind = "function" if match.group(1) else "class"
+ return {"kind": kind, "name": name, "entry": entry}
+
+
+def find_api_renames(files):
+ renames = []
+ for file_change in files:
+ for hunk in file_change["hunks"]:
+ removed = [declaration(e) for e in hunk["lines"] if e["marker"] == "-"]
+ added = [declaration(e) for e in hunk["lines"] if e["marker"] == "+"]
+ removed = [item for item in removed if item]
+ added = [item for item in added if item]
+ used = set()
+ for old in removed:
+ candidates = [
+ (abs(old["entry"]["index"] - new["entry"]["index"]), index, new)
+ for index, new in enumerate(added)
+ if index not in used
+ and new["kind"] == old["kind"]
+ and new["name"] != old["name"]
+ ]
+ if not candidates:
+ continue
+ distance, index, new = min(candidates)
+ if distance > 12:
+ continue
+ used.add(index)
+ renames.append({
+ "path": file_change["path"],
+ "kind": old["kind"],
+ "from": old["name"],
+ "to": new["name"],
+ "hunk": hunk["header"],
+ })
+ return sorted(renames, key=lambda item: (item["path"], item["from"], item["to"]))
+
+
+def lines_are_formatting_only(removed, added):
+ if not removed or len(removed) != len(added):
+ return False
+ normalize = lambda line: re.sub(r"\s+", "", line)
+ return [normalize(line) for line in removed] == [normalize(line) for line in added]
+
+
+def classify(files, intent, hunk_threshold):
+ intent_words = tokenize(intent)
+ new_deps = find_new_dependencies(files)
+ api_renames = find_api_renames(files)
+ dep_paths = {item["path"] for item in new_deps}
+ rename_paths = {item["path"] for item in api_renames}
+
+ config_edits = []
+ oversized = []
+ formatting_only = []
+ subsystems = collections.Counter()
+ additions = deletions = 0
+ file_metrics = {}
+
+ for file_change in files:
+ path = file_change["path"]
+ subsystems[subsystem(path)] += 1
+ added_lines = changed_lines(file_change, "+")
+ removed_lines = changed_lines(file_change, "-")
+ file_additions = len(added_lines)
+ file_deletions = len(removed_lines)
+ file_metrics[id(file_change)] = (file_additions, file_deletions)
+ additions += file_additions
+ deletions += file_deletions
+ kind = config_kind(path)
+ if kind:
+ config_edits.append({
+ "path": path,
+ "kind": kind,
+ "churn": file_additions + file_deletions,
+ })
+ if lines_are_formatting_only(removed_lines, added_lines):
+ formatting_only.append(path)
+ for hunk in file_change["hunks"]:
+ churn = sum(1 for entry in hunk["lines"] if entry["marker"] in {"+", "-"})
+ if churn > hunk_threshold:
+ oversized.append({"path": path, "hunk": hunk["header"], "churn": churn})
+
+ config_paths = {item["path"] for item in config_edits}
+ oversized_paths = {item["path"] for item in oversized}
+ formatting_paths = set(formatting_only)
+ in_scope = []
+ likely_creep = []
+
+ for file_change in sorted(files, key=lambda item: item["path"]):
+ path = file_change["path"]
+ overlap = sorted(intent_words & tokenize(path))
+ score = round(len(overlap) / max(1, len(intent_words)), 3)
+ signals = []
+ if path in dep_paths:
+ signals.append("new_dependency")
+ if path in rename_paths:
+ signals.append("public_api_rename")
+ if path in config_paths:
+ signals.append("config_edit")
+ if path in oversized_paths:
+ signals.append("oversized_hunk")
+ if path in formatting_paths:
+ signals.append("formatting_only")
+
+ additions_for_file, deletions_for_file = file_metrics[id(file_change)]
+ reasons = []
+ if overlap:
+ reasons.append("intent/path overlap: %s" % ", ".join(overlap))
+ elif intent_words:
+ reasons.append("no intent/path keyword overlap")
+ else:
+ reasons.append("intent has no usable keywords")
+ reasons.extend(signal.replace("_", " ") for signal in signals)
+ item = {
+ "path": path,
+ "subsystem": subsystem(path),
+ "relatedness": score,
+ "overlap": overlap,
+ "signals": signals,
+ "reasons": reasons,
+ "additions": additions_for_file,
+ "deletions": deletions_for_file,
+ }
+ (in_scope if overlap else likely_creep).append(item)
+
+ return {
+ "intent": intent,
+ "in_scope": in_scope,
+ "likely_creep": likely_creep,
+ "new_deps": new_deps,
+ "api_renames": api_renames,
+ "config_edits": sorted(config_edits, key=lambda item: item["path"]),
+ "stats": {
+ "files_touched": len(files),
+ "additions": additions,
+ "deletions": deletions,
+ "subsystems": dict(sorted(subsystems.items())),
+ "oversized_hunks": oversized,
+ "formatting_only_files": sorted(formatting_only),
+ "hunk_threshold": hunk_threshold,
+ },
+ }
+
+
+def run_git(repo, args):
+ result = subprocess.run(
+ ["git", "-C", repo, *args],
+ capture_output=True,
+ text=True,
+ timeout=30,
+ )
+ if result.returncode != 0:
+ raise RuntimeError(result.stderr.strip() or "git command failed")
+ return result.stdout
+
+
+def read_diff(args):
+ if args.diff == "-":
+ return sys.stdin.read()
+ if args.diff:
+ with open(args.diff, encoding="utf-8", errors="replace") as handle:
+ return handle.read()
+ command = ["diff", "--no-ext-diff", "--no-textconv", "--unified=3"]
+ if args.staged:
+ command.append("--cached")
+ elif args.base:
+ command.append("%s...HEAD" % args.base)
+ command.append("--")
+ return run_git(args.repo, command)
+
+
+def fallback_intent(repo):
+ try:
+ branch = run_git(repo, ["branch", "--show-current"]).strip()
+ except RuntimeError:
+ branch = ""
+ return branch or "detached HEAD"
+
+
+def print_human(report):
+ stats = report["stats"]
+ print("SCOPE REPORT")
+ print("intent: %s" % report["intent"])
+ print(
+ "files: %(files_touched)d additions: %(additions)d deletions: %(deletions)d"
+ % stats
+ )
+ print("subsystems: %s" % (", ".join(
+ "%s=%d" % item for item in stats["subsystems"].items()
+ ) or "none"))
+ print("in scope: %d" % len(report["in_scope"]))
+ for item in report["in_scope"]:
+ print(" KEEP? %s (%s)" % (item["path"], "; ".join(item["reasons"])))
+ print("likely creep: %d" % len(report["likely_creep"]))
+ for item in report["likely_creep"]:
+ print(" SPLIT OR JUSTIFY: %s (%s)" % (item["path"], "; ".join(item["reasons"])))
+
+
+def build_parser():
+ parser = argparse.ArgumentParser(description="Detect scope signals in a git unified diff.")
+ parser.add_argument("--repo", default=".", help="Target git repository (default: current directory).")
+ parser.add_argument("--diff", help="Read a unified diff from a file, or '-' for stdin.")
+ modes = parser.add_mutually_exclusive_group()
+ modes.add_argument("--staged", action="store_true", help="Analyze the staged diff.")
+ modes.add_argument("--base", help="Analyze BASE...HEAD for a branch diff.")
+ parser.add_argument("--intent", help="One-line intent; defaults to the current branch name.")
+ parser.add_argument(
+ "--hunk-threshold",
+ type=int,
+ default=DEFAULT_HUNK_THRESHOLD,
+ help="Flag hunks with churn above this value (default: 80).",
+ )
+ parser.add_argument("--json", action="store_true", help="Emit the full JSON report.")
+ return parser
+
+
+def main(argv=None):
+ parser = build_parser()
+ args = parser.parse_args(argv)
+ if args.diff and (args.staged or args.base):
+ parser.error("--diff cannot be combined with --staged or --base")
+ if args.hunk_threshold < 1:
+ parser.error("--hunk-threshold must be at least 1")
+
+ try:
+ diff_text = read_diff(args)
+ intent = args.intent.strip() if args.intent and args.intent.strip() else fallback_intent(args.repo)
+ report = classify(parse_diff(diff_text), intent, args.hunk_threshold)
+ except (OSError, RuntimeError, subprocess.TimeoutExpired) as error:
+ print("scope_creep.py: error: %s" % error, file=sys.stderr)
+ return 2
+
+ if args.json:
+ json.dump(report, sys.stdout, indent=2, sort_keys=True)
+ sys.stdout.write("\n")
+ else:
+ print_human(report)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())