diff --git a/plugins/code-tidying/.claude-plugin/plugin.json b/plugins/code-tidying/.claude-plugin/plugin.json index 83e613faff2..ff99cd9180c 100644 --- a/plugins/code-tidying/.claude-plugin/plugin.json +++ b/plugins/code-tidying/.claude-plugin/plugin.json @@ -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", diff --git a/plugins/code-tidying/CHANGELOG.md b/plugins/code-tidying/CHANGELOG.md index 06e1b826783..0aedd646e3f 100644 --- a/plugins/code-tidying/CHANGELOG.md +++ b/plugins/code-tidying/CHANGELOG.md @@ -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 + (, 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 diff --git a/plugins/code-tidying/scripts/allowed-tools-pairing.test.sh b/plugins/code-tidying/scripts/allowed-tools-pairing.test.sh index a6b5ef1caa5..2b314ef21cf 100755 --- a/plugins/code-tidying/scripts/allowed-tools-pairing.test.sh +++ b/plugins/code-tidying/scripts/allowed-tools-pairing.test.sh @@ -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 +# (, 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 @@ -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 @@ -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 — diff --git a/plugins/code-tidying/scripts/comment-census.py b/plugins/code-tidying/scripts/comment-census.py index cdd6133c594..8cb8879b5c5 100755 --- a/plugins/code-tidying/scripts/comment-census.py +++ b/plugins/code-tidying/scripts/comment-census.py @@ -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 @@ -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} @@ -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 @@ -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")), } @@ -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"]: diff --git a/plugins/code-tidying/scripts/comment-tooling-probe.sh b/plugins/code-tidying/scripts/comment-tooling-probe.sh index 5b36495679e..a2e6ea51260 100755 --- a/plugins/code-tidying/scripts/comment-tooling-probe.sh +++ b/plugins/code-tidying/scripts/comment-tooling-probe.sh @@ -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="" diff --git a/plugins/code-tidying/scripts/rank-comment-targets.py b/plugins/code-tidying/scripts/rank-comment-targets.py index 53be3fc7644..8988b8355ea 100755 --- a/plugins/code-tidying/scripts/rank-comment-targets.py +++ b/plugins/code-tidying/scripts/rank-comment-targets.py @@ -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"] diff --git a/plugins/code-tidying/scripts/test_comment_census.py b/plugins/code-tidying/scripts/test_comment_census.py index d7264521629..f53da3c0eeb 100755 --- a/plugins/code-tidying/scripts/test_comment_census.py +++ b/plugins/code-tidying/scripts/test_comment_census.py @@ -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 -- ` run from inside looks for / and diff --git a/plugins/code-tidying/scripts/test_rank_comment_targets.py b/plugins/code-tidying/scripts/test_rank_comment_targets.py index bb51fd75af1..cdf199f5249 100755 --- a/plugins/code-tidying/scripts/test_rank_comment_targets.py +++ b/plugins/code-tidying/scripts/test_rank_comment_targets.py @@ -204,6 +204,34 @@ def test_outside_git_exits_1(self): p = self.run_rank(cwd=self.tmp) self.assertEqual(p.returncode, 1, p.stderr) + @unittest.skipIf(shutil.which("scc"), "scc on PATH supplies the count layer") + def test_no_layer_relays_the_census_install_hint(self): + """Exit 3 must say why. It used to exit with stdout AND stderr empty. + + The census names the missing analyser and the install command on stderr; + the no-layer branch here dropped it, leaving a caller unable to tell a + missing layer from a tree with nothing to rank. + """ + blocked = self.tmp / "blocked" + blocked.mkdir(exist_ok=True) + (blocked / "pygments.py").write_text( + 'raise ImportError("blocked so the no-layer path is reachable")\n', + encoding="utf-8", + ) + env = dict(os.environ) + env["PYTHONPATH"] = str(blocked) + os.pathsep + env.get("PYTHONPATH", "") + p = subprocess.run( + [sys.executable, str(SCRIPT)], + capture_output=True, + text=True, + check=False, + cwd=str(self.repo), + env=env, + ) + self.assertEqual(p.returncode, 3, p.stderr) + self.assertNotEqual(p.stderr.strip(), "", "exit 3 must not be silent") + self.assertIn("pygments", p.stderr) + class RankNormalisation(unittest.TestCase): """Ties share one rank, so path spelling never moves a score.""" diff --git a/plugins/code-tidying/skills/audit-comment-residue/SKILL.md b/plugins/code-tidying/skills/audit-comment-residue/SKILL.md index 8b01f0e82be..84e49397555 100644 --- a/plugins/code-tidying/skills/audit-comment-residue/SKILL.md +++ b/plugins/code-tidying/skills/audit-comment-residue/SKILL.md @@ -3,7 +3,7 @@ description: "Classify code comments for four residue shapes. History narration argument-hint: "[audit] [target]" user-invocable: true disable-model-invocation: false -allowed-tools: ["Bash(${CLAUDE_SKILL_DIR}/scripts/detect.sh:*)", "Bash(grep:*)", "Bash(head:*)", "Bash(echo:*)"] +allowed-tools: ["Bash(${CLAUDE_SKILL_DIR}/scripts/detect.sh:*)", "Bash(${CLAUDE_SKILL_DIR}/scripts/changed-code-files.sh:*)", "Bash(grep:*)", "Bash(head:*)", "Bash(echo:*)"] shell: bash metadata: workflow-stage: review @@ -26,7 +26,7 @@ contains git. The dated record for that composition claim is the `source-control ## Pre-computed context -Uncommitted code files (empty = none matched or the probe returned nothing): !`bash "${CLAUDE_PLUGIN_ROOT}/scripts/changed-code-files.sh" 10 2>/dev/null || echo "(git status unavailable)"` +Uncommitted code files (empty = none matched or the probe returned nothing): !`${CLAUDE_SKILL_DIR}/scripts/changed-code-files.sh 10 2>/dev/null || echo "(git status unavailable)"` Residue findings (sample): !`${CLAUDE_SKILL_DIR}/scripts/detect.sh 2>/dev/null | grep -E '^(Summary total:|Finding shape:)' | head -20 || echo "none"` ## Purpose diff --git a/plugins/code-tidying/skills/audit-comment-residue/scripts/changed-code-files.sh b/plugins/code-tidying/skills/audit-comment-residue/scripts/changed-code-files.sh new file mode 100755 index 00000000000..aa020276b63 --- /dev/null +++ b/plugins/code-tidying/skills/audit-comment-residue/scripts/changed-code-files.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +# Skill-local entry point for ../../../scripts/changed-code-files.sh. +# +# The grant covering this script names ${CLAUDE_SKILL_DIR}. ${CLAUDE_PLUGIN_ROOT} +# does substitute in a plugin skill's `allowed-tools` Bash rules +# (, fetched 2026-09-07), but the docs do +# not establish 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). The skill-local path is the +# exercised shape; the implementation stays single-source at the plugin root. +set -euo pipefail +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +exec "$here/../../../scripts/changed-code-files.sh" "$@" diff --git a/plugins/code-tidying/skills/audit-comment-residue/scripts/detect.test.sh b/plugins/code-tidying/skills/audit-comment-residue/scripts/detect.test.sh index 9a9b0f8f2f6..ed1d59e7962 100755 --- a/plugins/code-tidying/skills/audit-comment-residue/scripts/detect.test.sh +++ b/plugins/code-tidying/skills/audit-comment-residue/scripts/detect.test.sh @@ -294,9 +294,14 @@ PREVIEW_SCRIPT="$SCRIPT_DIR/../../../scripts/changed-code-files.sh" if [[ ! -f "$SKILL_MD" || ! -f "$PREVIEW_SCRIPT" ]]; then fail "preview surfaces located for parity check" "SKILL.md and scripts/changed-code-files.sh" "missing" else - # shellcheck disable=SC2016 # fixed-string match for the literal ${CLAUDE_PLUGIN_ROOT} in SKILL.md; no expansion wanted. - if ! grep -qF '!`bash "${CLAUDE_PLUGIN_ROOT}/scripts/changed-code-files.sh"' "$SKILL_MD"; then - fail "SKILL.md preview line calls the shared script" "a call through \${CLAUDE_PLUGIN_ROOT}/scripts/changed-code-files.sh" "line shape changed" + # shellcheck disable=SC2016 # fixed-string match for the literal ${CLAUDE_SKILL_DIR} in SKILL.md; no expansion wanted. + # The line now goes through the skill-local exec wrapper, not the shared path + # directly: ${CLAUDE_PLUGIN_ROOT} is never substituted in `allowed-tools`, so + # the grant covering this injection can only name ${CLAUDE_SKILL_DIR}, and an + # injection no grant can match aborts under default permissions. The wrapper + # execs the same shared script this parity check runs, so parity is unchanged. + if ! grep -qF '!`${CLAUDE_SKILL_DIR}/scripts/changed-code-files.sh' "$SKILL_MD"; then + fail "SKILL.md preview line calls the shared script" "a call through \${CLAUDE_SKILL_DIR}/scripts/changed-code-files.sh" "line shape changed" else pass "SKILL.md preview line calls the shared script" diff --git a/plugins/code-tidying/skills/dissolve-comments/SKILL.md b/plugins/code-tidying/skills/dissolve-comments/SKILL.md index fa7ba533589..4768767c1bc 100644 --- a/plugins/code-tidying/skills/dissolve-comments/SKILL.md +++ b/plugins/code-tidying/skills/dissolve-comments/SKILL.md @@ -1,6 +1,7 @@ --- -description: "Enforce self-describing code over a resolved scope (diff, branch, or ranked repository): a three-way comment triage that deletes zero-information comments, dissolves code-expressible comments into names and structure via behavior-preserving refactoring, and keeps only terse, load-bearing comments code cannot express. Deletions and local renames apply behind a token-level proof, other refactors behind a discovered test net, else proposed; 'safe' mode restricts applied edits to removals. Use when: 'dissolve comments', 'remove comments', 'strip agent comments', 'too many comments', 'make it self-documenting', 'make the code expressive', 'comments must earn their keep', after an agent wrote over-commented code. Skip when: read-only residue classification (audit-comment-residue), lane-hunting structural tidyings (tidy), simplification waves (batch-simplify), markdown noise (docs-hygiene audit-noise), adding why-comments (tidy #14). Never touches public-API doc comments, license headers, or machine-read directives." +description: "Enforce self-describing code over a diff, branch, or ranked repository: a three-way comment triage that deletes zero-information comments, dissolves code-expressible ones into names and structure by behavior-preserving refactoring, and keeps only terse, load-bearing comments code cannot express. Deletions and local renames apply behind a token-level proof, other refactors behind a test net, else proposed; 'safe' mode restricts applied edits to removals. Use when: 'dissolve comments', 'remove comments', 'strip agent comments', 'too many comments', 'make it self-documenting', 'make the code expressive', 'comments must earn their keep', after an agent wrote over-commented code. Skip when: read-only residue classification (audit-comment-residue), structural tidyings (tidy), simplification waves (batch-simplify), markdown noise (docs-hygiene audit-noise), adding why-comments (tidy #14). Never touches public-API doc comments, license headers, or machine-read directives." argument-hint: "[safe] [target]" +allowed-tools: ["Bash(${CLAUDE_SKILL_DIR}/scripts/scope-code-files.sh:*)", "Bash(${CLAUDE_SKILL_DIR}/scripts/comment-tooling-probe.sh:*)", "Bash(git branch:*)", "Bash(git log:*)", "Bash(grep:*)", "Bash(echo:*)"] disable-model-invocation: false user-invocable: true shell: bash @@ -25,8 +26,8 @@ contains git. The dated record for that composition claim is the `source-control ## Pre-computed context -Scope (rung, base, count, then a 10-path preview; re-run the script without `--max` for the full set): !`bash "${CLAUDE_PLUGIN_ROOT}/scripts/scope-code-files.sh" --max 10 2>/dev/null || echo "(not a git repository)"` -Tooling layer (present/absent per analysis layer; an absent row names the capability lost): !`bash "${CLAUDE_PLUGIN_ROOT}/scripts/comment-tooling-probe.sh" 2>/dev/null || echo "(probe unavailable)"` +Scope (rung, base, count, then a 10-path preview; re-run the script without `--max` for the full set): !`${CLAUDE_SKILL_DIR}/scripts/scope-code-files.sh --max 10 2>/dev/null || echo "(not a git repository)"` +Tooling layer (present/absent per analysis layer; an absent row names the capability lost): !`${CLAUDE_SKILL_DIR}/scripts/comment-tooling-probe.sh 2>/dev/null || echo "(probe unavailable)"` ## Variables @@ -56,7 +57,12 @@ line budget, and worked examples: [reference/triage.md](reference/triage.md). |---|---|---| | **A, zero/negative information** | Restates adjacent code, obsolete, commented-out code | Delete outright, certified by the token proof | | **B, information code could carry** | The comment compensates for a naming/structure deficiency | Refactor until the comment is superfluous, then delete, never delete first | -| **C, information code cannot carry** | Why/rationale, constraint, warning, contract, negative or operational information | Keep only if load-bearing at the point of reading; held to the line budget, rewritten terser when over it, narrative staged | +| **C, information code cannot carry** | Why/rationale, constraint, warning, contract, negative or operational information | **Kept** when load-bearing at the point of reading and not recoverable where a reader would look; held to the line budget, rewritten terser when over it, narrative staged | +| **C, same test failed** | Inexpressible, but the earn-its-keep test's criterion 2 fails: recoverable from version control, an ADR, or an external source | **Deleted** under `strict`, certified by the same token proof class A uses, narrative staged before the deletion is final; **proposed** under `safe` and `conservative`, which apply class-A deletions only. The negative branch of the class-C test, not a fourth class | + +The two class-C rows are one class and one test — three criteria that must **all** hold — named on +each side, so a comment that fails it has somewhere to go. A criterion-1 failure is not this branch: +expressible is class B, redundant with code that IS present is class A. Class-B moves and their tiers: [reference/dissolving-moves.md](reference/dissolving-moves.md). @@ -69,8 +75,19 @@ Class-B moves and their tiers: [reference/dissolving-moves.md](reference/dissolv | `safe [target]` | **Safe mode**: only class-A deletions are applied; every class-B treatment and class-C rewrite is emitted as a proposal. For codebases whose guardrails you do not know. | Posture `conservative` is safe mode as a standing default; `balanced` keeps the full contract but -reports an over-budget class-C comment instead of rewriting it. In every posture and mode, doubt -keeps the comment: "when uncertain, keep or propose" is doctrine, not timidity. +reports an over-budget class-C comment instead of rewriting it. + +**The posture ladder only descends.** `strict` is both the default and the ceiling; `balanced`, +`conservative` and `safe` each narrow what gets applied, `class_c_max_lines` bottoms out at 1, and +nothing removes more than `strict` does. Deliberate — no knob loosens a gate +([reference/safety.md](reference/safety.md)) — and stated here because a user wanting a more +aggressive pass would otherwise hunt for a setting that does not exist. + +In every posture and mode, doubt keeps the comment: "when uncertain, keep or propose" is doctrine, +not timidity. Doubt means an unresolved *classification*, not a resolved one whose verdict is +delete. A criterion-2 failure established by the step-5 evidence check is not doubt, and the tie- +break does not reinstate it; that rule is what stops the earn-its-keep test from collapsing into +"keep everything". Default mode applies the full contract: class A applies, each deletion certified by a token-level proof that no code changed; class B applies **per its tier**: a function-local rename behind the @@ -78,6 +95,12 @@ same proof (RENAME-ONLY), an additive move behind a discovered test net, an inte move behind the net and proposal-first. Whatever a tier's gate does not pass is proposed. Tiers, the proof tool, the test-discovery procedure, and the mode ladder: [reference/safety.md](reference/safety.md). +**Class B applies less than it looks like it does**, and a run planned around it should know that +first: 2 of 15 moves need no test net, 0 of 15 apply with tree-sitter absent, and no move dissolves +a *why*. Both limits are deliberate — see "Apply capacity" in +[reference/dissolving-moves.md](reference/dissolving-moves.md) for the numbers and what follows +from them. + ## Hard rules - **Never delete information without a landing place.** A class-B comment's information moves into @@ -93,8 +116,10 @@ the proof tool, the test-discovery procedure, and the mode ladder: [reference/sa string-keyed access. A rename applied on its strength is reported with its mapping, never silently. - **Exempt surfaces are invisible to this skill** ([reference/safety.md](reference/safety.md)): public-API doc comments; legal headers; machine-read directives, universal and repo-local; - units, sentinels and suppression justifications; negative and operational information; - `TODO(#issue)` markers; lines carrying `dissolve-comments-ignore`. + units, sentinels and suppression justifications; `TODO(#issue)` markers; lines carrying + `dissolve-comments-ignore`. **Negative and operational information are not on that list** — they + are class C with a raised evidence bar, held to the same test and budget as any class-C comment. + Exempting the category outright would contradict this skill's own eval 13. - **Path exclusions are the plugin's standard tier**, tidy's [exclusions reference](${CLAUDE_PLUGIN_ROOT}/skills/tidy/reference/exclusions.md) GLOBAL HARD list. Agent/enforcement config, CI workflows, hook chains, lint config are never edited. @@ -108,34 +133,59 @@ the proof tool, the test-discovery procedure, and the mode ladder: [reference/sa 1. **Scope.** Resolve targets from the action router. Empty argument: run `scope-code-files.sh` (never the truncated preview), confirm a widening to the repository rung interactively, and take any widened rung in safe mode when non-interactive. On the repository rung, run - `rank-comment-targets.py` and triage in its order. Drop excluded paths and exempt surfaces with a - per-reason tally; check survivors for SSOT/materialized-copy declarations (triage the source, - run its sync, never touch a copy). Done when the file list and the tally are written down. + `rank-comment-targets.py` and triage in its order; **exit 3 from it or from the census means the + analysis layer is missing, never that there is nothing to rank** — relay the script's stderr, + which names the install command, and stop rather than proceeding on an empty ranking. Drop + excluded paths and exempt surfaces, listing **every dropped path with its reason**, not only a + per-reason tally: a count cannot tell the user which file went, and a silently dropped file is + indistinguishable from one that was triaged and kept. Check survivors for SSOT/materialized-copy + declarations (triage the source, run its sync, never touch a copy). Done when the file list, the + per-path drop list, and the tally are written down. 2. **Discover repo-local machine-read markers** before any comment is classified: a marker the repo's own gates read is compiler input that looks like prose. Whole-repository scan, test fixtures treated as live, query form varied before concluding absence ([reference/safety.md](reference/safety.md)). Done when the discovered families, or an explicit "none found", are in the report. 3. **Read the tooling layer** from the probe and state it. The layer sets the ceiling: at grep - precision, a language with heredocs or block comments gets no applied edits. Name each absent + precision a language with heredocs or block comments gets no applied edits, with tree-sitter + absent no deletion or rename carries a proof, and the 13 extensions no grammar covers stay + proposals even when it is present ([reference/safety.md](reference/safety.md)). Name each absent layer's lost capability as the probe phrases it. Done when the layer line is in the report. 4. **Baseline the census.** Run `comment-census.py --json` over the scope and keep the output; it is - the before-figure for the delta in step 7 and for the next pass. Done when the file exists. + the before-figure for the delta in step 7 and for the next pass. **Exit 3 is a stop, not a + zero:** it means neither `scc` nor pygments resolved, so there is no baseline and step 7's delta + is unobtainable. Report the layer, quote the script's install hint, and stop; never continue with + an all-zero baseline, which would report every later count as an improvement. Done when the file + exists, or the run has stopped with the missing layer named. 5. **Triage.** Classify every remaining comment A/B/C per [reference/triage.md](reference/triage.md). Feed `commented-out-code.py` (and Ruff ERA001 on Python, via the repository's pinned wrapper - where one exists) as class-A input. Done when every comment carries exactly one class. + where one exists) as class-A input. + **Criterion 2 is decided on evidence, never on impression.** For every class-C candidate whose + content is rationale, run `git log -L ,:` over its own lines and check the + repo's ADR or decision-log directory where one is declared; recoverable there **fails** the + criterion, absent from both **passes**, unreadable history is recorded as unavailable and keeps + the comment. Full procedure: [reference/triage.md](reference/triage.md). Done when every comment + carries exactly one class and every class-C candidate carries a criterion-2 verdict with the + evidence that produced it. 6. **Apply**, one item at a time, each behind its tier's gate. Class A: delete, run `change-shape.py` on before and after; anything but COMMENT-ONLY (exit 0) restores the comment. - Class B: apply the named move, run the tier's gate, then delete the comment. Class C over - budget: rewrite to the budget under `strict`, stage the narrative; report only under `balanced`. - A failed gate reverts, restores, and demotes to a proposal quoting the verdict. Done when every - item is either applied with its verdict or listed as a proposal with its reason. -7. **Report.** Tooling layer and discovered markers first; then per file: counts per class, applied - versus proposed with each applied item's verdict (and the mapping for every RENAME-ONLY), the - staged commit-message block, the class-C keeps and rewrites with one-line reasons; then the - census delta against step 4 (`comment-census.py --baseline`), in lines, bytes and estimated - tokens. A scope whose every file was dropped reports the tally instead of exiting silently. The - user reviews the diff; this skill does not commit. Done when the delta line is printed. + Class B: apply the named move, run the tier's gate, then delete the comment. Class C that + **failed** the earn-its-keep test: under `strict`, stage the narrative then delete behind the + same COMMENT-ONLY proof class A uses; under `safe` or `conservative`, propose it instead — those + modes apply class-A deletions only, and a rationale comment is not class A however its test + resolved. Class C over budget: rewrite to the budget under `strict`, + stage the narrative; report only under `balanced`. A failed gate reverts, restores, and demotes + to a proposal quoting the verdict. Done when every item is either applied with its verdict or + listed as a proposal with its reason. +7. **Report.** Tooling layer and discovered markers first, then the per-path drop list from step 1; + then per file: counts per class, applied versus proposed with each applied item's verdict (and + the mapping for every RENAME-ONLY), the staged commit-message block, the class-C keeps and + rewrites with one-line reasons, **each keep naming its criterion-2 evidence** from step 5; then + the census delta against step 4 (`comment-census.py --baseline`), in lines, bytes and estimated + tokens. A scope whose every file was dropped reports the tally instead of exiting silently. When + the census could not run, say so in place of the delta line and name the missing layer — an + absent delta is never reported as `+0`. The user reviews the diff; this skill does not commit. + Done when the delta line, or the explicit reason there is none, is printed. ## What this skill is NOT diff --git a/plugins/code-tidying/skills/dissolve-comments/reference/dissolving-moves.md b/plugins/code-tidying/skills/dissolve-comments/reference/dissolving-moves.md index 9faeb12c3f9..63f9867c65d 100644 --- a/plugins/code-tidying/skills/dissolve-comments/reference/dissolving-moves.md +++ b/plugins/code-tidying/skills/dissolve-comments/reference/dissolving-moves.md @@ -43,3 +43,24 @@ net; interface-creating moves need a test net and stay proposals in non-interact - **Renames have blast radius.** Change Function Declaration / Rename on anything referenced outside the run's scope needs every call site updated in the same pass; if references cannot be fully resolved (dynamic dispatch, reflection, string-based lookup), demote to a proposal. + +## Apply capacity — what class B can actually change on a given repository + +Class B reads like the skill's main engine. On many repositories it turns over nothing, and a run +planned around it should know the three limits up front. All three are deliberate. + +- **2 of the 15 moves need no test net.** Only Rename Variable and Rename Field are tier 1, and + only on a *function-local* identifier. Every other move adds tokens, so the token proof reports + CODE-CHANGED by construction ([safety.md](safety.md)) and a discovered test net is required; + without one they are proposed, never applied. +- **0 of 15 apply with tree-sitter absent.** The proof is unavailable, so "tier 1 without its proof + is tier 2" ([safety.md](safety.md)) demotes the two renames into the test-net tier with + everything else. On a repository with neither a runnable test net nor tree-sitter, a class-B pass + produces a proposal list and no edits. +- **No move dissolves a why.** Names carry what and how, not why — the cost curve above says a name + that grows to carry rationale is a dishonest name. Rationale therefore never leaves through + class B; it is decided by the class-C earn-its-keep test, which `SKILL.md` step 5 evaluates on + evidence. + +The consequence worth stating plainly: on a rationale-dense codebase a class-B count of zero is the +expected result, not a sign the pass failed to look. diff --git a/plugins/code-tidying/skills/dissolve-comments/reference/safety.md b/plugins/code-tidying/skills/dissolve-comments/reference/safety.md index c29e1633790..f0e1cede4cf 100644 --- a/plugins/code-tidying/skills/dissolve-comments/reference/safety.md +++ b/plugins/code-tidying/skills/dissolve-comments/reference/safety.md @@ -11,8 +11,13 @@ behavior, while a token comparison is exhaustive over the file. | Mode | Class A | Class B | Class C | |---|---|---|---| -| **Default** | Applied, each deletion certified by the tier-0 proof | Applied per the tier table below; otherwise proposed | Earn-its-keep triage; narrative staging | -| **`safe`** | Applied, same certification | Always proposed — no code-structure change is applied | Same triage; deletions of pure narrative still apply, with staging | +| **Default** | Applied, each deletion certified by the tier-0 proof | Applied per the tier table below; otherwise proposed | Earn-its-keep triage; a criterion-2 failure is deleted behind the tier-0 proof, an over-budget comment rewritten; narrative staged before either | +| **`safe`** | Applied, same certification | Always proposed — no code-structure change is applied | Same triage, but **nothing class-C is applied**: a criterion-2 deletion and an over-budget rewrite are both proposed, with the narrative staged. Only class A deletes here | + +`conservative` is `safe` as a standing default, so it reads the `safe` row. The class-C column is +the one to get right: the triage still runs in every mode and still returns a verdict, but a +verdict is not an application. `safe` narrowing class C to proposals is what makes "only class-A +deletions are applied" in the action router true rather than approximately true. In **no mode** does the skill: apply an edit whose tier gate did not pass, touch an exempt surface or excluded path, or delete text without a landing place (staging rule below). @@ -26,12 +31,24 @@ or excluded path, or delete text without a landing place (staging rule below). | **2** | Additive local move: Extract Variable, Replace Magic Literal, Introduce Assertion, Slide Statements, Decompose Conditional | discovered test net, run before and after | These add tokens, so the token proof reports CODE-CHANGED by construction and cannot certify them. Only tests attest behavior preservation here | | **3** | Interface-creating move: Extract Function, Change Function Declaration, Extract Class, Introduce Parameter Object, Move Statements into Function, Replace Inline Code with Function Call | discovered test net, and **always a proposal in a non-interactive run** | Creates or renames an interface other code depends on. Ousterhout (APOSD §9.8) and Anthropic's own overeagerness guidance both warn against automating exactly this; the test net is necessary, not sufficient | -`change-shape.py` is at `${CLAUDE_PLUGIN_ROOT}/scripts/change-shape.py` and carries its verdict in +`change-shape.py` is at `../../../scripts/change-shape.py` (relative to this file; the +`${CLAUDE_PLUGIN_ROOT}` token is substituted in `SKILL.md` but **not** in a reference file, which +arrives through the Read tool with the placeholder intact) and carries its verdict in the exit code: 0 COMMENT-ONLY, 10 RENAME-ONLY, 20 CODE-CHANGED, 21 UNPROVABLE, 3 tooling -unavailable. Run it against the file's content before and after each edit, and before the comment -is deleted. Any verdict other than the tier's required one reverts the edit and demotes the item to -a proposal that quotes the verdict, including which token kinds differed. UNPROVABLE (a parse -error on either side) is a revert, never a pass. +unavailable, **2 no grammar mapping for the file's extension** (or a usage error). Run it against +the file's content before and after each edit, and before the comment is deleted. Any verdict other +than the tier's required one reverts the edit and demotes the item to a proposal that quotes the +verdict, including which token kinds differed. UNPROVABLE (a parse error on either side) is a +revert, never a pass, and so is exit 2: an unmapped extension is an *unproven* edit, never a +tacit pass. + +**Exit 2 is the common case on a mixed-language repository, not an edge case.** `CODE_EXT` in +`scope-code-files.sh` admits 28 extensions; `change-shape.py` maps 15 of them and +`commented-out-code.py` 11, and their union is 15. The 13 with no grammar in either — +`.c .cpp .go .h .hpp .java .lua .ps1 .psm1 .rb .rs .sql .toml` — reach triage normally and then +have **no** applicable tier-0 or tier-1 proof, so every deletion and rename in them is a proposal. +Say so in the report rather than reporting those files as clean: a file nothing could prove is not +a file with nothing to fix. When tree-sitter is unavailable (exit 3), tier 0 falls back to whatever reading layer the tooling probe reported: a pygments-level read may still apply deletions; a grep-level read applies nothing @@ -70,13 +87,40 @@ open the apply path, because they cannot attest behavior preservation. - Suppression justifications: the reason attached to a lint waiver, a cast-safety claim, or a narrowing assertion (`@SuppressWarnings("unchecked") // safe because …`). The waiver is a directive and the reason is what makes it reviewable. Removing either breaks the pair +- `TODO(#issue)` / `FIXME(#issue)` markers tracking real work +- Lines carrying `dissolve-comments-ignore` (on the line or the line immediately before) + +## Not exempt, but the highest-cost misclassification: route to class C + +These three are **not** on the list above, and the distinction is deliberate. They are not +machine-read, not legal, and not a contract another tool consumes; they are prose that a reader +needs, which makes them class C — subject to the earn-its-keep test and the line budget like any +other class-C comment, not exempt from them. + - **Negative information**: what the code deliberately does NOT do, and why an alternative was rejected. This class has no referent in the adjacent code, which gives it the same surface signature as a stale comment. It is the tool's most likely false positive. See the gotcha below - **Operational information**: how this component fits the wider system. By construction it cannot live in the code of an encapsulated unit without breaking that encapsulation -- `TODO(#issue)` / `FIXME(#issue)` markers tracking real work -- Lines carrying `dissolve-comments-ignore` (on the line or the line immediately before) +- Rejected-alternative rationale, the narrative form of the first bullet + +**What "route to class C" buys them**, and what it does not. Each passes criterion 1 automatically: +none of it is expressible in a name, a type, or an assertion, so no class-B move applies and a +class-A deletion is never correct. Criteria 2 and 3 still bind. A rejected alternative recorded +nowhere else is load-bearing and is kept. The same rationale already in the commit that made the +change, an ADR, or a linked issue fails criterion 2. Twelve lines of narrative about three +alternatives exceeds the budget and is *rewritten* to the durable constraint with the narrative +staged, which is exactly what the skill's own eval 13 asserts. + +Treating the whole category as untouchable instead would contradict that eval, and would contradict +the class-C test in [triage.md](triage.md), which the skill body applies to precisely this content. +The discriminator the design uses is the **budget, not the category**. + +Because this class is the likeliest false positive, its evidence bar is raised rather than lowered: +a criterion-2 failure here needs the alternative recorded *somewhere a reader would actually reach* +— a commit message, an ADR, a linked issue — and "it is probably in the history" is not that. Where +a repository pairs such a comment with a regression test, the comment is half of a two-part record +and is kept; see the gotcha below. ### Repo-local machine-read markers: discover, never assume @@ -118,7 +162,7 @@ default rather than betting deletion on a clean discovery pass. ## Path exclusions The canonical baseline is the plugin's standard tier — tidy's -[exclusions reference](${CLAUDE_PLUGIN_ROOT}/skills/tidy/reference/exclusions.md), GLOBAL HARD +[exclusions reference](../../tidy/reference/exclusions.md), GLOBAL HARD list: the whole `.claude/**` tree plus any script wired as a hook command in `.claude/settings.json` or `.claude/settings.local.json` (wherever it lives), other agents' config bundles, `.github/workflows/**` and CI surface, git-hook manager config, cross-ecosystem diff --git a/plugins/code-tidying/skills/dissolve-comments/reference/scope.md b/plugins/code-tidying/skills/dissolve-comments/reference/scope.md index 6e57abcf9ed..f3fc9d6a71d 100644 --- a/plugins/code-tidying/skills/dissolve-comments/reference/scope.md +++ b/plugins/code-tidying/skills/dissolve-comments/reference/scope.md @@ -1,7 +1,12 @@ # Scope — the empty-argument ladder, resolved by script -`${CLAUDE_PLUGIN_ROOT}/scripts/scope-code-files.sh` resolves the ladder deterministically and prints -the rung it landed on, the base it compared against, the count, and the paths: +The plugin's `scripts/scope-code-files.sh` (`../../../scripts/scope-code-files.sh` from this file) +resolves the ladder deterministically and prints the rung it landed on, the base it compared +against, the count, and the paths: + +> Paths in this file are written relative to the plugin, not as `${CLAUDE_PLUGIN_ROOT}`. That token +> is substituted in `SKILL.md`, which Claude Code loads as skill content, but **not** in a reference +> file, which arrives through the Read tool with the placeholder intact. ```text rung= base= files= @@ -30,7 +35,7 @@ get read, and the tier-0 proof in [safety.md](safety.md) makes each deletion saf which commit introduced the comment. On the `repository` rung, order the files with -`${CLAUDE_PLUGIN_ROOT}/scripts/rank-comment-targets.py` before triage. Its ranking is a reading +`../../../scripts/rank-comment-targets.py` before triage. Its ranking is a reading order and never evidence: a high rank says look here first, not that a comment there is wrong. Byte-identical files collapse to one row with an `instances` count; triage the canonical copy and run its declared sync afterwards, never a copy. diff --git a/plugins/code-tidying/skills/dissolve-comments/reference/sources.md b/plugins/code-tidying/skills/dissolve-comments/reference/sources.md index 54898bd7084..d6e4718e695 100644 --- a/plugins/code-tidying/skills/dissolve-comments/reference/sources.md +++ b/plugins/code-tidying/skills/dissolve-comments/reference/sources.md @@ -37,4 +37,4 @@ not a scoped rule. licensed, which is why every treatment here is per comment. Ranking and census sources are listed in [tooling.md](tooling.md) and in the header of -`${CLAUDE_PLUGIN_ROOT}/scripts/rank-comment-targets.py`. +`../../../scripts/rank-comment-targets.py`. diff --git a/plugins/code-tidying/skills/dissolve-comments/reference/tooling.md b/plugins/code-tidying/skills/dissolve-comments/reference/tooling.md index d1a7013f2b0..70aba7d8a80 100644 --- a/plugins/code-tidying/skills/dissolve-comments/reference/tooling.md +++ b/plugins/code-tidying/skills/dissolve-comments/reference/tooling.md @@ -1,6 +1,6 @@ # Tooling — the reading layers, what each proves, how to get it -`dissolve-comments` never assumes a tool. `${CLAUDE_PLUGIN_ROOT}/scripts/comment-tooling-probe.sh` +`dissolve-comments` never assumes a tool. `../../../scripts/comment-tooling-probe.sh` asks the environment at scope time and the run states the layer it operated at. Every layer is optional; each row below names what its absence costs, so the reader can decide whether to install it. The consumer's own `.claude/ecosystems/*.yaml` (the ecosystem-commands convention) is read as an diff --git a/plugins/code-tidying/skills/dissolve-comments/reference/triage.md b/plugins/code-tidying/skills/dissolve-comments/reference/triage.md index ee8729db623..5cadab86359 100644 --- a/plugins/code-tidying/skills/dissolve-comments/reference/triage.md +++ b/plugins/code-tidying/skills/dissolve-comments/reference/triage.md @@ -1,9 +1,11 @@ # The three-way triage -Every comment in scope gets exactly one class. The classes have **different tests** — class A is -judged on information content, class B on expressibility, class C on necessity — and conflating -them applies the wrong treatment. The classic failure is deleting a class-B comment as if it were -class A: that destroys information the code was supposed to absorb first. +Every comment in scope gets exactly one class, and every class has a treatment on **both** sides of +its test — a comment that fails class C's test is deleted, not kept for want of a branch. The +classes have **different tests** — class A is judged on information content, class B on +expressibility, class C on necessity — and conflating them applies the wrong treatment. The classic +failure is deleting a class-B comment as if it were class A: that destroys information the code was +supposed to absorb first. ## Class A — zero or negative information: delete outright @@ -49,14 +51,36 @@ A comment survives only if **all three** hold: *at this location*. Rationale discoverable from context or version control does not need restating here; a constraint whose violation silently breaks something does, because blame trails are fragile across refactors. + **Decide this on evidence, not impression.** Step 5 of the workflow runs + `git log -L ,:` over the comment's own lines (or `git log -S` on a distinctive + phrase) and checks the repo's ADR or decision-log directory where one is declared. A rationale a + reader would find there **fails** this criterion; one absent from both, or whose commit trail + restates only what the diff already shows, **passes**. History that cannot be read (shallow + clone, unreadable blame) is recorded as unavailable and the comment is kept. Note the carve-out + in the sentence above is about *constraints*, not rationale: a silent-breakage constraint is + restated here even when history also carries it, and rationale gets no such exception. 3. **Within the line budget.** A kept comment is held to `class_c_max_lines` (default 2, from the plugin's user config). Over budget, the treatment is Henney's second verb, *rewritten*: keep the durable constraint in one or two lines, stage the narrative for the commit message ([safety.md](safety.md)), delete the rest. A genuinely load-bearing multi-line contract (a regex explanation, a concurrency invariant, a rejected-alternative record paired with a regression - test) may exceed the budget when the report says why in one line. What never survives is - length spent on justification narrative. Posture `balanced` reports an over-budget comment - instead of rewriting it; `conservative` proposes the rewrite. + test) may exceed the budget when the report says why in one line **for that comment**, naming + it by file and line. A single reason covering a category, a file, or a batch does not satisfy + this and does not license the keeps under it: the per-comment sentence is the cost that keeps + the exception rare. What never survives is length spent on justification narrative. Posture + `balanced` reports an over-budget comment instead of rewriting it; `conservative` proposes the + rewrite. + +**When the test fails.** A comment that passes criterion 1 and fails criterion 2 is **deleted** +under `strict`, behind the same COMMENT-ONLY token proof class A uses, with its narrative staged +first per [safety.md](safety.md). It is not reclassified as class A — class A is redundancy with +code that is present, and this comment is not redundant — and it is not kept for want of a branch. +Criterion 3 has its own treatment, the rewrite above; only criterion 2 sends a comment to deletion. + +Under `safe` mode and posture `conservative` this deletion is **proposed, never applied**. Those +modes apply class-A deletions only, and a comment that reached this branch is class C whatever its +test returned — the mode ladder narrows what is applied, and it does not get to be widened by a +verdict reached inside it. A rewrite is an edit with a gate: the comment's replacement text is checked by `change-shape.py` like any deletion (COMMENT-ONLY, since only comment tokens changed), and the @@ -88,4 +112,6 @@ before the deletion is final — see [safety.md](safety.md). | `// check if the order qualifies for the discount` above 6 lines of conditions | B | Extract Function `QualifiesForDiscount(order)`, test, delete | | `// 86400 = seconds per day` | B | Replace Magic Literal `SecondsPerDay`, delete | | `// items must stay sorted; binary search below depends on it` | C | Keep (constraint, load-bearing, terse) | -| 12-line comment explaining why approach X was chosen over Y | C-adjacent narrative | Extract any durable constraint to one line; stage the narrative for the commit message; delete the rest | +| `// we retry twice here because the upstream 502s on cold start`, and the commit that added it says exactly that | C, criterion 2 fails | Stage the narrative, delete behind the COMMENT-ONLY proof (recoverable where a reader would look) | +| `// this is NOT thread-safe; callers serialize`, recorded nowhere else | C | Keep (negative information, load-bearing, terse — not exempt, but it passes the test) | +| 12-line comment explaining why approach X was chosen over Y | C, criterion 3 fails | Extract any durable constraint to one line; stage the narrative for the commit message; delete the rest | diff --git a/plugins/code-tidying/skills/dissolve-comments/scripts/comment-tooling-probe.sh b/plugins/code-tidying/skills/dissolve-comments/scripts/comment-tooling-probe.sh new file mode 100755 index 00000000000..fe0b1132547 --- /dev/null +++ b/plugins/code-tidying/skills/dissolve-comments/scripts/comment-tooling-probe.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# Skill-local entry point for ../../../scripts/comment-tooling-probe.sh. +# +# Same reason as the sibling wrapper: the grant names ${CLAUDE_SKILL_DIR} +# because that shape's runtime matching is already exercised here, not because +# ${CLAUDE_PLUGIN_ROOT} fails to substitute — it does substitute in a plugin +# skill's `allowed-tools`. See scope-code-files.sh for the citation. +set -euo pipefail +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +exec "$here/../../../scripts/comment-tooling-probe.sh" "$@" diff --git a/plugins/code-tidying/skills/dissolve-comments/scripts/scope-code-files.sh b/plugins/code-tidying/skills/dissolve-comments/scripts/scope-code-files.sh new file mode 100755 index 00000000000..1678ff1bda5 --- /dev/null +++ b/plugins/code-tidying/skills/dissolve-comments/scripts/scope-code-files.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# Skill-local entry point for ../../../scripts/scope-code-files.sh. +# +# The grant that covers this script names ${CLAUDE_SKILL_DIR}, not the shared +# plugin-root path. ${CLAUDE_PLUGIN_ROOT} does substitute in a plugin skill's +# `allowed-tools` Bash rules (, 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 token is not the +# obstacle it once was. What the docs do not establish is that such a rule +# matches at runtime on every host, and this repo's standing position is not to +# ship a grant on docs alone (plugins/discovery/reference/parent-contract.md). +# The skill-local path is the shape whose matching is already exercised here, so +# it is what the grant names, while the implementation stays single-source at +# the plugin root — one file to change, and no copy to drift. +set -euo pipefail +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +exec "$here/../../../scripts/scope-code-files.sh" "$@"