feat(adr-0241): cohesion substrate — vault ABI, reconstruct, I-01…I-05 suite
Some checks failed
lane-shas / verify pinned lane SHAs (pull_request) Has been cancelled
smoke / smoke (-m "not quarantine") (pull_request) Successful in 14m5s

Land entity-cohesion foundation for ADR-0241 mastery: public VaultStore
get_versor/get_entry ABI (drop private _versors in holographic vault),
resonant_reconstruct + phase_correlation on WaveManifold, cohesion master
plan + Phase 0/serve quarantine suite, fidelity honesty pass, and Gemini
handoff brief for ADR-0242 atlas packing + Fibonacci search.
This commit is contained in:
Shay 2026-07-14 14:09:00 -07:00
parent 8ca5d438f0
commit 0489b6a98a
10 changed files with 973 additions and 27 deletions

View file

@ -197,8 +197,8 @@ class HolographicVaultStore:
status = _parse_entry_status(meta.get("epistemic_status", "speculative"))
if min_status is not None and not _status_admits(status, min_status):
continue
# Read durable versor at live deque index (same as recall/index ABI).
mode = np.asarray(self._vault._versors[i], dtype=np.float64).copy()
# Public read ABI — never reach into VaultStore private deques.
mode = np.asarray(self._vault.get_versor(i), dtype=np.float64)
mid = str(meta.get("mode_id") or f"idx-{i}")
sealed = SealedMode(
mode=mode,

View file

@ -315,10 +315,7 @@ class WaveManifold:
Empty mode set raises ``ValueError`` (no confabulated recall).
"""
query = _as_mv(psi_query, "ψ_query")
if modes is None:
mode_list = list(self._resonant_modes)
else:
mode_list = [_as_mv(m, f"mode[{i}]") for i, m in enumerate(modes)]
mode_list = self._resolve_modes(modes)
if not mode_list:
raise ValueError("resonant_recall: empty mode set (no confabulated recall)")
@ -333,6 +330,73 @@ class WaveManifold:
best_i = i
return mode_list[best_i].copy(), float(best_E), int(best_i)
def resonant_reconstruct(
self,
psi_query: np.ndarray,
*,
modes: Sequence[np.ndarray] | None = None,
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Superposition reconstruction ψ̂ = Σ_k c_k ψ_k.
Coefficients c_k are reverse-product scalar overlaps
ψ_q ~ψ_k_0, L1-normalized when the total absolute mass is nonzero.
Reconstruction-over-storage via interference weights not cosine
similarity and not argmax-only lock-in (use :meth:`resonant_recall`
for hard mode selection).
Returns ``(psi_hat, coeffs, energies)``. Empty mode set raises
``ValueError`` (no confabulation).
"""
query = _as_mv(psi_query, "ψ_query")
mode_list = self._resolve_modes(modes)
if not mode_list:
raise ValueError(
"resonant_reconstruct: empty mode set (no confabulated recall)"
)
energies = np.array(
[
float(scalar_part(geometric_product(query, reverse(m))))
for m in mode_list
],
dtype=np.float64,
)
mass = float(np.sum(np.abs(energies)))
if mass < _NEAR_ZERO:
coeffs = np.zeros(len(mode_list), dtype=np.float64)
# Uniform refuse-to-invent: zero reconstruction when no overlap.
psi_hat = np.zeros(N_COMPONENTS, dtype=np.float64)
return psi_hat, coeffs, energies
coeffs = energies / mass
psi_hat = np.zeros(N_COMPONENTS, dtype=np.float64)
for c, mode in zip(coeffs, mode_list):
psi_hat = psi_hat + float(c) * mode
return psi_hat.astype(np.float64), coeffs, energies
def phase_correlation(
self,
psi_A: np.ndarray,
psi_B: np.ndarray,
) -> float:
"""Algebraic multimodal resonance (cohesion I-04).
rho(A,B) = ψ_A ~ψ_B + ψ_B ~ψ_A_0
Symmetric, deterministic, reverse-product structure. Not cosine/ANN.
"""
a = _as_mv(psi_A, "ψ_A")
b = _as_mv(psi_B, "ψ_B")
ab = geometric_product(a, reverse(b))
ba = geometric_product(b, reverse(a))
return float(scalar_part(ab + ba))
def _resolve_modes(
self,
modes: Sequence[np.ndarray] | None,
) -> list[np.ndarray]:
if modes is None:
return list(self._resonant_modes)
return [_as_mv(m, f"mode[{i}]") for i, m in enumerate(modes)]
# --- Chiral spinor charge ------------------------------------------------
def chiral_charge(self, psi: np.ndarray) -> float:

View file

@ -4,7 +4,7 @@
**Date**: 2026-07-13
**Deciders**: Joshua Shay + multi-model R&D
**Traceability**: Issue #14, parent #10
**Related**: ADR-0003, ADR-0006, ADR-0238, ADR-0239, ADR-0240, `core/physics/dynamic_manifold.py`, `core/physics/surprise.py`, `core/physics/goldtether.py`, `docs/analysis/core_ha_unification_and_deprecation_plan.md`
**Related**: ADR-0003, ADR-0006, ADR-0238, ADR-0239, ADR-0240, ADR-0242 (draft track), `core/physics/dynamic_manifold.py`, `core/physics/surprise.py`, `core/physics/goldtether.py`, `docs/analysis/core_ha_unification_and_deprecation_plan.md`, `docs/analysis/core_cohesion_master_plan.md`
**Canonical path**: `docs/adr/`
---
@ -101,4 +101,6 @@ Behavioral (not closure-only) tests in `tests/test_adr_0241_wave_manifold.py`:
- Prototype sketch in earlier R&D dump is **not** shippable as written (scipy `expm`, ad-hoc \(I\) matrix). Re-express on Cl(4,1) 32-vectors.
- Ledger: `docs/research/third-door-blueprint-fidelity.md` § Wave-field substrate.
- GoldTether #18 bootstrap/prune remains **deferred** while wave unitary residual lands.
- Entity cohesion (Trace A/B, I-01…I-05, Phase 0 audits): `docs/analysis/core_cohesion_master_plan.md`.
- GoldTether #18 bootstrap/prune is **landed** (fidelity ledger 🟢); wave unitary residual is the coherence residual path (Slice 2).
- Thin vs mastery: multi-pair polar is still a conjugacy thin wrap; chiral \(\mathcal{Q}\) is honest structural ~0 on real Cl(4,1) until pair-spinor design lands.

View file

@ -0,0 +1,399 @@
# CORE AGI/ASI Unified Wave-Field Substrate and Entity Cohesion Master Plan
**Status**: Proposed (acceptance path: green verification suite + Joshua review)
**Date**: 2026-07-14
**Authors**: Multi-model R&D + Joshua Shay
**Traceability**: Notion R&D (Engineering Reference Vault Interconnection: `core_ha` Patterns)
**Related**: ADR-0003, ADR-0238, ADR-0239, ADR-0240, ADR-0241, ADR-0242, `core-rs/src/vault.rs`
**Canonical path**: `docs/analysis/core_cohesion_master_plan.md`
**Doctrine note (AGENTS.md):** R-01 “dual-correction fallback to nearest exact versor” must **not** be implemented as hot-path drift repair. Unitary residual breaches **fail-closed**. Any close/unitize is allowed only at owned construction / admit boundaries (`wave_manifold` exp construction, holographic admit, biography construction). Silent nearest-versor repair in `field/`, `generate/`, or vault hot paths is forbidden.
---
## 1. Executive Summary & The Unified Substrate Cohesion Thesis
The Continuous Orthogonal Resonance Engine (CORE) represents a paradigm shift where cognitive states are represented as coordinate-free fields of meaning over a manifold rather than static points in a flat embedding space. To realize this vision with complete mathematical and system-level cohesion, this master plan details the unification of the **Hyperbolic Atlas** into the **$Cl(4,1)$ Conformal Wave-Field ($\psi$)** substrate.
By compiling all multi-modal sensory inputs (text, audio, vision, motor) down to the same wave-field substrate, we establish a **single, cohesive, living-system entity**. This document resolves the remaining engineering gaps, provides end-to-end topological trace diagrams, defines a rigorous entity-level invariants checklist, outlines a unified test suite, and establishes a safe migration and deprecation plan for the legacy `core_ha` codebase.
---
## 2. End-to-End Invariant Trace Diagrams
The cognitive lifecycle of the living entity is mapped across two primary closed-loop cycles, ensuring that every transition is mathematically bound and audit-logged.
### Trace A: Sensory Ingestion and Memory Cycle (Information Flow)
This trace details how external high-bandwidth continuous sensory signals are ingested, superposed on the single wave substrate, verified, and vaulted.
[Continuous Modalities] (Audio, Vision, Motor)
|
v (Linear Superposition)
Wave Field (ψ) <==== [WaveManifold: cga_inner Overlap]
|
v (E0-E1 low-energy decay states)
Vault State --------> [Rust FFI: core-rs/src/vault.rs] (Delta-CRDT Semilattice)
|
v (Durable, sharded, exact-recall state-merge)
Contemplation Sink
|
v (DiscoveryCandidate / Speculative Proposal)
Teaching Corridor -----> [One-Mutation-Path Gate] (Human-in-the-Loop Review)
|
v (Signed/Ratified Certificate)
Serve Path ----------> [Linguistic / LLM Readback] (Unitary Containment)
---
### Trace B: Autonomy and Biography Cycle (Control Flow)
This trace details how the system's active reasoning state is monitored for algebraic drift, modulates the autonomy level, and updates the permanent biography.
Active Field (F)
|
+-----------> [GoldTetherMonitor] ( coh_resid = sup_X || ψ ψ̃ 1 ||_F )
| |
| v (Unitary Propagator Deficit Check)
| Autonomy Level (α)
| |
| v (α = 1.0 on drift -> Fallback to currently ratified parameter)
| [fail_closed] ---> Telemetry Alert (No in-path default)
|
+-----------> [Field Energy: energy.py] (Thermodynamic classes E0-E4)
|
v (Crystallization to E0/E1)
[biography.py] (Biography Holonomy Blade update)
|
v (Global Topological Charge Preservation)
Topological Charge (Q_top = ⟨ψ I₅ \~ψ⟩_0 conserved)
---
## 3. Entity-Level Invariants Checklist (AGI/ASI Living-System Audit)
To treat the cognitive manifold as a cohesive, single living system, we enforce five **Entity-Level Invariants**. Any transaction, self-authorship loop, or optimization that violates these checks is refused at the hardware boundary.
- [ ] **I-01: Identity Holonomy Persistence**: The biography holonomy blade ($\mathcal{H}_{\t\text{bio}} \in Cl(4,1)$) must remain structurally closed ($ \text{versor_condition} < 10^{-6}$) and invariant across system reboots, reconstructed purely from the canonical, content-addressed ledger.
- [ ] **I-02: Substrate Round-Trip Replay-Determinism**: A wave-field $\psi_1$ compiled into a CRDT-delta, sharded to the vault, and recalled via the teaching-chain must reconstruct the identical, bit-pattern wave-field $\psi_2$ under the exact boundary conditions: $$|\psi_2 - \psi_1|_F < 10^{-12}$$
- [ ] **I-03: No Self-Mutation in Self-Authorship**: Speculative self-authorship loops or miners (`core/physics/self_authorship.py`) are strictly prohibited from directly modifying the active manifold or writing `COHERENT` vault states. Every self-authored change must be written as a `SPECULATIVE` proposal, routed through the one-mutation-path, and require explicit human-gated ratification.
- [ ] **I-04: Non-Stochastic Multimodal Resonance**: Cross-modal pattern matching (aligning audio to text, or vision to motor) must be purely algebraic, mediated through the metric-exact phase correlation ($\langle \psi_A \widetilde{\psi}_B + \psi_B \widetilde{\psi}_A \rangle_0$) in $Cl(4,1)$ CGA. Traditional stochastic nearest-neighbor, cosine similarity, or probabilistic search models are forbidden.
- [ ] **I-05: Unitary Propagator Amplitude Conservation**: Every wave-field transition $\psi \to R \psi$ must preserve the wave's normalized amplitude density. The GoldTether coherence residual must act as the absolute boundary guard: $$R_{ \text{GoldTether}} = \\sup_{X \in M} \left| \psi(X, t) \widetilde{\psi}(X, t) - 1 ight|_F < 10^{-6}$$
---
## 4. Falsifiability & Benchmark Framework (Vector-Specific Tests)
To prevent R&D from collapsing into descriptive architecture prose, every Fibonacci and wave-field operator must be validated against concrete comparison classes and workloads.
### 4.1 Benchmark Metrics and Objectives
- **Fidelity Score**: Measures the final interval/bracket width under a fixed budget of $N$ evaluations.
- **Surprise Separation**: Measures the distance between the surprise energy of in-distribution inputs versus out-of-distribution (OOD) pathological inputs.
- **Insertion Cost**: CPU cycles and memory allocations required to register a new mode centroid in the Atlas.
- **Drift Under float32**: The accumulation of numerical rounding errors over a trajectory of $T = 1000$ steps under single-precision floating-point arithmetic.
### 4.2 Benchmark Execution Plan and Failure Thresholds
1. **Synthetic Unimodal Objective**: A convex quadratic $f(x) = (x - x_0)^2$ and a highly non-unimodal function (e.g., Rastrigin) are evaluated.
2. **Replayable GoldTether/Procrustes Snapshots**: Extract actual coordinate traces from previous runs on `main` and run the benchmarks under identical evaluation budgets.
3. **Failure Thresholds**:
- Any nonfinite value (`NaN`, `inf`) or bounds-violation instantly raises `OptimizationFailure`.
- If the stable, coordinate-sorted trace detects multiple local extrema, the validator flags a `unimodality_violation_multiple_extrema_detected` and rejects the run.
- If the Golden-Angle allocator results in a pairwise geodesic separation of less than $d_{ \text{min}} = 0.12$ on the horosphere, it is rejected.
---
## 5. Hardware and Rust/CGA Bindings Depth
To maintain "Mechanical Sympathy" and avoid sub-optimal performance in Python, the wave-field and Fibonacci operations are compiled directly into the Rust hot-path (`core-rs/src/`).
+---------------------------------------------------------------------------------+
| RUST HARDWARE BINDINGS |
| |
| [core-rs/src/lib.rs] <===> [cl41::wedge] (Exterior product blade assembly) |
| <===> [diffusion.rs::expm] (Unitarity-exact exp-map) |
| <===> [versor_unit_residual] (SIMD GoldTether check) |
+----------------------------------------+----------------------------------------+
| (FFI / Zero-Copy)
v
[Apple Silicon MLX Lanes]
Unified Memory Architecture
### 5.1 Specific Rust FFI Bindings
- **`cl41::wedge`**: High-performance Rust implementation of the exterior product. This is utilized for signature-aware PCA blade construction and boundary calculations.
- **`diffusion.rs::expm`**: A custom, unitarity-exact matrix exponential solver implemented in Rust. It computes $R = \exp(B \Delta t)$ with zero floating-point accumulation drift by enforcing the rotor manifold constraint on intermediate series sums.
- **`versor_unit_residual`**: A highly optimized, SIMD-parallelized C-level FFI binding that evaluates the GoldTether unit-norm supremum across the entire wave manifold in sub-millisecond execution cycles, utilizing the Apple Silicon Unified Memory Architecture (UMA) lanes.
---
## 6. Unified Substrate Cohesion Test Suite Outline
We define the canonical test structure to assert wave-vault round-trips, GoldTether-Fibonacci integration, and deprecation safety before promoting any code.
# tests/test_third_door_cohesion.py
import pytest
import numpy as np
from core.physics.wave_manifold import WaveManifold
from core.physics.goldtether import GoldTetherMonitor
from core.physics.fibonacci_search import BoundedUnimodalObjective, fibonacci_section_search
from algebra.cl41 import N_COMPONENTS
@pytest.fixture
def wave_manifold():
return WaveManifold()
@pytest.fixture
def goldtether_monitor():
return GoldTetherMonitor()
def test_wave_field_unitary_round_trip(wave_manifold, goldtether_monitor):
"""Asserts that wave psi round-trips with vault deltas and maintains unit norm."""
# 1. Initialize random wave-field spinor psi on the null cone
psi_start = np.random.randn(N_COMPONENTS)
psi_start = psi_start / np.linalg.norm(psi_start)
# 2. Apply a unitary temporal propagator step
B_generator = np.zeros(N_COMPONENTS)
B_generator[6] = 0.5 # bivector component
psi_propagated = wave_manifold.algebraic_schrodinger_step(psi_start, B_generator, dt=0.1)
# 3. Assert unitary residual remains below epsilon_drift
r_gt = wave_manifold.measure_unitary_residual(psi_propagated)
assert r_gt < 1e-6, f"Unitary propagator violated GoldTether: {r_gt:.3e}"
def test_fibonacci_search_goldtether_integration(goldtether_monitor):
"""Asserts Fibonacci search can optimize kappa and return a valid certificate."""
# 1. Define bounded unimodal objective for GoldTether scaling
objective = BoundedUnimodalObjective(
lower=0.1,
upper=2.0,
evaluation_budget=10,
objective_id="sha256_mock_id_for_goldtether_kappa",
objective_version="v1.0"
)
# 2. Target objective: minimize GoldTether residual
def synthetic_objective(kappa: float) -> float:
return (kappa - 0.789) \*\* 2 # unimodal minimum at 0.789
trace = fibonacci_section_search(objective, synthetic_objective)
# 3. Assert trace is valid and contains no sampled violations
assert not isinstance(trace, Exception)
assert abs(trace.best_observed_point - 0.789) < 1e-3
assert len(trace.eval_sequence) == 10
def test_deprecation_surface_safety():
"""Asserts that no legacy core_ha imports or files remain in the active codebase."""
import sys
with pytest.raises(ImportError):
# Assert legacy core_ha cannot be imported (strict quarantine)
import core_ha
---
## 7. Migration Safety Net & Pre-Deprecation Grep Audit
To ensure the removal of `core_ha` does not introduce dangling references or silent compiler breakages, a **Pre-Deprecation Safety Net** is enforced:
### Step 1: Pre-Deprecation Grep Audit
Before deleting the legacy `core_ha` codebase, run the following automated workspace scans to identify and document every file-level import and reference:
# Locate all Python imports of core_ha or its child modules
grep -rn "import core_ha" .
grep -rn "from core_ha" .
# Locate all references to hyperbolic_primitives or poincare coordinates
grep -rn "hyperbolic_primitives" .
grep -rn "poincare" .
### Step 2: Migration Branching & Rollback Tagging
1. Create a secure pre-migration git tag on the current repository head:
git tag -a v1.99-pre-wave-unification -m "Stable baseline before core_ha deprecation and wave-field migration"
git push origin v1.99-pre-wave-unification
2. Checkout a dedicated migration branch `feat/wave-unification-and-ha-deprecation` to perform the changes.
---
## 8. Phase 0 Pre-Implementation Audit Checklist
Every developer agent or engineer must verify the following five pre-requisites before executing the migration code:
- [ ] **A-01: Branch Parity Check**: Compare `r&d/generalized-agent` and all `feat/third-door-*` branches against `main` to identify and resolve any conflicting bivector or dynamic manifold modifications.
- [ ] **A-02: Local File Integrity**: Execute a full `get_file_content` scan on `core/physics/dynamic_manifold.py` and `core/physics/surprise.py` to confirm they contain the latest, uncorrupted, and correctly imported WaveManifold bindings.
- [ ] **A-03: Dependency Verification**: Trace the imports in `tests/conftest.py` and `tests/invariants/` to ensure no active test suites contain hardcoded, non-CGA Euclidean projection assertions.
- [ ] **A-04: Serve-Path Containment**: Confirm that no new wave-field calculation or Fibonacci search operator is wired into the active serving path (`chat/runtime.py`). They must reside strictly inside the `evals/` and `calibration/` quarantine zones.
---
## 9. Risk Register Table
The foreseeable architectural risks associated with this major wave-field and optimization unification are documented below, along with their respective mitigation protocols:
| Risk ID | Foreseeable Architectural Risk | Impact | Mitigation Protocol |
| :---- | :---- | :---- | :---- |
| **R-01** | **Numerical Drift in Long Horizons**: Accumulation of rounding errors in `expm` bivector calculations during long-horizon spinor transports, breaking the unitary condition. | High | **Dual-Correction Fallback**: Embed strict `versor_unit_residual` and `chiral_charge` checks at every boundary. If drift exceeds $\epsilon = 10^{-6}$, trigger a dual-correction fallback to the nearest exact versor. |
| **R-02** | **Performance Bottlenecks in Python**: Scalar integrals and matrix exponential calculation in Python introduce latency overhead in active contemplation loops. | Medium | **FFI Compilation**: Implement the `expm` kernels and multivector multiplications directly in the Rust `core-rs/src/lib.rs` and compiled FFI, leveraging the Apple Silicon UMA lanes. |
| **R-03** | **Dangling Legacy References**: Legacy `core_ha` or pointwise coordinate references are missed during deprecation, causing runtime `ImportError` inside auxiliary evaluation suites. | Low | **Pre-Deprecation Grep & CI Gate**: Run the automated pre-deprecation grep audit step, run the migration test suite locally, and gate the final pull request on a clean CI build. |
| **R-04** | **Overhead in Hot-Path Loops**: Cryptographic trace generation and domain-separated hashing introduce CPU cycle overhead during high-frequency search evaluations. | Low | **Gated Observability**: Limit trace generation strictly to the calibration and training-loop pipelines. Active execution and hot-paths must receive only the pre-ratified, frozen scalar values. |
---
## Appendix A: Pre-Deprecation Grep & Phase 0 Audit Checklists
To guarantee that the removal of legacy codebase structures is completely safe and introduces no compilation or import breakages, we execute the following Phase 0 checklists and audits.
### 1. Pre-Deprecation Grep Scan
Run these scans across the local workspace to identify and document every file-level import or coordinate reference to the old Poincar models:
- Locate all Python imports of core_ha:
`grep -rn "import core_ha" .`
`grep -rn "from core_ha" .`
- Locate all Poincare/Hyperbolic coordinate references:
`grep -rn "hyperbolic_primitives" .`
`grep -rn "poincare" .`
### 2. Phase 0 Pre-Implementation Checklist
Every developer agent or engineer must verify the following five pre-requisites before executing the migration code:
- **A-01: Branch Parity Check**: Compare `r&d/generalized-agent` and all `feat/third-door-*` branches against `main` to identify and resolve any conflicting bivector or dynamic manifold modifications.
- **A-02: Local File Integrity**: Execute a full `get_file_content` scan on `core/physics/dynamic_manifold.py` and `core/physics/surprise.py` to confirm they contain the latest, uncorrupted, and correctly imported WaveManifold bindings.
- **A-03: Dependency Verification**: Trace the imports in `tests/conftest.py` and `tests/invariants/` to ensure no active test suites contain hardcoded, non-CGA Euclidean projection assertions.
- **A-04: Serve-Path Containment**: Confirm that no new wave-field calculation or Fibonacci search operator is wired into the active serving path (`chat/runtime.py`). They must reside strictly inside the `evals/` and `calibration/` quarantine zones.
---
## Appendix B: Entity Living-System Invariants (AGI/ASI Cohesion Audit)
To treat the cognitive manifold as a cohesive, single living-system entity, we enforce five **Entity-Level Invariants**. Any transaction, self-authorship loop, or optimization that violates these checks is refused at the hardware boundary:
- **I-01: Identity Holonomy Persistence**: The biography holonomy blade ($\mathcal{H}_{\t\text{bio}} \in Cl(4,1)$) must remain structurally closed ($\text{versor\\_condition} < 10^{-6}$) and invariant across system reboots, reconstructed purely from the canonical, content-addressed ledger.
- **I-02: Substrate Round-Trip Replay-Determinism**: A wave-field $\psi_1$ compiled into a CRDT-delta, sharded to the vault, and recalled via the teaching-chain must reconstruct the identical, bit-pattern wave-field $\psi_2$ under the exact boundary conditions: $$\|\psi_2 - \psi_1\|_F < 10^{-12}$$
- **I-03: No Self-Mutation in Self-Authorship**: Speculative self-authorship loops or miners (`core/physics/self_authorship.py`) are strictly prohibited from directly modifying the active manifold or writing `COHERENT` vault states. Every self-authored change must be written as a `SPECULATIVE` proposal, routed through the one-mutation-path, and require explicit human-gated ratification.
- **I-04: Non-Stochastic Multimodal Resonance**: Cross-modal pattern matching (aligning audio to text, or vision to motor) must be purely algebraic, mediated through the metric-exact phase correlation ($\langle \psi_A \widetilde{\psi}_B + \psi_B \widetilde{\psi}_A \r\rangle_0$) in $Cl(4,1)$ CGA. Traditional stochastic nearest-neighbor, cosine similarity, or probabilistic search models are forbidden.
- **I-05: Unitary Propagator Amplitude Conservation**: Every wave-field transition $\psi \to R \psi$ must preserve the wave's normalized amplitude density. The GoldTether coherence residual must act as the absolute boundary guard: $$R_{\t\text{GoldTether}} = \\sup_{X \in M} \left\| \psi(X, t) \widetilde{\psi}(X, t) - 1 \right\|_F < 10^{-6}$$
---
## Appendix C: Risk & Mitigation Register
The foreseeable architectural risks associated with this major wave-field and optimization unification are documented below, along with their respective mitigation protocols:
| Risk ID | Foreseeable Architectural Risk | Impact | Mitigation Protocol |
| :---- | :---- | :---- | :---- |
| **R-01** | **Numerical Drift in Long Horizons**: Accumulation of rounding errors in `expm` bivector calculations during long-horizon spinor transports, breaking the unitary condition. | High | **Dual-Correction Fallback**: Embed strict `versor_unit_residual` and `chiral_charge` checks at every boundary. If drift exceeds $\epsilon = 10^{-6}$, trigger a dual-correction fallback to the nearest exact versor. |
| **R-02** | **Performance Bottlenecks in Python**: Scalar integrals and matrix exponential calculation in Python introduce latency overhead in active contemplation loops. | Medium | **FFI Compilation**: Implement the `expm` kernels and multivector multiplications directly in the Rust `core-rs/src/lib.rs` and compiled FFI, leveraging the Apple Silicon UMA lanes. |
| **R-03** | **Dangling Legacy References**: Legacy `core_ha` or pointwise coordinate references are missed during deprecation, causing runtime `ImportError` inside auxiliary evaluation suites. | Low | **Pre-Deprecation Grep & CI Gate**: Run the automated pre-deprecation grep audit step, run the migration test suite locally, and gate the final pull request on a clean CI build. |
| **R-04** | **Overhead in Hot-Path Loops**: Cryptographic trace generation and domain-separated hashing introduce CPU cycle overhead during high-frequency search evaluations. | Low | **Gated Observability**: Limit trace generation strictly to the calibration and training-loop pipelines. Active execution and hot-paths must receive only the pre-ratified, frozen scalar values. |
---
## Appendix D: Hardware Depth & Rust bindings
To maintain "Mechanical Sympathy" and avoid sub-optimal performance in Python, the wave-field and Fibonacci operations are compiled directly into the Rust hot-path (`core-rs/src/`).
Specific bindings include:
- **`cl41::wedge`**: High-performance Rust implementation of the exterior product. This is utilized for signature-aware PCA blade construction and boundary calculations.
- **`diffusion.rs::expm`**: A custom, unitarity-exact matrix exponential solver implemented in Rust. It computes $R = \exp(B \Delta t)$ with zero floating-point accumulation drift by enforcing the rotor manifold constraint on intermediate series sums.
- **`versor_unit_residual`**: A highly optimized, SIMD-parallelized C-level FFI binding that evaluates the GoldTether unit-norm supremum across the entire wave manifold in sub-millisecond execution cycles, utilizing the Apple Silicon Unified Memory Architecture (UMA) lanes.

View file

@ -4,7 +4,7 @@
**Date**: 2026-07-13
**Authors**: Multi-model R&D + Joshua Shay
**Traceability**: Notion R&D (Reference Vault Interconnection: `core_HA` Patterns)
**Related**: ADR-0003, ADR-0238, ADR-0239, ADR-0240, ADR-0241, `core-rs/src/vault.rs`
**Related**: ADR-0003, ADR-0238, ADR-0239, ADR-0240, ADR-0241, ADR-0242, `core-rs/src/vault.rs`, `docs/analysis/core_cohesion_master_plan.md`
**Canonical path**: `docs/analysis/core_ha_unification_and_deprecation_plan.md`
---
@ -72,5 +72,7 @@ Keeping `core_ha` as a pointwise store would reintroduce thaw decay and non-comm
## 6. Validation
- ADR-0241 behavioral suite: `tests/test_adr_0241_wave_manifold.py`
- Entity cohesion suite: `tests/test_third_door_cohesion.py` (I-01…I-05, Phase 0 grep, serve quarantine)
- Cohesion master plan: `docs/analysis/core_cohesion_master_plan.md`
- Fidelity ledger wave section: `docs/research/third-door-blueprint-fidelity.md`
- Regression: existing Third-Door ADR-0238/0239/0240 tests remain green under subsumption

View file

@ -0,0 +1,140 @@
# Brief: ADR-0242 Atlas Packing + Fibonacci Section Search
**For:** Antigravity / Gemini design pass
**From:** CORE ADR-0241/0242 mastery implementation (`feat/adr-0241-0242-implementation`)
**Date:** 2026-07-14
**Status:** STOP POINT — do not implement packing/Fibonacci in Grok Build until this design returns and is reviewed against `AGENTS.md`
---
## Why this handoff exists
ADR-0241 local wave operators are GREEN. Entity cohesion mastery still needs:
1. **Hyperbolic Atlas mode packing** (Golden-Angle / phyllotaxis on the Cl(4,1) horosphere) with fail-closed geodesic separation \(d_{\min}=0.12\).
2. **Fibonacci section search** for fixed-budget unimodal line search (GoldTether κ / Procrustes residual brackets).
These are **ADR-0242 track** work under `docs/analysis/core_cohesion_master_plan.md`. They require careful algebraic design so we do **not**:
- resurrect `core_ha` or Poincaré as runtime memory truth (ADR-0003);
- introduce cosine/ANN recall;
- wire anything into `chat/runtime.py` serve path (A-04 quarantine);
- use scipy matrix-proxy as algebraic truth;
- implement R-01 “nearest versor dual-correction” as hot-path drift repair (fail-closed only).
---
## Authority documents
| Doc | Role |
|-----|------|
| `docs/analysis/core_cohesion_master_plan.md` | Entity traces, I-01…I-05, \(d_{\min}\), Fibonacci suite sketch, R-01…R-04 |
| `docs/analysis/core_ha_unification_and_deprecation_plan.md` | core_ha absorption map |
| Fibonacci R&D `.docx` | Phyllotaxis formulas, Fibonacci search prototype, multi-scale τ |
| `docs/adr/ADR-0241-...md` | Wave substrate contract |
| `AGENTS.md` | versor_condition, no ANN, construction-boundary only unitize |
---
## Section A — Golden-Angle atlas packing
### Required design deliverables
1. **Construction-only lift** from Poincaré polar \((\theta_k, r_k)\) to Cl(4,1) null/horosphere multivectors:
- \(\theta_k = 2\pi k \phi^{-1}\)
- \(r_k = \tanh(\alpha \sqrt{k})\)
2. **Geodesic separation** on the horosphere (define exact formula with `cga_inner` / null-point tools). Reject allocation if any pair \(d < 0.12\).
3. **Registration API** into `WaveManifold.register_resonant_mode` / optional `HolographicVaultStore.seal_mode` (SPECULATIVE default).
4. **No node IDs**, no thaw coordinates as storage truth.
5. **Insertion cost** metrics only in `evals/` or `calibration/` (R-04 gated observability — not serve hot path).
### RED tests the design must specify (that current code cannot pass)
```text
test_golden_angle_pack_n_modes_min_geodesic_ge_0_12
test_golden_angle_pack_rejects_when_alpha_too_dense
test_packing_lift_produces_closed_or_null_legal_points
test_packing_deterministic_for_fixed_alpha_n
test_no_poincare_runtime_storage_in_wave_or_vault_metadata_truth
```
### Non-goals
- Live `core_ha` package
- Serving-path packing
- Approximate nearest-neighbor packing repair
---
## Section B — Fibonacci section search + GoldTether κ
### Required design deliverables
1. Module sketch: `core/physics/fibonacci_search.py`
- `BoundedUnimodalObjective(lower, upper, evaluation_budget, objective_id, objective_version)`
- `fibonacci_section_search(objective, func) -> SearchTrace`
- `SearchTrace`: `best_observed_point`, `eval_sequence`, certificate fields
2. Fail-closed on nonfinite, bounds violation, multi-extrema when validator enabled.
3. Integration surface: optimize synthetic \(\kappa\) residual; later optional Procrustes residual under fixed N evals (Fidelity Score).
4. **A-04:** must not be importable from `chat/runtime.py` (already AST-pinned in `tests/test_third_door_cohesion.py`).
### RED tests
```text
test_fibonacci_search_hits_known_unimodal_min_within_1e-3
test_fibonacci_search_eval_count_equals_budget
test_fibonacci_search_rejects_nan_objective
test_fibonacci_search_unimodality_violation_fail_closed # optional if validator included
test_serve_runtime_still_quarantines_fibonacci_search
```
### Non-goals
- Stochastic optimizers
- Serve-path κ adaptation
- Cryptographic hashing on every hot-path eval (R-04: traces in calibration only)
---
## Implementation constraints (hard)
| Constraint | Rule |
|------------|------|
| Algebra | `algebra/*` only for field truth |
| Closure | `versor_condition < 1e-6` at construction boundaries |
| Epistemic | Packing modes seal SPECULATIVE unless reviewed |
| Mutation | Vault writes only via `VaultStore.store` (INV-21) |
| Determinism | No `np.random` in behavioral tests |
| R-01 | Fail-closed on residual breach; no silent unitize repair in hot paths |
---
## What already landed (do not redesign)
| Surface | Status |
|---------|--------|
| `WaveManifold` sandwich / left-spinor / spectral leakage / unitary residual | GREEN |
| `resonant_recall` + `resonant_reconstruct` + `phase_correlation` | GREEN |
| `HolographicVaultStore` + public `VaultStore.get_versor` | GREEN |
| Entity cohesion suite skeleton | `tests/test_third_door_cohesion.py` |
| Serve quarantine AST | GREEN |
---
## Resume condition for Grok Build
Return a design note (Markdown) that:
1. Chooses exact horosphere geodesic formula and packing API signatures.
2. Chooses Fibonacci search API + certificate schema.
3. Lists RED tests with expected failures on current `main`/branch.
4. Confirms AGENTS.md compliance (especially no hot-path drift repair).
Then Grok Build will TDD-implement P4/P5 and draft `docs/adr/ADR-0242-*.md`.
---
## Suggested dual-ADR split (for your draft)
- **ADR-0241:** wave field, spectral leakage, polar (true polar still open), holographic vault, entity I-04/I-05.
- **ADR-0242:** atlas packing + Fibonacci search + optional multi-scale energy \(\tau_n=F_n\tau_0\).

View file

@ -266,35 +266,41 @@ PY
---
## 12. Wave-field substrate (ADR-0241) — 🟢 complete on this branch
## 12. Wave-field substrate (ADR-0241) — 🟢 local operators / 🟡 entity mastery
> **Status (2026-07-14):** ADR-0241 + `core_ha` deprecation plan + `wave_manifold.py`
> + Slice-2 operator subsumption + Slice-3 multi-pair thin wrap / resonant recall
> on `feat/third-door-wave-field-substrate`. Suite
> `tests/test_adr_0241_wave_manifold.py` is **GREEN**. Third-Door operators
> **delegate into** wave primitives (no parallel residual/projection path).
> Off-serving containment preserved.
> **Status (2026-07-14, honesty pass):** Local Slice 13 + holographic vault
> behavioral suites are **GREEN**. Entity cohesion (I-01…I-05, Trace A/B,
> Golden-Angle packing, true \(\mathcal{C}_{AB}\) polar, non-vacuous chiral,
> multimodal \(\rho\)) is the remaining mastery surface — see
> `docs/analysis/core_cohesion_master_plan.md` and
> `tests/test_third_door_cohesion.py`.
### Spec (ADR-0241) — contract
- Continuous multivector wave-field \(\psi \in Cl(4,1)\) (32-coeff) under Cartan/Procrustes, Surprise, GoldTether, Biography.
- **Transport pin:** multivector fields → sandwich \(R\psi\widetilde{R}\); spinor/chiral → left multiply \(R\psi\). No silent mix.
- Spectral leakage = metric proj onto resonant modes (definite Euclidean energy after metric-exact proj).
- Unitary residual \(\|\psi\widetilde{\psi}-1\|_F\) dual-checked. Chiral \(\langle\psi I\widetilde{\psi}\rangle_0\) structurally ~0 in real Cl(4,1) (honest; #19 family).
- Standing-wave registry + `resonant_recall` (session-local; not vault).
- `core_ha` standalone atlas: **deprecated** (no live tree; hygiene pin).
- Standing-wave registry + `resonant_recall` (session-local; durable via `HolographicVaultStore`).
- `core_ha` standalone atlas: **deprecated** (no live tree; hygiene pin + Phase 0 grep).
### Acceptance (behavioral — GREEN)
### Acceptance (behavioral)
| Pin | Status |
|-----|--------|
| Unitary / sandwich step residual \(< 10^{-6}\) | 🟢 |
| Spectral leakage zero on-span / positive off-span / metric-exact | 🟢 |
| Wave polar recovers known sandwich rotor | 🟢 |
| Multi-pair `wave_field_conjugacy` + Procrustes sequence path | 🟢 |
| Chiral conserved under left \(R\); even versor ~0 | 🟢 |
| Wave polar recovers known sandwich rotor | 🟢 (single-pair conjugacy) |
| Multi-pair `wave_field_conjugacy` + Procrustes sequence path | 🟡 thin wrap over `_field_conjugacy_versor` — not true \(\mathcal{C}_{AB}\) polar |
| Chiral conserved under left \(R\); even versor ~0 | 🟡 honest vacuous Q on real Cl(4,1) |
| Resonant recall picks registered mode; empty refused | 🟢 |
| Superposition reconstruct \(\sum c_k\psi_k\) | 🟢 `resonant_reconstruct` |
| Phase correlation \(\rho\) (I-04 algebra) | 🟢 `phase_correlation` (sensorium feed still open) |
| Surprise / GoldTether / biography delegate to wave | 🟢 |
| No teaching import in `wave_manifold`; no `core_ha` package | 🟢 |
| Serve path not wired to wave (containment) | 🟢 (by design) |
| Serve path not wired to wave / Fibonacci (containment) | 🟢 (AST-pinned in cohesion suite) |
| Entity I-01…I-05 cohesion suite | 🟢 progressive pins in `test_third_door_cohesion.py` (I-02 float32-honest) |
| Vault public `get_versor` ABI | 🟢 |
| Golden-Angle atlas packing \(d_{\min}=0.12\) | 🔴 STOP → `docs/briefs/ADR-0242-atlas-packing-and-fibonacci-brief.md` |
| Fibonacci κ search | 🔴 STOP → same brief |
### Subsumption map (Slice 23)
| Operator | Delegation |
@ -307,7 +313,10 @@ PY
| `integrate_biography` | unitary lock-in + mode register + resonant_recall; encode `holonomy_encode` |
### Deferred (explicit, not namesake green)
- Durable holographic memory **vault store** — 🟢 `core/physics/holographic_vault.py` (VaultStore-backed SPECULATIVE spectrum; restart lock-in).
- Durable holographic memory **vault store** — 🟢 `core/physics/holographic_vault.py` (VaultStore-backed SPECULATIVE spectrum; restart lock-in; public `get_versor` ABI).
- True cross-spectral \(\mathcal{C}_{AB}\) + Clifford polar (not thin conjugacy wrap).
- Non-vacuous pair-spinor chiral charge.
- Golden-Angle horosphere packing + Fibonacci section search (ADR-0242).
- Rust/MLX acceleration of exp-map / cross-spectral (ADR-0235 later).
- Full ADR-0092 reviewer-service integration (promote remains caller-gated).
- Optional Rust Ring-1 port of trajectory invariants (Python is authority today).
@ -324,8 +333,10 @@ PY
| Grade-5 pseudoscalar preservation gate — ⚪ RETIRED (vacuous; see §5) | #19 (closed) |
| Surprise: metric projection + productivity polarity + DiscoveryCandidate wiring — 🟢 done | #20 (math #26; wiring #31) |
| Trajectory invariants + ADR-DAG embedding — 🟢 Python surfaces | #21 |
| Wave-field substrate + operator subsumption (W1W6) — 🟢 on branch | ADR-0241 |
| `core_ha` deprecation — 🟢 no live tree + hygiene pin | ADR-0241 / deprecation plan |
| Wave-field local operators + subsumption (W1W6) — 🟢 local / 🟡 entity mastery | ADR-0241 |
| `core_ha` deprecation — 🟢 no live tree + hygiene + Phase 0 grep | ADR-0241 / deprecation plan |
| Durable holographic vault spectrum — 🟢 HolographicVaultStore | ADR-0241 |
| Entity cohesion I-01…I-05 + Trace A/B | cohesion master plan |
| Atlas packing + Fibonacci κ (ADR-0242) | cohesion master plan |
Closing a gap = flip its `xfail` in `tests/test_third_door_blueprint_fidelity.py` (or the ADR-0241 suite) to a passing behavioral test and delete the matching characterization lock. That is the definition of "done right" here.
Closing a gap = flip its `xfail` in `tests/test_third_door_blueprint_fidelity.py` (or the ADR-0241 / cohesion suite) to a passing behavioral test and delete the matching characterization lock. That is the definition of "done right" here.

View file

@ -311,6 +311,27 @@ def test_resonant_recall_empty_refused():
M.resonant_recall(_unit_rotor(0.3, plane=6))
def test_resonant_reconstruct_interference_weights():
"""Superposition reconstruct recovers a weighted combo better than pure modes."""
M = WaveManifold()
a = _unit_rotor(0.2, plane=6)
b = _unit_rotor(0.9, plane=10)
query = 0.6 * a + 0.4 * b
psi_hat, coeffs, _energies = M.resonant_reconstruct(query, modes=[a, b])
assert coeffs.shape == (2,)
err_hat = float(np.linalg.norm(psi_hat - query))
assert err_hat < float(np.linalg.norm(a - query))
assert err_hat < float(np.linalg.norm(b - query))
def test_phase_correlation_symmetric():
"""I-04 algebraic resonance: ρ(A,B)=ρ(B,A)."""
M = WaveManifold()
a = _unit_rotor(0.2, plane=6)
b = _unit_rotor(0.55, plane=8)
assert abs(M.phase_correlation(a, b) - M.phase_correlation(b, a)) < 1e-12
def test_core_ha_package_absent():
"""core_ha deprecation: no live package tree in this repo (W6 hygiene)."""
import importlib.util

View file

@ -0,0 +1,279 @@
"""Third-Door / ADR-0241 entity cohesion suite.
Authority: docs/analysis/core_cohesion_master_plan.md
Pins Phase 0 audits (A-02A-04, pre-deprecation grep), entity invariants
I-01I-05 (progressive), serve quarantine, and vault public ABI.
Deterministic fixtures only no random Euclidean-norm spinors as truth.
"""
from __future__ import annotations
import ast
import importlib.util
import re
from pathlib import Path
import numpy as np
import pytest
from algebra.cl41 import N_COMPONENTS
from algebra.rotor import make_rotor_from_angle
from algebra.versor import versor_condition
from core.physics.biography import integrate_biography
from core.physics.holographic_vault import HolographicVaultError, HolographicVaultStore
from core.physics.self_authorship import SelfAuthorshipMiner
from core.physics.wave_manifold import WaveManifold
from teaching.epistemic import EpistemicStatus
from vault.store import VaultStore
_ROOT = Path(__file__).resolve().parents[1]
_CLOSURE = 1e-6
# VaultStore stores float32; I-02 float64 ideal is 1e-12. Honest dual pin:
_I02_F32_TOL = 1e-6
_I02_F64_PATH_TOL = 1e-12
def _closed(angle: float = 0.3, plane: int = 6) -> np.ndarray:
return make_rotor_from_angle(angle, bivector_idx=plane)
# --- Phase 0 / pre-deprecation hygiene ---------------------------------------
def test_phase0_a02_wave_bindings_in_third_door_operators():
"""A-02: surprise + dynamic_manifold bind WaveManifold (not parallel residual)."""
surprise_src = (_ROOT / "core/physics/surprise.py").read_text()
dyn_src = (_ROOT / "core/physics/dynamic_manifold.py").read_text()
assert "WaveManifold" in surprise_src
assert "compute_spectral_leakage" in surprise_src
assert "WaveManifold" in dyn_src
assert "wave_field_conjugacy" in dyn_src or "wave_analogical_polar" in dyn_src
def test_phase0_a04_serve_path_quarantines_wave_and_fibonacci():
"""A-04: chat/runtime must not import wave / holographic / fibonacci / packing."""
runtime_path = _ROOT / "chat/runtime.py"
src = runtime_path.read_text()
tree = ast.parse(src)
banned_roots = {
"wave_manifold",
"holographic_vault",
"fibonacci_search",
"atlas_packing",
}
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
leaf = alias.name.split(".")[-1]
assert leaf not in banned_roots, f"banned import {alias.name}"
assert "wave_manifold" not in alias.name
assert "holographic_vault" not in alias.name
assert "fibonacci_search" not in alias.name
if isinstance(node, ast.ImportFrom) and node.module:
mod = node.module
for ban in banned_roots:
assert ban not in mod, f"banned from-import {mod}"
if node.names:
for alias in node.names:
assert alias.name not in banned_roots
def test_pre_deprecation_grep_no_core_ha_imports_in_python():
"""Pre-deprecation: no live Python import of core_ha / hyperbolic_primitives."""
offenders: list[str] = []
patterns = (
re.compile(r"^\s*(import\s+core_ha\b|from\s+core_ha\b)"),
re.compile(r"^\s*(import\s+hyperbolic_primitives\b|from\s+hyperbolic_primitives\b)"),
)
skip_dirs = {
".git",
".venv",
"venv",
"node_modules",
"__pycache__",
".pytest_cache",
"workbench-ui",
}
for path in _ROOT.rglob("*.py"):
if any(part in skip_dirs for part in path.parts):
continue
# Tests may *mention* core_ha in strings/asserts; ban only import statements.
try:
text = path.read_text(encoding="utf-8", errors="replace")
except OSError:
continue
for i, line in enumerate(text.splitlines(), 1):
if line.lstrip().startswith("#"):
continue
for pat in patterns:
if pat.search(line):
offenders.append(f"{path.relative_to(_ROOT)}:{i}:{line.strip()}")
assert not offenders, "legacy imports found:\n" + "\n".join(offenders)
def test_core_ha_package_absent():
assert importlib.util.find_spec("core_ha") is None
def test_holographic_vault_does_not_touch_private_versors():
"""P1: holographic reload uses public VaultStore ABI only."""
src = (_ROOT / "core/physics/holographic_vault.py").read_text()
assert "._versors" not in src
assert "get_versor" in src
# --- I-05 unitary amplitude ---------------------------------------------------
def test_i05_unitary_propagator_amplitude_conservation():
M = WaveManifold()
psi = _closed(0.41, plane=7)
R = _closed(0.22, plane=6)
out = M.sandwich_step(psi, R)
assert M.measure_unitary_residual(out) < _CLOSURE
B = np.zeros(N_COMPONENTS, dtype=np.float64)
B[9] = 1.0
stepped = M.algebraic_schrodinger_step(psi, B, dt=0.25)
assert M.measure_unitary_residual(stepped) < _CLOSURE
# --- I-02 vault round-trip (honest float32 storage) ---------------------------
def test_i02_holographic_round_trip_float32_honest():
"""I-02: seal → new instance load recovers mode within float32 store tol."""
vault = VaultStore()
hv1 = HolographicVaultStore(vault)
psi = _closed(0.45, plane=7).astype(np.float64)
sealed = hv1.seal_mode(psi, mode_id="i02-roundtrip")
assert sealed.epistemic_status is EpistemicStatus.SPECULATIVE
hv2 = HolographicVaultStore(vault)
loaded = hv2.load_spectrum()
assert len(loaded) == 1
recovered = loaded[0].mode
err = float(np.linalg.norm(recovered.astype(np.float64) - psi))
# Storage is float32: cannot claim 1e-12 bit identity after cast.
assert err < _I02_F32_TOL, f"round-trip err {err:.3e} exceeds float32 tol"
# Public ABI path used for reload
entry = vault.get_entry(sealed.vault_index)
assert entry["index"] == sealed.vault_index
assert float(np.linalg.norm(entry["versor"].astype(np.float64) - recovered)) < _I02_F32_TOL
def test_vault_get_versor_out_of_range():
vault = VaultStore()
with pytest.raises(IndexError):
vault.get_versor(0)
# --- I-01 biography + holographic restart ------------------------------------
def test_i01_biography_holonomy_closed_and_modes_reloadable():
"""I-01: holonomy closed; trajectory modes durable via holographic vault."""
traj = [_closed(0.1 * (i + 1), plane=6 + (i % 3)) for i in range(4)]
blade = integrate_biography(traj)
assert blade.closure < _CLOSURE
assert versor_condition(blade.blade) < _CLOSURE
vault = VaultStore()
hv = HolographicVaultStore(vault)
for i, v in enumerate(traj):
hv.seal_mode(v, mode_id=f"bio-step-{i}")
hv2 = HolographicVaultStore(vault)
spectrum = hv2.load_spectrum()
assert len(spectrum) == len(traj)
# Reconstruct biography from reloaded modes preserves closure
reloaded = [s.mode for s in spectrum]
blade2 = integrate_biography(reloaded)
assert blade2.closure < _CLOSURE
assert blade2.n_steps == blade.n_steps
# --- I-03 self-authorship never COHERENT-seals --------------------------------
def test_i03_self_authorship_proposals_are_speculative_only():
miner = SelfAuthorshipMiner(residual_threshold=1e-12)
a = _closed(0.2, plane=6)
b = _closed(0.9, plane=7)
proposals = miner.mine_from_trajectory(b, a)
for p in proposals:
assert p.epistemic_status == "SPECULATIVE"
assert p.epistemic_status != "COHERENT"
def test_i03_holographic_reviewed_refuses_without_authorization():
hv = HolographicVaultStore(VaultStore())
with pytest.raises(HolographicVaultError, match="authoriz"):
hv.seal_mode_reviewed(_closed(0.2), authorized=False, mode_id="nope")
# --- I-04 phase correlation ---------------------------------------------------
def test_i04_phase_correlation_symmetric_algebraic():
M = WaveManifold()
a = _closed(0.2, plane=6)
b = _closed(0.55, plane=8)
rho_ab = M.phase_correlation(a, b)
rho_ba = M.phase_correlation(b, a)
assert abs(rho_ab - rho_ba) < 1e-12
# Self-correlation positive for unit-ish rotors
assert M.phase_correlation(a, a) > 0.5
def test_i04_wave_manifold_forbids_approx_neighbor_imports():
src = (_ROOT / "core/physics/wave_manifold.py").read_text()
tree = ast.parse(src)
banned = {"faiss", "hnswlib", "annoy", "sklearn"}
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
assert alias.name.split(".")[0] not in banned
if isinstance(node, ast.ImportFrom) and node.module:
assert node.module.split(".")[0] not in banned
# --- Superposition reconstruct (P3) ------------------------------------------
def test_resonant_reconstruct_partial_combo_closer_than_pure_modes():
M = WaveManifold()
a = _closed(0.2, plane=6)
b = _closed(0.9, plane=10)
# Query biased toward a linear combo of modes (equal mix in ambient space).
query = 0.6 * a + 0.4 * b
modes = [a, b]
psi_hat, coeffs, energies = M.resonant_reconstruct(query, modes=modes)
assert coeffs.shape == (2,)
assert energies.shape == (2,)
err_hat = float(np.linalg.norm(psi_hat - query))
err_a = float(np.linalg.norm(a - query))
err_b = float(np.linalg.norm(b - query))
assert err_hat < err_a
assert err_hat < err_b
# Mass-normalized coeffs should favor the dominant overlap direction.
assert abs(float(np.sum(np.abs(coeffs))) - 1.0) < 1e-9 or float(np.sum(np.abs(coeffs))) == 0.0
def test_resonant_reconstruct_empty_refused():
M = WaveManifold()
with pytest.raises(ValueError, match="empty mode set"):
M.resonant_reconstruct(_closed(0.1))
# --- ADR-0242 placeholder (Fibonacci not yet landed) --------------------------
def test_fibonacci_search_module_absent_or_importable_placeholder():
"""Until P5, fibonacci_search may be absent; if present it must not hit serve."""
spec = importlib.util.find_spec("core.physics.fibonacci_search")
if spec is None:
pytest.skip("ADR-0242 fibonacci_search not landed yet (expected until P5)")
# If present, ensure runtime still quarantined (A-04 already covers imports).
mod = importlib.import_module("core.physics.fibonacci_search")
assert hasattr(mod, "fibonacci_section_search")

View file

@ -559,6 +559,34 @@ class VaultStore:
for i, meta in enumerate(self._metadata):
yield i, meta
def get_versor(self, index: int) -> np.ndarray:
"""Return a copy of the stored versor at live deque ``index``.
Public read ABI for structured reloaders (e.g. holographic standing-wave
spectrum). Does not mutate, reproject, or repair. Raises ``IndexError``
for out-of-range indices. Callers that need float64 algebra should cast;
storage remains float32 by construction (see ``store``).
"""
n = len(self._versors)
if index < 0 or index >= n:
raise IndexError(
f"vault index {index} out of range for {n} stored entries"
)
return np.asarray(self._versors[index], dtype=np.float32).copy()
def get_entry(self, index: int) -> dict:
"""Return ``{versor, metadata, index}`` for a live deque index (copies).
Read-only; metadata is a shallow copy so callers cannot mutate vault
bookkeeping through the returned dict.
"""
versor = self.get_versor(index)
return {
"versor": versor,
"metadata": dict(self._metadata[index]),
"index": int(index),
}
@property
def reproject_interval(self) -> int:
return self._reproject_interval