chore: codebase audit cleanup + 0.5.0 release#59
Merged
Conversation
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.6bbe259) — 23 functions converted to single-return; extractedformat_depth_labeland_dump_model_jsonhelpers;Any-typed formatters tightened; baretupleannotation fixed; trimmed two oversized parameter docstrings.fa3a813) — AddedGroundingResult.get_primitives()/.get_pathway_steps()and migrated 7 callers off.trace.result.*drill-down. Memoized_contiguous_max_depthvia@functools.cachekeyed on afrozenset[DepthLevel]shape. Dropped defensive.copy()inbuild_name_map; switched_filter_depthstomodel_copy(deep=True).TemplateFactoryclass → module-leveltemplate_for_gaprewritten withmatch/case.301a866) — The two "hard" multi-returns inlearning/engine.py(_persist,_persist_reachability) collapsed viamatch/caseand a single outcome variable. Codebase now has zero multi-return functions per AST audit.8caf8bf) — VRE god-class split into focused coordinators. Newvre/metrics.py(MetricsManager) andTraceManagerinvre/tracing.pyencapsulate the metrics-update and trace-suppression bookkeeping that was inlined in VRE.gap_primitive_idsmoved tocore/models.pyas a free function next to the gap types. VRE class body shrunk ~290 → ~175 LOC;learn_allnow reads as orchestration viawith self._traces.suppress(), callback:.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
PolicyCallContextredesign — both the leakygrounding: GroundingResultfield and the missing edge-identity in policy callbacks. Surfaced during this pass; deserves its own design pass.Test plan
TemplateFactory→template_for_gapimport + class rename, per "import changes due to refactor")src/vre/src/,tests/,examples/GroundingResult.get_primitives()migration sites invre/__init__.py:_update_grounding_metrics,vre/learning/engine.py:_resolve_name_to_id,vre/tracing.py:build_trace_entry, plus the two example callersTraceManager.suppress()re-entrant context manager swap-in for the old_suppress_tracemutex inlearn_all_filter_depthsnow usesmodel_copy(deep=True)instead of full reconstruction (deliberate trade-off — discussed in the session)🤖 Generated with Claude Code