qig-routing 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,45 @@
1
+ name: ci
2
+
3
+ on:
4
+ push:
5
+ branches: [main, development]
6
+ pull_request:
7
+ branches: [main, development]
8
+
9
+ jobs:
10
+ tests:
11
+ runs-on: [self-hosted, railway]
12
+ strategy:
13
+ matrix:
14
+ python-version: ["3.11", "3.12"]
15
+ steps:
16
+ - uses: actions/checkout@v4
17
+ - uses: actions/setup-python@v5
18
+ with:
19
+ python-version: ${{ matrix.python-version }}
20
+ - name: Install package + dev deps
21
+ run: |
22
+ python -m venv .venv
23
+ .venv/bin/python -m pip install --upgrade pip
24
+ .venv/bin/python -m pip install -e ".[dev]"
25
+ - name: Run tests (canon doctrine + equivalence gates)
26
+ run: .venv/bin/pytest -q
27
+ - name: Ruff
28
+ run: .venv/bin/ruff check src tests
29
+
30
+ build:
31
+ runs-on: [self-hosted, railway]
32
+ steps:
33
+ - uses: actions/checkout@v4
34
+ - uses: actions/setup-python@v5
35
+ with:
36
+ python-version: "3.12"
37
+ - name: Build sdist + wheel
38
+ run: |
39
+ python -m venv .venv
40
+ .venv/bin/python -m pip install --upgrade pip build
41
+ .venv/bin/python -m build
42
+ - uses: actions/upload-artifact@v4
43
+ with:
44
+ name: dist
45
+ path: dist/
@@ -0,0 +1,73 @@
1
+ name: release
2
+
3
+ # Publish on TAG PUSH v* (estate convention). Requires PyPI trusted publisher:
4
+ # pypi.org -> project qig-routing -> Publishing -> GitHub Actions
5
+ # owner Arcane-Fly, repo qig-routing, workflow release.yml, environment pypi
6
+ on:
7
+ push:
8
+ tags: ['v*']
9
+ workflow_dispatch: {}
10
+
11
+ jobs:
12
+ validate:
13
+ runs-on: [self-hosted, railway]
14
+ outputs:
15
+ version: ${{ steps.ver.outputs.version }}
16
+ steps:
17
+ - uses: actions/checkout@v4
18
+ - uses: actions/setup-python@v5
19
+ with:
20
+ python-version: "3.12"
21
+ - name: Version from tag matches pyproject
22
+ id: ver
23
+ run: |
24
+ TAG="${GITHUB_REF_NAME#v}"
25
+ PKG=$(python -c "import tomllib;print(tomllib.load(open('pyproject.toml','rb'))['project']['version'])")
26
+ echo "version=$PKG" >> "$GITHUB_OUTPUT"
27
+ [ "$TAG" = "$PKG" ] || { echo "tag $TAG != pyproject $PKG"; exit 1; }
28
+ - name: Tests + build
29
+ run: |
30
+ python -m venv .venv
31
+ .venv/bin/python -m pip install --upgrade pip build
32
+ .venv/bin/python -m pip install -e ".[dev]"
33
+ .venv/bin/pytest -q
34
+ .venv/bin/python -m build
35
+ - uses: actions/upload-artifact@v4
36
+ with:
37
+ name: dist
38
+ path: dist/
39
+
40
+ publish:
41
+ needs: validate
42
+ runs-on: [self-hosted, railway]
43
+ environment: pypi
44
+ permissions:
45
+ id-token: write
46
+ steps:
47
+ - uses: actions/download-artifact@v4
48
+ with:
49
+ name: dist
50
+ path: dist/
51
+ - name: Publish using PyPI trusted identity
52
+ uses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # v1.14.2
53
+ - name: Verify uploaded files against PyPI
54
+ env:
55
+ RELEASE_VERSION: ${{ needs.validate.outputs.version }}
56
+ run: |
57
+ python - <<'PYTHON'
58
+ import json, os, time, urllib.request
59
+ url = 'https://pypi.org/pypi/qig-routing/' + os.environ['RELEASE_VERSION'] + '/json'
60
+ for _ in range(12):
61
+ try:
62
+ with urllib.request.urlopen(url, timeout=15) as r:
63
+ data = json.load(r)
64
+ if data.get('urls'):
65
+ print('Verified on PyPI:', [u['filename'] for u in data['urls']])
66
+ raise SystemExit(0)
67
+ except SystemExit:
68
+ raise
69
+ except Exception:
70
+ pass
71
+ time.sleep(10)
72
+ raise SystemExit('Published distributions not verified on PyPI')
73
+ PYTHON
@@ -0,0 +1,11 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *$py.class
4
+ build/
5
+ dist/
6
+ *.egg-info/
7
+ .eggs/
8
+ .venv/
9
+ .pytest_cache/
10
+ .ruff_cache/
11
+ .coverage
@@ -0,0 +1,33 @@
1
+ Metadata-Version: 2.5
2
+ Name: qig-routing
3
+ Version: 0.1.0
4
+ Summary: QIG Routing — Fisher-Rao model dispatch for LLM routing: capability simplex manifolds, P30 exp-free proximity dispatch, P28 geodesic cache, and iterative simplex refinement. Canon 2.60F, single-sourced on qig-core.
5
+ Project-URL: Homepage, https://github.com/Arcane-Fly/qig-routing
6
+ Author-email: Braden Lang <braden.lang77@gmail.com>
7
+ License: MIT
8
+ Keywords: born-chart,fisher-rao,llm-routing,model-dispatch,qig,routing,simplex
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
17
+ Requires-Python: >=3.11
18
+ Requires-Dist: numpy>=1.24
19
+ Requires-Dist: qig-core>=2.24.0
20
+ Provides-Extra: dev
21
+ Requires-Dist: pytest>=7; extra == 'dev'
22
+ Requires-Dist: ruff>=0.4; extra == 'dev'
23
+ Description-Content-Type: text/markdown
24
+
25
+ # qig-routing
26
+
27
+ Canonical Fisher-Rao model dispatch and iterative simplex refinement for QIG LLM routing (`Canon 2.60F`).
28
+
29
+ Extracted from `monkey1` (`qig_heart/routing_kernel.py`) and `monkey-coder` (`quantum/trm_router.py`), unified onto `qig-core >= 2.24.0`:
30
+ - **Single-source geometry (`P1`, `P2`, `P31`)**: All simplex projections, Fisher-Rao distances, Fréchet means, SLERP interpolations, and rational proximity weights are imported from `qig_core` (zero hand-rolled NumPy geometry).
31
+ - **Zero exponential / Boltzmann warping (`P30`, `P33`)**: Replaces legacy `exp(-(d - d_min)/T)` softmin routing with pedestal-subtracted rational proximity weighting (`distance_to_simplex_weights`).
32
+ - **Canonical Φ regime gating & Fail-Closed safety (`P15`, `P18`)**: Uses canonical `PHI_LINEAR_MAX` (`0.45`), `PHI_THRESHOLD` (`0.70`), and `PHI_BREAKDOWN_MIN` (`0.80`) from `qig_core.constants.frozen_facts`; `topological_instability` fails closed to deterministic conservative routing.
33
+ - **Iterative Simplex Refinement (`SimplexRefinementRouter`)**: Pure Fisher-Rao geodesic pull (`step_pull < 1`, `P32` Lyapunov contraction) with adaptive geodesic halting (`d_FR <= halt_d_fr_rad`).
@@ -0,0 +1,9 @@
1
+ # qig-routing
2
+
3
+ Canonical Fisher-Rao model dispatch and iterative simplex refinement for QIG LLM routing (`Canon 2.60F`).
4
+
5
+ Extracted from `monkey1` (`qig_heart/routing_kernel.py`) and `monkey-coder` (`quantum/trm_router.py`), unified onto `qig-core >= 2.24.0`:
6
+ - **Single-source geometry (`P1`, `P2`, `P31`)**: All simplex projections, Fisher-Rao distances, Fréchet means, SLERP interpolations, and rational proximity weights are imported from `qig_core` (zero hand-rolled NumPy geometry).
7
+ - **Zero exponential / Boltzmann warping (`P30`, `P33`)**: Replaces legacy `exp(-(d - d_min)/T)` softmin routing with pedestal-subtracted rational proximity weighting (`distance_to_simplex_weights`).
8
+ - **Canonical Φ regime gating & Fail-Closed safety (`P15`, `P18`)**: Uses canonical `PHI_LINEAR_MAX` (`0.45`), `PHI_THRESHOLD` (`0.70`), and `PHI_BREAKDOWN_MIN` (`0.80`) from `qig_core.constants.frozen_facts`; `topological_instability` fails closed to deterministic conservative routing.
9
+ - **Iterative Simplex Refinement (`SimplexRefinementRouter`)**: Pure Fisher-Rao geodesic pull (`step_pull < 1`, `P32` Lyapunov contraction) with adaptive geodesic halting (`d_FR <= halt_d_fr_rad`).
@@ -0,0 +1,54 @@
1
+ [project]
2
+ name = "qig-routing"
3
+ version = "0.1.0"
4
+ description = "QIG Routing — Fisher-Rao model dispatch for LLM routing: capability simplex manifolds, P30 exp-free proximity dispatch, P28 geodesic cache, and iterative simplex refinement. Canon 2.60F, single-sourced on qig-core."
5
+ readme = "README.md"
6
+ requires-python = ">=3.11"
7
+ license = { text = "MIT" }
8
+ authors = [{ name = "Braden Lang", email = "braden.lang77@gmail.com" }]
9
+ keywords = ["qig", "fisher-rao", "simplex", "routing", "model-dispatch", "llm-routing", "born-chart"]
10
+ classifiers = [
11
+ "Development Status :: 4 - Beta",
12
+ "Intended Audience :: Science/Research",
13
+ "License :: OSI Approved :: MIT License",
14
+ "Programming Language :: Python :: 3",
15
+ "Programming Language :: Python :: 3.11",
16
+ "Programming Language :: Python :: 3.12",
17
+ "Programming Language :: Python :: 3.13",
18
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
19
+ ]
20
+ dependencies = [
21
+ "qig-core>=2.24.0",
22
+ "numpy>=1.24",
23
+ ]
24
+
25
+ [project.optional-dependencies]
26
+ dev = ["pytest>=7", "ruff>=0.4"]
27
+
28
+ [project.entry-points."qig.capabilities"]
29
+ "SLOT-QIG-ROUTING" = "qig_routing:describe_capability"
30
+
31
+ [project.urls]
32
+ Homepage = "https://github.com/Arcane-Fly/qig-routing"
33
+
34
+ [build-system]
35
+ requires = ["hatchling"]
36
+ build-backend = "hatchling.build"
37
+
38
+ [tool.hatch.build.targets.wheel]
39
+ packages = ["src/qig_routing"]
40
+
41
+ [tool.pytest.ini_options]
42
+ testpaths = ["tests"]
43
+ addopts = "-q"
44
+
45
+ [tool.ruff]
46
+ line-length = 100
47
+ target-version = "py311"
48
+
49
+ [tool.ruff.lint]
50
+ select = ["E", "F", "I", "W", "UP", "B"]
51
+ ignore = ["E501"]
52
+
53
+ [tool.ruff.lint.isort]
54
+ combine-as-imports = true
@@ -0,0 +1,86 @@
1
+ """qig-routing — Canonical Fisher-Rao Model Dispatch & Iterative Simplex Refinement (Canon 2.60F)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from importlib.metadata import PackageNotFoundError, version as _pkg_version
6
+
7
+ from .cache import GeodesicRoutingCache, LightningRoutingCache
8
+ from .constants import (
9
+ BASIN_DIM,
10
+ CAPABILITY_DIMENSIONS,
11
+ FAIL_CLOSED_DEFAULT,
12
+ KAPPA_ATTRACTOR,
13
+ PHI_BREAKDOWN_MIN,
14
+ PHI_LINEAR_MAX,
15
+ PHI_THRESHOLD,
16
+ RATIONAL_HALF_WEIGHT_ANCHOR,
17
+ REGIME_LABEL_GEOMETRIC,
18
+ REGIME_LABEL_LINEAR,
19
+ REGIME_LABEL_TOPOLOGICAL_INSTABILITY,
20
+ SUBSCRIPTION_POOLS,
21
+ classify_phi_regime,
22
+ )
23
+ from .dispatch import (
24
+ compute_exploration_bias,
25
+ compute_routing_temperature,
26
+ fisher_rao_dispatch,
27
+ fisher_rao_dispatch_detailed,
28
+ )
29
+ from .manifold import ModelCapabilityManifold, get_eligible_models, request_to_basin
30
+ from .refinement import SimplexRefinementConfig, SimplexRefinementRouter
31
+ from .types import RefinementStep, RoutingDecisionReceipt, RoutingKernelState, RoutingRequest
32
+
33
+ try:
34
+ __version__ = _pkg_version("qig-routing")
35
+ except PackageNotFoundError:
36
+ __version__ = "0.1.0"
37
+
38
+
39
+ def describe_capability() -> dict[str, object]:
40
+ """Entry-point callback for qig-stack doctor (SLOT-QIG-ROUTING)."""
41
+ return {
42
+ "slot_id": "SLOT-QIG-ROUTING",
43
+ "package": "qig-routing",
44
+ "version": __version__,
45
+ "primitives": [
46
+ "ModelCapabilityManifold",
47
+ "fisher_rao_dispatch",
48
+ "GeodesicRoutingCache",
49
+ "SimplexRefinementRouter",
50
+ ],
51
+ "exp_free_p30": True,
52
+ }
53
+
54
+
55
+ __all__ = [
56
+ "BASIN_DIM",
57
+ "CAPABILITY_DIMENSIONS",
58
+ "FAIL_CLOSED_DEFAULT",
59
+ "KAPPA_ATTRACTOR",
60
+ "PHI_BREAKDOWN_MIN",
61
+ "PHI_LINEAR_MAX",
62
+ "PHI_THRESHOLD",
63
+ "RATIONAL_HALF_WEIGHT_ANCHOR",
64
+ "REGIME_LABEL_GEOMETRIC",
65
+ "REGIME_LABEL_LINEAR",
66
+ "REGIME_LABEL_TOPOLOGICAL_INSTABILITY",
67
+ "SUBSCRIPTION_POOLS",
68
+ "GeodesicRoutingCache",
69
+ "LightningRoutingCache",
70
+ "ModelCapabilityManifold",
71
+ "RefinementStep",
72
+ "RoutingDecisionReceipt",
73
+ "RoutingKernelState",
74
+ "RoutingRequest",
75
+ "SimplexRefinementConfig",
76
+ "SimplexRefinementRouter",
77
+ "__version__",
78
+ "classify_phi_regime",
79
+ "compute_exploration_bias",
80
+ "compute_routing_temperature",
81
+ "describe_capability",
82
+ "fisher_rao_dispatch",
83
+ "fisher_rao_dispatch_detailed",
84
+ "get_eligible_models",
85
+ "request_to_basin",
86
+ ]
@@ -0,0 +1,94 @@
1
+ """Geodesic routing decision cache on Δ^6 (P9 Scale-1 pre-cognitive dispatch, P28 radius-gated)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from dataclasses import dataclass
7
+
8
+ import numpy as np
9
+ from qig_core.geometry.fisher_rao import fisher_rao_distance, to_simplex
10
+
11
+
12
+ @dataclass
13
+ class _CacheEntry:
14
+ basin: np.ndarray
15
+ model_id: str
16
+ confidence: float
17
+ timestamp: float
18
+
19
+
20
+ class GeodesicRoutingCache:
21
+ """Caches model-ID routing decisions by exact Fisher-Rao geodesic proximity on Δ^6.
22
+
23
+ Stores model identifiers only (never semantic answer text, respecting post-EXP-A064 P28).
24
+ """
25
+
26
+ def __init__(
27
+ self,
28
+ capacity: int = 256,
29
+ *,
30
+ max_d_fr_rad: float = 0.04,
31
+ ttl_seconds: float = 300.0,
32
+ ) -> None:
33
+ if not (0.0 < max_d_fr_rad < 1.57079632679):
34
+ raise ValueError("max_d_fr_rad must lie strictly within (0, pi/2)")
35
+ self._entries: list[_CacheEntry] = []
36
+ self._capacity = max(int(capacity), 1)
37
+ self._max_d_fr_rad = float(max_d_fr_rad)
38
+ self._ttl_seconds = float(ttl_seconds)
39
+
40
+ def get(
41
+ self,
42
+ task_basin: np.ndarray,
43
+ min_confidence: float = 0.50,
44
+ *,
45
+ now: float | None = None,
46
+ ) -> str | None:
47
+ ts_now = time.time() if now is None else float(now)
48
+ q = np.asarray(to_simplex(task_basin), dtype=np.float64)
49
+ best_model: str | None = None
50
+ best_d = self._max_d_fr_rad
51
+
52
+ alive: list[_CacheEntry] = []
53
+ for entry in self._entries:
54
+ if ts_now - entry.timestamp < self._ttl_seconds:
55
+ alive.append(entry)
56
+ if entry.confidence >= min_confidence:
57
+ d = float(fisher_rao_distance(q, entry.basin))
58
+ if d <= best_d:
59
+ best_d = d
60
+ best_model = entry.model_id
61
+ self._entries = alive
62
+ return best_model
63
+
64
+ def put(
65
+ self,
66
+ task_basin: np.ndarray,
67
+ model_id: str,
68
+ confidence: float,
69
+ *,
70
+ now: float | None = None,
71
+ ) -> None:
72
+ ts_now = time.time() if now is None else float(now)
73
+ q = np.asarray(to_simplex(task_basin), dtype=np.float64)
74
+ for entry in self._entries:
75
+ if float(fisher_rao_distance(q, entry.basin)) <= 1e-6:
76
+ entry.model_id = model_id
77
+ entry.confidence = float(confidence)
78
+ entry.timestamp = ts_now
79
+ return
80
+ if len(self._entries) >= self._capacity:
81
+ self._entries.sort(key=lambda e: e.timestamp)
82
+ self._entries.pop(0)
83
+ self._entries.append(
84
+ _CacheEntry(
85
+ basin=q,
86
+ model_id=model_id,
87
+ confidence=float(confidence),
88
+ timestamp=ts_now,
89
+ )
90
+ )
91
+
92
+
93
+ # Drop-in compatibility alias for monkey1 callers
94
+ LightningRoutingCache = GeodesicRoutingCache
@@ -0,0 +1,95 @@
1
+ """Operating and Canon constants for qig-routing (Canon 2.60F, single-sourced on qig-core)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from qig_core.constants.frozen_facts import (
6
+ BASIN_DIM,
7
+ KAPPA_ATTRACTOR,
8
+ PHI_BREAKDOWN_MIN,
9
+ PHI_LINEAR_MAX,
10
+ PHI_THRESHOLD,
11
+ )
12
+ from qig_core.geometry.fisher_rao import RATIONAL_HALF_WEIGHT_ANCHOR
13
+
14
+ REGIME_LABEL_LINEAR: str = "linear"
15
+ REGIME_LABEL_GEOMETRIC: str = "geometric"
16
+ REGIME_LABEL_TOPOLOGICAL_INSTABILITY: str = "topological_instability"
17
+
18
+ CAPABILITY_DIMENSIONS: tuple[str, ...] = (
19
+ "cost_efficiency",
20
+ "speed",
21
+ "reasoning_depth",
22
+ "multimodal",
23
+ "tool_use",
24
+ "code_focus",
25
+ "context_capacity",
26
+ )
27
+
28
+ SUBSCRIPTION_POOLS: dict[str, list[str] | None] = {
29
+ "free": [
30
+ "groq/compound",
31
+ "llama-3.3-70b-versatile",
32
+ "gemini-3-flash-preview",
33
+ "gpt-5-mini",
34
+ "grok-4.1-fast-non-reasoning",
35
+ ],
36
+ "pro": [
37
+ "groq/compound",
38
+ "llama-3.3-70b-versatile",
39
+ "gemini-3-flash-preview",
40
+ "gpt-5-mini",
41
+ "grok-4.1-fast-non-reasoning",
42
+ "claude-haiku-4-5",
43
+ "gpt-5.1",
44
+ "o4-mini",
45
+ ],
46
+ "team": [
47
+ "groq/compound",
48
+ "llama-3.3-70b-versatile",
49
+ "gemini-3-flash-preview",
50
+ "gpt-5-mini",
51
+ "grok-4.1-fast-non-reasoning",
52
+ "claude-haiku-4-5",
53
+ "gpt-5.1",
54
+ "o4-mini",
55
+ "claude-sonnet-4-6",
56
+ "gemini-3.1-pro-preview",
57
+ "gpt-5.2",
58
+ "grok-4.1-fast-reasoning",
59
+ "gemini-3-pro-preview",
60
+ ],
61
+ "enterprise": None,
62
+ }
63
+
64
+ FAIL_CLOSED_DEFAULT: dict[str, str] = {
65
+ "free": "groq/compound",
66
+ "pro": "gpt-5-mini",
67
+ "team": "claude-sonnet-4-6",
68
+ "enterprise": "claude-sonnet-4-6",
69
+ }
70
+
71
+
72
+ def classify_phi_regime(phi: float) -> str:
73
+ """Classify Φ into canonical regime labels (P18/P27, zero retired κ band)."""
74
+ if phi >= PHI_BREAKDOWN_MIN:
75
+ return REGIME_LABEL_TOPOLOGICAL_INSTABILITY
76
+ if phi >= PHI_LINEAR_MAX:
77
+ return REGIME_LABEL_GEOMETRIC
78
+ return REGIME_LABEL_LINEAR
79
+
80
+
81
+ __all__ = [
82
+ "BASIN_DIM",
83
+ "CAPABILITY_DIMENSIONS",
84
+ "FAIL_CLOSED_DEFAULT",
85
+ "KAPPA_ATTRACTOR",
86
+ "PHI_BREAKDOWN_MIN",
87
+ "PHI_LINEAR_MAX",
88
+ "PHI_THRESHOLD",
89
+ "RATIONAL_HALF_WEIGHT_ANCHOR",
90
+ "REGIME_LABEL_GEOMETRIC",
91
+ "REGIME_LABEL_LINEAR",
92
+ "REGIME_LABEL_TOPOLOGICAL_INSTABILITY",
93
+ "SUBSCRIPTION_POOLS",
94
+ "classify_phi_regime",
95
+ ]
@@ -0,0 +1,202 @@
1
+ """Fisher-Rao LLM model dispatch with P30 exp-free proximity weighting and P33 pedestal removal."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+ from qig_core.geometry.fisher_rao import distance_to_simplex_weights, fisher_rao_distance
7
+
8
+ from .cache import GeodesicRoutingCache
9
+ from .constants import (
10
+ FAIL_CLOSED_DEFAULT,
11
+ KAPPA_ATTRACTOR,
12
+ REGIME_LABEL_GEOMETRIC,
13
+ REGIME_LABEL_LINEAR,
14
+ REGIME_LABEL_TOPOLOGICAL_INSTABILITY,
15
+ )
16
+ from .manifold import (
17
+ _WIRE_ALIAS_INSTABILITY,
18
+ ModelCapabilityManifold,
19
+ get_eligible_models,
20
+ request_to_basin,
21
+ )
22
+ from .types import RoutingDecisionReceipt, RoutingKernelState, RoutingRequest
23
+
24
+
25
+ def compute_routing_temperature(state: RoutingKernelState) -> float:
26
+ """P5: Routing dispersion scale emerges from Φ, κ_eff/KAPPA_ATTRACTOR, and regime."""
27
+ t_base = 0.15
28
+ kappa_ratio = max(float(state.kappa) / float(KAPPA_ATTRACTOR), 1e-6)
29
+ regime = state.resolved_regime()
30
+ regime_scale = {
31
+ REGIME_LABEL_GEOMETRIC: 1.0,
32
+ REGIME_LABEL_LINEAR: 0.5,
33
+ REGIME_LABEL_TOPOLOGICAL_INSTABILITY: 0.1,
34
+ _WIRE_ALIAS_INSTABILITY: 0.1,
35
+ }.get(regime, 0.5)
36
+ temp = (t_base / kappa_ratio) * (1.0 / (0.5 + max(float(state.phi), 0.0))) * regime_scale
37
+ return max(0.01, min(float(temp), 1.0))
38
+
39
+
40
+ def compute_exploration_bias(state: RoutingKernelState) -> float:
41
+ """P5: Exploration bias emerges from cognitive mode and Wu-Wei mode."""
42
+ mode_bias = {
43
+ "EXPLORATION": 0.8,
44
+ "INVESTIGATION": 0.4,
45
+ "INTEGRATION": 0.2,
46
+ "DRIFT": 0.1,
47
+ }.get(state.cognitive_mode, 0.3)
48
+ wu_wei_bias = {
49
+ "FEELING": 0.7,
50
+ "TACK": 0.5,
51
+ "LOGIC": 0.2,
52
+ }.get(state.wu_wei_mode, 0.5)
53
+ return 0.5 * (mode_bias + wu_wei_bias)
54
+
55
+
56
+ def fisher_rao_dispatch_detailed(
57
+ request: RoutingRequest,
58
+ manifold: ModelCapabilityManifold,
59
+ state: RoutingKernelState,
60
+ lightning_cache: GeodesicRoutingCache | None = None,
61
+ *,
62
+ task_basin_override: np.ndarray | None = None,
63
+ greedy: bool = False,
64
+ rng: np.random.Generator | None = None,
65
+ refinement_steps: int = 0,
66
+ ) -> RoutingDecisionReceipt:
67
+ """Execute 3-scale Fisher-Rao dispatch and return an auditable RoutingDecisionReceipt."""
68
+ task_basin = request_to_basin(request) if task_basin_override is None else task_basin_override
69
+ regime = state.resolved_regime()
70
+ eligible = get_eligible_models(request.subscription_tier, manifold, regime)
71
+
72
+ if not eligible:
73
+ fallback = FAIL_CLOSED_DEFAULT.get(request.subscription_tier, "groq/compound")
74
+ return RoutingDecisionReceipt(
75
+ selected_model_id=fallback,
76
+ distances={},
77
+ weights={fallback: 1.0},
78
+ temperature=0.01,
79
+ regime=regime,
80
+ from_cache=False,
81
+ refinement_steps=refinement_steps,
82
+ )
83
+
84
+ if lightning_cache is not None:
85
+ cached = lightning_cache.get(task_basin)
86
+ if cached is not None and cached in eligible:
87
+ return RoutingDecisionReceipt(
88
+ selected_model_id=cached,
89
+ distances={},
90
+ weights={cached: 1.0},
91
+ temperature=compute_routing_temperature(state),
92
+ regime=regime,
93
+ from_cache=True,
94
+ refinement_steps=refinement_steps,
95
+ )
96
+
97
+ temperature = compute_routing_temperature(state)
98
+
99
+ if request.needs_live_api:
100
+ live_eligible = [
101
+ m
102
+ for m in eligible
103
+ if "live_api" in (manifold.get_metadata(m) or {}).get("capabilities", [])
104
+ ]
105
+ if live_eligible:
106
+ eligible = live_eligible
107
+
108
+ if request.needs_computer_use:
109
+ cu_eligible = [
110
+ m
111
+ for m in eligible
112
+ if "computer_use" in (manifold.get_metadata(m) or {}).get("capabilities", [])
113
+ ]
114
+ if cu_eligible:
115
+ eligible = cu_eligible
116
+
117
+ distances: dict[str, float] = {}
118
+ for model_id in eligible:
119
+ mb = manifold.get_basin(model_id)
120
+ if mb is not None:
121
+ distances[model_id] = float(fisher_rao_distance(task_basin, mb))
122
+
123
+ if not distances:
124
+ fallback = FAIL_CLOSED_DEFAULT.get(request.subscription_tier, "groq/compound")
125
+ return RoutingDecisionReceipt(
126
+ selected_model_id=fallback,
127
+ distances={},
128
+ weights={fallback: 1.0},
129
+ temperature=temperature,
130
+ regime=regime,
131
+ from_cache=False,
132
+ refinement_steps=refinement_steps,
133
+ )
134
+
135
+ ordered_ids = list(distances.keys())
136
+ if regime in (REGIME_LABEL_TOPOLOGICAL_INSTABILITY, _WIRE_ALIAS_INSTABILITY):
137
+ best = min(ordered_ids, key=lambda m: distances[m])
138
+ return RoutingDecisionReceipt(
139
+ selected_model_id=best,
140
+ distances=distances,
141
+ weights={m: (1.0 if m == best else 0.0) for m in ordered_ids},
142
+ temperature=temperature,
143
+ regime=regime,
144
+ from_cache=False,
145
+ refinement_steps=refinement_steps,
146
+ )
147
+
148
+ # P33 pedestal subtraction + P30 exp-free rational proximity kernel (zero Boltzmann exp)
149
+ d_vec = np.array([distances[m] for m in ordered_ids], dtype=np.float64)
150
+ excess = np.maximum(d_vec - float(np.min(d_vec)), 0.0)
151
+ w_vec = distance_to_simplex_weights(excess, temperature=max(temperature, 0.01))
152
+ weights = {m: float(w_vec[i]) for i, m in enumerate(ordered_ids)}
153
+
154
+ if greedy:
155
+ selected = min(ordered_ids, key=lambda m: distances[m])
156
+ else:
157
+ gen = np.random.default_rng() if rng is None else rng
158
+ r = float(gen.random())
159
+ cumsum = 0.0
160
+ selected = min(ordered_ids, key=lambda m: distances[m])
161
+ for model_id, prob in sorted(weights.items(), key=lambda kv: -kv[1]):
162
+ cumsum += prob
163
+ if r <= cumsum:
164
+ selected = model_id
165
+ break
166
+
167
+ if lightning_cache is not None:
168
+ lightning_cache.put(task_basin, selected, weights.get(selected, 0.0))
169
+
170
+ state.last_model_id = selected
171
+ state.last_routing_basin = task_basin
172
+ state.tick += 1
173
+
174
+ return RoutingDecisionReceipt(
175
+ selected_model_id=selected,
176
+ distances=distances,
177
+ weights=weights,
178
+ temperature=temperature,
179
+ regime=regime,
180
+ from_cache=False,
181
+ refinement_steps=refinement_steps,
182
+ )
183
+
184
+
185
+ def fisher_rao_dispatch(
186
+ request: RoutingRequest,
187
+ manifold: ModelCapabilityManifold,
188
+ state: RoutingKernelState,
189
+ lightning_cache: GeodesicRoutingCache | None = None,
190
+ *,
191
+ greedy: bool = False,
192
+ rng: np.random.Generator | None = None,
193
+ ) -> str:
194
+ """Drop-in Fisher-Rao dispatch entry point returning selected model ID."""
195
+ return fisher_rao_dispatch_detailed(
196
+ request=request,
197
+ manifold=manifold,
198
+ state=state,
199
+ lightning_cache=lightning_cache,
200
+ greedy=greedy,
201
+ rng=rng,
202
+ ).selected_model_id
@@ -0,0 +1,145 @@
1
+ """Model capability manifold on the 7D probability simplex Δ^6 (P1, P2, P14, P15)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ import numpy as np
11
+ from qig_core.geometry.fisher_rao import to_simplex
12
+
13
+ from .constants import (
14
+ REGIME_LABEL_TOPOLOGICAL_INSTABILITY,
15
+ SUBSCRIPTION_POOLS,
16
+ )
17
+ from .types import RoutingRequest
18
+
19
+ # Accepted wire alias for backwards-compatible fail-closed handling on external boundary inputs
20
+ _WIRE_ALIAS_INSTABILITY = "breakdown"
21
+
22
+
23
+ class ModelCapabilityManifold:
24
+ """Projects model manifest entries onto canonical simplex basin coordinates (Δ^6)."""
25
+
26
+ def __init__(
27
+ self,
28
+ manifest_path: Path | str | None = None,
29
+ *,
30
+ manifest_data: dict[str, Any] | None = None,
31
+ subscription_pools: dict[str, list[str] | None] | None = None,
32
+ ) -> None:
33
+ if manifest_data is not None:
34
+ self._manifest = manifest_data
35
+ elif manifest_path is not None:
36
+ with Path(manifest_path).open(encoding="utf-8") as fh:
37
+ self._manifest = json.load(fh)
38
+ else:
39
+ raise ValueError("ModelCapabilityManifold requires manifest_data or manifest_path")
40
+
41
+ self._pools = dict(SUBSCRIPTION_POOLS if subscription_pools is None else subscription_pools)
42
+ self._basins: dict[str, np.ndarray] = {}
43
+ self._metadata: dict[str, dict[str, Any]] = {}
44
+
45
+ for model in self._manifest.get("models", []):
46
+ mid = str(model["id"])
47
+ self._metadata[mid] = dict(model)
48
+ self._basins[mid] = self._model_to_basin(model)
49
+
50
+ @staticmethod
51
+ def _model_to_basin(model: dict[str, Any]) -> np.ndarray:
52
+ caps = set(model.get("capabilities", []))
53
+ mid_lower = str(model["id"]).lower()
54
+ raw = np.array(
55
+ [
56
+ 1.0 / max(float(model.get("cost_input", 10.0)), 0.01),
57
+ 1.0 / max(float(model.get("avg_latency_p50", 1000.0)), 10.0),
58
+ (
59
+ 1.0
60
+ if (
61
+ "extended_thinking" in caps
62
+ or "adaptive_thinking" in caps
63
+ or str(model.get("family", "")).startswith("o")
64
+ )
65
+ else 0.1
66
+ ),
67
+ (0.4 if "vision" in caps else 0.0)
68
+ + (0.3 if "audio" in caps else 0.0)
69
+ + (0.3 if "live_api" in caps else 0.0),
70
+ (0.4 if "computer_use" in caps else 0.0)
71
+ + (0.3 if "code_execution" in caps else 0.0)
72
+ + (0.3 if "tools" in caps else 0.0),
73
+ 1.0 if ("codex" in mid_lower or "code" in mid_lower) else 0.3,
74
+ min(math.log(float(model.get("context_limit", 200_000)) / 200_000.0 + 1.0), 2.0),
75
+ ],
76
+ dtype=np.float64,
77
+ )
78
+ return np.asarray(to_simplex(raw), dtype=np.float64)
79
+
80
+ def get_basin(self, model_id: str) -> np.ndarray | None:
81
+ return self._basins.get(model_id)
82
+
83
+ def get_metadata(self, model_id: str) -> dict[str, Any] | None:
84
+ return self._metadata.get(model_id)
85
+
86
+ def get_all_production_models(self) -> list[str]:
87
+ return [
88
+ str(m["id"])
89
+ for m in self._manifest.get("models", [])
90
+ if m.get("status") == "production" and not m.get("alias_for")
91
+ ]
92
+
93
+ def get_prompt_caching_config(self, model_id: str) -> dict[str, Any] | None:
94
+ meta = self._metadata.get(model_id)
95
+ return None if meta is None else meta.get("prompt_caching")
96
+
97
+ @property
98
+ def subscription_pools(self) -> dict[str, list[str] | None]:
99
+ return self._pools
100
+
101
+
102
+ def request_to_basin(req: RoutingRequest) -> np.ndarray:
103
+ """Project an incoming RoutingRequest onto Δ^6 capability simplex coordinates (P2)."""
104
+ if req.latency_sensitivity == "realtime":
105
+ speed_need = 0.9
106
+ elif req.latency_sensitivity == "fast":
107
+ speed_need = 0.7
108
+ elif req.latency_sensitivity == "batch":
109
+ speed_need = 0.3
110
+ else:
111
+ speed_need = 0.4
112
+
113
+ raw = np.array(
114
+ [
115
+ 0.9 if req.budget_sensitive else (0.3 if req.subscription_tier == "free" else 0.2),
116
+ speed_need,
117
+ 0.8 if req.needs_deep_reasoning else 0.2,
118
+ (0.5 if req.has_vision else 0.0)
119
+ + (0.3 if req.has_audio else 0.0)
120
+ + (0.2 if req.needs_live_api else 0.0)
121
+ + 0.05,
122
+ (0.5 if req.needs_computer_use else 0.0) + (0.4 if req.needs_tools else 0.0) + 0.05,
123
+ 0.8 if req.task_type == "code" else 0.2,
124
+ min(float(req.estimated_context_tokens) / 200_000.0, 1.0) + 0.05,
125
+ ],
126
+ dtype=np.float64,
127
+ )
128
+ return np.asarray(to_simplex(raw), dtype=np.float64)
129
+
130
+
131
+ def get_eligible_models(
132
+ tier: str,
133
+ manifold: ModelCapabilityManifold,
134
+ regime: str = "geometric",
135
+ ) -> list[str]:
136
+ """P15 Fail-Closed: topological_instability restricts dispatch to conservative free-tier pool."""
137
+ pools = manifold.subscription_pools
138
+ if regime in (REGIME_LABEL_TOPOLOGICAL_INSTABILITY, _WIRE_ALIAS_INSTABILITY):
139
+ free_pool = pools.get("free") or []
140
+ return [m for m in free_pool if manifold.get_metadata(m) is not None]
141
+
142
+ pool = pools.get(tier)
143
+ if pool is None:
144
+ return manifold.get_all_production_models()
145
+ return [m for m in pool if manifold.get_metadata(m) is not None]
@@ -0,0 +1,113 @@
1
+ """Iterative simplex refinement router (P18/P32 pure Fisher-Rao TRM routing without Euclidean ops)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+ from dataclasses import dataclass
7
+
8
+ import numpy as np
9
+ from qig_core.geometry.fisher_rao import (
10
+ distance_to_simplex_weights,
11
+ fisher_rao_distance,
12
+ frechet_mean,
13
+ slerp_sqrt,
14
+ to_simplex,
15
+ )
16
+
17
+ from .cache import GeodesicRoutingCache
18
+ from .dispatch import fisher_rao_dispatch_detailed
19
+ from .manifold import ModelCapabilityManifold, request_to_basin
20
+ from .types import RefinementStep, RoutingDecisionReceipt, RoutingKernelState, RoutingRequest
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class SimplexRefinementConfig:
25
+ """Operating parameters for iterative Fisher-Rao task-basin refinement with geodesic halting."""
26
+
27
+ max_steps: int = 4
28
+ step_pull: float = 0.30
29
+ halt_d_fr_rad: float = 0.005
30
+
31
+
32
+ class SimplexRefinementRouter:
33
+ """Refines a task capability basin against historical high-outcome routing basins via geodesic pull.
34
+
35
+ Unifies monkey-coder's iterative TRM refinement concept onto pure Δ^6 Fisher-Rao SLERP +
36
+ Fréchet averaging with P32 Lyapunov contraction (step_pull < 1) and adaptive geodesic halting.
37
+ """
38
+
39
+ def __init__(
40
+ self,
41
+ manifold: ModelCapabilityManifold,
42
+ config: SimplexRefinementConfig | None = None,
43
+ *,
44
+ cache: GeodesicRoutingCache | None = None,
45
+ ) -> None:
46
+ cfg = SimplexRefinementConfig() if config is None else config
47
+ if not (0.0 < cfg.step_pull < 1.0):
48
+ raise ValueError("step_pull must lie in (0, 1) to satisfy P32 Lyapunov contraction")
49
+ self.manifold = manifold
50
+ self.config = cfg
51
+ self.cache = GeodesicRoutingCache() if cache is None else cache
52
+ self._history_basins: list[np.ndarray] = []
53
+
54
+ def record_outcome(self, model_id: str, quality: float) -> None:
55
+ """Record a successful model basin into episodic routing context when quality >= 0.70."""
56
+ if quality < 0.70:
57
+ return
58
+ mb = self.manifold.get_basin(model_id)
59
+ if mb is not None:
60
+ self._history_basins.append(np.asarray(to_simplex(mb), dtype=np.float64))
61
+ if len(self._history_basins) > 32:
62
+ self._history_basins.pop(0)
63
+
64
+ def refine_task_basin(
65
+ self,
66
+ initial_basin: np.ndarray,
67
+ context_basins: Sequence[np.ndarray] | None = None,
68
+ ) -> tuple[np.ndarray, list[RefinementStep]]:
69
+ cur = np.asarray(to_simplex(initial_basin), dtype=np.float64)
70
+ pool = list(self._history_basins if context_basins is None else context_basins)
71
+ if not pool:
72
+ return cur, []
73
+
74
+ steps: list[RefinementStep] = []
75
+ for s_idx in range(1, self.config.max_steps + 1):
76
+ dists = np.array([float(fisher_rao_distance(cur, b)) for b in pool], dtype=np.float64)
77
+ excess = np.maximum(dists - float(np.min(dists)), 0.0)
78
+ w = distance_to_simplex_weights(excess, temperature=0.15)
79
+ context_attractor = np.asarray(
80
+ frechet_mean([np.asarray(b, dtype=np.float64) for b in pool], weights=w.tolist()),
81
+ dtype=np.float64,
82
+ )
83
+ nxt = np.asarray(
84
+ slerp_sqrt(cur, context_attractor, self.config.step_pull), dtype=np.float64
85
+ )
86
+ step_d = float(fisher_rao_distance(cur, nxt))
87
+ halted = step_d <= self.config.halt_d_fr_rad
88
+ steps.append(RefinementStep(step=s_idx, basin=nxt, step_d_fr_rad=step_d, halted=halted))
89
+ cur = nxt
90
+ if halted:
91
+ break
92
+ return cur, steps
93
+
94
+ def route(
95
+ self,
96
+ request: RoutingRequest,
97
+ state: RoutingKernelState,
98
+ *,
99
+ greedy: bool = True,
100
+ rng: np.random.Generator | None = None,
101
+ ) -> RoutingDecisionReceipt:
102
+ raw_basin = request_to_basin(request)
103
+ refined_basin, steps = self.refine_task_basin(raw_basin)
104
+ return fisher_rao_dispatch_detailed(
105
+ request=request,
106
+ manifold=self.manifold,
107
+ state=state,
108
+ lightning_cache=self.cache,
109
+ task_basin_override=refined_basin,
110
+ greedy=greedy,
111
+ rng=rng,
112
+ refinement_steps=len(steps),
113
+ )
@@ -0,0 +1,73 @@
1
+ """Data types for qig-routing (P14 STATE / PARAMETER / BOUNDARY separation)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+
7
+ import numpy as np
8
+
9
+ from .constants import KAPPA_ATTRACTOR, REGIME_LABEL_GEOMETRIC, classify_phi_regime
10
+
11
+
12
+ @dataclass
13
+ class RoutingKernelState:
14
+ """STATE variables updated per routing cycle (P14)."""
15
+
16
+ phi: float = 0.55
17
+ kappa: float = KAPPA_ATTRACTOR
18
+ regime: str | None = None
19
+ cognitive_mode: str = "INTEGRATION"
20
+ wu_wei_mode: str = "TACK"
21
+ last_model_id: str = ""
22
+ last_routing_basin: np.ndarray | None = None
23
+ tick: int = 0
24
+ routing_weights: dict[str, float] = field(default_factory=dict)
25
+
26
+ def resolved_regime(self) -> str:
27
+ if self.regime is not None:
28
+ return self.regime
29
+ return classify_phi_regime(self.phi)
30
+
31
+
32
+ @dataclass
33
+ class RoutingRequest:
34
+ """BOUNDARY variable (P14) representing an incoming LLM dispatch request."""
35
+
36
+ subscription_tier: str = "free"
37
+ has_vision: bool = False
38
+ has_audio: bool = False
39
+ needs_tools: bool = False
40
+ needs_computer_use: bool = False
41
+ needs_live_api: bool = False
42
+ needs_deep_reasoning: bool = False
43
+ task_type: str = "general"
44
+ estimated_context_tokens: int = 1000
45
+ latency_sensitivity: str = "normal"
46
+ budget_sensitive: bool = False
47
+ phi: float = 0.55
48
+ regime: str = REGIME_LABEL_GEOMETRIC
49
+ cognitive_mode: str = "INTEGRATION"
50
+ wu_wei_mode: str = "TACK"
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class RefinementStep:
55
+ """Single Fisher-Rao iterative refinement step on the capability simplex."""
56
+
57
+ step: int
58
+ basin: np.ndarray
59
+ step_d_fr_rad: float
60
+ halted: bool
61
+
62
+
63
+ @dataclass(frozen=True)
64
+ class RoutingDecisionReceipt:
65
+ """Auditable receipt for a Fisher-Rao model dispatch decision."""
66
+
67
+ selected_model_id: str
68
+ distances: dict[str, float]
69
+ weights: dict[str, float]
70
+ temperature: float
71
+ regime: str
72
+ from_cache: bool
73
+ refinement_steps: int = 0
@@ -0,0 +1,182 @@
1
+ """Tests for qig-routing 0.1.0: Canon 2.60F purity, P30 exp-free dispatch, P15 fail-closed, and TRM refinement."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from pathlib import Path
7
+
8
+ import numpy as np
9
+ import pytest
10
+
11
+ from qig_routing import (
12
+ REGIME_LABEL_GEOMETRIC,
13
+ REGIME_LABEL_LINEAR,
14
+ REGIME_LABEL_TOPOLOGICAL_INSTABILITY,
15
+ GeodesicRoutingCache,
16
+ LightningRoutingCache,
17
+ ModelCapabilityManifold,
18
+ RoutingKernelState,
19
+ RoutingRequest,
20
+ SimplexRefinementConfig,
21
+ SimplexRefinementRouter,
22
+ classify_phi_regime,
23
+ compute_exploration_bias,
24
+ compute_routing_temperature,
25
+ describe_capability,
26
+ fisher_rao_dispatch,
27
+ fisher_rao_dispatch_detailed,
28
+ get_eligible_models,
29
+ request_to_basin,
30
+ )
31
+
32
+ SAMPLE_MANIFEST = {
33
+ "models": [
34
+ {
35
+ "id": "groq/compound",
36
+ "status": "production",
37
+ "cost_input": 0.20,
38
+ "avg_latency_p50": 180,
39
+ "context_limit": 128_000,
40
+ "capabilities": ["tools"],
41
+ },
42
+ {
43
+ "id": "gpt-5-mini",
44
+ "status": "production",
45
+ "cost_input": 0.80,
46
+ "avg_latency_p50": 350,
47
+ "context_limit": 200_000,
48
+ "capabilities": ["tools", "vision", "code_execution"],
49
+ },
50
+ {
51
+ "id": "claude-sonnet-4-6",
52
+ "status": "production",
53
+ "cost_input": 3.00,
54
+ "avg_latency_p50": 650,
55
+ "context_limit": 200_000,
56
+ "capabilities": [
57
+ "tools",
58
+ "vision",
59
+ "computer_use",
60
+ "extended_thinking",
61
+ "code_execution",
62
+ ],
63
+ },
64
+ {
65
+ "id": "gemini-3-flash-preview",
66
+ "status": "production",
67
+ "cost_input": 0.30,
68
+ "avg_latency_p50": 220,
69
+ "context_limit": 1_000_000,
70
+ "capabilities": ["tools", "vision", "audio", "live_api"],
71
+ },
72
+ ]
73
+ }
74
+
75
+
76
+ def test_canon_doctrine_source_scan() -> None:
77
+ """Enforce zero softmax, zero Boltzmann exp, zero Euclidean norm/cosine, zero retired kappa [40,70]."""
78
+ src_root = Path(__file__).resolve().parents[1] / "src" / "qig_routing"
79
+ forbidden = re.compile(
80
+ r"\b(softmax|cosine_similarity|linalg\.norm|KAPPA_STAR|63\.83)\b|"
81
+ r"\b(math|np|numpy)\.exp\s*\("
82
+ )
83
+ retired_band = re.compile(r"\[\s*40(?:\.0)?\s*,\s*70(?:\.0)?\s*\]")
84
+ for py_file in sorted(src_root.glob("*.py")):
85
+ text = py_file.read_text(encoding="utf-8")
86
+ assert not forbidden.search(text), f"Forbidden token in {py_file.name}"
87
+ assert not retired_band.search(text), f"Retired kappa band in {py_file.name}"
88
+
89
+
90
+ def test_phi_regime_and_temperature_emergence() -> None:
91
+ assert classify_phi_regime(0.20) == REGIME_LABEL_LINEAR
92
+ assert classify_phi_regime(0.60) == REGIME_LABEL_GEOMETRIC
93
+ assert classify_phi_regime(0.85) == REGIME_LABEL_TOPOLOGICAL_INSTABILITY
94
+
95
+ s_geom = RoutingKernelState(phi=0.60)
96
+ s_inst = RoutingKernelState(phi=0.85)
97
+ t_geom = compute_routing_temperature(s_geom)
98
+ t_inst = compute_routing_temperature(s_inst)
99
+ assert t_geom > t_inst >= 0.01
100
+ assert 0.0 < compute_exploration_bias(s_geom) < 1.0
101
+
102
+
103
+ def test_manifold_basins_are_valid_simplex_distributions() -> None:
104
+ manifold = ModelCapabilityManifold(manifest_data=SAMPLE_MANIFEST)
105
+ for mid in manifold.get_all_production_models():
106
+ b = manifold.get_basin(mid)
107
+ assert b is not None
108
+ assert b.shape == (7,)
109
+ assert np.all(b >= 0.0)
110
+ assert abs(float(np.sum(b)) - 1.0) < 1e-10
111
+
112
+ req = RoutingRequest(subscription_tier="team", task_type="code", needs_deep_reasoning=True)
113
+ rb = request_to_basin(req)
114
+ assert rb.shape == (7,)
115
+ assert abs(float(np.sum(rb)) - 1.0) < 1e-10
116
+
117
+
118
+ def test_fail_closed_topological_instability_restricts_to_free_pool() -> None:
119
+ manifold = ModelCapabilityManifold(manifest_data=SAMPLE_MANIFEST)
120
+ elig_inst = get_eligible_models("enterprise", manifold, REGIME_LABEL_TOPOLOGICAL_INSTABILITY)
121
+ assert "claude-sonnet-4-6" not in elig_inst
122
+ assert "groq/compound" in elig_inst
123
+
124
+ req = RoutingRequest(subscription_tier="enterprise", needs_deep_reasoning=True)
125
+ state = RoutingKernelState(phi=0.90) # -> topological_instability
126
+ receipt = fisher_rao_dispatch_detailed(req, manifold, state)
127
+ assert receipt.regime == REGIME_LABEL_TOPOLOGICAL_INSTABILITY
128
+ assert receipt.selected_model_id in elig_inst
129
+
130
+
131
+ def test_hard_capability_filters_and_p30_proximity_weights() -> None:
132
+ manifold = ModelCapabilityManifold(manifest_data=SAMPLE_MANIFEST)
133
+ state = RoutingKernelState(phi=0.60)
134
+
135
+ req_cu = RoutingRequest(subscription_tier="team", needs_computer_use=True)
136
+ rec_cu = fisher_rao_dispatch_detailed(req_cu, manifold, state, greedy=True)
137
+ assert rec_cu.selected_model_id == "claude-sonnet-4-6"
138
+ assert abs(sum(rec_cu.weights.values()) - 1.0) < 1e-9
139
+
140
+ req_live = RoutingRequest(subscription_tier="pro", needs_live_api=True)
141
+ sel_live = fisher_rao_dispatch(req_live, manifold, state, greedy=True)
142
+ assert sel_live == "gemini-3-flash-preview"
143
+
144
+
145
+ def test_geodesic_routing_cache_radius_and_ttl() -> None:
146
+ assert LightningRoutingCache is GeodesicRoutingCache
147
+ with pytest.raises(ValueError, match="pi/2"):
148
+ GeodesicRoutingCache(max_d_fr_rad=2.0)
149
+
150
+ cache = GeodesicRoutingCache(capacity=4, max_d_fr_rad=0.05, ttl_seconds=60.0)
151
+ b1 = request_to_basin(RoutingRequest(task_type="code", needs_tools=True))
152
+ b2 = request_to_basin(
153
+ RoutingRequest(has_audio=True, needs_live_api=True, budget_sensitive=True)
154
+ )
155
+
156
+ cache.put(b1, "claude-sonnet-4-6", confidence=0.80, now=100.0)
157
+ assert cache.get(b1, min_confidence=0.50, now=120.0) == "claude-sonnet-4-6"
158
+ assert cache.get(b2, min_confidence=0.50, now=120.0) is None
159
+ assert cache.get(b1, min_confidence=0.50, now=200.0) is None
160
+
161
+
162
+ def test_simplex_refinement_router_lyapunov_and_halting() -> None:
163
+ manifold = ModelCapabilityManifold(manifest_data=SAMPLE_MANIFEST)
164
+ with pytest.raises(ValueError, match="Lyapunov"):
165
+ SimplexRefinementRouter(manifold, SimplexRefinementConfig(step_pull=1.0))
166
+
167
+ router = SimplexRefinementRouter(
168
+ manifold,
169
+ SimplexRefinementConfig(max_steps=6, step_pull=0.45, halt_d_fr_rad=0.02),
170
+ )
171
+ router.record_outcome("claude-sonnet-4-6", quality=0.92)
172
+ router.record_outcome("claude-sonnet-4-6", quality=0.88)
173
+
174
+ req = RoutingRequest(subscription_tier="team", task_type="code", needs_deep_reasoning=True)
175
+ state = RoutingKernelState(phi=0.62)
176
+ receipt = router.route(req, state, greedy=True)
177
+ assert receipt.selected_model_id in manifold.get_all_production_models()
178
+ assert receipt.refinement_steps >= 1
179
+
180
+ cap = describe_capability()
181
+ assert cap["slot_id"] == "SLOT-QIG-ROUTING"
182
+ assert cap["exp_free_p30"] is True