Repository navigation
feat(devtools): make architectural cohesion executable (Phase 1 of #429) - #438
Conversation
Promotes the pre-flight artifact prepared in .agent/scratch/ to the repo so structural-cohesion claims become CI-checkable. - docs/plans/topology-target.yaml: 638-row projection covering every polylogue/**/*.py with current path, target path, owning issue, and cross-cut tags. First-cut from build_topology_projection.py rules. - devtools/build_topology_projection.py: regenerates the YAML from placement rules derived from the seven topology refactor issues. - devtools/verify_topology.py: lints the realized tree against the projection — flags orphans, conflicts, missing files, and kernel-rule violations. Returns 0 with TBD warnings (use --strict-tbd to gate). - devtools/verify_cluster_cohesion.py: AST-based check that proposed clusters would be cohesive — surfaces cross-cluster imports through internals plus cycles between clusters. Phase 1 of #429. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Each xfail corresponds to a topology refactor and encodes its post-state invariant. When the refactor lands, the xfail flips to UNEXPECTED PASS; the test author then converts it to a regular assert. Subsequent regression fails CI. Covers: #424 (lib subpackages, no query_* at lib root), #425 (storage subpackages, no session_product_* at storage root), #414 (no archive_product modules at root), #426 (no facade/sync at root, kernel rule), #413 (devtools verify-showcase removed, retired CLI baselines gone), #427 (architecture docs document cross-cuts), #429 Phase 3 (drift dashboard rendered). Three tests pass today (lints exist, projection YAML exists), confirming Phase 1 of #429 has landed; eleven xfail awaiting subsequent refactors. Phase 1 of #429. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
- Register verify-topology, verify-cluster-cohesion, build-topology-projection as devtools commands in command_catalog.py. - Add verify-topology to the verify --quick step list so structural drift fails the local pre-push gate. - Regenerate docs/devtools.md via devtools render-all. verify-cluster-cohesion is intentionally not yet wired into verify because the realized tree currently has 43 surfaced cycles that #430, #431, and the topology-refactor issues will resolve incrementally; running it as a standalone reporter for now. Phase 1 of #429. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
📝 WalkthroughWalkthroughThis PR introduces a comprehensive topology projection system consisting of a generator script that scans and classifies Python files, assigns targets and ownership, and emits YAML mapping; two verification utilities that validate the projection against the realized tree and check cluster import cohesion; CLI command integration; and supporting tests and documentation. Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related issues
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8a1e65737d
ℹ️ 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".
There was a problem hiding this comment.
Actionable comments posted: 11
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
devtools/verify.py (1)
6-13:⚠️ Potential issue | 🟡 MinorStale module docstring —
--quicknow runs five steps, not four.The numbered list still ends at step 5 =
pytest, soverify-topologyis undocumented, and the line "Use --quick to run only steps 1-4" is wrong now that--quickalso runsverify-topology.📝 Proposed docstring refresh
Steps: 1. ruff format --check (fast, <2s) 2. ruff check (fast, <2s) 3. mypy (polylogue + tests + devtools) (warm ~1s, cold ~25s) 4. devtools render-all --check (fast, <5s) - 5. pytest --ignore=tests/integration (slow but essential, ~3min) + 5. devtools verify-topology (fast, <1s) + 6. pytest --ignore=tests/integration (slow but essential, ~3min) -Use --quick to run only steps 1-4 (suitable for pre-commit). +Use --quick to run only steps 1-5 (suitable for pre-commit). Use --lab to add verification-lab scenario checks through lab commands.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@devtools/verify.py` around lines 6 - 13, Update the module docstring in devtools/verify.py to reflect the current steps: enumerate all five steps including the newly undocumented "verify-topology" between step 4 and 5 (or wherever it runs), and change the usage line to "Use --quick to run only steps 1-5" (or explicitly list which steps --quick runs) so the docstring and the --quick description are accurate; locate the top-of-file module docstring in devtools/verify.py and edit the numbered list and the --quick explanatory sentence accordingly.docs/plans/topology-target.yaml (1)
1-2719:⚠️ Potential issue | 🔴 CriticalGenerated projection contains many malformed target paths and yamllint violations — fix in the generator.
This file is generator output. Multiple categories of malformed
target:values are visible and would mislead reviewers/refactor work that consumes this projection:
- Targets ending in
/.py(empty stem): e.g. lines 400, 404, 427, 431, 435, 472, 500, 514, 632, 686 (polylogue/lib/semantic/s.py), 694, 708, 722, 744, 2342, 2350, 2367, 2385, 2440, 2464, 2468, 2482, 2600.- Targets like
polylogue/storage/repository/__init__.pyinit__.py: lines 2410, 2492, 2596 (forrepository.py,search.py,store.py).polylogue/sources/parsers/claude/py(missing dot): line 1910 (forparsers/claude.py).In addition, every
cross_cut: { ... }line (≈200 occurrences) tripsyamllint'sbracesrule because of the leading/trailing space inside the flow mapping.Both classes of issues originate in
devtools/build_topology_projection.py; please see the comments there. Once fixed, regenerate this file withdevtools build-topology-projection.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@docs/plans/topology-target.yaml` around lines 1 - 2719, The projection generator emits malformed target strings and flow-mapping spacing; in devtools/build_topology_projection.py fix the target path construction logic (normalize/strip empty stems and ensure file extensions are preserved) so entries never produce trailing "/.py", duplicate suffixes like "__init__.pyinit__.py", or miss a dot (e.g. "claude/py"); also change the YAML serialization for cross_cut to emit compact flow mappings without extra spaces (e.g. {"lifecycle":"model"} or use safe_dump options) to satisfy yamllint's braces rule, then re-run `devtools build-topology-projection` to regenerate the file.
🤖 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/build_topology_projection.py`:
- Around line 341-354: The parsers/claude branch has an off-by-one slice: in the
block that examines suffix (variable suffix derived from rel) you should treat
both "parsers/claude.py" and names like "parsers/claude_x.py" correctly by
removing the exact prefix "parsers/claude" and then, if the remainder is empty
or equals ".py", map to "__init__.py", otherwise strip a single leading "_" (if
present) to build the stem; set target accordingly (set target and issue
variables). Similarly, replace the brittle chained replace in the drive branch:
check if suffix == "drive.py" -> "__init__.py", else if suffix startswith
"drive_" remove only the single "drive_" prefix to form the filename, then build
target and issue. Use the existing rel, suffix, target, and issue symbols to
locate and update the logic.
- Around line 380-393: The YAML emitter emit_yaml is producing flow-mappings
with extra spaces around braces for cross_cut, which trips yamllint; locate the
emit_yaml function and the block that builds `tags = ", ".join(...)` and change
the string formatting for the cross_cut line to remove the spaces inside the
braces so the flow mapping becomes `{k: v, k2: v2}` without leading/trailing
spaces (i.e., adjust the format expression that currently emits the cross_cut
line for row["cross_cut"] to use braces immediately adjacent to the tags);
regenerate the YAML output after the change.
- Around line 137-169: STORAGE_PREFIX_TO_SUBPACKAGE contains a mix of directory
prefixes and full file-target mappings which leads to malformed paths (e.g.
"__init__.pyinit__.py") when storage_target concatenates sub + stem; fix by
handling exact-file overrides before the prefix loop: detect keys like
"repository.py", "store.py", "search.py" and map them directly to their full
target values rather than treating them as prefixes, and replace any use of
stem.lstrip("_") with a removeprefix-style operation that only strips a single
leading underscore (or explicit logic that leaves "__init__.py" intact) so
"__init__.py" is not mutated; update the code paths that build storage_target
(referencing STORAGE_PREFIX_TO_SUBPACKAGE and the storage_target construction
logic) to first check exact-key matches, then fallback to prefix-matching with
safe prefix-stripping.
- Around line 396-413: Add a post-generation invariant check in main (after rows
are computed and before/after emit_yaml) that validates every row["target"] is
either the literal "TBD" or a well-formed Python module path; use the existing
classify/rows output and reject values containing path separators, repeated
suffixes, or non-module characters (e.g. enforce regex like
^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$), and if any row fails, log
the offending filename/target and fail fast (raise an exception or return
non-zero) so bad values (e.g. "polylogue/lib/<x>/.py", "__init__.pyinit__.py",
"claude/py") cannot be emitted; also add a unit test in tests/unit/architecture
that constructs sample rows and asserts the validator accepts only "TBD" or
valid module paths.
- Around line 232-259: Both lib_target and storage_target produce malformed
targets when the slice after a matching prefix yields only ".py" (e.g., name ==
"<prefix>.py"), resulting in paths like "<sub>/.py"; fix by normalizing the stem
extraction logic: after computing stem = name[len(prefix):], strip a leading dot
and leading underscores and treat an empty result as "__init__.py" (i.e.,
convert ".py" or "" to "__init__.py"); update both lib_target and storage_target
(they use LIB_PREFIX_TO_SUBPACKAGE and STORAGE_PREFIX_TO_SUBPACKAGE) to apply
this normalized-stem rule so targets become "polylogue/<sub>__init__.py" or
"<sub><stem>.py" correctly.
In `@devtools/verify_cluster_cohesion.py`:
- Around line 188-215: The --cluster filter currently only narrows
targets_to_show but leaves cycles, lonely and cross_internals global; when
args.cluster is set, filter those collections to the requested cluster.
Concretely: if args.cluster is truthy (same place where targets_to_show is set),
replace cycles with [p for p in cycles if args.cluster in p], replace lonely
with [c for c in lonely if c == args.cluster], and reduce cross_internals to {k:
v for k, v in cross_internals.items() if k == args.cluster} (or empty structures
if missing) before printing so the cycles, lonely and cross-internals sections
only show data for the requested cluster; keep using the existing symbols
cycles, lonely, cross_internals, args.cluster, targets_to_show, cluster_sizes,
cluster_edges, inbound.
- Around line 98-110: The code uses Path.read_text() without specifying encoding
which can break on non-UTF-8 locales; update collect_imports to call
path.read_text(encoding="utf-8") and likewise change the other YAML read call
that currently uses Path.read_text() (the YAML parsing site) to pass
encoding="utf-8" so source and YAML reads are consistently decoded as UTF-8;
adjust any tests or callers if they rely on default behavior.
- Around line 98-110: collect_imports currently drops relative imports because
it appends node.module verbatim and ignores node.level; update collect_imports
to resolve relative imports to their fully qualified package names before
appending. Specifically, compute the importing module's package from the Path
argument (derive its module path by converting the file path to a dotted package
path using package directories / __init__.py presence or by using the file's
parent package parts), then for ast.ImportFrom nodes use node.level to walk up
that package (remove last `node.level` components) and then append node.module
(or the imported names if node.module is None) to form the full dotted name;
keep existing behavior for absolute imports (ast.Import and node.level == 0).
Ensure the function returns these resolved fully qualified module names so
module_name_to_cluster can correctly detect cross-cluster edges.
- Around line 163-172: The current pairwise check using cluster_edges, cycles
and seen_pairs only finds mutual 2-cycles; replace it with a Strongly Connected
Components algorithm (Tarjan or Kosaraju) over the directed graph represented by
cluster_edges: build the graph from cluster_edges, run SCC to produce
components, collect any component with length >1 (or length==1 with a self-edge)
as a cycle, replace the cycles:list[tuple[str,str]] logic (and drop seen_pairs)
with cycles:list[list[str]] of SCCs, and update the subsequent print/render loop
to display each component list instead of pair tuples.
In `@devtools/verify_topology.py`:
- Line 92: The main function signature in verify_topology.py currently uses "def
main(argv: Iterable[str]) -> int" with no default, which breaks the CommandMain
type; change it to "def main(argv: list[str] | None = None) -> int" (and update
any other main definitions at the same file locations around lines 171-172) so
it matches the CommandMain = Callable[[list[str] | None], int] alias used across
devtools; adjust imports/types if necessary (replace Iterable[str] with
list[str] | None) and ensure any callers that pass None or call main() without
args continue to work.
- Line 11: Docstring claims exit 2 for warnings-only but the end-of-run logic
only returns 0 or 1; update the exit decision in the verification entrypoint
(e.g., the main() function in verify_topology.py or the function that aggregates
check results) to return 2 when there are no blocking findings but there are
warnings (taking into account the --strict-tbd flag: if strict_tbd is True treat
TBDs as blocking, otherwise count them as warnings); compute blocking_count and
warning_count from the existing result objects/collections and replace the final
return/exit call so it returns 2 when blocking_count == 0 and warning_count > 0,
1 when blocking_count > 0, and 0 when both are zero.
---
Outside diff comments:
In `@devtools/verify.py`:
- Around line 6-13: Update the module docstring in devtools/verify.py to reflect
the current steps: enumerate all five steps including the newly undocumented
"verify-topology" between step 4 and 5 (or wherever it runs), and change the
usage line to "Use --quick to run only steps 1-5" (or explicitly list which
steps --quick runs) so the docstring and the --quick description are accurate;
locate the top-of-file module docstring in devtools/verify.py and edit the
numbered list and the --quick explanatory sentence accordingly.
In `@docs/plans/topology-target.yaml`:
- Around line 1-2719: The projection generator emits malformed target strings
and flow-mapping spacing; in devtools/build_topology_projection.py fix the
target path construction logic (normalize/strip empty stems and ensure file
extensions are preserved) so entries never produce trailing "/.py", duplicate
suffixes like "__init__.pyinit__.py", or miss a dot (e.g. "claude/py"); also
change the YAML serialization for cross_cut to emit compact flow mappings
without extra spaces (e.g. {"lifecycle":"model"} or use safe_dump options) to
satisfy yamllint's braces rule, then re-run `devtools build-topology-projection`
to regenerate the file.
🪄 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: a6eeb874-5d22-4886-a289-d64d0a7c558f
📒 Files selected for processing (10)
devtools/build_topology_projection.pydevtools/command_catalog.pydevtools/verify.pydevtools/verify_cluster_cohesion.pydevtools/verify_topology.pydocs/devtools.mddocs/plans/topology-target.yamltests/unit/architecture/__init__.pytests/unit/architecture/test_topology_invariants.pytests/unit/devtools/test_verify.py
| STORAGE_PREFIX_TO_SUBPACKAGE = { | ||
| "repository_archive_": "storage/repository/archive/", | ||
| "repository_product_": "storage/repository/product/", | ||
| "repository_action_": "storage/repository/archive/", | ||
| "repository_raw": "storage/repository/raw/", | ||
| "repository_vectors": "storage/repository/vectors/", | ||
| "repository_write_": "storage/repository/archive/", | ||
| "repository_writes": "storage/repository/archive/", | ||
| "repository_contracts": "storage/repository/", | ||
| "repository.py": "storage/repository/__init__.py", | ||
| "session_product_": "storage/products/session/", | ||
| "store_runtime_action_": "storage/runtime/action/", | ||
| "store_runtime_archive_": "storage/runtime/archive/", | ||
| "store_runtime_raw_": "storage/runtime/raw/", | ||
| "store_product_aggregate_": "storage/products/aggregate/", | ||
| "store_product_session_": "storage/products/session/", | ||
| "store_product_timeline_": "storage/products/timeline/", | ||
| "store_constants": "storage/runtime/", | ||
| "store.py": "storage/runtime/__init__.py", | ||
| "action_event_": "storage/action_events/", | ||
| "embedding_stats_": "storage/embeddings/", | ||
| "embedding_stats": "storage/embeddings/", | ||
| "search_": "storage/search/", | ||
| "search.py": "storage/search/__init__.py", | ||
| "artifact_": "storage/artifacts/", | ||
| "fts_lifecycle": "storage/fts/", | ||
| "raw_ingest_": "storage/raw/", | ||
| "raw_state_": "storage/raw/", | ||
| "derived_status": "storage/derived/", | ||
| "product_read_support": "storage/products/", | ||
| "store_product": "storage/products/", # catch | ||
| "store_runtime": "storage/runtime/", # catch | ||
| } |
There was a problem hiding this comment.
STORAGE_PREFIX_TO_SUBPACKAGE mixes directory prefixes with file targets — produces __init__.pyinit__.py.
Most entries are directory prefixes (e.g. "session_product_": "storage/products/session/"), but three are full file paths: "repository.py": "storage/repository/__init__.py", "store.py": "storage/runtime/__init__.py", "search.py": "storage/search/__init__.py". When storage_target then concatenates sub + stem, it appends to a filename and produces e.g. polylogue/storage/repository/__init__.pyinit__.py (visible at lines 2410, 2492, 2596 of topology-target.yaml).
Note also that lstrip("_") mangles __init__.py itself into init__.py regardless of which path triggers it — "__init__.py".lstrip("_") removes both leading underscores.
Suggest treating these as exact-name overrides handled before the prefix loop, and using removeprefix-style stripping that doesn't mutate __init__.py:
🐛 Proposed fix
+STORAGE_EXACT_TARGETS = {
+ "repository.py": "polylogue/storage/repository/__init__.py",
+ "store.py": "polylogue/storage/runtime/__init__.py",
+ "search.py": "polylogue/storage/search/__init__.py",
+}
+
STORAGE_PREFIX_TO_SUBPACKAGE = {
...
- "repository.py": "storage/repository/__init__.py",
+ # (exact targets above; do not list as prefixes)
...
- "store.py": "storage/runtime/__init__.py",
...
- "search.py": "storage/search/__init__.py",
...
}
@@
def storage_target(name: str) -> str:
if name in STORAGE_ROOT_KEEP:
return f"polylogue/storage/{name}"
+ if name in STORAGE_EXACT_TARGETS:
+ return STORAGE_EXACT_TARGETS[name]
for prefix in sorted(STORAGE_PREFIX_TO_SUBPACKAGE, key=len, reverse=True):
...(Combined with the empty-stem fix in the other comment, this also avoids ever calling lstrip("_") on __init__.py.)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@devtools/build_topology_projection.py` around lines 137 - 169,
STORAGE_PREFIX_TO_SUBPACKAGE contains a mix of directory prefixes and full
file-target mappings which leads to malformed paths (e.g.
"__init__.pyinit__.py") when storage_target concatenates sub + stem; fix by
handling exact-file overrides before the prefix loop: detect keys like
"repository.py", "store.py", "search.py" and map them directly to their full
target values rather than treating them as prefixes, and replace any use of
stem.lstrip("_") with a removeprefix-style operation that only strips a single
leading underscore (or explicit logic that leaves "__init__.py" intact) so
"__init__.py" is not mutated; update the code paths that build storage_target
(referencing STORAGE_PREFIX_TO_SUBPACKAGE and the storage_target construction
logic) to first check exact-key matches, then fallback to prefix-matching with
safe prefix-stripping.
| def lib_target(name: str) -> str: | ||
| """Return target path for a polylogue/lib/<name> file, or 'TBD'.""" | ||
| if name in LIB_ROOT_PRIMITIVES: | ||
| return f"polylogue/lib/{name}" | ||
| # match longest prefix first | ||
| for prefix in sorted(LIB_PREFIX_TO_SUBPACKAGE, key=len, reverse=True): | ||
| if name.startswith(prefix): | ||
| sub = LIB_PREFIX_TO_SUBPACKAGE[prefix] | ||
| stem = name[len(prefix) :] or "__init__.py" | ||
| if not stem.endswith(".py"): | ||
| stem = stem + ".py" | ||
| stem = stem.lstrip("_") or "__init__.py" | ||
| return f"polylogue/{sub}{stem}" | ||
| return "TBD" | ||
|
|
||
|
|
||
| def storage_target(name: str) -> str: | ||
| if name in STORAGE_ROOT_KEEP: | ||
| return f"polylogue/storage/{name}" | ||
| for prefix in sorted(STORAGE_PREFIX_TO_SUBPACKAGE, key=len, reverse=True): | ||
| if name.startswith(prefix): | ||
| sub = STORAGE_PREFIX_TO_SUBPACKAGE[prefix] | ||
| stem = name[len(prefix) :] or "__init__.py" | ||
| if not stem.endswith(".py"): | ||
| stem = stem + ".py" | ||
| stem = stem.lstrip("_") or "__init__.py" | ||
| return f"polylogue/{sub}{stem}" | ||
| return "TBD" |
There was a problem hiding this comment.
Empty-stem bug: <prefix>.py files produce malformed <sub>/.py targets.
In both lib_target (lines 232-245) and storage_target (lines 248-259), when name == "<prefix>.py" and prefix is the entire stem, the slice name[len(prefix):] is ".py" (truthy, so the or "__init__.py" fallback doesn't fire), then it already ends in .py, then lstrip("_") is a no-op. Result: target ends with <sub>/.py.
Trace for filters.py (prefix filters):
stem = "filters.py"[7:] = ".py"not stem.endswith(".py")→ False, no appendstem.lstrip("_") = ".py"(truthy) → no fallback- target =
polylogue/lib/filter/.py❌
Same pattern broken for attribution.py, branch_type.py, threads.py, messages.py, neighbor_candidates.py, viewports.py, messages.py, content_projection.py, action_events.py, artifact_taxonomy.py, raw_payload.py, work_event_extraction.py, session_profile.py, session_summaries.py, plus storage equivalents (derived_status.py, embedding_stats.py, fts_lifecycle.py, product_read_support.py, repository_contracts.py, repository_raw.py, repository_vectors.py, repository_writes.py, store_constants.py). And semantic_facts.py becomes …/semantic/s.py due to a related prefix-overlap (semantic_fact swallows everything except the trailing s).
Fixing it once at the helper level resolves all the downstream YAML defects:
🐛 Proposed fix (factor stem normalization)
+def _stem_after_prefix(name: str, prefix: str) -> str:
+ """Return the .py filename to place under a subpackage when ``name`` matched ``prefix``.
+
+ ``polylogue/lib/messages.py`` with prefix ``messages`` → ``__init__.py``.
+ ``polylogue/lib/message_models.py`` with prefix ``message_`` → ``models.py``.
+ """
+ rest = name[len(prefix):]
+ core = rest.removesuffix(".py").lstrip("_")
+ return (core or "__init__") + ".py"
+
+
def lib_target(name: str) -> str:
"""Return target path for a polylogue/lib/<name> file, or 'TBD'."""
if name in LIB_ROOT_PRIMITIVES:
return f"polylogue/lib/{name}"
- # match longest prefix first
for prefix in sorted(LIB_PREFIX_TO_SUBPACKAGE, key=len, reverse=True):
if name.startswith(prefix):
sub = LIB_PREFIX_TO_SUBPACKAGE[prefix]
- stem = name[len(prefix) :] or "__init__.py"
- if not stem.endswith(".py"):
- stem = stem + ".py"
- stem = stem.lstrip("_") or "__init__.py"
- return f"polylogue/{sub}{stem}"
+ return f"polylogue/{sub}{_stem_after_prefix(name, prefix)}"
return "TBD"
def storage_target(name: str) -> str:
if name in STORAGE_ROOT_KEEP:
return f"polylogue/storage/{name}"
for prefix in sorted(STORAGE_PREFIX_TO_SUBPACKAGE, key=len, reverse=True):
if name.startswith(prefix):
sub = STORAGE_PREFIX_TO_SUBPACKAGE[prefix]
- stem = name[len(prefix) :] or "__init__.py"
- if not stem.endswith(".py"):
- stem = stem + ".py"
- stem = stem.lstrip("_") or "__init__.py"
- return f"polylogue/{sub}{stem}"
+ return f"polylogue/{sub}{_stem_after_prefix(name, prefix)}"
return "TBD"🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@devtools/build_topology_projection.py` around lines 232 - 259, Both
lib_target and storage_target produce malformed targets when the slice after a
matching prefix yields only ".py" (e.g., name == "<prefix>.py"), resulting in
paths like "<sub>/.py"; fix by normalizing the stem extraction logic: after
computing stem = name[len(prefix):], strip a leading dot and leading underscores
and treat an empty result as "__init__.py" (i.e., convert ".py" or "" to
"__init__.py"); update both lib_target and storage_target (they use
LIB_PREFIX_TO_SUBPACKAGE and STORAGE_PREFIX_TO_SUBPACKAGE) to apply this
normalized-stem rule so targets become "polylogue/<sub>__init__.py" or
"<sub><stem>.py" correctly.
| elif rel.startswith("polylogue/sources/"): | ||
| # Drive-specific files cluster | ||
| suffix = rel[len("polylogue/sources/") :] | ||
| if suffix.startswith("drive") and "/" not in suffix: | ||
| target = f"polylogue/sources/drive/{suffix.replace('drive_', '').replace('drive.py', '__init__.py') or '__init__.py'}" | ||
| issue = "#403" | ||
| elif suffix.startswith("parsers/claude") and "/" not in suffix[len("parsers/") :]: | ||
| # parsers/claude_* | ||
| stem = suffix[len("parsers/claude_") :] or "__init__.py" | ||
| target = f"polylogue/sources/parsers/claude/{stem}" | ||
| issue = "#403" | ||
| else: | ||
| target = rel | ||
| issue = "stable" |
There was a problem hiding this comment.
Off-by-one in the parsers/claude branch yields parsers/claude/py.
For polylogue/sources/parsers/claude.py, suffix == "parsers/claude.py". Line 349 strips len("parsers/claude_") == 15 chars, but the file's prefix is parsers/claude (no trailing underscore), so the slice is "py" and the target becomes polylogue/sources/parsers/claude/py (see line 1910 of topology-target.yaml). The intent is clearly that claude.py becomes the new package's __init__.py.
🐛 Proposed fix
- elif suffix.startswith("parsers/claude") and "/" not in suffix[len("parsers/") :]:
- # parsers/claude_*
- stem = suffix[len("parsers/claude_") :] or "__init__.py"
- target = f"polylogue/sources/parsers/claude/{stem}"
- issue = "#403"
+ elif suffix.startswith("parsers/claude") and "/" not in suffix[len("parsers/") :]:
+ # parsers/claude.py → __init__.py; parsers/claude_<x>.py → <x>.py
+ rest = suffix[len("parsers/claude") :] # ".py" or "_<rest>.py"
+ stem = "__init__.py" if rest == ".py" else rest.lstrip("_")
+ target = f"polylogue/sources/parsers/claude/{stem}"
+ issue = "#403"The same pattern is worth eyeballing for the drive branch above (line 345), which uses replace('drive_', '').replace('drive.py', '__init__.py'); today's set of files works, but the chained replace is global and brittle (e.g. a future drive_drive_x.py would lose both occurrences of drive_).
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@devtools/build_topology_projection.py` around lines 341 - 354, The
parsers/claude branch has an off-by-one slice: in the block that examines suffix
(variable suffix derived from rel) you should treat both "parsers/claude.py" and
names like "parsers/claude_x.py" correctly by removing the exact prefix
"parsers/claude" and then, if the remainder is empty or equals ".py", map to
"__init__.py", otherwise strip a single leading "_" (if present) to build the
stem; set target accordingly (set target and issue variables). Similarly,
replace the brittle chained replace in the drive branch: check if suffix ==
"drive.py" -> "__init__.py", else if suffix startswith "drive_" remove only the
single "drive_" prefix to form the filename, then build target and issue. Use
the existing rel, suffix, target, and issue symbols to locate and update the
logic.
| def emit_yaml(rows: list[dict[str, Any]], out: Path) -> None: | ||
| lines: list[str] = ["# Topology projection — generated by build_projection.py", "# See #429.", "", "files:"] | ||
| for row in rows: | ||
| lines.append(f" - path: {row['path']}") | ||
| lines.append(f" loc: {row['loc']}") | ||
| lines.append(f" target: {yaml_escape(row['target'])}") | ||
| if row["owner"]: | ||
| lines.append(f" owner: {row['owner']}") | ||
| if row["reason"]: | ||
| lines.append(f" reason: {yaml_escape(row['reason'])}") | ||
| if row["cross_cut"]: | ||
| tags = ", ".join(f"{k}: {v}" for k, v in sorted(row["cross_cut"].items())) | ||
| lines.append(f" cross_cut: {{ {tags} }}") | ||
| out.write_text("\n".join(lines) + "\n") |
There was a problem hiding this comment.
emit_yaml flow-mapping with spaces trips yamllint on every cross_cut row.
Line 392 emits " cross_cut: {{ {tags} }}" → { k: v, k2: v2 }. yamllint's default braces rule disallows the leading/trailing space inside flow mappings, producing ~200 errors against the generated file (visible in this PR's static-analysis hints). Cheapest fix is to drop the spaces; alternatively use block style.
🛠 Proposed fix
- if row["cross_cut"]:
- tags = ", ".join(f"{k}: {v}" for k, v in sorted(row["cross_cut"].items()))
- lines.append(f" cross_cut: {{ {tags} }}")
+ if row["cross_cut"]:
+ tags = ", ".join(f"{k}: {v}" for k, v in sorted(row["cross_cut"].items()))
+ lines.append(f" cross_cut: {{{tags}}}")After regenerating, all the too many spaces inside braces yamllint errors against docs/plans/topology-target.yaml should clear.
📝 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.
| def emit_yaml(rows: list[dict[str, Any]], out: Path) -> None: | |
| lines: list[str] = ["# Topology projection — generated by build_projection.py", "# See #429.", "", "files:"] | |
| for row in rows: | |
| lines.append(f" - path: {row['path']}") | |
| lines.append(f" loc: {row['loc']}") | |
| lines.append(f" target: {yaml_escape(row['target'])}") | |
| if row["owner"]: | |
| lines.append(f" owner: {row['owner']}") | |
| if row["reason"]: | |
| lines.append(f" reason: {yaml_escape(row['reason'])}") | |
| if row["cross_cut"]: | |
| tags = ", ".join(f"{k}: {v}" for k, v in sorted(row["cross_cut"].items())) | |
| lines.append(f" cross_cut: {{ {tags} }}") | |
| out.write_text("\n".join(lines) + "\n") | |
| def emit_yaml(rows: list[dict[str, Any]], out: Path) -> None: | |
| lines: list[str] = ["# Topology projection — generated by build_projection.py", "# See `#429`.", "", "files:"] | |
| for row in rows: | |
| lines.append(f" - path: {row['path']}") | |
| lines.append(f" loc: {row['loc']}") | |
| lines.append(f" target: {yaml_escape(row['target'])}") | |
| if row["owner"]: | |
| lines.append(f" owner: {row['owner']}") | |
| if row["reason"]: | |
| lines.append(f" reason: {yaml_escape(row['reason'])}") | |
| if row["cross_cut"]: | |
| tags = ", ".join(f"{k}: {v}" for k, v in sorted(row["cross_cut"].items())) | |
| lines.append(f" cross_cut: {{{tags}}}") | |
| out.write_text("\n".join(lines) + "\n") |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@devtools/build_topology_projection.py` around lines 380 - 393, The YAML
emitter emit_yaml is producing flow-mappings with extra spaces around braces for
cross_cut, which trips yamllint; locate the emit_yaml function and the block
that builds `tags = ", ".join(...)` and change the string formatting for the
cross_cut line to remove the spaces inside the braces so the flow mapping
becomes `{k: v, k2: v2}` without leading/trailing spaces (i.e., adjust the
format expression that currently emits the cross_cut line for row["cross_cut"]
to use braces immediately adjacent to the tags); regenerate the YAML output
after the change.
| def main(argv: Iterable[str] | None = None) -> int: | ||
| files = sorted(ROOT.glob("polylogue/**/*.py")) | ||
| rows = [classify(f) for f in files if "__pycache__" not in f.parts] | ||
| out = PROJECTION | ||
| out.parent.mkdir(parents=True, exist_ok=True) | ||
| emit_yaml(rows, out) | ||
| # Stats | ||
| by_owner: dict[str, int] = {} | ||
| tbd = 0 | ||
| for row in rows: | ||
| by_owner[row["owner"] or "(none)"] = by_owner.get(row["owner"] or "(none)", 0) + 1 | ||
| if row["target"] == "TBD": | ||
| tbd += 1 | ||
| print(f"Wrote {out} with {len(rows)} rows. TBD: {tbd}.") | ||
| print("By owner:") | ||
| for owner, count in sorted(by_owner.items(), key=lambda x: -x[1]): | ||
| print(f" {owner:>20s} {count:>4d}") | ||
| return 0 |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Add an invariant against malformed targets so this class of bug stops escaping.
Once the three classification bugs above are fixed, lock the result in: every emitted target should either be "TBD" or a valid Python module path. A cheap post-emission check would have caught all of polylogue/lib/<x>/.py, …/__init__.pyinit__.py, and …/claude/py before they shipped.
♻️ Proposed addition
def main(argv: Iterable[str] | None = None) -> int:
files = sorted(ROOT.glob("polylogue/**/*.py"))
rows = [classify(f) for f in files if "__pycache__" not in f.parts]
+ _validate_targets(rows)
out = PROJECTION
...
+def _validate_targets(rows: list[dict[str, Any]]) -> None:
+ bad: list[str] = []
+ for row in rows:
+ target = row["target"]
+ if target == "TBD":
+ continue
+ leaf = target.rsplit("/", 1)[-1]
+ if not target.endswith(".py") or leaf == ".py" or "/" in target and leaf.startswith(".") or ".pyinit" in target or "/py" == target[-3:]:
+ bad.append(f"{row['path']} -> {target}")
+ if bad:
+ raise SystemExit("malformed targets:\n " + "\n ".join(bad))Equivalent test in tests/unit/architecture/ would also work and would catch regressions without requiring the generator to be re-run.
📝 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.
| def main(argv: Iterable[str] | None = None) -> int: | |
| files = sorted(ROOT.glob("polylogue/**/*.py")) | |
| rows = [classify(f) for f in files if "__pycache__" not in f.parts] | |
| out = PROJECTION | |
| out.parent.mkdir(parents=True, exist_ok=True) | |
| emit_yaml(rows, out) | |
| # Stats | |
| by_owner: dict[str, int] = {} | |
| tbd = 0 | |
| for row in rows: | |
| by_owner[row["owner"] or "(none)"] = by_owner.get(row["owner"] or "(none)", 0) + 1 | |
| if row["target"] == "TBD": | |
| tbd += 1 | |
| print(f"Wrote {out} with {len(rows)} rows. TBD: {tbd}.") | |
| print("By owner:") | |
| for owner, count in sorted(by_owner.items(), key=lambda x: -x[1]): | |
| print(f" {owner:>20s} {count:>4d}") | |
| return 0 | |
| def main(argv: Iterable[str] | None = None) -> int: | |
| files = sorted(ROOT.glob("polylogue/**/*.py")) | |
| rows = [classify(f) for f in files if "__pycache__" not in f.parts] | |
| _validate_targets(rows) | |
| out = PROJECTION | |
| out.parent.mkdir(parents=True, exist_ok=True) | |
| emit_yaml(rows, out) | |
| # Stats | |
| by_owner: dict[str, int] = {} | |
| tbd = 0 | |
| for row in rows: | |
| by_owner[row["owner"] or "(none)"] = by_owner.get(row["owner"] or "(none)", 0) + 1 | |
| if row["target"] == "TBD": | |
| tbd += 1 | |
| print(f"Wrote {out} with {len(rows)} rows. TBD: {tbd}.") | |
| print("By owner:") | |
| for owner, count in sorted(by_owner.items(), key=lambda x: -x[1]): | |
| print(f" {owner:>20s} {count:>4d}") | |
| return 0 | |
| def _validate_targets(rows: list[dict[str, Any]]) -> None: | |
| bad: list[str] = [] | |
| for row in rows: | |
| target = row["target"] | |
| if target == "TBD": | |
| continue | |
| leaf = target.rsplit("/", 1)[-1] | |
| if not target.endswith(".py") or leaf == ".py" or "/" in target and leaf.startswith(".") or ".pyinit" in target or "/py" == target[-3:]: | |
| bad.append(f"{row['path']} -> {target}") | |
| if bad: | |
| raise SystemExit("malformed targets:\n " + "\n ".join(bad)) |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@devtools/build_topology_projection.py` around lines 396 - 413, Add a
post-generation invariant check in main (after rows are computed and
before/after emit_yaml) that validates every row["target"] is either the literal
"TBD" or a well-formed Python module path; use the existing classify/rows output
and reject values containing path separators, repeated suffixes, or non-module
characters (e.g. enforce regex like
^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$), and if any row fails, log
the offending filename/target and fail fast (raise an exception or return
non-zero) so bad values (e.g. "polylogue/lib/<x>/.py", "__init__.pyinit__.py",
"claude/py") cannot be emitted; also add a unit test in tests/unit/architecture
that constructs sample rows and asserts the validator accepts only "TBD" or
valid module paths.
| def collect_imports(path: Path) -> list[str]: | ||
| try: | ||
| tree = ast.parse(path.read_text()) | ||
| except Exception: | ||
| return [] | ||
| imports: list[str] = [] | ||
| for node in ast.walk(tree): | ||
| if isinstance(node, ast.Import): | ||
| for alias in node.names: | ||
| imports.append(alias.name) | ||
| elif isinstance(node, ast.ImportFrom) and node.module: | ||
| imports.append(node.module) | ||
| return imports |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Specify UTF-8 explicitly for source reads.
path.read_text() (here and at Line 120 for the YAML) uses the platform default encoding, which is locale-dependent on Windows / non-UTF-8 LANG setups and can corrupt non-ASCII identifiers/comments before parsing. The same applies to the YAML read at Line 120. Pass encoding="utf-8" so the verifier behaves identically across CI hosts.
- tree = ast.parse(path.read_text())
+ tree = ast.parse(path.read_text(encoding="utf-8"))- rows = parse_yaml(args.yaml.read_text())
+ rows = parse_yaml(args.yaml.read_text(encoding="utf-8"))🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@devtools/verify_cluster_cohesion.py` around lines 98 - 110, The code uses
Path.read_text() without specifying encoding which can break on non-UTF-8
locales; update collect_imports to call path.read_text(encoding="utf-8") and
likewise change the other YAML read call that currently uses Path.read_text()
(the YAML parsing site) to pass encoding="utf-8" so source and YAML reads are
consistently decoded as UTF-8; adjust any tests or callers if they rely on
default behavior.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Count relative ImportFrom nodes (level > 0) under polylogue/.
fd -e py . polylogue | xargs -I{} python -c "
import ast, sys
try:
t = ast.parse(open('{}').read())
except Exception:
sys.exit(0)
for n in ast.walk(t):
if isinstance(n, ast.ImportFrom) and n.level:
print('{}', n.level, n.module)
" | head -50Repository: Sinity/polylogue
Length of output: 9428
Relative imports are silently dropped, undercounting cross-cluster edges.
collect_imports records node.module as-is for ast.ImportFrom, ignoring node.level. For relative imports (e.g. from .query_plan import foo inside polylogue/lib/query_plan_execution.py, or from ..core import bar), the recorded name is "query_plan" / "core", which fails the name.startswith("polylogue.") check in module_name_to_cluster and is discarded. Relative imports are extensively used throughout the codebase (50+ confirmed cases), so any cross-cluster edge expressed via relative imports is invisible to cycle detection, fan-in/out counts, and through-internals reporting — undermining the cohesion claim the script is trying to make executable.
Resolve relative imports against the importing file's package before recording:
🔧 Proposed fix
-def collect_imports(path: Path) -> list[str]:
+def _module_name_for(path: Path) -> str | None:
+ """Derive the dotted module name for a file under polylogue/."""
+ try:
+ rel = path.relative_to(ROOT).with_suffix("")
+ except ValueError:
+ return None
+ parts = list(rel.parts)
+ if not parts or parts[0] != "polylogue":
+ return None
+ if parts[-1] == "__init__":
+ parts = parts[:-1]
+ return ".".join(parts)
+
+
+def collect_imports(path: Path) -> list[str]:
try:
- tree = ast.parse(path.read_text())
+ tree = ast.parse(path.read_text(encoding="utf-8"))
except Exception:
return []
+ pkg = _module_name_for(path)
+ pkg_parts = pkg.split(".") if pkg else []
imports: list[str] = []
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
imports.append(alias.name)
- elif isinstance(node, ast.ImportFrom) and node.module:
- imports.append(node.module)
+ elif isinstance(node, ast.ImportFrom):
+ if node.level and pkg_parts:
+ # `from . import x` inside polylogue.lib.query.foo
+ # resolves the package up `level` segments from foo's parent.
+ base = pkg_parts[: max(0, len(pkg_parts) - node.level)]
+ if not base:
+ continue
+ resolved = ".".join(base + ([node.module] if node.module else []))
+ imports.append(resolved)
+ elif node.module:
+ imports.append(node.module)
return imports🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@devtools/verify_cluster_cohesion.py` around lines 98 - 110, collect_imports
currently drops relative imports because it appends node.module verbatim and
ignores node.level; update collect_imports to resolve relative imports to their
fully qualified package names before appending. Specifically, compute the
importing module's package from the Path argument (derive its module path by
converting the file path to a dotted package path using package directories /
__init__.py presence or by using the file's parent package parts), then for
ast.ImportFrom nodes use node.level to walk up that package (remove last
`node.level` components) and then append node.module (or the imported names if
node.module is None) to form the full dotted name; keep existing behavior for
absolute imports (ast.Import and node.level == 0). Ensure the function returns
these resolved fully qualified module names so module_name_to_cluster can
correctly detect cross-cluster edges.
| # Cycles between clusters | ||
| cycles: list[tuple[str, str]] = [] | ||
| seen_pairs: set[frozenset[str]] = set() | ||
| for src, tgts in cluster_edges.items(): | ||
| for tgt in tgts: | ||
| if src in cluster_edges.get(tgt, set()): | ||
| pair = frozenset([src, tgt]) | ||
| if pair not in seen_pairs and src != tgt: | ||
| cycles.append((src, tgt)) | ||
| seen_pairs.add(pair) |
There was a problem hiding this comment.
Cycle detection only catches 2-cycles; longer cluster cycles are missed.
The current logic flags a cycle iff src ∈ edges[tgt] and tgt ∈ edges[src] — i.e. mutual edges. A 3+ cluster cycle such as lib/query → lib/index → core → lib/query has no mutual edges and will be silently absent from the report, so the headline BLOCKING= count understates true cohesion failures. Given the PR mentions ~43 surfaced cycles (and that this is the gating metric for wiring into verify), prefer Tarjan/Kosaraju SCC over the pairwise check.
🔧 Proposed fix using stdlib
- # Cycles between clusters
- cycles: list[tuple[str, str]] = []
- seen_pairs: set[frozenset[str]] = set()
- for src, tgts in cluster_edges.items():
- for tgt in tgts:
- if src in cluster_edges.get(tgt, set()):
- pair = frozenset([src, tgt])
- if pair not in seen_pairs and src != tgt:
- cycles.append((src, tgt))
- seen_pairs.add(pair)
+ # Cycles between clusters via strongly-connected components.
+ from graphlib import TopologicalSorter # noqa: PLC0415
+ # Build SCCs with iterative Tarjan to capture cycles of any length.
+ index: dict[str, int] = {}
+ lowlink: dict[str, int] = {}
+ on_stack: set[str] = set()
+ stack: list[str] = []
+ sccs: list[list[str]] = []
+ counter = 0
+
+ def strongconnect(v: str) -> None:
+ nonlocal counter
+ work = [(v, iter(cluster_edges.get(v, set())))]
+ index[v] = lowlink[v] = counter
+ counter += 1
+ stack.append(v); on_stack.add(v)
+ while work:
+ node, it = work[-1]
+ for w in it:
+ if w not in index:
+ index[w] = lowlink[w] = counter
+ counter += 1
+ stack.append(w); on_stack.add(w)
+ work.append((w, iter(cluster_edges.get(w, set()))))
+ break
+ if w in on_stack:
+ lowlink[node] = min(lowlink[node], index[w])
+ else:
+ if lowlink[node] == index[node]:
+ comp: list[str] = []
+ while True:
+ x = stack.pop(); on_stack.discard(x); comp.append(x)
+ if x == node:
+ break
+ if len(comp) > 1:
+ sccs.append(comp)
+ work.pop()
+ if work:
+ parent = work[-1][0]
+ lowlink[parent] = min(lowlink[parent], lowlink[node])
+
+ for v in list(cluster_edges):
+ if v not in index:
+ strongconnect(v)
+ cycles = sccs(and update the print loop to render comp lists rather than pairs.)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@devtools/verify_cluster_cohesion.py` around lines 163 - 172, The current
pairwise check using cluster_edges, cycles and seen_pairs only finds mutual
2-cycles; replace it with a Strongly Connected Components algorithm (Tarjan or
Kosaraju) over the directed graph represented by cluster_edges: build the graph
from cluster_edges, run SCC to produce components, collect any component with
length >1 (or length==1 with a self-edge) as a cycle, replace the
cycles:list[tuple[str,str]] logic (and drop seen_pairs) with
cycles:list[list[str]] of SCCs, and update the subsequent print/render loop to
display each component list instead of pair tuples.
| if args.cluster: | ||
| targets_to_show = [args.cluster] if args.cluster in cluster_sizes else [] | ||
| for c in targets_to_show: | ||
| size = cluster_sizes[c] | ||
| fan_out = len(cluster_edges.get(c, set())) | ||
| ib = inbound.get(c, 0) | ||
| print(f"{c:<40s} {size:>6d} {fan_out:>9d} {ib:>9d}") | ||
|
|
||
| print() | ||
| print(f"Cycles between proposed clusters: {len(cycles)}") | ||
| for a, b in cycles[:20]: | ||
| print(f" {a} <-> {b}") | ||
| if len(cycles) > 20: | ||
| print(f" ... and {len(cycles) - 20} more") | ||
|
|
||
| print() | ||
| print(f"Lonely clusters (< {args.min_cluster_size} modules): {len(lonely)}") | ||
| for c in lonely: | ||
| print(f" {c} ({cluster_sizes[c]})") | ||
|
|
||
| print() | ||
| cross_total = sum(len(v) for v in cross_internals.values()) | ||
| print(f"Cross-cluster imports through internals (bypass __init__): {cross_total}") | ||
| for c in sorted(cross_internals, key=lambda k: -len(cross_internals[k]))[:5]: | ||
| items = cross_internals[c] | ||
| print(f" {c}: {len(items)} (top samples)") | ||
| for src, imp, dst in items[:3]: | ||
| print(f" {src} -> {imp} (cluster {dst})") |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
--cluster filter is inconsistent: it narrows the size table but not the cycles / lonely / cross-internals sections.
When the user passes --cluster lib/query, only the per-cluster summary table at Lines 190-194 is filtered; the cycles list (197-201), lonely list (204-206), and cross-internals report (209-215) still print globally. Either filter all sections to the requested cluster (recommended for "drill into one cluster" use cases) or document that --cluster only affects the top table.
♻️ Sketch
- print(f"Cycles between proposed clusters: {len(cycles)}")
- for a, b in cycles[:20]:
+ shown_cycles = [
+ (a, b) for a, b in cycles
+ if not args.cluster or args.cluster in (a, b)
+ ]
+ print(f"Cycles between proposed clusters: {len(shown_cycles)}")
+ for a, b in shown_cycles[:20]:
print(f" {a} <-> {b}")(apply analogously to lonely and the cross_internals keys)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@devtools/verify_cluster_cohesion.py` around lines 188 - 215, The --cluster
filter currently only narrows targets_to_show but leaves cycles, lonely and
cross_internals global; when args.cluster is set, filter those collections to
the requested cluster. Concretely: if args.cluster is truthy (same place where
targets_to_show is set), replace cycles with [p for p in cycles if args.cluster
in p], replace lonely with [c for c in lonely if c == args.cluster], and reduce
cross_internals to {k: v for k, v in cross_internals.items() if k ==
args.cluster} (or empty structures if missing) before printing so the cycles,
lonely and cross-internals sections only show data for the requested cluster;
keep using the existing symbols cycles, lonely, cross_internals, args.cluster,
targets_to_show, cluster_sizes, cluster_edges, inbound.
| * kernel-rule — root file not in the declared kernel set | ||
| * tbd — projection cells still marked TBD | ||
|
|
||
| Exits 0 if everything passes, 1 if any blocking finding, 2 if only warnings. |
There was a problem hiding this comment.
Docstring promises exit code 2 for warnings — implementation never returns it.
Line 11 says "Exits 0 if everything passes, 1 if any blocking finding, 2 if only warnings." but line 168 only ever returns 0 or 1. Unless --strict-tbd is set, TBD warnings produce exit 0, so the documented "2 = warnings only" contract is unimplemented.
Either return 2 when there are warnings without blocking findings, or update the docstring to match actual behavior:
📝 Proposed alignment (option: implement the contract)
- return 1 if blocking else 0
+ if blocking:
+ return 1
+ if warnings:
+ return 2
+ return 0If you keep exit-2 as a future feature, please update the docstring instead so callers (incl. the new verify --quick wiring) don't rely on a contract that isn't there.
Also applies to: 137-168
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@devtools/verify_topology.py` at line 11, Docstring claims exit 2 for
warnings-only but the end-of-run logic only returns 0 or 1; update the exit
decision in the verification entrypoint (e.g., the main() function in
verify_topology.py or the function that aggregates check results) to return 2
when there are no blocking findings but there are warnings (taking into account
the --strict-tbd flag: if strict_tbd is True treat TBDs as blocking, otherwise
count them as warnings); compute blocking_count and warning_count from the
existing result objects/collections and replace the final return/exit call so it
returns 2 when blocking_count == 0 and warning_count > 0, 1 when blocking_count
> 0, and 0 when both are zero.
| return "/" not in suffix | ||
|
|
||
|
|
||
| def main(argv: Iterable[str]) -> int: |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Align main signature with the rest of devtools commands.
Other devtools entrypoints follow def main(argv: list[str] | None = None) -> int (see devtools/verify.py line 61, devtools/build_topology_projection.py line 396), which matches the CommandMain = Callable[[list[str] | None], int] type alias in command_catalog.py. Here argv: Iterable[str] has no default, so main() (no-arg) raises TypeError and the type doesn't satisfy CommandMain.
♻️ Proposed signature change
-def main(argv: Iterable[str]) -> int:
+def main(argv: list[str] | None = None) -> int:
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--yaml", type=Path, default=PROJECTION)
p.add_argument("--strict-tbd", action="store_true", help="Treat TBD entries as blocking.")
p.add_argument("--json", action="store_true", help="Emit JSON for tooling.")
- args = p.parse_args(list(argv))
+ args = p.parse_args(list(argv) if argv is not None else None)Also applies to: 171-172
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@devtools/verify_topology.py` at line 92, The main function signature in
verify_topology.py currently uses "def main(argv: Iterable[str]) -> int" with no
default, which breaks the CommandMain type; change it to "def main(argv:
list[str] | None = None) -> int" (and update any other main definitions at the
same file locations around lines 171-172) so it matches the CommandMain =
Callable[[list[str] | None], int] alias used across devtools; adjust
imports/types if necessary (replace Iterable[str] with list[str] | None) and
ensure any callers that pass None or call main() without args continue to work.
## Summary Closes #435. Reopens the work from #439 (auto-closed when its base branch was deleted by #438's merge). Adds the second evidence-driven structural lint after #429 (topology). Catches file accretion early. ## Problem Polylogue has several modules and tests that grew past sustainable size: `pipeline_probe.py` (1,468 LOC), `proof/runners.py` (1,339 LOC), several test files at 2,000+ LOC. Issue #419 splits the worst offenders, but nothing prevents the next file from accreting in the same shape. ## Solution Same shape as #429: a declarative YAML manifest plus a small lint that walks the realized tree. - **`docs/plans/file-size-budgets.yaml`**: defaults (source 1100, test 1500); per-package ceilings for `devtools/`, `polylogue/proof/`, `polylogue/pipeline/services/`, `polylogue/operations/`, `polylogue/storage/`, `tests/infra/`; nine exceptions naming sunset issues (#403, #419). - **`devtools/verify_file_budgets.py`** (~150 LOC): walks `polylogue/`, `devtools/`, `tests/`. Resolves ceilings via exception → per-package → default. Reports overages with file path, current LOC, and ceiling source. - Wired into `devtools verify --quick` after `verify-topology`. - `tests/unit/devtools/test_verify_file_budgets.py`: parser round-trip, resolution-order, and "committed budgets are clean" smoke test. ## Verification ``` $ devtools verify-file-budgets file-size budgets: clean $ devtools verify --quick verify: all checks passed (incl. verify-topology, verify-file-budgets) $ pytest tests/unit/devtools/test_verify_file_budgets.py 3 passed ``` ## Context Previously stacked on `feature/feat/topology-cohesion-executable`; rebased to master after #438 merged. Refs #401, #419, #429, #435. 🤖 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 `devtools verify-file-budgets` command to enforce per-file line-of-code budgets defined in a configuration file * Supports JSON output format and policy configuration with per-package overrides and temporary exceptions * **Documentation** * Added documentation for the new file budget verification command * **Tests** * Added tests for file budget verification functionality <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
## 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]>
## Summary Phase 3 of #429. Renders `docs/topology-status.md` from the topology projection (`docs/plans/topology-target.yaml`) plus the realized `polylogue/` tree. The dashboard is checked-in markdown so structural-cohesion progress is visible to anyone reading docs, not just to those who run lints locally. ## Problem After Phase 1 of #429 landed (`devtools verify-topology` lint, plus xfail tests), structural drift was checkable only via local commands. Outsiders looking at the architecture-cohesion track had no single artifact telling them "of the seven topology refactors, here's how far each has gotten." ## Solution `devtools render-topology-status` builds a per-issue dashboard table: ``` | Issue | Title | Cells | At target | Pending | Conflicts | | --- | --- | --: | --: | --: | --: | | #403 | rationalize source and test module structure | 16 | 0 | 16 | 0 | | #414 | rationalize product ownership and package boundary | 8 | 0 | 8 | 0 | | #424 | group lib by domain cluster | 57 | 0 | 57 | 8 | | #425 | group storage by ownership domain | 63 | 0 | 63 | 4 | | #426 | rationalize package-root layout and consolidate facade surface | 15 | 0 | 15 | 0 | ``` Plus summary counts (stable / kernel / primitives / TBD) and the explicit TBD list. Wired into `devtools render-all` as a generated surface — drift fails `render-all --check`. Each refactor PR updates the dashboard automatically as cells move. ## Verification ``` $ devtools render-topology-status $ devtools render-all --check render-all: check topology-status ... sync OK $ devtools verify --quick verify: all checks passed (incl. all 8 lints) ``` ## Coordinates with Pattern complete for #429: 1. **Phase 1** (PR #438): projection + lints + xfail tests. 2. **Phase 2**: topology obligation family in `polylogue/proof/catalog.py` (still pending). 3. **Phase 3** (this PR): drift dashboard. ## Related - #429 — pattern source. - #432 — evidence-driven structural specification (Phase 2 substrate). - #401 — post-renewal consolidation umbrella. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added `devtools render-topology-status` CLI command to generate topology status dashboard. * Topology status dashboard displays per-issue migration progress, cell counts, target status, and conflict detection. * Dashboard automatically renders from target configuration and project codebase. * **Tests** * Resolved previously failing topology status documentation test. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
…) (#438) ## Summary Phase 1 of #429: convert structural-cohesion claims from observational ("subpackage layout is obvious") to CI-checkable invariants. Three new devtools commands plus a 638-row projection plus an xfail invariant suite that flips green as the topology refactors land. ## Problem The seven topology refactors (#403, #413, #414, #419, #420, #424, #425, #426) all carried acceptance criteria of the form *"subpackage layout is obvious," "no compatibility re-exports survive," "future contributor can place a module deterministically."* These criteria are observational — they only become true after the change, can only be checked by human review, and silently rot as the tree drifts. Polylogue already has the right substrate for executable structural claims (the proof kernel, `devtools affected-obligations`). This PR builds the projection + lints layer that the topology issues can hook into, and seeds the post-state invariants as xfail tests. ## Solution Three new devtools commands, one projection YAML, one xfail test suite. All structural-cohesion claims become CI-checkable. ### `docs/plans/topology-target.yaml` — projection 638 rows, one per `polylogue/**/*.py`. Each row declares current path, target path, owning issue, and (planned) cross-cut tags. Cells are derived by `devtools build-topology-projection` from placement rules embedded in the topology refactor issues; 39 are `target: TBD` where the rule could not infer a destination. Those TBDs are concrete prompts for the implementer of #424 (9 lib files) and #413 (29 showcase files). ### `devtools verify-topology` Lints the realized tree against the projection. Reports orphans (file in tree, not in YAML), conflicts (declared twice), missing (in YAML, not in tree), and kernel-rule violations (root file not declared kernel). TBDs surface as warnings; `--strict-tbd` promotes them to blocking. Exit 0 if clean (with warnings); exit 1 if blocking. Wired into `devtools verify --quick`. Currently runs in 0.2s with zero blocking findings against `master`. ### `devtools verify-cluster-cohesion` AST-based check of the proposed clusters. For each declared subpackage, builds the import graph and reports cross-cluster imports through internals (bypassing `__init__.py`), cycles between clusters, lonely clusters, and per-cluster fan-in/fan-out. Catches *bad cuts* before any file moves. This pre-flight already surfaced two real architectural cycles that no human review of the existing tree had spotted: pipeline → cli (filed as #430) and cli/commands → cli (filed as #431). Not yet wired into `verify` because the realized tree currently has 43 surfaced cycles that the topology refactors and #430/#431 will resolve incrementally. ### `devtools build-topology-projection` Generates the YAML projection from placement rules. Re-runnable as the rules iterate. ### `tests/unit/architecture/test_topology_invariants.py` 13 tests, each tagged `@pytest.mark.xfail(strict=True)` with a reference to its owning refactor issue. Three pass today (the lints exist, the projection YAML exists), confirming Phase 1 has landed. Eleven xfail awaiting subsequent refactors; each xfail flips to UNEXPECTED PASS when its refactor lands and the test author converts it to a regular `assert`. Subsequent regression then fails CI. ### Pattern The pattern this PR establishes — projection YAML + lint + cohesion check + xfail invariants — is reusable for any future architectural claim. Issues #432 (cross-cuts), #433 (layering rules), #434 (migration completeness), #435 (file-size budgets), #436 (mypy coverage), #437 (test ownership) all apply the same shape to other axes. ## Verification ```bash $ devtools verify --quick verify: running local verification baseline ruff format ... ok (0.0s) ruff check ... ok (0.0s) mypy ... ok (2.5s) render-all ... ok (44.4s) verify-topology ... ok (0.2s) verify: all checks passed $ devtools verify-topology [warn] tbd: 39 realized=638 declared=638 blocking=False $ devtools verify-cluster-cohesion 2>&1 | tail Cycles between proposed clusters: 43 Lonely clusters (< 3 modules): 8 Cross-cluster imports through internals (bypass __init__): 1273 BLOCKING=True (cycles between clusters) $ nix develop -c pytest tests/unit/architecture/ -q 3 passed, 11 xfailed in 8.43s $ nix develop -c pytest -q --ignore=tests/integration 4463 passed in ~165s ``` ## Migration / follow-ups - This PR is **Phase 1**: projection + lints + xfails + wiring. - **Phase 2** (per #429): topology obligation family in `polylogue/proof/catalog.py`; routes through `devtools affected-obligations`. - **Phase 3** (per #429): `docs/topology-status.md` drift dashboard rendered by `devtools render-all`. The seven topology refactor issues now reference the projection cells they own and the lints as their acceptance criteria (added 2026-04-26 by the verification addendum on #403/#413/#414/#420/#424/#425/#426). Closes Phase 1 of #429. Refs #401, #403, #413, #414, #420, #424, #425, #426, #427, #432, #433, #434, #435, #436, #437. 🤖 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 topology projection generator to document module organization * Added topology verification to validate consistency between declared and realized modules * Added cluster cohesion validator to detect cross-cluster dependency violations * Topology verification now included in pre-push checks * **Documentation** * Added architecture invariants and module topology reference <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
## Summary Closes #435. Reopens the work from #439 (auto-closed when its base branch was deleted by #438's merge). Adds the second evidence-driven structural lint after #429 (topology). Catches file accretion early. ## Problem Polylogue has several modules and tests that grew past sustainable size: `pipeline_probe.py` (1,468 LOC), `proof/runners.py` (1,339 LOC), several test files at 2,000+ LOC. Issue #419 splits the worst offenders, but nothing prevents the next file from accreting in the same shape. ## Solution Same shape as #429: a declarative YAML manifest plus a small lint that walks the realized tree. - **`docs/plans/file-size-budgets.yaml`**: defaults (source 1100, test 1500); per-package ceilings for `devtools/`, `polylogue/proof/`, `polylogue/pipeline/services/`, `polylogue/operations/`, `polylogue/storage/`, `tests/infra/`; nine exceptions naming sunset issues (#403, #419). - **`devtools/verify_file_budgets.py`** (~150 LOC): walks `polylogue/`, `devtools/`, `tests/`. Resolves ceilings via exception → per-package → default. Reports overages with file path, current LOC, and ceiling source. - Wired into `devtools verify --quick` after `verify-topology`. - `tests/unit/devtools/test_verify_file_budgets.py`: parser round-trip, resolution-order, and "committed budgets are clean" smoke test. ## Verification ``` $ devtools verify-file-budgets file-size budgets: clean $ devtools verify --quick verify: all checks passed (incl. verify-topology, verify-file-budgets) $ pytest tests/unit/devtools/test_verify_file_budgets.py 3 passed ``` ## Context Previously stacked on `feature/feat/topology-cohesion-executable`; rebased to master after #438 merged. Refs #401, #419, #429, #435. 🤖 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 `devtools verify-file-budgets` command to enforce per-file line-of-code budgets defined in a configuration file * Supports JSON output format and policy configuration with per-package overrides and temporary exceptions * **Documentation** * Added documentation for the new file budget verification command * **Tests** * Added tests for file budget verification functionality <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
## 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]>
## Summary Phase 3 of #429. Renders `docs/topology-status.md` from the topology projection (`docs/plans/topology-target.yaml`) plus the realized `polylogue/` tree. The dashboard is checked-in markdown so structural-cohesion progress is visible to anyone reading docs, not just to those who run lints locally. ## Problem After Phase 1 of #429 landed (`devtools verify-topology` lint, plus xfail tests), structural drift was checkable only via local commands. Outsiders looking at the architecture-cohesion track had no single artifact telling them "of the seven topology refactors, here's how far each has gotten." ## Solution `devtools render-topology-status` builds a per-issue dashboard table: ``` | Issue | Title | Cells | At target | Pending | Conflicts | | --- | --- | --: | --: | --: | --: | | #403 | rationalize source and test module structure | 16 | 0 | 16 | 0 | | #414 | rationalize product ownership and package boundary | 8 | 0 | 8 | 0 | | #424 | group lib by domain cluster | 57 | 0 | 57 | 8 | | #425 | group storage by ownership domain | 63 | 0 | 63 | 4 | | #426 | rationalize package-root layout and consolidate facade surface | 15 | 0 | 15 | 0 | ``` Plus summary counts (stable / kernel / primitives / TBD) and the explicit TBD list. Wired into `devtools render-all` as a generated surface — drift fails `render-all --check`. Each refactor PR updates the dashboard automatically as cells move. ## Verification ``` $ devtools render-topology-status $ devtools render-all --check render-all: check topology-status ... sync OK $ devtools verify --quick verify: all checks passed (incl. all 8 lints) ``` ## Coordinates with Pattern complete for #429: 1. **Phase 1** (PR #438): projection + lints + xfail tests. 2. **Phase 2**: topology obligation family in `polylogue/proof/catalog.py` (still pending). 3. **Phase 3** (this PR): drift dashboard. ## Related - #429 — pattern source. - #432 — evidence-driven structural specification (Phase 2 substrate). - #401 — post-renewal consolidation umbrella. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added `devtools render-topology-status` CLI command to generate topology status dashboard. * Topology status dashboard displays per-issue migration progress, cell counts, target status, and conflict detection. * Dashboard automatically renders from target configuration and project codebase. * **Tests** * Resolved previously failing topology status documentation test. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
|
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. |
|
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. |
|
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. |
Summary
Phase 1 of #429: convert structural-cohesion claims from observational ("subpackage layout is obvious") to CI-checkable invariants. Three new devtools commands plus a 638-row projection plus an xfail invariant suite that flips green as the topology refactors land.
Problem
The seven topology refactors (#403, #413, #414, #419, #420, #424, #425, #426) all carried acceptance criteria of the form "subpackage layout is obvious," "no compatibility re-exports survive," "future contributor can place a module deterministically." These criteria are observational — they only become true after the change, can only be checked by human review, and silently rot as the tree drifts.
Polylogue already has the right substrate for executable structural claims (the proof kernel,
devtools affected-obligations). This PR builds the projection + lints layer that the topology issues can hook into, and seeds the post-state invariants as xfail tests.Solution
Three new devtools commands, one projection YAML, one xfail test suite. All structural-cohesion claims become CI-checkable.
docs/plans/topology-target.yaml— projection638 rows, one per
polylogue/**/*.py. Each row declares current path, target path, owning issue, and (planned) cross-cut tags. Cells are derived bydevtools build-topology-projectionfrom placement rules embedded in the topology refactor issues; 39 aretarget: TBDwhere the rule could not infer a destination. Those TBDs are concrete prompts for the implementer of #424 (9 lib files) and #413 (29 showcase files).devtools verify-topologyLints the realized tree against the projection. Reports orphans (file in tree, not in YAML), conflicts (declared twice), missing (in YAML, not in tree), and kernel-rule violations (root file not declared kernel). TBDs surface as warnings;
--strict-tbdpromotes them to blocking.Exit 0 if clean (with warnings); exit 1 if blocking. Wired into
devtools verify --quick. Currently runs in 0.2s with zero blocking findings againstmaster.devtools verify-cluster-cohesionAST-based check of the proposed clusters. For each declared subpackage, builds the import graph and reports cross-cluster imports through internals (bypassing
__init__.py), cycles between clusters, lonely clusters, and per-cluster fan-in/fan-out. Catches bad cuts before any file moves.This pre-flight already surfaced two real architectural cycles that no human review of the existing tree had spotted: pipeline → cli (filed as #430) and cli/commands → cli (filed as #431). Not yet wired into
verifybecause the realized tree currently has 43 surfaced cycles that the topology refactors and #430/#431 will resolve incrementally.devtools build-topology-projectionGenerates the YAML projection from placement rules. Re-runnable as the rules iterate.
tests/unit/architecture/test_topology_invariants.py13 tests, each tagged
@pytest.mark.xfail(strict=True)with a reference to its owning refactor issue. Three pass today (the lints exist, the projection YAML exists), confirming Phase 1 has landed. Eleven xfail awaiting subsequent refactors; each xfail flips to UNEXPECTED PASS when its refactor lands and the test author converts it to a regularassert. Subsequent regression then fails CI.Pattern
The pattern this PR establishes — projection YAML + lint + cohesion check + xfail invariants — is reusable for any future architectural claim. Issues #432 (cross-cuts), #433 (layering rules), #434 (migration completeness), #435 (file-size budgets), #436 (mypy coverage), #437 (test ownership) all apply the same shape to other axes.
Verification
Migration / follow-ups
polylogue/proof/catalog.py; routes throughdevtools affected-obligations.docs/topology-status.mddrift dashboard rendered bydevtools render-all.The seven topology refactor issues now reference the projection cells they own and the lints as their acceptance criteria (added 2026-04-26 by the verification addendum on #403/#413/#414/#420/#424/#425/#426).
Closes Phase 1 of #429.
Refs #401, #403, #413, #414, #420, #424, #425, #426, #427, #432, #433, #434, #435, #436, #437.
🤖 Generated with Claude Code
Summary by CodeRabbit
Release Notes
New Features
Documentation