Skip to content

feat(devtools): test-ownership manifest with import-resolution - #450

Merged
Sinity merged 1 commit into
masterfrom
feature/feat/test-ownership-manifest
Apr 26, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/feat/test-ownership-manifest

Conversation

@Sinity

@Sinity Sinity commented Apr 26, 2026 •

Copy link
Copy Markdown
Owner

Summary

Closes #437. Replaces #440 (closed because branches were rebased after #438 merged). Adds the third evidence-driven structural lint after #429 (topology) and #435 (file-size). Verifies each production module is imported by at least one unit test.

Problem

When a production module moves (per the topology refactors #424/#425/#426/#403), test files often stay put — the test-tree mirror of the production tree drifts. Coverage analysis is wrong because tests update imports but never move.

Solution

Same shape as #429 and #435: declarative YAML manifest plus an AST-based lint.

  • docs/plans/test-ownership.yaml: untested[] (modules legitimately not needing unit tests, with justification) plus shared[] (cross-cutting test infrastructure).
  • devtools/verify_test_ownership.py (~200 LOC): for each production module under polylogue/ or devtools/, verifies at least one unit test imports it. Reports uncovered (blocking), stale untested (blocking), orphan tests (warning).
  • Wired into devtools verify --quick after verify-file-budgets.
  • tests/unit/devtools/test_verify_test_ownership.py: parser, import-filter, "committed manifest is clean" smoke.

Verification

$ devtools verify-test-ownership
production modules: 674
covered: 698
untested (declared): 0
blocking=False

$ devtools verify --quick
verify: all checks passed (incl. all 7 lints)

$ pytest tests/unit/devtools/test_verify_test_ownership.py
3 passed

Currently 0 uncovered production modules across 674 files. Four legitimate orphan tests are listed in shared: with reasons.

Stacked on

Based on feature/feat/file-size-budgets (#442). Merge order: #442 → this.

Refs #401, #429, #437, #440 (closed predecessor).

🤖 Generated with Claude Code

Summary by CodeRabbit

Release Notes

  • New Features

    • Added verify-test-ownership verification command that validates all production modules are imported by at least one unit test, with support for JSON output.
  • Documentation

    • Updated devtools documentation with new verification command.
    • Added test-ownership manifest file to manage module coverage exceptions and cross-cutting test infrastructure.

@coderabbitai

coderabbitai Bot commented Apr 26, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

A new test-ownership verification system is introduced, comprising a CLI command that scans production modules and unit tests using AST parsing to ensure test coverage mapping, reads exemptions from a YAML manifest, and reports coverage gaps with JSON output support. The command is registered in the catalog and integrated into the verification pipeline.

Changes

Cohort / File(s) Summary
Command Registration
devtools/command_catalog.py
Registers verify-test-ownership as a new devtools command under the verification category with example invocations.
Verification Pipeline
devtools/verify.py
Appends verify-test-ownership step to the ordered verification steps executed by build_verify_steps().
Core Implementation
devtools/verify_test_ownership.py
Implements test ownership verification CLI with AST-based import extraction, YAML manifest reading for exemptions, and structured reporting of uncovered, stale, and orphan test cases with optional JSON output.
Test Ownership Manifest
docs/plans/test-ownership.yaml
New manifest file seeding untested and shared exemption lists with reasons, establishing the baseline test-ownership rules.
Documentation & Tests
docs/devtools.md, tests/unit/devtools/test_verify.py, tests/unit/devtools/test_verify_test_ownership.py
Adds command documentation, updates verify test expectations for the new step, and introduces comprehensive test suite validating YAML parsing, import extraction, and end-to-end verification flow.

Sequence Diagram

sequenceDiagram
    participant User as User/CLI
    participant Verify as verify-test-ownership
    participant ManifestReader as Manifest Reader
    participant Scanner as Module Scanner
    participant ASTParser as AST Parser
    participant Reporter as Reporter
    participant Output as Output

    User->>Verify: main(argv)
    Verify->>ManifestReader: read_yaml('docs/plans/test-ownership.yaml')
    ManifestReader-->>Verify: {untested: [], shared: [...]}
    
    Verify->>Scanner: scan_production_modules(polylogue, devtools)
    Scanner-->>Verify: [module_paths]
    
    Verify->>Scanner: scan_test_files(tests/unit)
    Scanner-->>Verify: [test_files]
    
    loop For each test file
        Verify->>ASTParser: extract_imports(test_content)
        ASTParser-->>Verify: [imported_modules]
    end
    
    Verify->>Reporter: compare_coverage(production, imports, manifest)
    Reporter-->>Verify: {uncovered, stale_untested, orphan_tests}
    
    alt blocking issues exist
        Verify->>Output: format_report(--json or human)
        Output-->>User: JSON/text report
        Verify-->>User: exit(1)
    else all clear
        Verify->>Output: format_report(blocking=False)
        Output-->>User: success message
        Verify-->>User: exit(0)
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related PRs

Suggested labels

area:qa


🐰 Our tests now claim their modules true,
With ownership both fair and new.
No orphan tests shall hop astray,
Each prod file guides a test today! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: adding a test-ownership manifest with import-resolution capabilities for verifying production module test coverage.
Description check ✅ Passed The description is comprehensive and follows the template with all required sections (Summary, Problem, Solution, Verification, Risks/Follow-ups). All information is specific and well-structured.
Linked Issues check ✅ Passed The PR fully addresses the objectives from issue #437: implements test-ownership manifest (docs/plans/test-ownership.yaml), creates verify_test_ownership.py with AST-based import resolution, wires it into devtools verify, and includes comprehensive test coverage.
Out of Scope Changes check ✅ Passed All changes are directly aligned with the linked issue #437 objectives. The new command registration, verification integration, documentation updates, and test additions are all within scope of enforcing test ownership.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/test-ownership-manifest

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d02238a6d4

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread devtools/verify_test_ownership.py Resolved
Comment thread devtools/verify_file_budgets.py Resolved
Base automatically changed from feature/feat/file-size-budgets to master April 26, 2026 06:26
Closes #437.

Adds the fourth evidence-driven structural lint after #429 (topology) and
#435 (file-size). Verifies each production module is imported by at least
one unit test.

- docs/plans/test-ownership.yaml: untested[] (modules legitimately not
  needing unit tests, with justification) plus shared[] (cross-cutting
  test infrastructure that does not own one production module).
- devtools/verify_test_ownership.py: AST-based import resolution. For
  each production module under polylogue/ or devtools/, verifies at
  least one unit test imports it. Reports uncovered modules (blocking),
  stale untested entries (blocking), and orphan tests (warning).
- Wired into devtools verify --quick alongside verify-topology and
  verify-file-budgets.

Currently 0 uncovered production modules across 674 production files
(polylogue + devtools). Four orphan tests are explicitly listed in
shared: with reasons (structural test, terminal-snapshot, growth budget,
entrypoints runtime).

Pattern reuse from #429: declarative YAML + lint + tracked exceptions.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@Sinity
Sinity force-pushed the feature/feat/test-ownership-manifest branch from d02238a to 2062796 Compare April 26, 2026 10:43

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 9

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@devtools/verify_test_ownership.py`:
- Around line 168-195: production_modules() is being called repeatedly in
main(), causing redundant filesystem walks; call it once, store the result in a
local variable (e.g., prod_modules = production_modules()), and reuse that
variable for all subsequent computations (uncovered, stale_untested, counts, and
prod_total) instead of re-invoking production_modules(); update uses of
len(production_modules()) and set(production_modules()) to use len(prod_modules)
and set(prod_modules) so the logic for uncovered, stale_untested, and
JSON/output counts remains identical but avoids repeated work.
- Around line 195-198: The printed "covered" metric is misleading because
coverage (the dict keyed from name_to_path) includes __init__.py entries while
production_modules() excludes them; change the reporting to compute production =
set(production_modules()) once, then compute covered_count = len([p for p in
coverage.keys() if p in production]) (or equivalently len(production &
set(coverage.keys()))) and print that covered_count instead of len(coverage);
ensure any JSON/metrics use the same filtered count and keep the existing
uncovered calculation (set(production) - set(coverage.keys()) - untested_paths)
unchanged.
- Line 156: Remove the redundant set comprehension "production_imports =
{name_to_path[n] for n in imports if n in name_to_path}" and instead ensure
production_imports is initialized as an empty set before the loop; let the
existing loop branch that checks "if imp == name" add entries to
production_imports (using name_to_path and imports) so behavior remains
identical but clearer.
- Around line 100-117: The imports_in function currently swallows
OSError/SyntaxError silently; update its exception handling to log the parse
failure (include the file path and exception details) instead of failing
silently so orphan-test reporting is accurate; locate imports_in in
devtools/verify_test_ownership.py and replace the bare except block with one
that logs a warning via the module logger (e.g.,
logging.getLogger(__name__).warning(...)) including the Path and exception, and
optionally re-raise or return a distinct failure signal when a strict
verification flag is enabled (so callers can treat parse errors as hard
failures).
- Around line 156-166: The descendant matching over-credits sibling submodules;
update imports_in to emit f"{node.module}.{alias.name}" for each ast.ImportFrom
alias so from polylogue.storage import repository becomes
"polylogue.storage.repository", and then in the production_imports resolution
loop (the for imp in imports / for name, prod_rel in name_to_path.items() block)
remove the branch that adds prod_rel when name.startswith(imp + ".") (the clause
that credits every descendant of imp), or alternatively only apply that
descendant-direction rule when the original import was an ast.Import (i.e., a
full package import) by tracking import kind; keep the existing imp == name and
imp.startswith(name + ".") checks.
- Around line 31-64: The custom YAML parser in parse_yaml is brittle and should
be replaced with pyyaml's safe_load; call yaml.safe_load(text) in parse_yaml
(import yaml) and coerce/normalize the result into the expected dict[str,
list[dict[str,str]]] shape instead of line-by-line parsing, preserving empty
inline lists and single-quoted strings and handling tab/space indentation
correctly. After loading, validate and normalize each item (the previously used
current_item logic) so each entry is a dict of strings, coerce values via your
existing _coerce where needed, and enforce required keys like "path" are present
on each item; keep the same return shape (sections keys "untested" and "shared")
and raise a clear error if validation fails.

In `@docs/plans/test-ownership.yaml`:
- Line 14: The section detector in devtools/verify_test_ownership.py (the
parse_yaml/section-detection block around the check that tests line.rstrip(":")
in {"untested","shared"}) fails on inline empty-list headers like "untested:
[]"; change the detector to extract the header key before the first colon (e.g.,
split on ':' or use a simple regex to capture the key name) and then compare
that stripped key against the sections set so lines like "untested: []" and
"shared: []" are recognized as empty sections rather than ignored.

In `@tests/unit/devtools/test_verify_test_ownership.py`:
- Around line 47-52: The test test_committed_manifest_is_clean currently invokes
verify_test_ownership.main([]) which reads the live MANIFEST and asserts on
human-readable output ("blocking=False"), making the test brittle; change it to
call verify_test_ownership.main(["--json"]) (or the JSON flag implemented by
verify_test_ownership.py), capture and parse the returned JSON payload, assert
rc == 0 and that payload["blocking"] is False (or equivalent key), and keep the
test name and intent but rely on the JSON structure rather than the printed
string so the human output format can change without breaking the test.
- Around line 12-26: Add a focused unit test that verifies parse_yaml correctly
handles the inline-empty-list form and comments used in the committed manifest:
call verify_test_ownership.parse_yaml with a YAML string like "untested: []"
plus a minimal "shared:" entry (and include example comments if desired), then
assert that the returned dict has parsed["untested"] == [] and that shared
entries parse correctly; add this as either a new test function (e.g.,
test_parse_yaml_handles_inline_empty_list) or augment test_parse_yaml_round_trip
to include this case so parse_yaml is validated against the actual manifest
shape.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 2b0223fe-991a-4962-ad24-9fdcaaa20296

📥 Commits

Reviewing files that changed from the base of the PR and between 9c264d8 and 2062796.

📒 Files selected for processing (7)
  • devtools/command_catalog.py
  • devtools/verify.py
  • devtools/verify_test_ownership.py
  • docs/devtools.md
  • docs/plans/test-ownership.yaml
  • tests/unit/devtools/test_verify.py
  • tests/unit/devtools/test_verify_test_ownership.py

Comment on lines +31 to +64
def parse_yaml(text: str) -> dict[str, list[dict[str, str]]]:
"""Tiny YAML reader for the test-ownership schema."""
sections: dict[str, list[dict[str, str]]] = {"untested": [], "shared": []}
current_section: str | None = None
current_item: dict[str, str] | None = None
for raw in text.splitlines():
line = raw.rstrip()
if not line or line.lstrip().startswith("#"):
continue
if not line.startswith(" "):
key = line.rstrip(":")
if key in sections:
if current_item is not None and current_section is not None:
sections[current_section].append(current_item)
current_section = key
current_item = None
continue
if current_section is None:
continue
stripped = line.lstrip()
if stripped.startswith("- "):
if current_item is not None:
sections[current_section].append(current_item)
current_item = {}
rest = stripped[2:]
if ": " in rest:
k, _, v = rest.partition(": ")
current_item[k] = _coerce(v.strip())
elif current_item is not None and ": " in stripped:
k, _, v = stripped.partition(": ")
current_item[k] = _coerce(v.strip())
if current_item is not None and current_section is not None:
sections[current_section].append(current_item)
return sections

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check whether PyYAML is already declared as a runtime/dev dependency.
fd -tf -e toml -e cfg -e txt -e in . | xargs rg -nP -i '\b(pyyaml|yaml)\b' 2>/dev/null
rg -nP --type=py -C1 '^\s*import yaml\b|^\s*from yaml\b'

Repository: Sinity/polylogue

Length of output: 2314


🏁 Script executed:

# First, let's view the complete file to see the _coerce function and full context
cat -n devtools/verify_test_ownership.py

Repository: Sinity/polylogue

Length of output: 9711


🏁 Script executed:

# Find and read the test-ownership.yaml manifest
cat docs/plans/test-ownership.yaml | head -80

# Also look for tests of the parse_yaml function
rg -n "parse_yaml|test.*ownership" tests/ --type py -A 3

Repository: Sinity/polylogue

Length of output: 4378


🏁 Script executed:

# Read the full test file for parse_yaml
cat -n tests/unit/devtools/test_verify_test_ownership.py

Repository: Sinity/polylogue

Length of output: 1893


🏁 Script executed:

# Check if there are any inline empty lists or problematic YAML patterns in the manifest
cat docs/plans/test-ownership.yaml

# Also search for any related issues or PR discussions about edge cases
git log --oneline --all -20 2>/dev/null | head -20

Repository: Sinity/polylogue

Length of output: 2327


Use yaml.safe_load() instead of the custom parser.

The custom parser has real gaps already reflected in the committed manifest. The inline untested: [] on line 18 of docs/plans/test-ownership.yaml would be mishandled (the parser requires - prefix for list items and cannot recognize empty inline lists). Additional gaps include no single-quote support in _coerce, tab-indented content misclassified as top-level, and missing validation that required keys like path exist. Since pyyaml>=6.0 is already a direct dependency in pyproject.toml, yaml.safe_load() would replace this without adding new dependencies.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@devtools/verify_test_ownership.py` around lines 31 - 64, The custom YAML
parser in parse_yaml is brittle and should be replaced with pyyaml's safe_load;
call yaml.safe_load(text) in parse_yaml (import yaml) and coerce/normalize the
result into the expected dict[str, list[dict[str,str]]] shape instead of
line-by-line parsing, preserving empty inline lists and single-quoted strings
and handling tab/space indentation correctly. After loading, validate and
normalize each item (the previously used current_item logic) so each entry is a
dict of strings, coerce values via your existing _coerce where needed, and
enforce required keys like "path" are present on each item; keep the same return
shape (sections keys "untested" and "shared") and raise a clear error if
validation fails.

Comment on lines +100 to +117
def imports_in(path: Path) -> set[str]:
try:
tree = ast.parse(path.read_text())
except (OSError, SyntaxError):
return set()
found: set[str] = set()
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
if any(alias.name.startswith(prefix) for prefix in PRODUCTION_PREFIXES):
found.add(alias.name)
elif (
isinstance(node, ast.ImportFrom)
and node.module
and any(node.module.startswith(prefix) for prefix in PRODUCTION_PREFIXES)
):
found.add(node.module)
return found

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

imports_in silently swallows SyntaxError/OSError — orphan-test reporting will lie.

A test file that fails to AST-parse (syntax error, encoding error) returns an empty set and then ends up in orphan_tests ("no production import") rather than being surfaced as a parse failure. That's worse than ignoring it: a broken test gets categorized as benign infrastructure. At minimum, log a warning, and consider treating a parse failure as a hard error in a verification-baseline gate.

🛡️ Proposed minimum: surface the failure
 def imports_in(path: Path) -> set[str]:
     try:
         tree = ast.parse(path.read_text())
-    except (OSError, SyntaxError):
+    except (OSError, SyntaxError) as exc:
+        sys.stderr.write(f"verify-test-ownership: could not parse {path}: {exc}\n")
         return set()
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@devtools/verify_test_ownership.py` around lines 100 - 117, The imports_in
function currently swallows OSError/SyntaxError silently; update its exception
handling to log the parse failure (include the file path and exception details)
instead of failing silently so orphan-test reporting is accurate; locate
imports_in in devtools/verify_test_ownership.py and replace the bare except
block with one that logs a warning via the module logger (e.g.,
logging.getLogger(__name__).warning(...)) including the Path and exception, and
optionally re-raise or return a distinct failure signal when a strict
verification flag is enabled (so callers can treat parse errors as hard
failures).

if rel in shared_paths:
continue
imports = imports_in(tf)
production_imports = {name_to_path[n] for n in imports if n in name_to_path}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Redundant initial set comprehension.

production_imports = {name_to_path[n] for n in imports if n in name_to_path} is fully subsumed by the if imp == name branch in the loop on lines 158-160. Drop it for clarity.

♻️ Proposed simplification
-        production_imports = {name_to_path[n] for n in imports if n in name_to_path}
-        # Also resolve sub-module imports: e.g. import polylogue.lib triggers any descendant.
+        production_imports: set[str] = set()
+        # Resolve direct hits and ancestor-package imports.
         for imp in imports:
             for name, prod_rel in name_to_path.items():
                 if imp == name or imp.startswith(name + "."):
                     production_imports.add(prod_rel)
-                if name.startswith(imp + "."):
-                    production_imports.add(prod_rel)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@devtools/verify_test_ownership.py` at line 156, Remove the redundant set
comprehension "production_imports = {name_to_path[n] for n in imports if n in
name_to_path}" and instead ensure production_imports is initialized as an empty
set before the loop; let the existing loop branch that checks "if imp == name"
add entries to production_imports (using name_to_path and imports) so behavior
remains identical but clearer.

Comment on lines +156 to +166
production_imports = {name_to_path[n] for n in imports if n in name_to_path}
# Also resolve sub-module imports: e.g. import polylogue.lib triggers any descendant.
for imp in imports:
for name, prod_rel in name_to_path.items():
if imp == name or imp.startswith(name + "."):
production_imports.add(prod_rel)
if name.startswith(imp + "."):
production_imports.add(prod_rel)
test_imports_count[rel] = len(production_imports)
for prod in production_imports:
coverage[prod].add(rel)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Descendant matching is too permissive and can hide uncovered modules — reconsider the resolution rule.

The current rule (lines 158-163) treats from polylogue.lib import json and import polylogue.lib identically: both yield imp = "polylogue.lib", which then matches every name.startswith("polylogue.lib.") in name_to_path and credits all sibling submodules of polylogue.lib as covered. That directly conflicts with #437's goal — a test that touches one submodule shouldn't satisfy ownership for its siblings, otherwise drift between production paths and owning tests is precisely what gets masked.

Concretely:

  • from polylogue.storage import repository is currently parsed as node.module = "polylogue.storage" only (the alias name repository — which may itself be a submodule — is discarded in imports_in line 116). Then the descendant rule on line 162 marks every polylogue.storage.* module covered, even ones no test references.
  • Conversely, the rule on line 160 (imp.startswith(name + ".")) is fine: importing polylogue.lib.json should credit polylogue.lib (the parent package).

Two targeted fixes:

  1. In imports_in, also emit f"{node.module}.{alias.name}" for each ast.ImportFrom alias — that captures from polylogue.storage import repository as a potential polylogue.storage.repository import without over-claiming siblings.
  2. Remove the descendant-direction rule on line 162, or scope it to whole-package imports only (ast.Import of polylogue.lib), not ast.ImportFrom.
♻️ Proposed adjustment
 def imports_in(path: Path) -> set[str]:
     ...
     for node in ast.walk(tree):
         if isinstance(node, ast.Import):
             for alias in node.names:
                 if any(alias.name.startswith(prefix) for prefix in PRODUCTION_PREFIXES):
                     found.add(alias.name)
         elif (
             isinstance(node, ast.ImportFrom)
             and node.module
             and any(node.module.startswith(prefix) for prefix in PRODUCTION_PREFIXES)
         ):
             found.add(node.module)
+            # `from polylogue.x import y` may import the submodule `polylogue.x.y`.
+            for alias in node.names:
+                if alias.name != "*":
+                    found.add(f"{node.module}.{alias.name}")
     return found
         for imp in imports:
             for name, prod_rel in name_to_path.items():
                 if imp == name or imp.startswith(name + "."):
                     production_imports.add(prod_rel)
-                if name.startswith(imp + "."):
-                    production_imports.add(prod_rel)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
production_imports = {name_to_path[n] for n in imports if n in name_to_path}
# Also resolve sub-module imports: e.g. import polylogue.lib triggers any descendant.
for imp in imports:
for name, prod_rel in name_to_path.items():
if imp == name or imp.startswith(name + "."):
production_imports.add(prod_rel)
if name.startswith(imp + "."):
production_imports.add(prod_rel)
test_imports_count[rel] = len(production_imports)
for prod in production_imports:
coverage[prod].add(rel)
production_imports = {name_to_path[n] for n in imports if n in name_to_path}
# Also resolve sub-module imports: e.g. import polylogue.lib triggers any descendant.
for imp in imports:
for name, prod_rel in name_to_path.items():
if imp == name or imp.startswith(name + "."):
production_imports.add(prod_rel)
test_imports_count[rel] = len(production_imports)
for prod in production_imports:
coverage[prod].add(rel)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@devtools/verify_test_ownership.py` around lines 156 - 166, The descendant
matching over-credits sibling submodules; update imports_in to emit
f"{node.module}.{alias.name}" for each ast.ImportFrom alias so from
polylogue.storage import repository becomes "polylogue.storage.repository", and
then in the production_imports resolution loop (the for imp in imports / for
name, prod_rel in name_to_path.items() block) remove the branch that adds
prod_rel when name.startswith(imp + ".") (the clause that credits every
descendant of imp), or alternatively only apply that descendant-direction rule
when the original import was an ast.Import (i.e., a full package import) by
tracking import kind; keep the existing imp == name and imp.startswith(name +
".") checks.

Comment on lines +168 to +195
uncovered = sorted(set(production_modules()) - set(coverage.keys()) - untested_paths)
stale_untested = sorted(untested_paths - set(production_modules()))
orphan_tests = sorted(rel for rel, count in test_imports_count.items() if count == 0)

blocking = bool(uncovered) or bool(stale_untested)

if args.json:
json.dump(
{
"blocking": blocking,
"counts": {
"production_modules": len(production_modules()),
"covered": len(coverage),
"uncovered": len(uncovered),
"untested_declared": len(untested_paths),
"stale_untested": len(stale_untested),
"orphan_tests": len(orphan_tests),
},
"uncovered": uncovered,
"stale_untested": stale_untested,
"orphan_tests": orphan_tests,
},
sys.stdout,
indent=2,
)
sys.stdout.write("\n")
else:
prod_total = len(production_modules())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

production_modules() is invoked four times in main() — cache it.

Each call rewalks both polylogue/ and devtools/ trees (lines 168, 169, 179, 195). Within the 5s budget today, but this is a hot path that runs in devtools verify --quick, and the redundancy is easy to remove (see the diff in the previous comment, which assigns prod_modules = production_modules() once and reuses it).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@devtools/verify_test_ownership.py` around lines 168 - 195,
production_modules() is being called repeatedly in main(), causing redundant
filesystem walks; call it once, store the result in a local variable (e.g.,
prod_modules = production_modules()), and reuse that variable for all subsequent
computations (uncovered, stale_untested, counts, and prod_total) instead of
re-invoking production_modules(); update uses of len(production_modules()) and
set(production_modules()) to use len(prod_modules) and set(prod_modules) so the
logic for uncovered, stale_untested, and JSON/output counts remains identical
but avoids repeated work.

Comment on lines +195 to +198
prod_total = len(production_modules())
print(f"production modules: {prod_total}")
print(f"covered: {len(coverage)}")
print(f"untested (declared): {len(untested_paths)}")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Misleading "covered" count — can exceed total production modules.

coverage is keyed by values of name_to_path, which includes __init__.py paths (lines 127-133), but production_modules() (lines 80-83) explicitly excludes __init__.py. So len(coverage) counts package init files that aren't in the denominator, which produces the puzzling output reported in the PR description (production modules: 674, covered: 698). The uncovered set computation on line 168 is still correct because it does set(production_modules()) - set(coverage.keys()) - untested_paths (extra keys don't hurt set difference), but the displayed/JSON metric will confuse anyone reading the report.

🐛 Proposed fix — count only coverage entries that are actual production modules
-    name_to_path = production_module_names()
+    prod_modules = production_modules()
+    prod_modules_set = set(prod_modules)
+    name_to_path = production_module_names()
     coverage: dict[str, set[str]] = defaultdict(set)
     ...
-    uncovered = sorted(set(production_modules()) - set(coverage.keys()) - untested_paths)
-    stale_untested = sorted(untested_paths - set(production_modules()))
+    covered_count = sum(1 for k in coverage if k in prod_modules_set)
+    uncovered = sorted(prod_modules_set - set(coverage.keys()) - untested_paths)
+    stale_untested = sorted(untested_paths - prod_modules_set)
     ...
-                    "production_modules": len(production_modules()),
-                    "covered": len(coverage),
+                    "production_modules": len(prod_modules),
+                    "covered": covered_count,
     ...
-        prod_total = len(production_modules())
-        print(f"production modules: {prod_total}")
-        print(f"covered: {len(coverage)}")
+        print(f"production modules: {len(prod_modules)}")
+        print(f"covered: {covered_count}")

This also folds in the next concern — production_modules() is now computed once.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@devtools/verify_test_ownership.py` around lines 195 - 198, The printed
"covered" metric is misleading because coverage (the dict keyed from
name_to_path) includes __init__.py entries while production_modules() excludes
them; change the reporting to compute production = set(production_modules())
once, then compute covered_count = len([p for p in coverage.keys() if p in
production]) (or equivalently len(production & set(coverage.keys()))) and print
that covered_count instead of len(coverage); ensure any JSON/metrics use the
same filtered count and keep the existing uncovered calculation (set(production)
- set(coverage.keys()) - untested_paths) unchanged.

# permissive: untested entries should be re-evaluated when their owning
# refactor lands, and the list should shrink over time.

untested: []

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Heads-up: untested: [] is not actually parsed by parse_yaml — it works only because the section defaults to empty.

In devtools/verify_test_ownership.py (lines 40-47), the section detector matches lines that don't start with a space and where line.rstrip(":") is in {"untested","shared"}. For untested: [] the key becomes the literal "untested: []", which is not in sections, so the line is ignored. It happens to be harmless today because sections["untested"] is pre-initialized to []. If anyone later writes shared: [] (or starts the file with one), the parser will silently treat the section as missing rather than empty, and any subsequent - path: … lines (without a recognized section header) would be dropped.

Either teach the parser to accept inline empty lists, or normalize the seed to:

📝 Suggested seed style
-untested: []
+untested:

(omitting the [] and leaving an empty section is parsed identically and matches how shared: is written below.)

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
untested: []
untested:
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/plans/test-ownership.yaml` at line 14, The section detector in
devtools/verify_test_ownership.py (the parse_yaml/section-detection block around
the check that tests line.rstrip(":") in {"untested","shared"}) fails on inline
empty-list headers like "untested: []"; change the detector to extract the
header key before the first colon (e.g., split on ':' or use a simple regex to
capture the key name) and then compare that stripped key against the sections
set so lines like "untested: []" and "shared: []" are recognized as empty
sections rather than ignored.

Comment on lines +12 to +26
def test_parse_yaml_round_trip(tmp_path: Path) -> None:
p = tmp_path / "manifest.yaml"
p.write_text(
"""untested:
- path: polylogue/__init__.py
reason: package marker

shared:
- path: tests/unit/__init__.py
reason: package marker
""",
)
parsed = verify_test_ownership.parse_yaml(p.read_text())
assert parsed["untested"][0]["path"] == "polylogue/__init__.py"
assert parsed["shared"][0]["reason"] == "package marker"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Consider adding a case for the committed manifest's actual shape (untested: [] inline + comments).

The round-trip test exercises only the "happy path" with a populated untested: list, but the committed seed in docs/plans/test-ownership.yaml uses untested: [] (inline empty list) plus heavy comment usage. As noted on the YAML file, the inline-empty-list form isn't actually recognized by parse_yaml — adding a focused test that asserts parse_yaml("untested: []\nshared:\n - path: x\n reason: y\n")["untested"] == [] would have flagged it.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/unit/devtools/test_verify_test_ownership.py` around lines 12 - 26, Add
a focused unit test that verifies parse_yaml correctly handles the
inline-empty-list form and comments used in the committed manifest: call
verify_test_ownership.parse_yaml with a YAML string like "untested: []" plus a
minimal "shared:" entry (and include example comments if desired), then assert
that the returned dict has parsed["untested"] == [] and that shared entries
parse correctly; add this as either a new test function (e.g.,
test_parse_yaml_handles_inline_empty_list) or augment test_parse_yaml_round_trip
to include this case so parse_yaml is validated against the actual manifest
shape.

Comment on lines +47 to +52
def test_committed_manifest_is_clean(capsys: pytest.CaptureFixture[str]) -> None:
"""The committed test-ownership manifest should pass."""
rc = verify_test_ownership.main([])
captured = capsys.readouterr()
assert rc == 0, captured.out
assert "blocking=False" in captured.out

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

test_committed_manifest_is_clean runs against the live repo tree — confirm intent.

main([]) resolves MANIFEST = ROOT/"docs/plans/test-ownership.yaml" from Path(__file__).resolve().parents[1] in verify_test_ownership.py, so this test is not hermetic — it walks polylogue/, devtools/, and tests/unit/ of the actual checkout. That is appropriate as a smoke check and matches the PR objective ("manifest validity assert in under 5 seconds"), but two things to confirm:

  1. It will start failing the moment any new production module lands without an importing unit test, even on unrelated PRs. That's by design here, but worth calling out so contributors know to update the manifest in the same PR.
  2. Asserting the literal substring "blocking=False" couples the test to the human-readable output format. Consider asserting on the --json form (rc, payload["blocking"] is False) so the human format can evolve without breaking tests.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/unit/devtools/test_verify_test_ownership.py` around lines 47 - 52, The
test test_committed_manifest_is_clean currently invokes
verify_test_ownership.main([]) which reads the live MANIFEST and asserts on
human-readable output ("blocking=False"), making the test brittle; change it to
call verify_test_ownership.main(["--json"]) (or the JSON flag implemented by
verify_test_ownership.py), capture and parse the returned JSON payload, assert
rc == 0 and that payload["blocking"] is False (or equivalent key), and keep the
test name and intent but rely on the JSON structure rather than the printed
string so the human output format can change without breaking the test.

@Sinity
Sinity merged commit 997f4d8 into master Apr 26, 2026
14 checks passed
@Sinity
Sinity deleted the feature/feat/test-ownership-manifest branch April 26, 2026 10:56
Sinity added a commit that referenced this pull request Apr 26, 2026
## Summary

Closes #434. Replaces #441 (closed after the rebase chain reset). Fifth
and final evidence-driven structural lint completing the pattern
established by #429 (topology), #435 (file-size), #437 (test-ownership).

## Problem

Retirement issues like #413 declare what must vanish in prose. Reviewers
eyeball `polylogue --help` after the PR. There is no machine-checkable
assertion that every targeted item has actually disappeared.

## Solution

Same shape as the prior four lints: declarative YAML + a small
subprocess-based lint.

- **`docs/plans/migrations.yaml`**: each named migration declares
`must_vanish_paths`, `must_vanish_cli_commands`,
`must_vanish_devtools_commands`, `forbidden_substrings`,
`accepted_aliases`. Seeded with `retire-audit-qa-showcase` (#413) and
`retire-inbox-source` (#409).
- **`devtools/verify_migrations.py`** (~200 LOC): file-existence +
subprocess scans of `polylogue --help` and `devtools --list-commands` +
forbidden-substring globs.
- Default mode is informational; `--strict <name>` promotes a migration
to blocking when it's in flight.
- Wired into `devtools verify --quick`.

## Verification

```
$ devtools verify-migrations
[info] retire-audit-qa-showcase (#413): 5 surviving
    surviving_paths: devtools/verify_showcase.py
    surviving_cli_commands: audit
    surviving_devtools_commands: verify-showcase
[info] retire-inbox-source (#409): complete

$ devtools verify-migrations --strict retire-audit-qa-showcase
exit 1  # would block #413's PR until findings are resolved

$ devtools verify --quick
verify: all checks passed (incl. all 8 lints)

$ pytest tests/unit/devtools/test_verify_migrations.py
5 passed
```

## Pattern complete

Five evidence-driven structural specifications now land:
1. **Placement** (#429): every file at a known target path.
2. **Cohesion** (#429): proposed subpackages don't have cross-cluster
cycles.
3. **Size** (#435): per-file LOC budgets with sunset exceptions.
4. **Coverage** (#437): every production module imported by ≥1 unit
test.
5. **Retirement** (this / #434): named migrations vanish what they
claim.

The pattern (declarative YAML + lint + tracked exceptions with sunset
issues) is reusable for any future architectural claim.

## Stacked on

Based on `feature/feat/test-ownership-manifest` (#450) →
`feature/feat/file-size-budgets` (#442) → master. Merge order: #442 →
#450 → this.

Refs #401, #413, #429, #434, #441 (closed predecessor).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
@Sinity

Sinity commented Apr 28, 2026

Copy link
Copy Markdown
Owner Author

🤖 Post-hoc audit note: this PR received bot review feedback verified against current HEAD as part of #544. 11 finding(s) confirmed still present → tracked in #547, #550.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

Sinity added a commit that referenced this pull request May 7, 2026
## Summary

Closes #437. Replaces #440 (closed because branches were rebased after
#438 merged). Adds the third evidence-driven structural lint after #429
(topology) and #435 (file-size). Verifies each production module is
imported by at least one unit test.

## Problem

When a production module moves (per the topology refactors
#424/#425/#426/#403), test files often stay put — the test-tree mirror
of the production tree drifts. Coverage analysis is wrong because tests
update imports but never move.

## Solution

Same shape as #429 and #435: declarative YAML manifest plus an AST-based
lint.

- **`docs/plans/test-ownership.yaml`**: `untested[]` (modules
legitimately not needing unit tests, with justification) plus `shared[]`
(cross-cutting test infrastructure).
- **`devtools/verify_test_ownership.py`** (~200 LOC): for each
production module under `polylogue/` or `devtools/`, verifies at least
one unit test imports it. Reports uncovered (blocking), stale untested
(blocking), orphan tests (warning).
- Wired into `devtools verify --quick` after `verify-file-budgets`.
- `tests/unit/devtools/test_verify_test_ownership.py`: parser,
import-filter, "committed manifest is clean" smoke.

## Verification

```
$ devtools verify-test-ownership
production modules: 674
covered: 698
untested (declared): 0
blocking=False

$ devtools verify --quick
verify: all checks passed (incl. all 7 lints)

$ pytest tests/unit/devtools/test_verify_test_ownership.py
3 passed
```

Currently 0 uncovered production modules across 674 files. Four
legitimate orphan tests are listed in `shared:` with reasons.

## Stacked on

Based on `feature/feat/file-size-budgets` (#442). Merge order: #442 →
this.

Refs #401, #429, #437, #440 (closed predecessor).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

## Release Notes

* **New Features**
* Added `verify-test-ownership` verification command that validates all
production modules are imported by at least one unit test, with support
for JSON output.

* **Documentation**
  * Updated devtools documentation with new verification command.
* Added test-ownership manifest file to manage module coverage
exceptions and cross-cutting test infrastructure.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Sinity added a commit that referenced this pull request May 7, 2026
## Summary

Closes #434. Replaces #441 (closed after the rebase chain reset). Fifth
and final evidence-driven structural lint completing the pattern
established by #429 (topology), #435 (file-size), #437 (test-ownership).

## Problem

Retirement issues like #413 declare what must vanish in prose. Reviewers
eyeball `polylogue --help` after the PR. There is no machine-checkable
assertion that every targeted item has actually disappeared.

## Solution

Same shape as the prior four lints: declarative YAML + a small
subprocess-based lint.

- **`docs/plans/migrations.yaml`**: each named migration declares
`must_vanish_paths`, `must_vanish_cli_commands`,
`must_vanish_devtools_commands`, `forbidden_substrings`,
`accepted_aliases`. Seeded with `retire-audit-qa-showcase` (#413) and
`retire-inbox-source` (#409).
- **`devtools/verify_migrations.py`** (~200 LOC): file-existence +
subprocess scans of `polylogue --help` and `devtools --list-commands` +
forbidden-substring globs.
- Default mode is informational; `--strict <name>` promotes a migration
to blocking when it's in flight.
- Wired into `devtools verify --quick`.

## Verification

```
$ devtools verify-migrations
[info] retire-audit-qa-showcase (#413): 5 surviving
    surviving_paths: devtools/verify_showcase.py
    surviving_cli_commands: audit
    surviving_devtools_commands: verify-showcase
[info] retire-inbox-source (#409): complete

$ devtools verify-migrations --strict retire-audit-qa-showcase
exit 1  # would block #413's PR until findings are resolved

$ devtools verify --quick
verify: all checks passed (incl. all 8 lints)

$ pytest tests/unit/devtools/test_verify_migrations.py
5 passed
```

## Pattern complete

Five evidence-driven structural specifications now land:
1. **Placement** (#429): every file at a known target path.
2. **Cohesion** (#429): proposed subpackages don't have cross-cluster
cycles.
3. **Size** (#435): per-file LOC budgets with sunset exceptions.
4. **Coverage** (#437): every production module imported by ≥1 unit
test.
5. **Retirement** (this / #434): named migrations vanish what they
claim.

The pattern (declarative YAML + lint + tracked exceptions with sunset
issues) is reusable for any future architectural claim.

## Stacked on

Based on `feature/feat/test-ownership-manifest` (#450) →
`feature/feat/file-size-budgets` (#442) → master. Merge order: #442 →
#450 → this.

Refs #401, #413, #429, #434, #441 (closed predecessor).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
@Sinity

Sinity commented Sep 30, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

Only the rows listed above are dispositioned. Held findings remain open.

@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

Only the rows listed above are dispositioned. Held findings remain open.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(devtools): test-ownership manifest

2 participants