Skip to content

chore: codebase audit cleanup + 0.5.0 release#59

Merged
anormang1992 merged 6 commits into
mainfrom
chore/audit-cleanup
May 4, 2026
Merged

chore: codebase audit cleanup + 0.5.0 release#59
anormang1992 merged 6 commits into
mainfrom
chore/audit-cleanup

Conversation

@anormang1992
Copy link
Copy Markdown
Owner

Summary

Multi-slice refactor pass driven by a parallel-agent codebase audit (duplication, multi-return style, bloat, consistency, coupling, perf). Public API is net-additive only — the single addition is GroundingResult.get_primitives() / .get_pathway_steps(), hence the 0.5.0 minor bump. All other changes are internal refactors with preserved behavior; all 256 tests pass without modification.

  • Slice 1 (6bbe259) — 23 functions converted to single-return; extracted format_depth_label and _dump_model_json helpers; Any-typed formatters tightened; bare tuple annotation fixed; trimmed two oversized parameter docstrings.
  • Slice 2 (fa3a813) — Added GroundingResult.get_primitives() / .get_pathway_steps() and migrated 7 callers off .trace.result.* drill-down. Memoized _contiguous_max_depth via @functools.cache keyed on a frozenset[DepthLevel] shape. Dropped defensive .copy() in build_name_map; switched _filter_depths to model_copy(deep=True). TemplateFactory class → module-level template_for_gap rewritten with match/case.
  • Slice 3 (301a866) — The two "hard" multi-returns in learning/engine.py (_persist, _persist_reachability) collapsed via match/case and a single outcome variable. Codebase now has zero multi-return functions per AST audit.
  • Slice 4 (8caf8bf) — VRE god-class split into focused coordinators. New vre/metrics.py (MetricsManager) and TraceManager in vre/tracing.py encapsulate the metrics-update and trace-suppression bookkeeping that was inlined in VRE. gap_primitive_ids moved to core/models.py as a free function next to the gap types. VRE class body shrunk ~290 → ~175 LOC; learn_all now reads as orchestration via with self._traces.suppress(), callback:.
  • Release + docs sync (185af17, 505cc8f) — Bumped to 0.5.0; updated README project tree to reflect new modules and renamed helper; aligned README + docs/index.html roadmap (renamed deferred "VRE Networks" → "Knowledge Import" matching the imports-over-hydration resume path documented in project memory; dropped redundant EPISTEMIC SCORE entry from docs).

Deferred (tracked in issue #58): the PolicyCallContext redesign — both the leaky grounding: GroundingResult field and the missing edge-identity in policy callbacks. Surfaced during this pass; deserves its own design pass.

Test plan

  • Full pytest suite — 256/256 passing without modification (only test change: TemplateFactorytemplate_for_gap import + class rename, per "import changes due to refactor")
  • Coverage held / improved — 75.56% → 76.80%
  • AST audit — zero multi-return functions across src/vre/
  • Ruff clean across src/, tests/, examples/
  • Reviewer spot-check: GroundingResult.get_primitives() migration sites in vre/__init__.py:_update_grounding_metrics, vre/learning/engine.py:_resolve_name_to_id, vre/tracing.py:build_trace_entry, plus the two example callers
  • Reviewer spot-check: TraceManager.suppress() re-entrant context manager swap-in for the old _suppress_trace mutex in learn_all
  • Reviewer spot-check: _filter_depths now uses model_copy(deep=True) instead of full reconstruction (deliberate trade-off — discussed in the session)

🤖 Generated with Claude Code

anormang1992 and others added 6 commits May 4, 2026 11:31
Codebase-audit cleanup pass:

- Refactor 23 functions to single-return form across __init__, core/graph,
  core/grounding/{engine,models,resolver}, core/models, core/policy/{models,
  wizard}, identity/registry, learning/{engine,templates}. Two-phase and
  polymorphic-dispatch functions in learning/engine left as-is by design.
- Extract format_depth_label() in core/models and adopt across grounding/models
  and policy/wizard (drops the local _DEPTH_LABELS dict).
- Extract PrimitiveRepository._dump_model_json() and adopt at three save_primitive
  call sites.
- Tighten Any-typed display formatters in grounding/models to typed parameters
  (KnowledgeGap, Relatum, Depth, Primitive).
- Fix bare `tuple` annotation in policy/callback.py and stdlib import order
  in learning/engine.py.
- Trim two oversized parameter docstrings in vre/__init__ (__init__, check)
  that mostly restated type hints.

Net -23 LOC. All 256 tests pass without modification.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Slice 2 of the codebase-audit cleanup:

- Add GroundingResult.get_primitives() and get_pathway_steps() helpers and
  migrate all 5 src callers + 2 example callers off the .trace.result.*
  drill-down. Internal __str__ formatting is unchanged.
- Memoize _contiguous_max_depth via @functools.cache on a frozenset[DepthLevel]
  shape key. Pure-function caching, no threading, safe across queries — every
  primitive sharing a depth shape now shares the cached answer.
- Drop the defensive .copy() in ConceptResolver.build_name_map (callers are
  read-only by contract; documented with a one-line note).
- Replace direct Primitive/Depth construction in GroundingEngine._filter_depths
  with model_copy(deep=True) — same semantics, skips Pydantic re-validation,
  fully detached output for safe downstream mutation.
- Convert TemplateFactory class to module-level template_for_gap function and
  rewrite the dispatch as match/case. Updated 2 src callers and the test class
  names + import.

All 256 tests pass without behavioral changes.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- Rewrite LearningEngine._persist with match/case on (gap, candidate) tuple,
  collapsing the four isinstance-pair branches into a single dispatch with
  one return point.
- Collapse the three returns in LearningEngine._persist_reachability into a
  single outcome variable. Phase 1 (depth learning) sets the outcome; phase
  2 (edge placement) only runs when phase 1 didn't override. Behavior is
  unchanged: REJECTED/SKIPPED from either side aborts the edge placement.
- Drop the unused `Depth` import in core/grounding/engine.py — _filter_depths
  no longer constructs Depth instances directly after the model_copy switch.

The codebase now has zero multi-return functions per AST audit. Ruff clean.
All 256 tests pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Slice 4 of the codebase-audit cleanup. Splits the 8-responsibility VRE
class into focused units while preserving the public API.

- New `core.models.gap_primitive_ids()` — free function to collect the
  primitive UUIDs each gap is "about". Lives with the gap types it
  operates on, used by the metrics coordinator.
- New `vre/metrics.py` — `MetricsManager` encapsulates the
  update_grounding and update_learning paths. Best-effort semantics
  preserved (logs and swallows). Gap dispatch in update_learning rewritten
  with match/case.
- New `TraceManager` in `vre/tracing.py` — owns the writer + suppression
  state. `suppress()` is now a re-entrant context manager (replaces the
  ad-hoc `_suppress_trace = True/False` mutex). `_safe_write` defined
  above its callers per the codebase's method-order convention.
- `VRE` now composes `MetricsManager` and `TraceManager` in `__init__`.
  `_update_grounding_metrics`, `_update_learning_metric`, `_gap_primitive_ids`,
  `_suppress_trace`, `_trace_writer`, and the inline trace try/except blocks
  are gone. `_stamp_identity` stays — 3 lines is too small for a class.
- `learn_all` body now reads as orchestration: suppress check traces →
  learn loop → write summary trace. Use of `with self._traces.suppress(),
  callback:` chains the two context managers cleanly.

Net: VRE class body 290 → 175 LOC. Public API unchanged. No tests required
modification. All 256 tests pass; ruff clean; zero multi-return functions
in the codebase.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Minor bump to 0.5.0 covering the audit-cleanup branch. The single public
API addition is `GroundingResult.get_primitives()` and `.get_pathway_steps()`
(net additive — no breaking changes). All other changes in slices 1–4 are
internal refactors with preserved behavior.

README updates:
- Project structure tree: add `metrics.py`; mention TraceManager in tracing.py;
  rename templates.py description from `TemplateFactory` to `template_for_gap`.
- GroundingResult section: brief mention of the new get_primitives() and
  get_pathway_steps() helpers so callers know not to drill into trace.result.

docs/index.html audited and required no changes — its code samples reference
only Policy(...) and @vre_guard(...) signatures, both unchanged.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…roadmap

Rewrites the deferred VRE Networks future-section item on both public
surfaces to reflect the actual stashed resume path: one-shot validated
imports of peer subgraphs rather than live-linked federation. Imported
primitives become ordinary local nodes stamped with PEER provenance and
a (peer_name, imported_at) attestation; refresh is an explicit operator
action. This preserves the depth-explicit validated-trust property the
rest of VRE's enforcement depends on, instead of eroding it under live
hydration.

Also drops the EPISTEMIC SCORE entry from docs/index.html — it's implied
by the Epistemic Memory work and the README didn't carry it. README and
docs roadmaps are now in sync (3 items each).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@anormang1992 anormang1992 merged commit c56c608 into main May 4, 2026
2 checks passed
@anormang1992 anormang1992 deleted the chore/audit-cleanup branch May 4, 2026 18:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant