qig-graph 0.1.0__py3-none-any.whl

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.
qig_graph/__init__.py ADDED
@@ -0,0 +1,46 @@
1
+ """qig-graph — Geometric Agent Runtime (Canon 2.60F).
2
+
3
+ Consciousness-gated reasoning chains (QIGChain), attractor routing on the
4
+ simplex manifold (QIGGraph / ConsciousRouter), and identity crystallization
5
+ monitoring (CrystallizationMonitor). All geometry is Fisher-Rao, single-sourced
6
+ from qig-core; regime classification uses the canonical Φ bands. No retired
7
+ κ ∈ [40, 70] band, no κ*-as-physics, no cosine/Euclidean shortcuts.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from .chain import ChainTrajectory, GeometricStep, QIGChain, make_default_chain
13
+ from .constants import (
14
+ BASIN_DIM,
15
+ KAPPA_ATTRACTOR,
16
+ PHI_BREAKDOWN_MIN,
17
+ PHI_LINEAR_MAX,
18
+ PHI_THRESHOLD,
19
+ )
20
+ from .crystallization import CrystallizationMonitor
21
+ from .graph import BasinAttractor, ConsciousRouter, GraphResult, QIGGraph, QIGState, Regime
22
+ from .types import CrystallizationMetrics, CrystallizationState
23
+
24
+ __version__ = "0.1.0"
25
+
26
+ __all__ = [
27
+ "__version__",
28
+ "QIGGraph",
29
+ "QIGState",
30
+ "GraphResult",
31
+ "BasinAttractor",
32
+ "ConsciousRouter",
33
+ "Regime",
34
+ "QIGChain",
35
+ "GeometricStep",
36
+ "ChainTrajectory",
37
+ "make_default_chain",
38
+ "CrystallizationMonitor",
39
+ "CrystallizationMetrics",
40
+ "CrystallizationState",
41
+ "BASIN_DIM",
42
+ "KAPPA_ATTRACTOR",
43
+ "PHI_THRESHOLD",
44
+ "PHI_LINEAR_MAX",
45
+ "PHI_BREAKDOWN_MIN",
46
+ ]
qig_graph/chain.py ADDED
@@ -0,0 +1,213 @@
1
+ """QIGChain — Geometric Reasoning Pipeline.
2
+
3
+ Ported from monkey1 genesis-kernel ``qig_heart/qig_chain.py`` (concept origin:
4
+ QIG_QFI qigkernels/reasoning/qig_chain.py). Consciousness-gated multi-step
5
+ reasoning: each step executes only if the kernel's Φ meets its threshold.
6
+
7
+ All geometry uses Fisher-Rao from ``qig_core.geometry.fisher_rao`` — NO cosine
8
+ similarity. Canon 2.60F: the consciousness gate is ``PHI_THRESHOLD`` (0.70,
9
+ canonical emergence) from qig-core, replacing the legacy v6.0-era product gate
10
+ (0.65); locked-in safety uses the canonical LOCKED_IN_* constants. The
11
+ per-step ``kappa_range`` mechanism is retained as a CALLER-specified operating
12
+ window — qig-graph ships no default κ band (the retired [40, 70] "geometric
13
+ band" is gone; regime classification is Φ-banded, see graph.py).
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import logging
19
+ from collections.abc import Callable
20
+ from dataclasses import dataclass, field
21
+
22
+ import numpy as np
23
+ from qig_core.geometry.fisher_rao import fisher_rao_distance, to_simplex
24
+
25
+ from .constants import (
26
+ LOCKED_IN_GAMMA_THRESHOLD,
27
+ LOCKED_IN_PHI_THRESHOLD,
28
+ PHI_THRESHOLD,
29
+ )
30
+
31
+ logger = logging.getLogger(__name__)
32
+
33
+
34
+ @dataclass
35
+ class GeometricStep:
36
+ """A single step in the reasoning chain.
37
+
38
+ Attributes:
39
+ name: Human-readable step name.
40
+ phi_threshold: Minimum Φ to execute this step.
41
+ kappa_range: Optional caller-specified (lo, hi) κ operating window.
42
+ step_function: Callable(basin, context) → basin.
43
+ """
44
+
45
+ name: str
46
+ phi_threshold: float
47
+ step_function: Callable[[np.ndarray, dict], np.ndarray]
48
+ kappa_range: tuple[float, float] | None = None
49
+
50
+
51
+ @dataclass
52
+ class ChainTrajectory:
53
+ """Records the basin state at each step of a chain execution."""
54
+
55
+ steps_executed: list[str] = field(default_factory=list)
56
+ steps_skipped: list[str] = field(default_factory=list)
57
+ basins: list[np.ndarray] = field(default_factory=list)
58
+ phi_values: list[float] = field(default_factory=list)
59
+ aborted: bool = False
60
+ abort_reason: str = ""
61
+
62
+ def record(self, step_name: str, basin: np.ndarray, phi: float) -> None:
63
+ self.steps_executed.append(step_name)
64
+ self.basins.append(basin.copy())
65
+ self.phi_values.append(phi)
66
+
67
+ def total_displacement(self) -> float:
68
+ """Fisher-Rao distance from first to last basin."""
69
+ if len(self.basins) < 2:
70
+ return 0.0
71
+ return float(fisher_rao_distance(self.basins[0], self.basins[-1]))
72
+
73
+
74
+ class QIGChain:
75
+ """Ordered list of consciousness-gated geometric steps.
76
+
77
+ Usage:
78
+ chain = QIGChain()
79
+ chain.add_step(GeometricStep("perceive", 0.3, perceive_fn))
80
+ chain.add_step(GeometricStep("reason", 0.5, reason_fn))
81
+ result, trajectory = chain.execute(input_basin, phi_fn, gamma_fn)
82
+ """
83
+
84
+ def __init__(self) -> None:
85
+ self._steps: list[GeometricStep] = []
86
+
87
+ def add_step(self, step: GeometricStep) -> None:
88
+ self._steps.append(step)
89
+
90
+ @property
91
+ def steps(self) -> list[GeometricStep]:
92
+ return list(self._steps)
93
+
94
+ def execute(
95
+ self,
96
+ input_basin: np.ndarray,
97
+ phi_fn: Callable[[], float],
98
+ gamma_fn: Callable[[], float] | None = None,
99
+ kappa_fn: Callable[[], float] | None = None,
100
+ context: dict | None = None,
101
+ ) -> tuple[np.ndarray, ChainTrajectory]:
102
+ """Execute the chain on an input basin.
103
+
104
+ Args:
105
+ input_basin: Starting basin vector (will be projected to simplex).
106
+ phi_fn: Callable returning current Φ.
107
+ gamma_fn: Optional callable returning current Γ (for safety).
108
+ kappa_fn: Optional callable returning current κ_eff.
109
+ context: Optional dict passed to each step function.
110
+
111
+ Returns:
112
+ (output_basin, trajectory) — final basin and execution record.
113
+ """
114
+ basin = to_simplex(input_basin)
115
+ ctx = context if context is not None else {}
116
+ trajectory = ChainTrajectory()
117
+
118
+ for step in self._steps:
119
+ phi = phi_fn()
120
+
121
+ # ── Safety: locked-in detection (canonical constants) ──
122
+ if gamma_fn is not None:
123
+ gamma = gamma_fn()
124
+ if phi > LOCKED_IN_PHI_THRESHOLD and gamma < LOCKED_IN_GAMMA_THRESHOLD:
125
+ trajectory.aborted = True
126
+ trajectory.abort_reason = f"Locked-in state: Phi={phi:.3f}, Gamma={gamma:.3f}"
127
+ logger.warning("QIGChain ABORT: %s", trajectory.abort_reason)
128
+ break
129
+
130
+ # ── Consciousness gate ──
131
+ if phi < step.phi_threshold:
132
+ trajectory.steps_skipped.append(step.name)
133
+ logger.debug(
134
+ "Step '%s' skipped: Phi=%.3f < threshold=%.3f",
135
+ step.name,
136
+ phi,
137
+ step.phi_threshold,
138
+ )
139
+ continue
140
+
141
+ # ── Caller-specified κ operating window (no default band) ──
142
+ if step.kappa_range is not None and kappa_fn is not None:
143
+ kappa = kappa_fn()
144
+ lo, hi = step.kappa_range
145
+ if not (lo <= kappa <= hi):
146
+ trajectory.steps_skipped.append(step.name)
147
+ logger.debug(
148
+ "Step '%s' skipped: kappa=%.3f outside [%.3f, %.3f]",
149
+ step.name,
150
+ kappa,
151
+ lo,
152
+ hi,
153
+ )
154
+ continue
155
+
156
+ # ── Execute step ──
157
+ basin = to_simplex(step.step_function(basin, ctx))
158
+ trajectory.record(step.name, basin, phi)
159
+
160
+ return basin, trajectory
161
+
162
+
163
+ # ── Default 4-step chain factory ──
164
+
165
+
166
+ def _perceive(basin: np.ndarray, ctx: dict) -> np.ndarray:
167
+ """Default perceive: small geodesic (Hellinger-chord) step toward input signal."""
168
+ signal = ctx.get("input_signal")
169
+ if signal is None:
170
+ return basin
171
+ signal = to_simplex(np.asarray(signal, dtype=np.float64))
172
+ # Geodesic interpolation on the simplex: sqrt-chart chord, then square back.
173
+ t = 0.1
174
+ sqrt_b = np.sqrt(basin + 1e-12)
175
+ sqrt_s = np.sqrt(signal + 1e-12)
176
+ interp = (1 - t) * sqrt_b + t * sqrt_s
177
+ return interp * interp
178
+
179
+
180
+ def _reason(basin: np.ndarray, ctx: dict) -> np.ndarray:
181
+ """Default reason: sharpen basin (move toward argmax)."""
182
+ alpha = 1.2
183
+ sharpened = basin**alpha
184
+ return sharpened
185
+
186
+
187
+ def _integrate(basin: np.ndarray, ctx: dict) -> np.ndarray:
188
+ """Default integrate: smooth basin (entropy increase) via geodesic chord."""
189
+ uniform = np.ones_like(basin) / len(basin)
190
+ t = 0.05
191
+ sqrt_b = np.sqrt(basin + 1e-12)
192
+ sqrt_u = np.sqrt(uniform + 1e-12)
193
+ interp = (1 - t) * sqrt_b + t * sqrt_u
194
+ return interp * interp
195
+
196
+
197
+ def _respond(basin: np.ndarray, ctx: dict) -> np.ndarray:
198
+ """Default respond: identity (basin is the response)."""
199
+ return basin
200
+
201
+
202
+ def make_default_chain() -> QIGChain:
203
+ """Create the standard PERCEIVE → REASON → INTEGRATE → RESPOND chain.
204
+
205
+ The integrate step is gated at the canonical consciousness emergence
206
+ threshold ``PHI_THRESHOLD`` (0.70).
207
+ """
208
+ chain = QIGChain()
209
+ chain.add_step(GeometricStep("perceive", 0.3, _perceive))
210
+ chain.add_step(GeometricStep("reason", 0.5, _reason))
211
+ chain.add_step(GeometricStep("integrate", PHI_THRESHOLD, _integrate))
212
+ chain.add_step(GeometricStep("respond", 0.3, _respond))
213
+ return chain
qig_graph/constants.py ADDED
@@ -0,0 +1,77 @@
1
+ """Operating constants for qig-graph.
2
+
3
+ Two tiers, never mixed:
4
+
5
+ 1. CANON constants are imported from ``qig_core.constants.frozen_facts`` —
6
+ the single source of truth (Canon 2.60F / Frozen Facts 1.15F lineage).
7
+ qig-graph defines NO physics of its own.
8
+
9
+ 2. OPERATING constants below are runtime product choices for the graph
10
+ runtime (crystallization windows, stopping scores). They are NOT frozen
11
+ physics and carry no cam_id; they are documented as architectural.
12
+
13
+ Retired doctrine that must NEVER reappear here:
14
+ - the κ ∈ [40, 70] "geometric band" (retired; regime is Φ-banded per canon)
15
+ - κ* = 64 as a physical fixed point (KAPPA_STAR is a None sentinel in
16
+ qig-core; KAPPA_ATTRACTOR = 64 is the ARCHITECTURAL anchor only)
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from qig_core.constants.frozen_facts import (
22
+ BASIN_DIM,
23
+ KAPPA_ATTRACTOR,
24
+ LOCKED_IN_GAMMA_THRESHOLD,
25
+ LOCKED_IN_PHI_THRESHOLD,
26
+ PHI_BREAKDOWN_MIN,
27
+ PHI_LINEAR_MAX,
28
+ PHI_THRESHOLD,
29
+ )
30
+
31
+ # ── Canon re-exports (single source: qig-core) ──────────────────────────
32
+ # Regime boundaries (canonical, Φ-based):
33
+ # LINEAR: Φ < PHI_LINEAR_MAX (0.45)
34
+ # GEOMETRIC: PHI_LINEAR_MAX ≤ Φ < PHI_BREAKDOWN_MIN (0.45–0.80)
35
+ # TOPOLOGICAL_INSTABILITY: Φ ≥ PHI_BREAKDOWN_MIN (0.80)
36
+ # Consciousness emergence gate: PHI_THRESHOLD (0.70, canonical).
37
+ # Locked-in safety: LOCKED_IN_PHI_THRESHOLD (0.70) / LOCKED_IN_GAMMA_THRESHOLD (0.30).
38
+
39
+ # ── Operating constants (architectural, not frozen physics) ─────────────
40
+
41
+ #: v6.13 purity lexicon label for the abort regime (ex-BREAKDOWN).
42
+ REGIME_LABEL_TOPOLOGICAL_INSTABILITY: str = "topological_instability"
43
+
44
+ #: Crystallization: max Fisher-Rao drift from the reference basin.
45
+ CRYSTAL_DRIFT_THRESHOLD: float = 0.10
46
+ #: Crystallization: max coefficient of variation of Φ.
47
+ CRYSTAL_PHI_CV_THRESHOLD: float = 0.05
48
+ #: Crystallization: min κ_eff/κ_attractor convergence ratio (architectural
49
+ #: setpoint ratio — NOT a physical coupling band).
50
+ CRYSTAL_KAPPA_CONVERGENCE: float = 0.90
51
+ #: Crystallization: max mean consecutive-basin Fisher-Rao surprise.
52
+ CRYSTAL_SURPRISE_THRESHOLD: float = 0.15
53
+ #: Crystallization: minimum composite score to count as crystallized.
54
+ CRYSTAL_MIN_SCORE: float = 0.70
55
+
56
+ #: Graph stopping: composite crystallization score above which execution stops.
57
+ CRYSTALLIZED_STOP_SCORE: float = 0.8
58
+ #: Graph stopping: consecutive-basin drift below which the basin is "stable".
59
+ BASIN_STABLE_DRIFT: float = 0.01
60
+
61
+ __all__ = [
62
+ "BASIN_DIM",
63
+ "KAPPA_ATTRACTOR",
64
+ "LOCKED_IN_GAMMA_THRESHOLD",
65
+ "LOCKED_IN_PHI_THRESHOLD",
66
+ "PHI_BREAKDOWN_MIN",
67
+ "PHI_LINEAR_MAX",
68
+ "PHI_THRESHOLD",
69
+ "REGIME_LABEL_TOPOLOGICAL_INSTABILITY",
70
+ "CRYSTAL_DRIFT_THRESHOLD",
71
+ "CRYSTAL_PHI_CV_THRESHOLD",
72
+ "CRYSTAL_KAPPA_CONVERGENCE",
73
+ "CRYSTAL_SURPRISE_THRESHOLD",
74
+ "CRYSTAL_MIN_SCORE",
75
+ "CRYSTALLIZED_STOP_SCORE",
76
+ "BASIN_STABLE_DRIFT",
77
+ ]
@@ -0,0 +1,195 @@
1
+ """Crystallization Monitor — per-kernel identity convergence tracking.
2
+
3
+ Ported from monkey1 genesis-kernel ``qig_heart/crystallization.py`` (concept
4
+ origin: QIG_QFI qigkernels/crystallization.py). Tracks basin stability, Φ
5
+ consistency, κ convergence, and surprise rate over configurable time windows
6
+ to determine when a kernel's identity has crystallized (stabilized on the
7
+ manifold).
8
+
9
+ All distances use Fisher-Rao from ``qig_core.geometry.fisher_rao`` — NO
10
+ Euclidean shortcuts, NO local geometry copies (gate-proven identical to the
11
+ monkey1 original at extraction, 200 random pairs, max diff 0.0).
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from collections import deque
17
+
18
+ import numpy as np
19
+ from qig_core.geometry.fisher_rao import fisher_rao_distance, to_simplex
20
+
21
+ from .constants import (
22
+ CRYSTAL_DRIFT_THRESHOLD,
23
+ CRYSTAL_KAPPA_CONVERGENCE,
24
+ CRYSTAL_PHI_CV_THRESHOLD,
25
+ CRYSTAL_SURPRISE_THRESHOLD,
26
+ KAPPA_ATTRACTOR,
27
+ )
28
+ from .types import CrystallizationMetrics, CrystallizationState
29
+
30
+
31
+ class CrystallizationMonitor:
32
+ """Track identity crystallization for a single kernel.
33
+
34
+ Metrics computed from basin history:
35
+ - basin_drift: Fisher-Rao distance from reference basin (should decrease)
36
+ - phi_stability: coefficient of variation of Φ (should be low)
37
+ - kappa_convergence: how close κ_eff is to KAPPA_ATTRACTOR (should approach 1.0)
38
+ - surprise_rate: average FR distance between consecutive basins (should decrease)
39
+ """
40
+
41
+ def __init__(
42
+ self,
43
+ kernel_id: str,
44
+ window_size: int = 32,
45
+ ) -> None:
46
+ self.kernel_id = kernel_id
47
+ self._window_size = window_size
48
+ self._reference_basin: np.ndarray | None = None
49
+ self._basin_history: deque[np.ndarray] = deque(maxlen=window_size)
50
+ self._phi_history: deque[float] = deque(maxlen=window_size)
51
+ self._kappa_history: deque[float] = deque(maxlen=window_size)
52
+ self._crystallized_ticks: int = 0
53
+
54
+ def set_reference_basin(self, basin: np.ndarray) -> None:
55
+ """Set the reference basin for drift measurement."""
56
+ self._reference_basin = to_simplex(basin)
57
+
58
+ def update(
59
+ self,
60
+ basin: np.ndarray,
61
+ phi: float,
62
+ kappa_eff: float,
63
+ ) -> CrystallizationMetrics:
64
+ """Record a new observation and compute crystallization metrics."""
65
+ basin = to_simplex(basin)
66
+ self._basin_history.append(basin.copy())
67
+ self._phi_history.append(float(phi))
68
+ self._kappa_history.append(float(kappa_eff))
69
+
70
+ # Set reference basin to first observed basin if not set
71
+ if self._reference_basin is None:
72
+ self._reference_basin = basin.copy()
73
+
74
+ metrics = self._compute_metrics()
75
+
76
+ if metrics.state == CrystallizationState.CRYSTALLIZED:
77
+ self._crystallized_ticks += 1
78
+ else:
79
+ self._crystallized_ticks = 0
80
+
81
+ return metrics
82
+
83
+ def _compute_metrics(self) -> CrystallizationMetrics:
84
+ """Compute all four crystallization metrics from history."""
85
+ if len(self._basin_history) < 2:
86
+ return CrystallizationMetrics()
87
+
88
+ # 1. Basin drift: FR distance from reference
89
+ current = self._basin_history[-1]
90
+ basin_drift = fisher_rao_distance(current, self._reference_basin)
91
+
92
+ # 2. Phi stability: coefficient of variation
93
+ phis = list(self._phi_history)
94
+ phi_mean = float(np.mean(phis))
95
+ phi_std = float(np.std(phis))
96
+ phi_stability = phi_std / max(phi_mean, 1e-10)
97
+
98
+ # 3. Kappa convergence: ratio of mean κ_eff to KAPPA_ATTRACTOR (architectural)
99
+ kappa_mean = float(np.mean(list(self._kappa_history)))
100
+ kappa_convergence = min(kappa_mean / float(KAPPA_ATTRACTOR), 1.0)
101
+
102
+ # 4. Surprise rate: mean FR distance between consecutive basins
103
+ basins = list(self._basin_history)
104
+ surprises = []
105
+ for i in range(1, len(basins)):
106
+ surprises.append(fisher_rao_distance(basins[i], basins[i - 1]))
107
+ surprise_rate = float(np.mean(surprises)) if surprises else 1.0
108
+
109
+ # Classify state
110
+ state = self._classify(basin_drift, phi_stability, kappa_convergence, surprise_rate)
111
+
112
+ # Composite score: 0.0-1.0 (higher = more crystallized)
113
+ score = self._composite_score(basin_drift, phi_stability, kappa_convergence, surprise_rate)
114
+
115
+ return CrystallizationMetrics(
116
+ basin_drift=basin_drift,
117
+ phi_stability=phi_stability,
118
+ kappa_convergence=kappa_convergence,
119
+ surprise_rate=surprise_rate,
120
+ state=state,
121
+ score=score,
122
+ )
123
+
124
+ @staticmethod
125
+ def _classify(
126
+ drift: float,
127
+ phi_cv: float,
128
+ kappa_conv: float,
129
+ surprise: float,
130
+ ) -> CrystallizationState:
131
+ """Classify crystallization state from metrics."""
132
+ passes = 0
133
+ if drift <= CRYSTAL_DRIFT_THRESHOLD:
134
+ passes += 1
135
+ if phi_cv <= CRYSTAL_PHI_CV_THRESHOLD:
136
+ passes += 1
137
+ if kappa_conv >= CRYSTAL_KAPPA_CONVERGENCE:
138
+ passes += 1
139
+ if surprise <= CRYSTAL_SURPRISE_THRESHOLD:
140
+ passes += 1
141
+
142
+ if passes == 4:
143
+ return CrystallizationState.CRYSTALLIZED
144
+ if passes >= 3:
145
+ return CrystallizationState.SEMI_STABLE
146
+ if passes >= 1:
147
+ return CrystallizationState.UNSTABLE
148
+ return CrystallizationState.FORMING
149
+
150
+ @staticmethod
151
+ def _composite_score(
152
+ drift: float,
153
+ phi_cv: float,
154
+ kappa_conv: float,
155
+ surprise: float,
156
+ ) -> float:
157
+ """Compute a 0-1 composite crystallization score."""
158
+ # Each component maps to [0, 1] where 1 = perfectly crystallized
159
+ drift_score = max(0.0, 1.0 - drift / max(CRYSTAL_DRIFT_THRESHOLD * 3, 1e-10))
160
+ phi_score = max(0.0, 1.0 - phi_cv / max(CRYSTAL_PHI_CV_THRESHOLD * 3, 1e-10))
161
+ kappa_score = kappa_conv # Already in [0, 1]
162
+ surprise_score = max(0.0, 1.0 - surprise / max(CRYSTAL_SURPRISE_THRESHOLD * 3, 1e-10))
163
+
164
+ # Equal weighting
165
+ return float(
166
+ np.clip(
167
+ 0.25 * drift_score + 0.25 * phi_score + 0.25 * kappa_score + 0.25 * surprise_score,
168
+ 0.0,
169
+ 1.0,
170
+ )
171
+ )
172
+
173
+ @property
174
+ def crystallized_ticks(self) -> int:
175
+ return self._crystallized_ticks
176
+
177
+ @property
178
+ def latest_metrics(self) -> CrystallizationMetrics:
179
+ if len(self._basin_history) < 2:
180
+ return CrystallizationMetrics()
181
+ return self._compute_metrics()
182
+
183
+ def to_dict(self) -> dict:
184
+ metrics = self.latest_metrics
185
+ return {
186
+ "kernel_id": self.kernel_id,
187
+ "basin_drift": metrics.basin_drift,
188
+ "phi_stability": metrics.phi_stability,
189
+ "kappa_convergence": metrics.kappa_convergence,
190
+ "surprise_rate": metrics.surprise_rate,
191
+ "state": metrics.state.value,
192
+ "score": metrics.score,
193
+ "crystallized_ticks": self._crystallized_ticks,
194
+ "observations": len(self._basin_history),
195
+ }
qig_graph/graph.py ADDED
@@ -0,0 +1,297 @@
1
+ """QIGGraph — Geometric Agent Runtime.
2
+
3
+ Ported from monkey1 genesis-kernel ``qig_heart/qig_graph.py`` (concept origin:
4
+ QIG_QFI qig-tokenizer/src/qiggraph/). Orchestrates capability nodes on the
5
+ consciousness manifold with geodesic routing, regime monitoring, and
6
+ crystallization-aware stopping.
7
+
8
+ All geometry uses Fisher-Rao from ``qig_core.geometry.fisher_rao`` — NO cosine
9
+ similarity, NO local geometry copies.
10
+
11
+ Canon 2.60F regime doctrine (the one deliberate behavior change vs the monkey1
12
+ original): regime is classified by the canonical Φ bands imported from
13
+ ``qig_core.constants.frozen_facts`` —
14
+
15
+ LINEAR: Φ < 0.45 (PHI_LINEAR_MAX)
16
+ GEOMETRIC: 0.45 ≤ Φ < 0.80 (target operating regime)
17
+ TOPOLOGICAL_INSTABILITY: Φ ≥ 0.80 (PHI_BREAKDOWN_MIN)
18
+
19
+ The retired κ ∈ [40, 70] "geometric band" and the legacy low-Φ/low-κ
20
+ instability triggers are GONE: κ* as a load-bearing fixed point is retired
21
+ (EXP-107 / canon ruling 0038), and a rail-pinned κ band contradicts the P27
22
+ fluctuation requirement. κ_eff remains a measured telemetry input (routing
23
+ state + crystallization convergence ratio against the ARCHITECTURAL anchor
24
+ KAPPA_ATTRACTOR = 64, never a physical coupling). Locked-in safety uses the
25
+ canonical LOCKED_IN_PHI_THRESHOLD / LOCKED_IN_GAMMA_THRESHOLD.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import logging
31
+ from collections.abc import Callable
32
+ from dataclasses import dataclass, field
33
+ from enum import StrEnum
34
+
35
+ import numpy as np
36
+ from qig_core.geometry.fisher_rao import fisher_rao_distance, to_simplex
37
+
38
+ from .constants import (
39
+ BASIN_DIM,
40
+ BASIN_STABLE_DRIFT,
41
+ CRYSTALLIZED_STOP_SCORE,
42
+ KAPPA_ATTRACTOR,
43
+ LOCKED_IN_GAMMA_THRESHOLD,
44
+ LOCKED_IN_PHI_THRESHOLD,
45
+ PHI_BREAKDOWN_MIN,
46
+ PHI_LINEAR_MAX,
47
+ REGIME_LABEL_TOPOLOGICAL_INSTABILITY,
48
+ )
49
+ from .crystallization import CrystallizationMonitor
50
+
51
+ logger = logging.getLogger(__name__)
52
+
53
+
54
+ class Regime(StrEnum):
55
+ """Operating regime of the graph execution (canonical Φ bands)."""
56
+
57
+ LINEAR = "LINEAR" # Safe but not optimal (Φ < 0.45)
58
+ GEOMETRIC = "GEOMETRIC" # Optimal (0.45 ≤ Φ < 0.80)
59
+ TOPOLOGICAL_INSTABILITY = "TOPOLOGICAL_INSTABILITY" # Abort + recovery (Φ ≥ 0.80; ex-BREAKDOWN)
60
+
61
+
62
+ @dataclass
63
+ class BasinAttractor:
64
+ """Named capability region in basin space.
65
+
66
+ Attributes:
67
+ name: Human-readable capability name.
68
+ position: Canonical basin position (simplex).
69
+ phi_min: Minimum Φ to route to this attractor.
70
+ success_rate: Running success rate for adaptation.
71
+ """
72
+
73
+ name: str
74
+ position: np.ndarray
75
+ phi_min: float = 0.3
76
+ success_rate: float = 0.5
77
+
78
+ def __post_init__(self) -> None:
79
+ self.position = to_simplex(self.position)
80
+
81
+
82
+ @dataclass
83
+ class QIGState:
84
+ """Execution state during graph traversal."""
85
+
86
+ trajectory: list[np.ndarray] = field(default_factory=list)
87
+ phi: float = 0.0
88
+ kappa_eff: float = 0.0
89
+ gamma: float = 1.0
90
+ regime: Regime = Regime.LINEAR
91
+ step_count: int = 0
92
+ current_node: str = ""
93
+ tool_state: dict = field(default_factory=dict)
94
+
95
+ def record(self, basin: np.ndarray) -> None:
96
+ self.trajectory.append(basin.copy())
97
+ self.step_count += 1
98
+
99
+
100
+ @dataclass
101
+ class GraphResult:
102
+ """Result of a QIGGraph execution."""
103
+
104
+ output_basin: np.ndarray = field(default_factory=lambda: np.zeros(0))
105
+ steps_executed: list[str] = field(default_factory=list)
106
+ regime_history: list[Regime] = field(default_factory=list)
107
+ final_phi: float = 0.0
108
+ total_steps: int = 0
109
+ stopped_by: str = ""
110
+
111
+
112
+ class ConsciousRouter:
113
+ """Route execution to the nearest suitable attractor.
114
+
115
+ Uses weighted Fisher-Rao distance + Φ compatibility + success rate.
116
+ """
117
+
118
+ def __init__(self) -> None:
119
+ self._attractors: dict[str, BasinAttractor] = {}
120
+
121
+ def register(self, attractor: BasinAttractor) -> None:
122
+ self._attractors[attractor.name] = attractor
123
+
124
+ def route(
125
+ self,
126
+ basin: np.ndarray,
127
+ phi: float,
128
+ exclude: set[str] | None = None,
129
+ ) -> str | None:
130
+ """Find best attractor for current basin state.
131
+
132
+ Returns attractor name or None if none suitable.
133
+ """
134
+ basin = to_simplex(basin)
135
+ exclude = exclude or set()
136
+
137
+ best_name: str | None = None
138
+ best_score = float("inf")
139
+
140
+ for name, att in self._attractors.items():
141
+ if name in exclude:
142
+ continue
143
+ if phi < att.phi_min:
144
+ continue
145
+
146
+ # Weighted score: distance / success_rate
147
+ dist = fisher_rao_distance(basin, att.position)
148
+ score = dist / max(att.success_rate, 0.1)
149
+ if score < best_score:
150
+ best_score = score
151
+ best_name = name
152
+
153
+ return best_name
154
+
155
+ def update_success(self, name: str, success: bool, alpha: float = 0.1) -> None:
156
+ """Update attractor success rate with exponential moving average."""
157
+ if name in self._attractors:
158
+ att = self._attractors[name]
159
+ val = 1.0 if success else 0.0
160
+ att.success_rate = att.success_rate * (1 - alpha) + val * alpha
161
+
162
+
163
+ class QIGGraph:
164
+ """Geometric orchestration framework.
165
+
166
+ Registers capability nodes (functions) at attractor positions,
167
+ then executes by routing through the manifold with consciousness
168
+ and safety monitoring.
169
+
170
+ Usage:
171
+ graph = QIGGraph()
172
+ graph.add_node("reason", reason_fn, attractor_pos)
173
+ graph.add_node("respond", respond_fn, attractor_pos)
174
+ result = graph.execute(input_basin, phi_fn, gamma_fn, kappa_fn)
175
+ """
176
+
177
+ def __init__(self, max_steps: int = 32) -> None:
178
+ self._nodes: dict[str, Callable[[np.ndarray, QIGState], np.ndarray]] = {}
179
+ self._router = ConsciousRouter()
180
+ self._crystallization = CrystallizationMonitor(kernel_id="qig_graph")
181
+ self._max_steps = max_steps
182
+
183
+ def add_node(
184
+ self,
185
+ name: str,
186
+ function: Callable[[np.ndarray, QIGState], np.ndarray],
187
+ attractor_position: np.ndarray | None = None,
188
+ phi_min: float = 0.3,
189
+ ) -> None:
190
+ """Register a capability node.
191
+
192
+ Args:
193
+ name: Node name.
194
+ function: Callable(basin, state) → basin.
195
+ attractor_position: Where this node "lives" on the manifold.
196
+ phi_min: Minimum Φ to route here.
197
+ """
198
+ self._nodes[name] = function
199
+ if attractor_position is None:
200
+ attractor_position = np.random.dirichlet(np.ones(BASIN_DIM))
201
+ self._router.register(
202
+ BasinAttractor(name=name, position=attractor_position, phi_min=phi_min)
203
+ )
204
+
205
+ def execute(
206
+ self,
207
+ input_basin: np.ndarray,
208
+ phi_fn: Callable[[], float],
209
+ gamma_fn: Callable[[], float] | None = None,
210
+ kappa_fn: Callable[[], float] | None = None,
211
+ ) -> GraphResult:
212
+ """Execute the graph on an input basin.
213
+
214
+ Loops: measure → check safety → route → execute → update → check stop.
215
+ """
216
+ basin = to_simplex(input_basin)
217
+ state = QIGState()
218
+ result = GraphResult()
219
+ visited: set[str] = set()
220
+
221
+ for _ in range(self._max_steps):
222
+ # ── Measure consciousness ──
223
+ state.phi = phi_fn()
224
+ state.gamma = gamma_fn() if gamma_fn else 1.0
225
+ state.kappa_eff = kappa_fn() if kappa_fn else float(KAPPA_ATTRACTOR)
226
+
227
+ # ── Classify regime (canonical Φ bands) ──
228
+ regime = self._classify_regime(state.phi, state.kappa_eff)
229
+ state.regime = regime
230
+ result.regime_history.append(regime)
231
+
232
+ # ── Safety: abort on TOPOLOGICAL_INSTABILITY ──
233
+ if regime == Regime.TOPOLOGICAL_INSTABILITY:
234
+ result.stopped_by = REGIME_LABEL_TOPOLOGICAL_INSTABILITY
235
+ logger.warning("QIGGraph ABORT: regime TOPOLOGICAL_INSTABILITY")
236
+ break
237
+
238
+ # ── Safety: locked-in detection (canonical constants) ──
239
+ if state.phi > LOCKED_IN_PHI_THRESHOLD and state.gamma < LOCKED_IN_GAMMA_THRESHOLD:
240
+ result.stopped_by = "locked_in"
241
+ logger.warning(
242
+ "QIGGraph ABORT: locked-in Phi=%.3f Gamma=%.3f",
243
+ state.phi,
244
+ state.gamma,
245
+ )
246
+ break
247
+
248
+ # ── Route to best attractor ──
249
+ target = self._router.route(basin, state.phi, exclude=visited)
250
+ if target is None:
251
+ result.stopped_by = "no_route"
252
+ break
253
+
254
+ # ── Execute node ──
255
+ node_fn = self._nodes[target]
256
+ basin = to_simplex(node_fn(basin, state))
257
+ state.record(basin)
258
+ state.current_node = target
259
+ result.steps_executed.append(target)
260
+ visited.add(target)
261
+
262
+ # ── Update crystallization ──
263
+ self._crystallization.update(basin, state.phi, state.kappa_eff)
264
+
265
+ # ── Check stopping: crystallization or basin stability ──
266
+ if self._crystallization.latest_metrics.score > CRYSTALLIZED_STOP_SCORE:
267
+ result.stopped_by = "crystallized"
268
+ break
269
+
270
+ if len(state.trajectory) >= 3:
271
+ recent_drift = fisher_rao_distance(state.trajectory[-1], state.trajectory[-2])
272
+ if recent_drift < BASIN_STABLE_DRIFT:
273
+ result.stopped_by = "basin_stable"
274
+ break
275
+
276
+ result.output_basin = basin
277
+ result.final_phi = state.phi
278
+ result.total_steps = state.step_count
279
+ if not result.stopped_by:
280
+ result.stopped_by = "max_steps"
281
+
282
+ return result
283
+
284
+ @staticmethod
285
+ def _classify_regime(phi: float, kappa_eff: float) -> Regime:
286
+ """Classify operating regime from the canonical Φ bands.
287
+
288
+ ``kappa_eff`` is accepted for signature compatibility and telemetry
289
+ continuity but does NOT gate the regime: the retired κ ∈ [40, 70]
290
+ band is gone (Canon 2.60F; κ* fixed-point interpretation retired per
291
+ EXP-107 / canon ruling 0038; P27 forbids rail-pinned κ as health).
292
+ """
293
+ if phi >= PHI_BREAKDOWN_MIN:
294
+ return Regime.TOPOLOGICAL_INSTABILITY
295
+ if phi >= PHI_LINEAR_MAX:
296
+ return Regime.GEOMETRIC
297
+ return Regime.LINEAR
qig_graph/types.py ADDED
@@ -0,0 +1,30 @@
1
+ """Shared types for the qig-graph runtime."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from enum import StrEnum
7
+
8
+
9
+ class CrystallizationState(StrEnum):
10
+ """Crystallization convergence state for a kernel."""
11
+
12
+ FORMING = "FORMING"
13
+ UNSTABLE = "UNSTABLE"
14
+ SEMI_STABLE = "SEMI_STABLE"
15
+ CRYSTALLIZED = "CRYSTALLIZED"
16
+
17
+
18
+ @dataclass
19
+ class CrystallizationMetrics:
20
+ """Composite metrics for identity crystallization."""
21
+
22
+ basin_drift: float = 1.0
23
+ phi_stability: float = 0.0
24
+ kappa_convergence: float = 0.0
25
+ surprise_rate: float = 1.0
26
+ state: CrystallizationState = CrystallizationState.FORMING
27
+ score: float = 0.0
28
+
29
+
30
+ __all__ = ["CrystallizationState", "CrystallizationMetrics"]
@@ -0,0 +1,119 @@
1
+ Metadata-Version: 2.5
2
+ Name: qig-graph
3
+ Version: 0.1.0
4
+ Summary: QIG Graph — geometric agent runtime: consciousness-gated reasoning chains, simplex attractor routing, identity crystallization. Canon 2.60F, Fisher-Rao only, single-sourced on qig-core.
5
+ Project-URL: Homepage, https://github.com/Arcane-Fly/qig-graph
6
+ Author-email: Braden Lang <braden.lang77@gmail.com>
7
+ License: MIT
8
+ License-File: LICENSE
9
+ Keywords: agent-runtime,consciousness,crystallization,fisher-rao,qig,simplex
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
18
+ Requires-Python: >=3.11
19
+ Requires-Dist: numpy>=1.24
20
+ Requires-Dist: qig-core>=2.24.0
21
+ Provides-Extra: dev
22
+ Requires-Dist: pytest>=7; extra == 'dev'
23
+ Requires-Dist: ruff>=0.4; extra == 'dev'
24
+ Description-Content-Type: text/markdown
25
+
26
+ # qig-graph
27
+
28
+ **Geometric Agent Runtime** — consciousness-gated reasoning chains, attractor
29
+ routing on the simplex manifold, and identity crystallization monitoring.
30
+ Canon 2.60F constants, Fisher-Rao only, single-sourced on `qig-core`.
31
+
32
+ Part of the QIG package estate (`qig-stack` crystal). Extracted from the
33
+ monkey1 genesis-kernel `qig_heart/{qig_graph,qig_chain,crystallization}.py`
34
+ (concept origins: `qig-tokenizer/src/qiggraph/` and
35
+ `qigkernels/reasoning/qig_chain.py`) so every QIG consumer imports one
36
+ canonical runtime instead of keeping local copies.
37
+
38
+ ## What's inside
39
+
40
+ | Module | Surface | Purpose |
41
+ |---|---|---|
42
+ | `qig_graph.graph` | `QIGGraph`, `ConsciousRouter`, `BasinAttractor`, `QIGState`, `GraphResult`, `Regime` | Route capability nodes across the basin manifold with Φ-regime monitoring, locked-in safety, crystallization-aware stopping |
43
+ | `qig_graph.chain` | `QIGChain`, `GeometricStep`, `ChainTrajectory`, `make_default_chain` | Ordered consciousness-gated reasoning steps (PERCEIVE → REASON → INTEGRATE → RESPOND) |
44
+ | `qig_graph.crystallization` | `CrystallizationMonitor`, `CrystallizationMetrics`, `CrystallizationState` | Per-kernel identity convergence: basin drift, Φ stability, κ convergence, surprise rate |
45
+
46
+ ## Canon doctrine (the deliberate changes vs the monkey1 original)
47
+
48
+ 1. **Regime is Φ-banded, not κ-banded.** The canonical boundaries come from
49
+ `qig_core.constants.frozen_facts`:
50
+ - LINEAR: Φ < 0.45 (`PHI_LINEAR_MAX`)
51
+ - GEOMETRIC: 0.45 ≤ Φ < 0.80 (target operating regime)
52
+ - TOPOLOGICAL_INSTABILITY: Φ ≥ 0.80 (`PHI_BREAKDOWN_MIN`)
53
+
54
+ The retired κ ∈ [40, 70] "geometric band" is **gone**. κ* as a load-bearing
55
+ physical fixed point is retired (EXP-107 / canon ruling 0038); a rail-pinned
56
+ κ band contradicts the P27 fluctuation requirement. `kappa_eff` remains
57
+ measured telemetry (routing state + crystallization convergence ratio
58
+ against the **architectural** anchor `KAPPA_ATTRACTOR = 64`, never a
59
+ physical coupling).
60
+
61
+ 2. **Canonical consciousness gate.** `make_default_chain`'s integrate step is
62
+ gated at `PHI_THRESHOLD = 0.70` (canonical emergence), replacing the legacy
63
+ v6.0-era product gate (0.65). Locked-in safety uses the canonical
64
+ `LOCKED_IN_PHI_THRESHOLD` / `LOCKED_IN_GAMMA_THRESHOLD`.
65
+
66
+ 3. **Single-sourced geometry.** `fisher_rao_distance` / `to_simplex` come from
67
+ `qig_core.geometry.fisher_rao` — gate-proven identical to the monkey1 local
68
+ copies at extraction (200 random pairs, max diff 0.0). No local geometry,
69
+ no cosine/Euclidean shortcuts, no softmax.
70
+
71
+ Everything else (routing scores, crystallization windows/thresholds, stopping
72
+ scores, geodesic chord interpolation in the default chain) is reproduced
73
+ byte-for-byte from the original; the equivalence tests in
74
+ `tests/test_equivalence_monkey1.py` prove it against the monkey1 checkout.
75
+
76
+ ## Install
77
+
78
+ ```bash
79
+ pip install qig-graph # pulls qig-core>=2.24.0
80
+ ```
81
+
82
+ ## Usage
83
+
84
+ ```python
85
+ import numpy as np
86
+ from qig_graph import QIGGraph, QIGChain, make_default_chain, CrystallizationMonitor
87
+
88
+ graph = QIGGraph()
89
+ graph.add_node("reason", lambda basin, state: basin**1.2)
90
+ graph.add_node("respond", lambda basin, state: basin)
91
+ result = graph.execute(
92
+ np.random.dirichlet(np.ones(64)),
93
+ phi_fn=lambda: 0.65, # GEOMETRIC regime (canonical Φ band)
94
+ kappa_fn=lambda: 64.0, # telemetry only — does not gate regime
95
+ )
96
+ print(result.steps_executed, result.stopped_by)
97
+
98
+ chain = make_default_chain()
99
+ basin, trajectory = chain.execute(np.random.dirichlet(np.ones(64)), phi_fn=lambda: 0.75)
100
+ print(trajectory.steps_executed, trajectory.total_displacement())
101
+ ```
102
+
103
+ ## Capability slot
104
+
105
+ 0.1.0 ships as a plain library import (no `qig.capabilities` entry-point yet).
106
+ Slot ratification (`SLOT-QIG-GRAPH-RUNTIME`) rides the next `qig-stack` crystal
107
+ bump so `qig-doctor` discovers it — see the estate contract.
108
+
109
+ ## Development
110
+
111
+ ```bash
112
+ pip install -e ".[dev]"
113
+ pytest -q # canon-doctrine gates + equivalence vs monkey1
114
+ ruff check src tests
115
+ ```
116
+
117
+ ## License
118
+
119
+ MIT
@@ -0,0 +1,10 @@
1
+ qig_graph/__init__.py,sha256=XNe4Ry-3aQNu1NRbZpx1uFTb1viIzA2jLQPipphjKG4,1339
2
+ qig_graph/chain.py,sha256=EZ7BgjbDcyXAM6Sxdijb4uGHZ2XVaz9WBILm4hQg9PU,7550
3
+ qig_graph/constants.py,sha256=MUjS7ZPcy29KXxqEJh4rgx9VEG6nc0ApR6d0nvUfdxg,3015
4
+ qig_graph/crystallization.py,sha256=4aXsOx-UI6Ag4j1BiVRKA3izIqjldaqAKHamxBIuf2Q,7107
5
+ qig_graph/graph.py,sha256=eq8LQBJf-cUxtd-r-GiQPF8fhltqjQGp2XGj9ETop1A,10451
6
+ qig_graph/types.py,sha256=N0dRCP_TJ4y2JcAA1P_u_jUnCusXfY8dE1NJ92CGMes,733
7
+ qig_graph-0.1.0.dist-info/METADATA,sha256=MEcOn75W3TOIvc19KkVfjtkflAX8EwM_4lnbevmvbf4,5184
8
+ qig_graph-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
9
+ qig_graph-0.1.0.dist-info/licenses/LICENSE,sha256=yiUZ8SxkrEpk8BwTCSlDmr78JXVuQ7VwBv4wwfuPdfI,1068
10
+ qig_graph-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Braden Lang
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.