diff --git a/plugins/generic/src/habit_hooks_generic/guides/unused-class-member.md b/plugins/generic/src/habit_hooks_generic/guides/unused-class-member.md
new file mode 100644
index 00000000..17b78b71
--- /dev/null
+++ b/plugins/generic/src/habit_hooks_generic/guides/unused-class-member.md
@@ -0,0 +1,19 @@
+An unused field, method, or property is dead surface that makes a type appear to
+have responsibilities and collaborations it does not exercise. It asks readers
+to understand and maintain behavior that may not exist.
+
+Investigate every occurrence before changing it. Static analysis may not see
+reflection, annotations or decorators, serialization, framework lifecycle
+hooks, dependency injection, generated callers, or other dynamic uses. When one
+of those mechanisms owns the call, preserve the member and make that use legible
+to the detector or future readers.
+
+Once those hidden uses are ruled out, choose the design that makes the type
+honest: connect an intended caller, extract a cohesive group of members into a
+real unit, or remove a member confirmed to be dead together with code that
+exists only to support it. Do not remove a member automatically from this
+report alone.
+
+The unused members:
+
+{% include "includes/line_level_issues.md" %}
diff --git a/plugins/java/docs/java-plugin.spec.md b/plugins/java/docs/java-plugin.spec.md
index ec36e239..1a20ca4b 100644
--- a/plugins/java/docs/java-plugin.spec.md
+++ b/plugins/java/docs/java-plugin.spec.md
@@ -66,6 +66,39 @@ habit-sensors --all | jq 'sort_by(.smell)[] | {smell, language, key: (.issues[0]
}
```
+## bundled PMD reports unused private fields and methods
+
+The fallback ruleset enables PMD's `UnusedPrivateField` and
+`UnusedPrivateMethod` rules. Both translate to one `unused-class-member`
+finding. The referenced field and method are controls: PMD does not report them.
+
+đź“„Members.java
+```java
+class Members {
+ private int staleField = 1;
+ private int liveField = 2;
+ private void staleMethod() {}
+ private int liveMethod() { return liveField; }
+ int value() { return liveMethod(); }
+}
+```
+
+```bash
+habit-sensors --all | jq '.[] | select(.smell == "unused-class-member") | {smell, language, sources: [.issues[].details.source]}'
+```
+
+🖥️ ✅
+```json
+{
+ "smell": "unused-class-member",
+ "language": "java",
+ "sources": [
+ "pmd:UnusedPrivateField",
+ "pmd:UnusedPrivateMethod"
+ ]
+}
+```
+
## pmd sensor reports the third nested if from the bundled ruleset
With no PMD ruleset in the project, the plugin's bundled fallback explicitly
diff --git a/plugins/java/src/habit_hooks_java/sensors/pmd-ruleset.xml b/plugins/java/src/habit_hooks_java/sensors/pmd-ruleset.xml
index 188791eb..c8fb1434 100644
--- a/plugins/java/src/habit_hooks_java/sensors/pmd-ruleset.xml
+++ b/plugins/java/src/habit_hooks_java/sensors/pmd-ruleset.xml
@@ -18,6 +18,8 @@
+
+
diff --git a/plugins/java/src/habit_hooks_java/sensors/pmd_sensor.py b/plugins/java/src/habit_hooks_java/sensors/pmd_sensor.py
index ec1e14b4..b5914e75 100644
--- a/plugins/java/src/habit_hooks_java/sensors/pmd_sensor.py
+++ b/plugins/java/src/habit_hooks_java/sensors/pmd_sensor.py
@@ -40,6 +40,8 @@
"CyclomaticComplexity": "high-complexity",
"NcssCount": "oversized-function",
"UnusedLocalVariable": "unused-variable",
+ "UnusedPrivateField": "unused-class-member",
+ "UnusedPrivateMethod": "unused-class-member",
"UnnecessaryImport": "unused-import",
"EmptyCatchBlock": "swallowed-exception",
}
@@ -105,16 +107,32 @@ def smell_of(entry: dict) -> str | None:
return RULE_SMELLS.get(rule)
-def issue(entry: dict) -> dict:
+def source_line(entry: dict) -> str | None:
violation = entry["violation"]
+ try:
+ line = Path(entry["file"]).read_text(
+ encoding="utf-8", errors="replace"
+ ).splitlines()[violation["beginline"] - 1]
+ except (OSError, IndexError):
+ return None
+ return line.strip() or None
+
+
+def issue(entry: dict, smell: str) -> dict:
+ violation = entry["violation"]
+ details = {
+ "file": entry["file"],
+ "line": violation["beginline"],
+ "message": violation["description"],
+ "source": "pmd:" + violation["rule"],
+ }
+ if smell == "unused-class-member":
+ content = source_line(entry)
+ if content is not None:
+ details["content"] = content
return {
"key": entry["file"],
- "details": {
- "file": entry["file"],
- "line": violation["beginline"],
- "message": violation["description"],
- "source": "pmd:" + violation["rule"],
- },
+ "details": details,
}
@@ -123,7 +141,7 @@ def findings(entries: list[dict]) -> list[dict]:
for entry in entries:
smell = smell_of(entry)
if smell is not None:
- by_smell.setdefault(smell, []).append(issue(entry))
+ by_smell.setdefault(smell, []).append(issue(entry, smell))
return [
{"smell": smell, "details": {}, "issues": issues}
for smell, issues in by_smell.items()
diff --git a/plugins/java/tests/test_bundled_ruleset_declares_its_contract.py b/plugins/java/tests/test_bundled_ruleset_declares_its_contract.py
index e1e99e08..46153dc7 100644
--- a/plugins/java/tests/test_bundled_ruleset_declares_its_contract.py
+++ b/plugins/java/tests/test_bundled_ruleset_declares_its_contract.py
@@ -14,6 +14,10 @@
)
PMD_NAMESPACE = {"pmd": "http://pmd.sourceforge.net/ruleset/2.0.0"}
DEEP_NESTING_RULE = "category/java/design.xml/AvoidDeeplyNestedIfStmts"
+UNUSED_PRIVATE_MEMBER_RULES = (
+ "category/java/bestpractices.xml/UnusedPrivateField",
+ "category/java/bestpractices.xml/UnusedPrivateMethod",
+)
def test_the_bundled_ruleset_explicitly_reports_the_third_nested_if() -> None:
@@ -31,3 +35,16 @@ def test_the_bundled_ruleset_explicitly_reports_the_third_nested_if() -> None:
)
assert len(problem_depth) == 1
assert problem_depth[0].get("value") == "3"
+
+
+def test_the_bundled_ruleset_enables_pmds_unused_private_member_defaults() -> None:
+ root = ElementTree.parse(RULESET).getroot()
+
+ rules = [
+ rule
+ for rule in root.findall("pmd:rule", PMD_NAMESPACE)
+ if rule.get("ref") in UNUSED_PRIVATE_MEMBER_RULES
+ ]
+
+ assert [rule.get("ref") for rule in rules] == list(UNUSED_PRIVATE_MEMBER_RULES)
+ assert all(len(rule) == 0 for rule in rules)
diff --git a/plugins/java/tests/test_class_level_metric_violations_are_dropped.py b/plugins/java/tests/test_class_level_metric_violations_are_dropped.py
index 55e286d9..80d2af99 100644
--- a/plugins/java/tests/test_class_level_metric_violations_are_dropped.py
+++ b/plugins/java/tests/test_class_level_metric_violations_are_dropped.py
@@ -127,3 +127,40 @@ def test_a_class_level_violation_never_reaches_findings() -> None:
assert len(result) == 1
assert result[0]["smell"] == "high-complexity"
assert len(result[0]["issues"]) == 1
+
+
+def test_unused_private_members_preserve_opaque_pmd_diagnostics() -> None:
+ entries = [
+ _entry("UnusedPrivateField", "Field is retained only by custom wiring", 7),
+ _entry("UnusedPrivateMethod", "Lifecycle entry point is never invoked", 11),
+ ]
+
+ result = findings(entries)
+
+ assert result == [
+ {
+ "smell": "unused-class-member",
+ "details": {},
+ "issues": [
+ {
+ "key": "Fat.java",
+ "details": {
+ "file": "Fat.java",
+ "line": 7,
+ "message": "Field is retained only by custom wiring",
+ "source": "pmd:UnusedPrivateField",
+ },
+ },
+ {
+ "key": "Fat.java",
+ "details": {
+ "file": "Fat.java",
+ "line": 11,
+ "message": "Lifecycle entry point is never invoked",
+ "source": "pmd:UnusedPrivateMethod",
+ },
+ },
+ ],
+ }
+ ]
+ assert all("name" not in issue["details"] for issue in result[0]["issues"])
diff --git a/plugins/java/tests/test_unused_private_members_follow_pmd.py b/plugins/java/tests/test_unused_private_members_follow_pmd.py
new file mode 100644
index 00000000..3498d2f1
--- /dev/null
+++ b/plugins/java/tests/test_unused_private_members_follow_pmd.py
@@ -0,0 +1,166 @@
+"""Unused private-member detection remains PMD's decision."""
+
+from __future__ import annotations
+
+import json
+import subprocess
+import sys
+from pathlib import Path
+
+SENSOR = (
+ Path(__file__).resolve().parents[1] / "src/habit_hooks_java/sensors/pmd_sensor.py"
+)
+RULESET_HEADER = """
+
+ project policy
+"""
+
+
+def _run(project: Path, pmd: str, *arguments: str) -> list[dict]:
+ result = subprocess.run(
+ [sys.executable, str(SENSOR), pmd, *arguments, "--", "Members.java"],
+ cwd=project,
+ capture_output=True,
+ encoding="utf-8",
+ errors="replace",
+ )
+ assert result.returncode == 0, result.stderr
+ return json.loads(result.stdout)
+
+
+def test_the_bundled_rules_report_only_unreferenced_private_members(
+ tmp_path: Path, pmd: str
+) -> None:
+ (tmp_path / "Members.java").write_text(
+ "class Members {\n"
+ " private int staleField = 1;\n"
+ " private int liveField = 2;\n"
+ " private void staleMethod() {}\n"
+ " private int liveMethod() { return liveField; }\n"
+ " int value() { return liveMethod(); }\n"
+ "}\n",
+ encoding="utf-8",
+ )
+
+ findings = _run(tmp_path, pmd)
+
+ assert [finding["smell"] for finding in findings] == ["unused-class-member"]
+ issues = findings[0]["issues"]
+ assert [issue["details"]["line"] for issue in issues] == [2, 4]
+ assert [issue["details"]["message"] for issue in issues] == [
+ "Avoid unused private fields such as 'staleField'.",
+ "Avoid unused private methods such as 'staleMethod()'.",
+ ]
+ assert [issue["details"]["source"] for issue in issues] == [
+ "pmd:UnusedPrivateField",
+ "pmd:UnusedPrivateMethod",
+ ]
+ assert [issue["details"]["content"] for issue in issues] == [
+ "private int staleField = 1;",
+ "private void staleMethod() {}",
+ ]
+ assert all(Path(issue["key"]).name == "Members.java" for issue in issues)
+ assert all("name" not in issue["details"] for issue in issues)
+
+
+def test_the_bundled_rules_leave_framework_and_serialization_exclusions_to_pmd(
+ tmp_path: Path, pmd: str
+) -> None:
+ (tmp_path / "Members.java").write_text(
+ "@interface Managed {}\n"
+ "class Members implements java.io.Serializable {\n"
+ " private static final long serialVersionUID = 1L;\n"
+ " @Managed private Object injected;\n"
+ " private Object staleField;\n"
+ " private void readObject(java.io.ObjectInputStream stream)\n"
+ " throws java.io.IOException, ClassNotFoundException {\n"
+ " stream.defaultReadObject();\n"
+ " }\n"
+ " private void staleMethod() {}\n"
+ "}\n",
+ encoding="utf-8",
+ )
+
+ findings = _run(tmp_path, pmd)
+
+ assert [finding["smell"] for finding in findings] == ["unused-class-member"]
+ issues = findings[0]["issues"]
+ assert [issue["details"]["line"] for issue in issues] == [5, 10]
+ assert [issue["details"]["source"] for issue in issues] == [
+ "pmd:UnusedPrivateField",
+ "pmd:UnusedPrivateMethod",
+ ]
+ messages = [issue["details"]["message"] for issue in issues]
+ assert all("serialVersionUID" not in message for message in messages)
+ assert all("injected" not in message for message in messages)
+ assert all("readObject" not in message for message in messages)
+
+
+def test_a_project_ruleset_decides_whether_unused_members_are_enabled(
+ tmp_path: Path, pmd: str
+) -> None:
+ (tmp_path / "Members.java").write_text(
+ "class Members {\n"
+ " private int staleField;\n"
+ " private void staleMethod() {}\n"
+ "}\n",
+ encoding="utf-8",
+ )
+ ruleset = tmp_path / "ruleset.xml"
+ ruleset.write_text(
+ RULESET_HEADER
+ + ' \n'
+ + "\n",
+ encoding="utf-8",
+ )
+
+ omitted = _run(tmp_path, pmd)
+
+ assert omitted == []
+
+ ruleset.write_text(
+ RULESET_HEADER
+ + ' \n'
+ + ' \n'
+ + "\n",
+ encoding="utf-8",
+ )
+
+ enabled = _run(tmp_path, pmd)
+
+ assert [issue["details"]["source"] for issue in enabled[0]["issues"]] == [
+ "pmd:UnusedPrivateField",
+ "pmd:UnusedPrivateMethod",
+ ]
+
+
+def test_a_project_ruleset_can_customize_pmds_ignored_field_names(
+ tmp_path: Path, pmd: str
+) -> None:
+ (tmp_path / "Members.java").write_text(
+ "class Members {\n"
+ " private int retainedByPolicy;\n"
+ " private int staleField;\n"
+ "}\n",
+ encoding="utf-8",
+ )
+ (tmp_path / "ruleset.xml").write_text(
+ RULESET_HEADER
+ + ' \n'
+ + " \n"
+ + ' \n'
+ + " \n"
+ + " \n"
+ + "\n",
+ encoding="utf-8",
+ )
+
+ findings = _run(tmp_path, pmd)
+
+ issues = findings[0]["issues"]
+ assert [issue["details"]["line"] for issue in issues] == [3]
+ assert issues[0]["details"]["message"] == (
+ "Avoid unused private fields such as 'staleField'."
+ )
diff --git a/plugins/typescript/src/habit_hooks_typescript/guides/unused-class-member.md b/plugins/typescript/src/habit_hooks_typescript/guides/unused-class-member.md
deleted file mode 100644
index 21125506..00000000
--- a/plugins/typescript/src/habit_hooks_typescript/guides/unused-class-member.md
+++ /dev/null
@@ -1,11 +0,0 @@
-A method or property no code outside the class ever touches — and that the class itself never uses — is dead surface pretending to be part of the design. It inflates the class's apparent responsibilities, invites a reader to reason about a collaboration that doesn't exist, and is the kind of thing a later change "maintains" for no reason.
-
-First rule out a false alarm: a member reached only by reflection, a framework lifecycle hook, or a decorator can be live yet invisible to static analysis — if that's the case, make the use legible rather than deleting a real seam. Otherwise decide which kind of dead it is. If nothing needs it, delete it and anything that existed only to feed it. If it's *meant* to be used but the caller was never wired up, connect it. And if a cluster of unused members shares state and behaviour, that's usually a class trying to split: extract them into their own unit where they become a real, used public surface instead of a private back room.
-
-Done right, every member of the class is reached by something real, so the class's public shape is an honest statement of what it does.
-
-The unused members:
-
-{% for issue in issues -%}
-{{ issue.details.file }}:{{ issue.details.line }} {{ issue.details.name }}
-{% endfor %}
diff --git a/plugins/typescript/src/habit_hooks_typescript/sensors/knip.cjs b/plugins/typescript/src/habit_hooks_typescript/sensors/knip.cjs
index 69fcd1c5..9c39ffe9 100644
--- a/plugins/typescript/src/habit_hooks_typescript/sensors/knip.cjs
+++ b/plugins/typescript/src/habit_hooks_typescript/sensors/knip.cjs
@@ -142,9 +142,12 @@ function signature(row) {
return `${row.knipKey}\n${row.file}\n${row.name ?? ""}`;
}
-function issueFrom(row, source) {
+function issueFrom(row, source, smell) {
const details = { file: row.file, source };
if (row.name !== undefined) details.name = row.name;
+ if (smell === "unused-class-member" && row.name !== undefined) {
+ details.content = row.name;
+ }
if (row.line !== undefined) details.line = row.line;
// knip spells it `col`; the sensor contract (docs/sensor-interface.spec.md)
// spells it `column`, as every other sensor does. Translating the tool's
@@ -170,7 +173,7 @@ function findings(defaultReport, productionReport) {
for (const row of defaultRows) {
const smell = SMELL_BY_KEY[row.knipKey];
if (!smell) continue;
- add(grouped, smell, issueFrom(row, `knip:${row.knipKey}`));
+ add(grouped, smell, issueFrom(row, `knip:${row.knipKey}`, smell));
}
if (productionReport) {
const alreadyDead = new Set(defaultRows.map(signature));
@@ -178,7 +181,11 @@ function findings(defaultReport, productionReport) {
if (!DEAD_CODE_KEYS.has(row.knipKey)) continue;
if (alreadyDead.has(signature(row))) continue;
if (isTestFile(row.file)) continue;
- add(grouped, PRODUCTION_SMELL, issueFrom(row, `knip:production:${row.knipKey}`));
+ add(
+ grouped,
+ PRODUCTION_SMELL,
+ issueFrom(row, `knip:production:${row.knipKey}`, PRODUCTION_SMELL),
+ );
}
}
return [...grouped.values()];
diff --git a/plugins/typescript/tests/test_knip_speaks_the_smell_vocabulary.py b/plugins/typescript/tests/test_knip_speaks_the_smell_vocabulary.py
index 1fe42593..b217c331 100644
--- a/plugins/typescript/tests/test_knip_speaks_the_smell_vocabulary.py
+++ b/plugins/typescript/tests/test_knip_speaks_the_smell_vocabulary.py
@@ -93,7 +93,10 @@ def test_an_unused_enum_member_arrives_as_unused_class_member(tmp_path: Path) ->
findings = _findings(tmp_path, report)
assert [f["smell"] for f in findings] == ["unused-class-member"]
- assert findings[0]["issues"][0]["key"] == "Green"
+ issue = findings[0]["issues"][0]
+ assert issue["key"] == "Green"
+ assert issue["details"]["name"] == "Green"
+ assert issue["details"]["content"] == "Green"
def test_dropping_an_untranslated_key_leaves_its_neighbours_alone(
diff --git a/tests/test_unused_member_guide.py b/tests/test_unused_member_guide.py
new file mode 100644
index 00000000..1fa3b598
--- /dev/null
+++ b/tests/test_unused_member_guide.py
@@ -0,0 +1,54 @@
+"""Shared unused-member coaching follows the line-level issue contract."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from habit_hooks import mapper
+from plugin_fixture import write_project_config
+
+
+def _finding(language: str, details: dict) -> dict:
+ return {
+ "smell": "unused-class-member",
+ "language": language,
+ "details": {},
+ "issues": [{"key": "producer-key", "details": details}],
+ }
+
+
+@pytest.mark.parametrize(
+ "case",
+ [
+ (
+ "java",
+ {
+ "file": "src/main/java/Foo.java",
+ "line": 17,
+ "content": "private int staleField;",
+ },
+ "src/main/java/Foo.java:17 private int staleField;",
+ ),
+ (
+ "typescript",
+ {"file": "src/helper.ts", "line": 8, "content": "unusedMethod"},
+ "src/helper.ts:8 unusedMethod",
+ ),
+ ],
+)
+def test_the_shared_guide_renders_line_level_content(
+ case: tuple[str, dict, str],
+ tmp_path: Path,
+ capsys: pytest.CaptureFixture[str],
+) -> None:
+ language, details, display = case
+ write_project_config(tmp_path, 'plugins = ["generic"]')
+
+ code = mapper.run([_finding(language, details)], tmp_path)
+
+ out = capsys.readouterr().out
+ assert display in out
+ assert "General guidance" not in out
+ assert code == 1