Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion plugins/code-tidying/.claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"$schema": "https://json.schemastore.org/claude-code-plugin-manifest.json",
"name": "code-tidying",
"version": "0.16.3",
"version": "0.17.0",
"description": "Code tidying and comment hygiene: /code-tidying:tidy proactively hunts a rotated, glob-scoped lane for Beck-style tidyings under a research-backed scope budget and ships one tight PR; /code-tidying:batch-simplify sweeps a time window, a branch, or an entire repository through grouped, dependency-ordered simplification waves with a fix-first deferral contract that resolves deferrals in the same run instead of filing issues; /code-tidying:dissolve-comments enforces self-describing expressive code over a diff or target, widening to the branch diff and then the whole repository when the tree is clean \u2014 deletes zero-information comments, dissolves code-expressible ones into names and structure behind a tests gate (safe mode restricts applied edits to removals), and keeps only terse load-bearing comments code cannot express; /code-tidying:audit-comment-residue is a read-only classifier that flags history, plan, conversational, and ticket/PR residue in code comments for author-applied deletion; /code-tidying:audit-dead-code is a read-only whole-repo dead-code hunter running four labelled lanes of unequal confidence (knip for TS/JS, vulture for Python, gopls for Go, and a portable grep lane for shell and other symbol languages), adjudicating every candidate against dynamic-usage evidence into a dead, uncertain, or alive verdict. Project-specific tidy lanes are scaffolded into a tracked .claude/tidy-lanes/ config folder by a re-runnable setup skill.",
"author": {
"name": "Melodic Software",
Expand Down
61 changes: 61 additions & 0 deletions plugins/code-tidying/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,67 @@
All notable changes to the `code-tidying` plugin are documented here. Format follows
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/); this plugin uses semantic versioning.

## [0.17.0]

### Fixed

- **`dissolve-comments`:** the class-C earn-its-keep test stated a decision the workflow never
implemented. A comment that was inexpressible, within budget, and **not** load-bearing had a
verdict and no treatment, and "doubt keeps the comment" resolved the gap to keep — so on a
rationale-dense repository the skill returned zero edits by construction. The triage table now
names the treatment on both sides of the test, and step 6 carries the delete branch.
- **`dissolve-comments`:** criterion 2 had no evidence procedure, so "recoverable from version
control" was decided by impression and every guess resolved to keep. Step 5 now runs
`git log -L` over the comment's own lines and checks the repo's ADR directory, recording a
per-comment verdict.
- **`rank-comment-targets.py`:** exit 3 discarded the census's stderr on the one branch where it
was the only actionable output, so a missing analyser exited with stdout **and** stderr empty and
was indistinguishable from a tree with nothing to rank. The hint is relayed, with a regression
test that fails on the previous shape.
- **`comment-tooling-probe.sh`:** both absent-layer cost strings claimed a line-prefix or grep
fallback that `comment-census.py` explicitly never performs. They now state the real
consequence: the census and the ranking cannot run at all.
- **`comment-census.py`:** an empty record set returned exit 0 with all-zero totals whether the
scope was empty or no analyser was installed, so a later count read as an improvement against a
baseline that was never measured. Layer availability is probed directly now. `unread=True` was
written and never read; unread files are counted and reported.
- **`dissolve-comments`, `audit-comment-residue`:** both injected a `${CLAUDE_PLUGIN_ROOT}` script
that no grant this repo permits can cover, so under default permissions the injection aborts
before the skill is reached. Both now go through a skill-local exec wrapper with a live
`${CLAUDE_SKILL_DIR}` grant, and `allowed-tools-pairing.test.sh` gained a body-side check for the
class plus coverage of `dissolve-comments`, which it had never checked.
- **`allowed-tools-pairing.test.sh`:** its header taught that `${CLAUDE_PLUGIN_ROOT}` is never
substituted in `allowed-tools` and a grant naming it is inert. That is stale — the token does
substitute in a plugin skill's `allowed-tools` Bash rules
(<https://code.claude.com/docs/en/skills>, fetched 2026-09-07). The gate's requirement stands on
its real reason instead: the docs establish substitution, not runtime matching on every host, and
this repo does not ship a grant on docs alone.
- **`dissolve-comments`:** the new class-C deletion branch contradicted `safe` mode and posture
`conservative`, which promise that only class-A deletions are applied. It is now proposed, never
applied, in both — a verdict reached inside a narrowed mode does not widen it.
- **`dissolve-comments`:** `description` sat at 1024/1024 against the Agent Skills spec field
maximum with zero headroom; trimmed to 978, all trigger phrases preserved.

### Changed

- **`dissolve-comments`:** negative information, operational information and rejected-alternative
rationale are no longer blanket-exempt surfaces. They were simultaneously "never touched, any
mode" in `safety.md` and a class-C criterion-1 pass everywhere else, and the plugin's own eval 13
requires rewriting rejected-alternative narrative to the budget. They are now class C with a
raised evidence bar, held to the same test and budget as any class-C comment.
- **`dissolve-comments`:** the one-directional posture ladder is documented — `strict` is both
default and ceiling — and class B's apply capacity (2 of 15 moves without a test net, 0 of 15
with tree-sitter absent, no move dissolves a why) is stated where class B is introduced rather
than left to be inferred from a zero result.
- **`dissolve-comments`:** scope reporting lists every dropped path with its reason instead of a
per-reason tally only; steps 1, 4 and 7 have explicit exit-3 stops so a missing analyser can no
longer surface as a `+0` delta; `safety.md` documents `change-shape.py`'s exit 2 and the 13 of 28
in-scope extensions no grammar covers; the over-budget escape clause requires a reason **per
comment**, not per category.
- **`dissolve-comments`:** reference-file paths are relative to the plugin rather than
`${CLAUDE_PLUGIN_ROOT}`, which is substituted in `SKILL.md` but arrives literal in a reference
file read through the Read tool.

## [0.16.3]

### Changed
Expand Down
30 changes: 26 additions & 4 deletions plugins/code-tidying/scripts/allowed-tools-pairing.test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,18 @@
# non-interpreter-led AND live. Quoting counts too: an unquoted rule does not
# match a quoted body path, which is how one grant in this repo shipped dead.
#
# `${CLAUDE_SKILL_DIR}` is the only skill-relative token substituted in
# `allowed-tools`; `${CLAUDE_PLUGIN_ROOT}` stays a literal string there and the
# grant is inert.
# This gate requires `${CLAUDE_SKILL_DIR}` in a grant, and that is a repo
# convention rather than a platform limit. `${CLAUDE_PLUGIN_ROOT}` DOES
# substitute in a plugin skill's `allowed-tools` Bash rules
# (<https://code.claude.com/docs/en/skills>, fetched 2026-09-07: "In a plugin
# skill, Claude Code substitutes `${CLAUDE_PLUGIN_ROOT}` and
# `${CLAUDE_PLUGIN_DATA}` in the same two places"), so the older "the token is
# inert there" reason is stale and is not why this rule exists. The reason it
# still holds: the docs establish substitution, not that such a rule matches at
# runtime on every host, and this repo does not ship a grant on docs alone
# (`plugins/discovery/reference/parent-contract.md`). Until a runtime check
# exists, the skill-local path is the exercised shape — reachable from a shared
# `scripts/` location through a thin exec wrapper.
#
# SC2016 is disabled file-wide on purpose. Every single-quoted `${…}` here is a
# fixed string searched for VERBATIM in markdown and frontmatter, where those
Expand All @@ -24,7 +33,7 @@ set -uo pipefail

cd "$(dirname "${BASH_SOURCE[0]}")/.." || exit 1

SKILLS=(tidy audit-comment-residue audit-dead-code)
SKILLS=(tidy audit-comment-residue audit-dead-code dissolve-comments)

# Optional per-skill allowlist, space-separated and sorted. When a skill names
# one, the granted set must equal it EXACTLY — this is the guard for a
Expand Down Expand Up @@ -82,6 +91,19 @@ for skill in "${SKILLS[@]}"; do
if grep -qF '"${CLAUDE_SKILL_DIR}/scripts/' "$f"; then
fail "$f: body quotes the bundled-script path — an unquoted rule will not match it"
fi
# An injected ${CLAUDE_PLUGIN_ROOT} script is unmatched by any grant this
# gate permits, so under default permissions the injection aborts before
# Claude sees the skill. The grant-side checks above cannot catch it — the
# grant is simply absent — which is how two skills shipped an ungranted
# injection while this gate passed green. Route the shared script through a
# skill-local exec wrapper instead. (Not because the token fails to
# substitute; see the header. It is that this repo grants only the shape
# whose runtime matching is exercised.)
if grep -qE '!`[^`]*\$\{CLAUDE_PLUGIN_ROOT\}/scripts/' "$f"; then
fail "$f: body injects a \${CLAUDE_PLUGIN_ROOT} script no permitted grant covers — add a \${CLAUDE_SKILL_DIR}/scripts wrapper"
else
pass "$(basename "$f"): no ungrantable \${CLAUDE_PLUGIN_ROOT} injection"
fi
done

# Each granted script must exist, be executable, and be invoked by the body —
Expand Down
53 changes: 49 additions & 4 deletions plugins/code-tidying/scripts/comment-census.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,31 @@ def scc_counts(files: list[Path]) -> dict[str, dict] | None:
return by_path


def pygments_available() -> bool:
"""Whether the pygments layer can be used at all, independent of any file.

`pygments_counts` answers this only as a side effect of reading a file, so a
scope with no readable files cannot distinguish "nothing to read" from "no
analyser installed" without asking separately.
"""
try:
import pygments # noqa: F401
except ImportError:
return False
return True


def scc_available() -> bool:
"""Whether the scc layer can be used at all, independent of any file.

The counterpart to `pygments_available`, and needed for the same reason:
`scc_counts` returns None both when the binary is missing AND when the file
list is empty, so its result cannot answer "is scc installed" on an empty
scope. Reusing it as that proxy reports an installed scc as unavailable.
"""
return shutil.which("scc") is not None


def pygments_counts(path: Path) -> dict | None:
try:
from pygments import lex
Expand Down Expand Up @@ -198,7 +223,8 @@ def sha256_of(path: Path) -> str:


def census(files: list[Path], layer: str) -> tuple[list[dict], dict]:
scc = scc_counts(files) if layer in ("auto", "scc") else None
use_scc = layer in ("auto", "scc")
scc = scc_counts(files) if use_scc else None
use_pygments = layer in ("auto", "pygments")
records = []
sources = {"lines": None, "bytes": None, "complexity": None}
Expand Down Expand Up @@ -233,12 +259,21 @@ def census(files: list[Path], layer: str) -> tuple[list[dict], dict]:
unread=True,
)
records.append(rec)
if not records:
return [], sources
if sources["lines"] is None:
# An empty scope and a missing analyser both yield zero records, and reporting
# the second as a clean zero is the worse error: every later count reads as an
# improvement against a baseline that was never measured. Probe each layer for
# INSTALLED-ness directly. Neither `sources["lines"]` nor the `scc` result can
# answer that here: the first stays None when there was simply nothing to read,
# and `scc_counts` returns None on an empty file list even when the binary is
# present, so using either as the proxy reports an installed analyser as
# missing and turns an empty scope into a false hard stop.
have_layer = (use_scc and scc_available()) or (use_pygments and pygments_available())
if sources["lines"] is None and not have_layer:
return [], {
"error": "neither scc nor pygments is available (install scc, or pip install pygments)"
}
if not records:
return [], sources
return records, sources


Expand All @@ -264,6 +299,10 @@ def totals(records: list[dict], dedupe: bool) -> dict:
"comment_ratio": round(cl / lines, 4) if lines else 0.0,
"comment_bytes": cb,
"approx_tokens": cb // 4,
# Files no analyser could read count 0 comments and 0 lines, which is
# indistinguishable from a genuinely comment-free file in every total
# above. Carry the count so the report can say the coverage is partial.
"unread_files": sum(1 for r in chosen if r.get("unread")),
}


Expand Down Expand Up @@ -310,6 +349,12 @@ def render(report: dict, top: int) -> str:
)
)
out.append("tokens are an estimate: comment_bytes / 4")
unread = report["deduped"].get("unread_files", 0)
if unread:
out.append(
f"NOTE: {unread} file(s) no analyser could read are counted as 0 comments — "
"the totals above are a floor, not a measurement, for those files"
)
out.append("")
out.append("language\tfiles\tcomment_lines\tlines\tratio\tcomment_bytes")
for r in report["by_language"]:
Expand Down
4 changes: 2 additions & 2 deletions plugins/code-tidying/scripts/comment-tooling-probe.sh
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,13 @@ add_row() { rows="${rows}${1}\t${2}\t${3}\t${4}\n"; }
if have scc; then
add_row count scc present "-"
else
add_row count scc absent "Per-file comment+complexity census and ranking. Falls back to line-prefix counting, which miscounts heredocs and block comments."
add_row count scc absent "The per-file complexity estimate the ranking uses. Census lines and bytes then come from pygments; with pygments absent too, the census and the ranking cannot run at all (exit 3)."
fi

if pyhas pygments; then
add_row extract pygments present "-"
else
add_row extract pygments absent "Accurate per-comment extraction in every language. Falls back to grep, which cannot see trailing or block comments and misreads heredoc bodies as comments."
add_row extract pygments absent "Per-comment byte counts and the token estimate, and correct extraction of trailing, block and heredoc-adjacent comments. With scc absent too, the census and the ranking cannot run at all (exit 3): a line-prefix grep is never substituted, because it counts heredoc bodies and string data as comments."
fi

TS_LANGS=""
Expand Down
7 changes: 6 additions & 1 deletion plugins/code-tidying/scripts/rank-comment-targets.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,10 +124,15 @@ def census_records() -> tuple[dict[str, dict], dict]:
text=True,
check=False,
)
# Relay the census's stderr on the no-layer path too. It names the missing
# layer and the install command, and this branch exits with no stdout, so
# dropping stderr as well left the caller nothing to act on and made a
# missing analyser indistinguishable from a tree with nothing to rank.
if proc.returncode == EXIT_NO_LAYER:
print(proc.stderr, file=sys.stderr, end="")
raise SystemExit(EXIT_NO_LAYER)
if proc.returncode != 0:
print(proc.stderr, file=sys.stderr)
print(proc.stderr, file=sys.stderr, end="")
raise SystemExit(proc.returncode)
rep = json.loads(proc.stdout)
return {os.path.normpath(r["path"]): r for r in rep["files"]}, rep["sources"]
Expand Down
101 changes: 101 additions & 0 deletions plugins/code-tidying/scripts/test_comment_census.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,107 @@ def test_no_layer_exits_3_with_install_hint(self):
finally:
shutil.rmtree(tmp)

def test_empty_scope_with_scc_installed_is_not_reported_as_no_layer(self):
"""An empty scope must not be diagnosed as a missing analyser.

`scc_counts` returns None both when the binary is absent AND when the
file list is empty, so using its result as the availability proxy makes
an installed scc read as "neither scc nor pygments is available" on an
empty scope. SKILL.md step 4 treats exit 3 as a hard stop, so that
aborts a run on a false diagnosis. Stub scc onto PATH and block pygments
so only the availability probe, never the record count, can decide.
"""
tmp = Path(tempfile.mkdtemp())
try:
bin_dir = tmp / "stub-bin"
bin_dir.mkdir()
scc_stub = bin_dir / "scc"
scc_stub.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")
scc_stub.chmod(0o755)
blocked = tmp / "blocked"
blocked.mkdir()
(blocked / "pygments.py").write_text(
'raise ImportError("blocked so only the probe decides")\n',
encoding="utf-8",
)
repo = tmp / "repo"
repo.mkdir()
env = {
k: v for k, v in os.environ.items() if not k.startswith("GIT_CONFIG")
}
env.update(
{
"GIT_AUTHOR_NAME": "t",
"GIT_AUTHOR_EMAIL": "t@x",
"GIT_COMMITTER_NAME": "t",
"GIT_COMMITTER_EMAIL": "t@x",
}
)
subprocess.run(["git", "init", "-q", str(repo)], check=True, env=env)
(repo / "README.md").write_text("# no code file here\n")
subprocess.run(["git", "-C", str(repo), "add", "-A"], check=True, env=env)
subprocess.run(
["git", "-C", str(repo), "commit", "-q", "-m", "init"],
check=True,
env=env,
)
env["PATH"] = f"{bin_dir}{os.pathsep}{env.get('PATH', '')}"
env["PYTHONPATH"] = f"{blocked}{os.pathsep}{env.get('PYTHONPATH', '')}"
p = subprocess.run(
[sys.executable, str(SCRIPT), ".", "--json"],
capture_output=True,
text=True,
check=False,
cwd=str(repo),
env=env,
)
self.assertNotEqual(
p.returncode, 3, f"empty scope misreported as no-layer: {p.stderr}"
)
self.assertNotIn("UNAVAILABLE", p.stderr)
finally:
shutil.rmtree(tmp)

def test_empty_scope_with_no_layer_exits_3(self):
"""The other half of the empty-vs-unavailable split: no layer is still a stop."""
tmp = Path(tempfile.mkdtemp())
try:
repo = tmp / "repo"
repo.mkdir()
env = {
k: v for k, v in os.environ.items() if not k.startswith("GIT_CONFIG")
}
env.update(
{
"GIT_AUTHOR_NAME": "t",
"GIT_AUTHOR_EMAIL": "t@x",
"GIT_COMMITTER_NAME": "t",
"GIT_COMMITTER_EMAIL": "t@x",
"PATH": f"{tmp}{os.pathsep}{Path(shutil.which('git')).parent}",
"PYTHONPATH": str(tmp),
}
)
subprocess.run(["git", "init", "-q", str(repo)], check=True, env=env)
(repo / "README.md").write_text("# no code file here\n")
subprocess.run(["git", "-C", str(repo), "add", "-A"], check=True, env=env)
subprocess.run(
["git", "-C", str(repo), "commit", "-q", "-m", "init"],
check=True,
env=env,
)
p = subprocess.run(
[sys.executable, "-S", str(SCRIPT), ".", "--json"],
capture_output=True,
text=True,
check=False,
cwd=str(repo),
env=env,
)
self.assertEqual(p.returncode, 3, p.stderr)
self.assertIn("UNAVAILABLE", p.stderr)
finally:
shutil.rmtree(tmp)

@unittest.skipUnless(pygments_present(), "pygments not installed")
def test_tracked_subdirectory_target_lists_its_files(self):
# `git ls-files -- <dir>` run from inside <dir> looks for <dir>/<dir> and
Expand Down
Loading