Repository navigation
Description
Parent
Part of #401. Companion to #420 (schemas), #414 (products), #403 (sources).
Problem
polylogue/lib/ is the largest non-storage non-schema package by file count: 83 modules, ~12,500 LOC. It is documented in docs/architecture.md as part of the substrate ring ("if it changes archive meaning"), but in practice it is a flat catch-all that mixes:
- domain logic (queries, sessions, viewports, threads, tail overlays, semantic facts);
- infrastructure primitives (
json,hashing,dates,timestamps,roles,security); - model carriers (
message_models,conversation_models,attachment_models,viewport_models); - runtime adapters (
*_runtimesuffix across half a dozen prefixes).
The ring rule does not survive the package: a contributor cannot tell from the rule alone whether a new query helper goes here, in pipeline/, in storage/, or at the package root. The flat layout also obscures import dependencies between clusters.
Current evidence
Prefix families in polylogue/lib/:
query_*— 15 modules (query_plan,query_runtime,query_retrieval,query_search_hits,query_sorting,query_runtime_filters,query_runtime_matching,query_runtime_plan,query_spec,query_support, …). The biggest single domain inlib/and arguably its own subpackage today.session_profile*,session_payload_documents,session_summaries— 5+ modules; session-product read substrate.viewport_*— 4 modules (enums, models, viewports, tools).raw_payload_*— 5 modules including sampling buckets/extract and decode.artifact_taxonomy_*— 4 modules.action_event_*— 3 modules.message_*— 4 modules includingmessage_model_runtime.conversation_*— 3 modules includingconversation_runtimeandconversation_summary_runtime.semantic_fact*— 3 modules.attachment_models,attribution,branch_type,content_projection,coverage,filters,filter_builder,filter_types,metrics,models,neighbor_candidates,outcomes,repo_identity,roles,run_activity,tail_overlay,threads,work_event_extraction— domain singletons.dates,hashing,json,messages,security,stats,timestamps— true primitives.
Roughly half of lib/ is domain logic that could live behind explicit subpackage boundaries; only a small kernel is genuinely "shared utilities."
Target shape
Define lib/ ownership with subpackages, driven by import dependencies rather than directory aesthetics. Candidate layout:
lib/query/— plan, runtime, retrieval, sorting, search-hits, spec, candidates.lib/session/— session profile, summaries, payload documents.lib/viewport/— enums, models, viewports, tools.lib/conversation/— conversation models, runtime, summary runtime, attribution, branch type, threads, neighbor candidates, work-event extraction.lib/message/— message models, message-model runtime, messages, roles.lib/raw_payload/— payload, decode, streams, sampling buckets/extract.lib/artifact_taxonomy/— models, runtime, support.lib/action_event/— fields, parsing, events.lib/semantic/— semantic_fact_models, semantic_facts, semantic_fact_support, content_projection.lib/(root, primitives only) —json,hashing,dates,timestamps,security,stats,metrics,outcomes,coverage,repo_identity,tail_overlay,models,filters/filter_builder/filter_types.
The exact split should follow imports. Do not introduce subpackages that are smaller than ~3 files unless they carry a clear contract.
Ambitious expansion
- Inventory
lib/*.pyand classify each by ownership and downstream importer. - Draw the import graph between candidate clusters; collapse groups whose imports cycle into a single subpackage.
- Move modules with explicit
__init__.pyre-exports only where there is a real public contract; do not preserve compatibility shims indefinitely. - Update
docs/architecture.mdanddocs/internals.mdplacement rules so a future contributor can picklib/<cluster>/deterministically. - Co-update validation lanes, mutation campaigns, generated quality references, and proof subjects that name
lib/paths so affected-obligation routing remains accurate after moves.
Acceptance criteria
- Each
lib/*module is classified assubpackage:<name>orlib-root-primitivewith a recorded reason. - The largest prefix families (
query_*,session_*,viewport_*,raw_payload_*,conversation_*,message_*) are subpackages; the rest may stay atlib/root if and only if they are true primitives. lib/root contains only modules that the architecture doc names as primitives.devtools render-all --check,devtools verify --quick, focused pytest slices, anddevtools affected-obligationsover moved paths all pass.- A short note in
docs/internals.mddocuments the newlib/placement rule. - No compatibility re-exports remain past the same PR (or the very next PR) that performs the move.
Related
- chore: track post-renewal consolidation and architectural cohesion #401 — post-renewal consolidation umbrella.
- refactor(schemas): group schema generation and inference modules #420 — schemas grouping (parallel pattern, schemas package).
- refactor: rationalize product ownership and package boundary #414 — product ownership and package boundary.
- refactor: rationalize source and test module structure #403 — sources/ topology.
- refactor(tests): split oversized contract suites #419 — oversized contract suites (some
lib/tests are likely affected).
Verification — added by #429
This issue's acceptance now references the topology projection (docs/plans/topology-target.yaml once promoted from .agent/scratch/topology-cohesion/topology-target.yaml) and the lints delivered by #429.
Cells this issue owns: polylogue/lib/* — 66 cells classified, 9 TBD cells (payload_coercion, phase_extraction, pricing, projection_*, projections, provider_capabilities, provider_semantics) need explicit assignment
Executable acceptance criteria added:
-
devtools verify-topology(per feat(devtools): make architectural cohesion executable #429) exits 0 against the cells this issue owns. Orphans, conflicts, kernel-rule violations are blocking. -
devtools verify-cluster-cohesion(per feat(devtools): make architectural cohesion executable #429) reports no new cycles introduced by this issue's moves. Cycles existing before this issue's changes are tracked in feat(devtools): make architectural cohesion executable #429's findings. - Each
@pytest.mark.xfail(strict=True)test intests/unit/scenarios/test_topology_invariants.py(or starter at.agent/scratch/topology-cohesion/test_topology_invariants.py) tagged with this issue number flips to a normalassertin the same PR. - No
# topology: shim until #NNNcomment outlives the merge of the issue it references;verify-topologyshim-TTL check fails on stale shims.
Pre-flight findings to address in this issue's PR: see .agent/scratch/topology-cohesion/findings.md for the cohesion-check output, particularly any cycles or lonely-cluster findings tagged with this issue number.
Pre-flight findings (added 2026-04-26 by #429)
The pre-flight projection in .agent/scratch/topology-cohesion/topology-target.yaml classifies 66 of 83 lib modules. Nine cells are TBD — the prefix-rule did not assign them and the implementer must explicitly route each:
| Module | LOC sketch | Suggested target | Confidence |
|---|---|---|---|
polylogue/lib/payload_coercion.py |
small | lib/raw_payload/coercion.py |
medium |
polylogue/lib/phase_extraction.py |
small | lib/conversation/phase_extraction.py |
medium (pairs with work_event_extraction.py) |
polylogue/lib/pricing.py |
small | lib/ root primitive |
medium |
polylogue/lib/projection_filter_mixin.py |
small | lib/projection/filter_mixin.py |
high |
polylogue/lib/projection_terminal_mixin.py |
small | lib/projection/terminal_mixin.py |
high |
polylogue/lib/projection_transform_mixin.py |
small | lib/projection/transform_mixin.py |
high |
polylogue/lib/projections.py |
medium | lib/projection/__init__.py |
high |
polylogue/lib/provider_capabilities.py |
medium | new lib/provider/capabilities.py |
low (also fits lib/semantic/) |
polylogue/lib/provider_semantics.py |
medium | new lib/provider/semantics.py |
low (same) |
Recommendation: introduce a new lib/projection/ subpackage (4 modules cluster naturally) and decide between lib/provider/ and lib/semantic/ based on the import graph. provider_identity.py is already a lib-root primitive; if provider_* becomes a subpackage, coordinate the move so provider_identity follows.
The cluster-cohesion check also surfaced a lib/ ↔ lib/query/ cycle, suggesting the proposed lib-root primitive set is too generous — lib-root files import from lib/query/. Tighten the lib-root primitive set to truly leaf-level utilities (json, hashing, dates, timestamps, security, stats, metrics). Anything that imports from a sibling subpackage probably belongs in that subpackage.
Cohesion-driven adjustments (added 2026-04-26 from swarm audit)
The lib-cohesion deep audit (.agent/scratch/swarm-2026-04-26/lib-cohesion-deep.md) ran the import graph against the proposed clusters. Concrete adjustments:
Lib-root cycle — break first
polylogue/lib/__init__.py imports from 8 lib clusters, creating the lib-root ↔ lib/* cycle that verify_cluster_cohesion flagged. Move the re-exports outside lib-root before introducing any subpackage:
- Option A:
polylogue/_lib_exports.py(private re-export module). - Option B: lift re-exports to top-level
polylogue/__init__.pyif they are public.
The cluster work cannot proceed cleanly while lib-root depends on its children.
Tightened lib-root primitive set
The proposed primitive set was too generous. Audit-confirmed primitives (zero imports from lib/ siblings): dates, hashing, json. Add: metrics, outcomes, provider_capabilities, roles, timestamps. Drop from the proposed primitive set: anything that imports from a sibling subpackage probably belongs in that subpackage, not at lib-root.
TBD module placement (concrete evidence)
| Module | Suggested target | Confidence |
|---|---|---|
polylogue/lib/payload_coercion.py |
lib/raw_payload/coercion.py |
medium |
polylogue/lib/phase_extraction.py |
lib/conversation/phase_extraction.py |
high (pairs with work_event_extraction.py) |
polylogue/lib/pricing.py |
lib-root primitive | medium |
polylogue/lib/projection_filter_mixin.py |
new lib/projection/filter_mixin.py |
high |
polylogue/lib/projection_terminal_mixin.py |
new lib/projection/terminal_mixin.py |
high |
polylogue/lib/projection_transform_mixin.py |
new lib/projection/transform_mixin.py |
high |
polylogue/lib/projections.py |
lib/projection/__init__.py |
high |
polylogue/lib/provider_capabilities.py |
lib/provider/capabilities.py (new) or lib/semantic/ |
low (decide via imports) |
polylogue/lib/provider_semantics.py |
lib/provider/semantics.py (new) or lib/semantic/ |
low |
Add lib/projection/ as a subpackage — the 4 projection modules cluster naturally and are surfaced by the audit as a real cluster missed by the original prefix rules.
Cluster cohesion grades (audit findings)
Per-cluster cohesion ratios (intra-cluster import / total imports):
- High (proceed): viewport 75%, artifact_taxonomy 67%, query 66%
- Moderate (proceed after TBDs route): action_event 38%, filter 30%, conversation 29%
- Low (TBD-blocked, will improve): semantic 13%, session 25%, message 25%
The low-cohesion clusters' grades reflect TBD modules artificially deflating the ratio; routing them per the table above will lift cohesion above threshold.
TBD cells owned by this issue
The dashboard currently lists 9 polylogue/lib/*.py files as TBD (no rule yet). They belong to this issue's scope and must be resolved during the refactor — assigned to a target subpackage in docs/plans/topology-target.yaml:
polylogue/lib/payload_coercion.pypolylogue/lib/phase_extraction.pypolylogue/lib/pricing.pypolylogue/lib/projection_filter_mixin.pypolylogue/lib/projection_terminal_mixin.pypolylogue/lib/projection_transform_mixin.pypolylogue/lib/projections.pypolylogue/lib/provider_capabilities.pypolylogue/lib/provider_semantics.py
Until each is assigned, verify-topology reports them under [warn] tbd: and they don't count against any issue's progress.
Coordination — conflict with other issues
The projection currently has one cell claimed twice within this issue's scope:
polylogue/lib/conversation/models.py— claimed by bothpolylogue/lib/attachment_models.pyandpolylogue/lib/conversation_models.py. Resolve by splitting target paths (e.g.polylogue/lib/attachment/models.pyandpolylogue/lib/conversation/models.py) before opening the move PR.
Acceptance (executable)
devtools verify-topology # 0 #424 cells pending; 0 conflicts
devtools verify-cluster-cohesion # cohesion grade per declared lib/ subpackage
Activity
feat(devtools): make architectural cohesion executable (Phase 1 of #429…
feat(devtools): test-ownership manifest with import-resolution (#450)
fix(devtools): topology projection avoids __init__.py target collisio…
feat(devtools): topology drift dashboard
feat(devtools): topology drift dashboard (#455)
chore(topology): resolve projection TBDs, conflicts, and missing rules
chore(topology): resolve projection TBDs, conflicts, and missing rules (
refactor(api): consolidate facade/sync/maintenance into subpackages (#…
refactor(lib): group lib by domain cluster (#424)
refactor(lib): group lib by domain cluster (#424)
refactor(lib): group lib by domain cluster (#424) (#537)
feat(devtools): make architectural cohesion executable (Phase 1 of #429…
feat(devtools): test-ownership manifest with import-resolution (#450)
fix(devtools): topology projection avoids __init__.py target collisio…
feat(devtools): topology drift dashboard (#455)
chore(topology): resolve projection TBDs, conflicts, and missing rules (
refactor(api): consolidate facade/sync/maintenance into subpackages (#…
refactor(lib): group lib by domain cluster (#424) (#537)