operon-langgraph-gates 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.
Files changed (33) hide show
  1. operon_langgraph_gates-0.1.0/.github/workflows/ci.yml +52 -0
  2. operon_langgraph_gates-0.1.0/.github/workflows/publish.yml +39 -0
  3. operon_langgraph_gates-0.1.0/.gitignore +35 -0
  4. operon_langgraph_gates-0.1.0/CHANGELOG.md +144 -0
  5. operon_langgraph_gates-0.1.0/LICENSE +21 -0
  6. operon_langgraph_gates-0.1.0/PKG-INFO +202 -0
  7. operon_langgraph_gates-0.1.0/README.md +167 -0
  8. operon_langgraph_gates-0.1.0/docs/paper-citations.md +155 -0
  9. operon_langgraph_gates-0.1.0/examples/01_stagnation_breaks_loop.ipynb +243 -0
  10. operon_langgraph_gates-0.1.0/examples/02_integrity_catches_drift.ipynb +269 -0
  11. operon_langgraph_gates-0.1.0/huggingface/space-stagnation-gate/.gitignore +6 -0
  12. operon_langgraph_gates-0.1.0/huggingface/space-stagnation-gate/README.md +21 -0
  13. operon_langgraph_gates-0.1.0/huggingface/space-stagnation-gate/app.py +324 -0
  14. operon_langgraph_gates-0.1.0/huggingface/space-stagnation-gate/requirements.txt +10 -0
  15. operon_langgraph_gates-0.1.0/huggingface/space-stagnation-gate/scenarios.py +120 -0
  16. operon_langgraph_gates-0.1.0/pyproject.toml +78 -0
  17. operon_langgraph_gates-0.1.0/scripts/build_examples.py +454 -0
  18. operon_langgraph_gates-0.1.0/src/operon_langgraph_gates/__init__.py +33 -0
  19. operon_langgraph_gates-0.1.0/src/operon_langgraph_gates/_common.py +79 -0
  20. operon_langgraph_gates-0.1.0/src/operon_langgraph_gates/embedders.py +65 -0
  21. operon_langgraph_gates-0.1.0/src/operon_langgraph_gates/integrity.py +229 -0
  22. operon_langgraph_gates-0.1.0/src/operon_langgraph_gates/py.typed +0 -0
  23. operon_langgraph_gates-0.1.0/src/operon_langgraph_gates/stagnation.py +337 -0
  24. operon_langgraph_gates-0.1.0/tests/__init__.py +0 -0
  25. operon_langgraph_gates-0.1.0/tests/integration/__init__.py +0 -0
  26. operon_langgraph_gates-0.1.0/tests/integration/test_loop_break.py +99 -0
  27. operon_langgraph_gates-0.1.0/tests/test_a2a_round_trip.py +101 -0
  28. operon_langgraph_gates-0.1.0/tests/test_build_examples.py +217 -0
  29. operon_langgraph_gates-0.1.0/tests/test_integrity_gate.py +130 -0
  30. operon_langgraph_gates-0.1.0/tests/test_ngram_embedder.py +68 -0
  31. operon_langgraph_gates-0.1.0/tests/test_public_api.py +39 -0
  32. operon_langgraph_gates-0.1.0/tests/test_space_scenarios.py +89 -0
  33. operon_langgraph_gates-0.1.0/tests/test_stagnation_gate.py +620 -0
@@ -0,0 +1,52 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ branches: [main]
8
+
9
+ jobs:
10
+ test:
11
+ runs-on: ubuntu-latest
12
+ strategy:
13
+ fail-fast: false
14
+ matrix:
15
+ python-version: ["3.11", "3.13"]
16
+
17
+ steps:
18
+ # Actions pinned to full commit SHAs (not mutable tags) so a
19
+ # supply-chain compromise of a moving ref cannot silently execute
20
+ # untrusted code in this workflow. Comments name the upgrade
21
+ # target used at pin time — refresh deliberately.
22
+ - uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5
23
+
24
+ - name: Set up Python ${{ matrix.python-version }}
25
+ uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6
26
+ with:
27
+ python-version: ${{ matrix.python-version }}
28
+ cache: pip
29
+
30
+ - name: Install dependencies
31
+ run: |
32
+ python -m pip install --upgrade pip
33
+ pip install -e ".[dev]"
34
+ pip install build
35
+
36
+ - name: Lint (ruff)
37
+ run: ruff check src tests
38
+
39
+ - name: Format check (ruff)
40
+ run: ruff format --check src tests
41
+
42
+ - name: Type check (mypy)
43
+ run: mypy src
44
+
45
+ - name: Test (pytest)
46
+ run: pytest -v
47
+
48
+ - name: Build package (wheel + sdist)
49
+ # Run the same build invocation the publish workflow uses, so
50
+ # packaging/metadata regressions surface on PRs rather than at
51
+ # release time.
52
+ run: python -m build
@@ -0,0 +1,39 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+
7
+ jobs:
8
+ publish:
9
+ runs-on: ubuntu-latest
10
+ permissions:
11
+ # Explicit ``permissions`` replaces the default GITHUB_TOKEN scopes
12
+ # wholesale, so we have to name every scope we need — ``id-token:
13
+ # write`` alone would break actions/checkout on any repo/org whose
14
+ # default scopes are restricted.
15
+ contents: read
16
+ id-token: write
17
+
18
+ steps:
19
+ # Actions pinned to full commit SHAs (not mutable tags) so a
20
+ # supply-chain compromise of a moving ref cannot publish a poisoned
21
+ # wheel to PyPI under this project's OIDC identity. Comments name
22
+ # the upgrade target used at pin time — refresh deliberately.
23
+ - uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5
24
+
25
+ - name: Set up Python
26
+ uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6
27
+ with:
28
+ python-version: "3.11"
29
+
30
+ - name: Install build dependencies
31
+ run: |
32
+ python -m pip install --upgrade pip
33
+ pip install build
34
+
35
+ - name: Build package
36
+ run: python -m build
37
+
38
+ - name: Publish to PyPI
39
+ uses: pypa/gh-action-pypi-publish@cef221092ed1bacb1cc03d23a2d87d1d172e277b # release/v1 (2025-11-17)
@@ -0,0 +1,35 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # Distribution / packaging
7
+ build/
8
+ dist/
9
+ *.egg-info/
10
+ *.egg
11
+
12
+ # Virtual environments
13
+ .venv/
14
+ venv/
15
+ env/
16
+
17
+ # Type checker caches
18
+ .mypy_cache/
19
+ .pyright/
20
+
21
+ # Test caches
22
+ .pytest_cache/
23
+ .ruff_cache/
24
+ .coverage
25
+ htmlcov/
26
+
27
+ # Editor
28
+ .vscode/
29
+ .idea/
30
+ *.swp
31
+ .DS_Store
32
+
33
+ # Local
34
+ *.log
35
+ .env
@@ -0,0 +1,144 @@
1
+ # Changelog
2
+
3
+ All notable changes to `operon-langgraph-gates` are documented in this file.
4
+
5
+ The format is based on [Keep a Changelog 1.1.0](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+ Pre-1.0.0 alpha releases follow [PEP 440](https://peps.python.org/pep-0440/).
8
+
9
+ ## [Unreleased]
10
+
11
+ _No changes since `0.1.0`._
12
+
13
+ ## [0.1.0] — 2026-04-30
14
+
15
+ **First stable release.** This release un-alphas the package: theorem-name
16
+ SSoT exposure (Wave 1), A2A round-trip enforcement and Public API
17
+ documentation (Wave 2), and version + classifier cutover (Wave 3) all
18
+ land here. The committed `0.1.x` public surface is documented in the
19
+ README "Public API" section; breaking changes from this point increment
20
+ to `0.2.0` per SemVer.
21
+
22
+ ### Added
23
+
24
+ - Public theorem-name constants `STAGNATION_THEOREM` and `INTEGRITY_THEOREM`
25
+ re-exported from the package root, so downstream consumers can key on
26
+ the emitted theorem names without hard-coding strings that drift if
27
+ `operon-ai` renames the underlying theorem.
28
+ - A2A round-trip test (`tests/test_a2a_round_trip.py`) promoting the
29
+ cross-repo binding with `operon-ai`'s certificate codec from
30
+ *informational* to *enforced*. The test drives both gates to emission,
31
+ encodes certificates via `certificate_to_a2a_part`, decodes via
32
+ `certificate_from_a2a_part`, and asserts that `Certificate.verify()`
33
+ returns the same result and that `parameters` are preserved exactly.
34
+ The `safe_certificate_from_a2a_part` graceful-degradation path is
35
+ also covered.
36
+ - README "Public API" section documenting the committed `0.1.x` surface
37
+ (classes, methods, theorem-name constants, version attributes) and
38
+ the explicitly-internal complement (underscore-prefixed names,
39
+ `EPHEMERAL_THREAD`, internal gate machinery). Includes the SemVer
40
+ stability commitment for `0.1.0` stable and beyond.
41
+ - `tests/test_public_api.py` — focused public-API surface tests:
42
+ theorem constants importable, listed in `__all__`, and equal to
43
+ the module-internal SSoT they re-export.
44
+
45
+ ### Changed
46
+
47
+ - **Version bump:** `0.1.0a2` → `0.1.0`. Development Status classifier
48
+ bumped from `3 - Alpha` to `4 - Beta` (conservative — alpha-1 was 13
49
+ days ago and there is no production user count yet, so Beta is the
50
+ honest level for the first stable release).
51
+ - `pyproject.toml` `operon-ai` dependency tightened from `>=0.36.1`
52
+ (no upper bound) to `>=0.36.1,<0.40`, matching the range the new
53
+ A2A round-trip test was authored against. Widening the pin requires
54
+ re-running the round-trip test against the new range.
55
+ - README "Install" line synced with `pyproject.toml`:
56
+ `operon-ai>=0.36.1,<0.40`, `langgraph>=1.0,<2.0`.
57
+ - README "Ecosystem note" section relabeled from "out of this repository"
58
+ to "A2A round-trip is enforced" and rewritten to document the binding.
59
+ Maintainer checklist item 3 updated accordingly: A2A is no longer
60
+ conditional on a future test, it's the current state.
61
+
62
+ ### Fixed
63
+
64
+ - Package docstring (`src/operon_langgraph_gates/__init__.py`) named the wrong
65
+ theorems for both gates: `behavioral_stability` instead of the windowed
66
+ variant emitted since `0.1.0a2`, and `state_integrity_verified` (a name
67
+ that has never existed elsewhere in the codebase) instead of
68
+ `langgraph_state_integrity`. Both corrected.
69
+ - `integrity.py` module docstring claimed Paper 5 proves preservation of
70
+ "the paper's `state_integrity_verified` theorem" — but no Operon paper
71
+ has a theorem with that name. Replaced with the honest claim that
72
+ Paper 5 §3 proves preservation of certificate-bearing morphisms in
73
+ general, and this module registers a distinct LangGraph-flavored
74
+ theorem (`langgraph_state_integrity`) that is structurally analogous
75
+ but not itself the subject of a preservation proof in the paper.
76
+ - HuggingFace Space app (`huggingface/space-stagnation-gate/app.py`) referenced
77
+ the pre-`0.1.0a2` theorem name `behavioral_stability` in its top-level
78
+ docstring. README maintainer-checklist item 4 had explicitly flagged this
79
+ as known drift; corrected to `behavioral_stability_windowed`.
80
+ - Example-rendering script (`scripts/build_examples.py`) had two prose blocks
81
+ describing emitted certificates as `behavioral_stability` rather than the
82
+ windowed name. Re-rendering example notebooks will pick up the fix.
83
+ - `stagnation.py` module docstring and one inline comment named
84
+ `behavioral_stability` where the windowed variant was meant; updated to
85
+ `behavioral_stability_windowed`. The intentional comparative reference
86
+ at `stagnation.py:278` ("distinct from the shared `behavioral_stability`")
87
+ is preserved as-is — it is naming the older theorem on purpose.
88
+
89
+ ## [0.1.0a2] — 2026-04-19
90
+
91
+ ### Changed
92
+
93
+ - **Breaking** for any consumer that keyed on the pre-alpha theorem name:
94
+ `StagnationGate` now emits certificates with theorem name
95
+ `behavioral_stability_windowed` rather than `behavioral_stability`.
96
+ The shared core verifier `behavioral_stability` is flat-mean-based;
97
+ the windowed variant is `max(per_window_severity_means) <=
98
+ stability_threshold`, which mirrors the gate's detection logic
99
+ exactly. Round-trip serialization through `Certificate.from_theorem`
100
+ resolves the correct verifier without the gate package needing to
101
+ bind to any upstream symbol beyond the public `Certificate` class.
102
+ - Cert semantics aligned with `operon-ai>=0.36.0` public API
103
+ (`resolve_verify_fn`, `_THEOREM_FN_PATHS`).
104
+ - Ephemeral-thread fallback (`__ephemeral__`) narrowed to fire only when
105
+ no `thread_id` can be extracted from the LangGraph config or runtime
106
+ at the wrapped node — explicitly internal, not public API.
107
+ - `EPHEMERAL_THREAD` constant marked internal (per Roborev #903).
108
+
109
+ ### Added
110
+
111
+ - "Theoretical basis" section in README citing the factor-graph SLAM
112
+ lineage (Kaess et al. 2012, Dellaert & Kaess 2017, Dellaert 2026 STAG)
113
+ with hard scope line against learned factors.
114
+ - Maintainer follow-up checklist keyed to stable symbols (not line
115
+ numbers), surviving ordinary refactors.
116
+ - CI hardening: workflow actions pinned to SHAs, `ruff format --check`
117
+ enforced on Python 3.11 / 3.13.
118
+
119
+ ## [0.1.0a1] — 2026-04-17
120
+
121
+ ### Added
122
+
123
+ - First public alpha. Two reliability primitives for LangGraph:
124
+ - `StagnationGate` — Bayesian stagnation detection on conditional
125
+ edges or node outputs. Per-thread state, async + class-callable
126
+ aware. Emits `behavioral_stability` certificates (renamed in
127
+ `0.1.0a2` — see above).
128
+ - `IntegrityGate` — runtime invariant check on wrapped node outputs.
129
+ First-violation-per-thread certificate emission with the
130
+ `(name, passed)` invariant-result vector. Detection-and-
131
+ certification only; does not repair state.
132
+ - Two example notebooks:
133
+ - `examples/01_stagnation_breaks_loop.ipynb`
134
+ - `examples/02_integrity_catches_drift.ipynb`
135
+ - HuggingFace Space deployed at
136
+ https://huggingface.co/spaces/coredipper/operon-stagnation-gate.
137
+ - Backed by Paper 4 §4.3 (96% real-embedding accuracy) and §4.1 (3/3
138
+ DNA-repair integrity benchmarks); cert preservation framework from
139
+ Paper 5 §3.
140
+
141
+ [Unreleased]: https://github.com/coredipper/operon-langgraph-gates/compare/v0.1.0...HEAD
142
+ [0.1.0]: https://github.com/coredipper/operon-langgraph-gates/releases/tag/v0.1.0
143
+ [0.1.0a2]: https://github.com/coredipper/operon-langgraph-gates/releases/tag/v0.1.0a2
144
+ [0.1.0a1]: https://github.com/coredipper/operon-langgraph-gates/releases/tag/v0.1.0a1
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bogdan Banu
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.
@@ -0,0 +1,202 @@
1
+ Metadata-Version: 2.4
2
+ Name: operon-langgraph-gates
3
+ Version: 0.1.0
4
+ Summary: Reliability primitives for LangGraph — certified stagnation and integrity gates, backed by the Operon categorical framework.
5
+ Project-URL: Homepage, https://github.com/coredipper/operon-langgraph-gates
6
+ Project-URL: Documentation, https://banu.be/operon/
7
+ Project-URL: Issues, https://github.com/coredipper/operon-langgraph-gates/issues
8
+ Project-URL: Paper 4, https://github.com/coredipper/operon/blob/main/article/paper4/main.pdf
9
+ Project-URL: Paper 5, https://github.com/coredipper/operon/blob/main/article/paper5/main.pdf
10
+ Author-email: Bogdan Banu <bogdan@banu.be>
11
+ License-Expression: MIT
12
+ License-File: LICENSE
13
+ Keywords: agents,certificates,integrity,langgraph,llm,reliability,stagnation
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.11
23
+ Requires-Dist: langgraph<2.0,>=1.0.0
24
+ Requires-Dist: operon-ai<0.40,>=0.36.1
25
+ Provides-Extra: dev
26
+ Requires-Dist: ipykernel>=6.0; extra == 'dev'
27
+ Requires-Dist: jupyter>=1.0; extra == 'dev'
28
+ Requires-Dist: mypy>=1.11; extra == 'dev'
29
+ Requires-Dist: nbconvert>=7.0; extra == 'dev'
30
+ Requires-Dist: nbformat>=5.0; extra == 'dev'
31
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
32
+ Requires-Dist: pytest>=8.0; extra == 'dev'
33
+ Requires-Dist: ruff>=0.6; extra == 'dev'
34
+ Description-Content-Type: text/markdown
35
+
36
+ # operon-langgraph-gates
37
+
38
+ > **In-graph** reliability gates for LangGraph — drop-in, cert-emitting.
39
+
40
+ [LangGraph issue #6731](https://github.com/langchain-ai/langgraph/issues/6731) — *"agent infinite-loops until recursion limit, burns tokens invisibly"* — was closed as **NOT_PLANNED**. LangChain's answer: *"use tool-call limits in middleware."*
41
+
42
+ This package ships that missing native gate, plus a second one for checkpointer-write integrity. Two primitives. No framework adoption. ~10-line diff on an existing `StateGraph`.
43
+
44
+ Both gates run **inside** the graph: they route conditional edges and can short-circuit the next step. This is a deliberate contrast to post-hoc observability tools — an observer tells you an agent looped after the fact; a gate stops the loop mid-run and emits a replayable certificate of what fired it.
45
+
46
+ **At a glance:**
47
+
48
+ - `StagnationGate` — Bayesian stagnation detection (Paper 4 §4.3, 0.960 on convergence / false-stagnation scenarios) with per-thread state, async + class-callable aware. [See it live.](https://huggingface.co/spaces/coredipper/operon-stagnation-gate)
49
+ - `IntegrityGate` — user-defined invariants checked on every wrapped node's output; violations emit a `langgraph_state_integrity` certificate with replayable evidence. Detection-and-certification only; does not repair state.
50
+
51
+ ## Install
52
+
53
+ ```bash
54
+ pip install operon-langgraph-gates
55
+ ```
56
+
57
+ Requires `operon-ai>=0.36.1,<0.40` and `langgraph>=1.0,<2.0`.
58
+
59
+ ## Quickstart
60
+
61
+ ### Break infinite loops (`StagnationGate`)
62
+
63
+ ```python
64
+ from langgraph.graph import StateGraph
65
+ from operon_langgraph_gates import StagnationGate
66
+
67
+ graph = StateGraph(State)
68
+ gate = StagnationGate(threshold=0.2, critical_duration=3)
69
+ graph.add_node("think", gate.wrap(think_fn))
70
+
71
+ # Or attach to a conditional edge (route loop-detected runs elsewhere)
72
+ graph.add_conditional_edges(
73
+ "think",
74
+ gate.edge(forward="answer", break_to="escalate"),
75
+ )
76
+
77
+ # All certificates the gate has emitted (across all threads)
78
+ certs = gate.certificates
79
+ # For thread-scoped views use gate.is_stagnant_for(thread_id_) /
80
+ # gate.integrals_for(thread_id_). The gate falls back to an internal
81
+ # ephemeral-thread id (__ephemeral__) whenever no thread_id can be
82
+ # extracted from the LangGraph config/runtime at the wrapped node
83
+ # (e.g. no config argument, or a config with no configurable.thread_id);
84
+ # this id is an implementation detail, not part of the public API.
85
+ ```
86
+
87
+ Backed by [Paper 4 §4.3](https://github.com/coredipper/operon/blob/main/article/paper4/main.pdf): convergence/false-stagnation accuracy **0.960** with real sentence embeddings (all-MiniLM-L6-v2, N = 300 trials). See [`docs/paper-citations.md`](./docs/paper-citations.md) for the full citation record, including the loop-detection caveat and a pointer to the archived benchmark data.
88
+
89
+ ### Catch state drift (`IntegrityGate`)
90
+
91
+ ```python
92
+ from langgraph.graph import StateGraph
93
+ from operon_langgraph_gates import IntegrityGate
94
+
95
+ gate = IntegrityGate(invariants=[has_required_user, budget_not_exceeded])
96
+
97
+ graph = StateGraph(State)
98
+ graph.add_node("tool_call", gate.wrap(tool_call_fn))
99
+
100
+ # Route runs that violated an invariant to a recovery node
101
+ graph.add_conditional_edges(
102
+ "tool_call",
103
+ gate.edge(forward="process", break_to="recover"),
104
+ )
105
+
106
+ # Certificates (one per thread, on first violation) are on the gate
107
+ certs = gate.certificates
108
+ ```
109
+
110
+ Backed by [Paper 4 §4, Table 3](https://github.com/coredipper/operon/blob/main/article/paper4/main.pdf): *in the paper's setup*, the FULL variant (with `DNARepair`) achieves 100% detection and 100% repair of injected state corruption, vs 0%/0% for RAW and GUARDED. **This package is detection-and-certification only — it does not repair state.** It reformulates the idea as a LangGraph-native invariant gate. [Paper 5 §3](https://github.com/coredipper/operon/blob/main/article/paper5/main.pdf) establishes the preservation-under-compilation framework that the gate's certificate follows. See [`docs/paper-citations.md`](./docs/paper-citations.md) for verbatim quotes and the honest caveat.
111
+
112
+ ## Theoretical basis
113
+
114
+ Both gates are a discrete-state port of the rolling-past reliability loop that has been standard in robotics state estimation since [Kaess et al. 2012](https://dspace.mit.edu/handle/1721.1/71582) (iSAM2) and is formalised in [Dellaert & Kaess 2017](https://www.cs.cmu.edu/~kaess/pub/Dellaert17fnt.pdf) (*Factor Graphs for Robot Perception*). A recent [GTSAM blog post](https://gtsam.org/2026/04/21/factor-graphs-and-world-models.html) frames that loop — **STAG**: Sense-Think-Act with Graphs — as a concrete structured instance of an energy-based world model.
115
+
116
+ ### Scope (normative for this package)
117
+
118
+ What this repository actually commits to under the factor-graph framing:
119
+
120
+ - **Binding**: `StagnationGate` replay equivalence — a `behavioral_stability_windowed` certificate emitted by the gate must verify identically offline when passed its own parameters. The emitted certificate parameters are in the **severity domain**, not the integral domain: `signal_values = tuple(1.0 - i for i in state.integrals[-critical_duration:])` and `threshold = 1.0 - detection_threshold` (see `src/operon_langgraph_gates/stagnation.py:266-269`), which keeps the replay predicate aligned with `operon_ai`'s shared `behavioral_stability_windowed` verifier semantics (`max(signal_values) ≤ threshold`).
121
+ - **Binding**: `IntegrityGate` frozen-result replay — a `langgraph_state_integrity` certificate's parameters are exactly `invariant_results: tuple[(str, bool), ...]` and `all_passed: False` (see `_make_certificate` in `src/operon_langgraph_gates/integrity.py`); replay must reproduce the same boolean vector. Node output is **not** captured in the certificate payload. Two notes on the `name` field in `(name, passed)`: (i) names are **descriptive labels only**, derived from `inv.__name__` at emit time; replay never resolves them back to live invariants, so lambdas (`<lambda>`) and duplicate names do not break replay correctness — they just collapse to lossy labels in logs and UIs. Treat them as descriptive, not as stable identifiers. (ii) exceptions raised inside an invariant are coerced to `False`, and neither the certificate nor the replay surfaces the offending state or the exception detail.
122
+ - **Binding**: A2A round-trip equivalence — under the pinned `operon-ai` range in `pyproject.toml` (`>=0.36.1,<0.40`), a certificate emitted by either gate must round-trip through `operon_ai.convergence.a2a_certificate.{certificate_to_a2a_part, certificate_from_a2a_part}` such that `Certificate.verify()` returns the same result and the parameter dict is preserved exactly. Enforced by `tests/test_a2a_round_trip.py`. Tightening the upper bound on the `operon-ai` pin requires re-running this test against the new range.
123
+ - **Non-binding**: no cross-agent inference or factor-graph joining is implemented in this package. Nothing below promises any behaviour beyond what is replayable from the emitted certificates.
124
+ - **Non-binding**: the factor-graph vocabulary is explanatory. Any analogy mapping in the next subsection can be re-tagged as *analogy only* without breaking any contract in this repository.
125
+
126
+ ### Mapping (explanatory, not normative)
127
+
128
+ - `StagnationGate` is the discrete-state analogue of a **past-graph fixed-lag smoother**. Concretely: on each turn, `EpiplexityMonitor.measure()` emits a scalar `epiplexic_integral` that is stored in `state.integrals`; the detector fires when the last `critical_duration` integrals fall below `detection_threshold` (`src/operon_langgraph_gates/stagnation.py:250-256`). At emission, that integral slice is converted to the severity domain via `1.0 - integral` and shipped in the certificate as `signal_values`, with the threshold also translated to `1.0 - detection_threshold` (`stagnation.py:266-269`). The offline replay predicate `max(signal_values) ≤ threshold` is therefore a translated, not raw, replay of the gate's decision — the translation is part of the replay contract and is required to match `operon_ai`'s shared `behavioral_stability_windowed` verifier semantics.
129
+ - `IntegrityGate` is a **dynamics-residual check**: user-defined invariants play the role of the dynamics model's consistency factors, and a violation at a wrapped node is a positive residual routed onto a conditional edge. The certificate is the replayable record of that residual — specifically the `(name, passed)` vector over invariants and the `all_passed` flag, as emitted by `_make_certificate`. Capturing the offending node output is a deliberate non-goal in the current schema (privacy/redaction would need a separate design); the cert fixes *which* invariants failed, not *what* triggered them.
130
+
131
+ ### Ecosystem note (A2A round-trip is enforced)
132
+
133
+ Operon's A2A certificate codec (in the [operon repo](https://github.com/coredipper/operon), `operon_ai/convergence/a2a_certificate.py`) transports certificates as `DataPart` payloads and handles graceful degradation for unknown theorems. Under the STAG framing that is a transport-layer analogy of factor joining along shared theorem variables, but the codec does *not* maintain an internal factor graph or perform joint inference.
134
+
135
+ The `Certificate` objects this package emits are guaranteed to round-trip through that codec under the pinned `operon-ai` range in `pyproject.toml` (`>=0.36.1,<0.40`). The guarantee is enforced by `tests/test_a2a_round_trip.py`, which drives both gates to emission, encodes their certificates via `certificate_to_a2a_part`, decodes via `certificate_from_a2a_part`, and asserts that `Certificate.verify()` returns the same result and that `parameters` are preserved exactly. The same test verifies that `safe_certificate_from_a2a_part` recovers the cert (not `None`) for both gate-emitted theorem names — i.e., the round-trip works even when the receiver opts into graceful-degradation mode.
136
+
137
+ This was previously informational; promoted to a binding claim in `0.1.0` per the maintainer checklist. If the upper bound on the `operon-ai` pin is widened, the round-trip test must be re-run against the new range before merging.
138
+
139
+ ### Follow-up checklist for maintainers
140
+
141
+ If the code changes, the bindings in *Scope (normative for this package)* above must be re-verified. Checklist items are keyed to stable symbols, not line numbers, so they survive ordinary refactors:
142
+
143
+ 1. `StagnationGate` — if *either* `_emit_certificate` (the integral-to-severity translation and emitted parameter names `signal_values`, `threshold`) *or* `_observe` (the detection predicate `integral < threshold`, the streak counting, and the `critical_duration` slice at emission) changes, update the *StagnationGate replay equivalence* scope entry and add or update an end-to-end test that exercises both the detection path and the replay predicate so detection changes cannot silently drift past the checklist.
144
+ 2. `IntegrityGate` — if `_make_certificate` (in `integrity.py`) changes the shape of `invariant_results` or `all_passed`, update the *IntegrityGate frozen-result replay* scope entry; and in the same change, update or add tests that cover: (a) label derivation from `inv.__name__` including the lambda / duplicate-name cases (treated as lossy labels, not identifiers); (b) exception-coerced-to-`False` behaviour; (c) serialization round-trip of `(name, passed)` pairs. If callers ever start round-tripping `name` back to a callable (e.g. an executable replay), introduce an explicit caller-supplied identifier and upgrade the binding before merging.
145
+ 3. A2A — the round-trip is binding under the current pinned `operon-ai` range (`>=0.36.1,<0.40`) and is enforced by `tests/test_a2a_round_trip.py`. If `certificate_to_a2a_part` / `certificate_from_a2a_part` change shape upstream, re-run the test against the new range; if the upper bound on the pin is widened, the test must be re-run against the new range before merging. If the `safe_certificate_from_a2a_part` graceful-degradation behaviour is removed upstream, the corresponding sub-test must be removed in lockstep with the pin update.
146
+ 4. Theorem-name changes are **repo-wide**, not README-only. If either `behavioral_stability_windowed` or `langgraph_state_integrity` is renamed in `operon-ai`, the following surfaces must all change in lockstep: this README (the quickstart text and the *Certificate theorem name and verification* section), `src/operon_langgraph_gates/__init__.py` and `stagnation.py` / `integrity.py` (emission sites), `scripts/build_examples.py` (currently references `langgraph_state_integrity` at 3 places), and `huggingface/space-stagnation-gate/app.py` (currently still references the pre-0.36 `behavioral_stability` name — known drift, fix when the theorem-rename PR next touches it). Prefer a single source of truth (e.g. a `_THEOREM` constant re-exported from the package) to prevent this list from growing.
147
+
148
+ ### Honest scope
149
+
150
+ This is a porting exercise, not new math. What is new is running the loop over symbolic LLM-agent state with a fixed verifier instead of gradient-based smoothing; see [paper 6 appendix §8](https://github.com/coredipper/operon/blob/main/article/paper6/sections/08-factor-graphs.tex) for the full term-by-term mapping, the worked example, and an explicit record of where the analogy stops. The scope-discipline rule inherited from the framing: **factors and topology are fixed; only the theorem set grows** — no learned factors, no horizon > 1 planning graphs.
151
+
152
+ ## Certificate theorem name and verification
153
+
154
+ `StagnationGate` emits certificates with theorem name `behavioral_stability_windowed` (not the core's shared `behavioral_stability`). The two differ in how they verify:
155
+
156
+ - `behavioral_stability` (shared core): `mean(severities) < threshold`. Loses the per-window structure rolling-integral detection operates on.
157
+ - `behavioral_stability_windowed` (shared core, since operon-ai 0.36.0): `max(per_window_severity_means) <= stability_threshold`. Mirrors detection exactly.
158
+
159
+ Both verifiers are registered in `operon_ai.core.certificate._THEOREM_FN_PATHS`, so deserialized certificates resolve through `_resolve_verify_fn` without this package needing to be imported. Any consumer with `operon-ai>=0.36.0` can round-trip a `behavioral_stability_windowed` certificate correctly.
160
+
161
+ ### Breaking change from pre-alpha prototypes
162
+
163
+ Earlier builds emitted certificates with theorem name `behavioral_stability`, bound to a locally-attached `_verify_fn`. That shape was semantically wrong — the shared verifier is flat-mean-based, so any cert round-tripped through serialization would silently revert to the wrong replay logic. Consumers that key on `certificate.theorem == "behavioral_stability"` must update to `"behavioral_stability_windowed"`. No migration path; alpha.
164
+
165
+ ## Try it — HuggingFace Space
166
+
167
+ [**Operon StagnationGate Demo**](https://huggingface.co/spaces/coredipper/operon-stagnation-gate) — interactive page: pick a preset (identical, diverse, noisy, slow drift), tune the gate parameters, watch `is_stagnant` flip and the certificate appear. Deterministic text trajectories — no LLM calls.
168
+
169
+ ## Examples
170
+
171
+ - [`examples/01_stagnation_breaks_loop.ipynb`](./examples/01_stagnation_breaks_loop.ipynb) — reproduces issue #6731 pathology, then fixes it with a ten-line diff.
172
+ - [`examples/02_integrity_catches_drift.ipynb`](./examples/02_integrity_catches_drift.ipynb) — a three-node graph silently corrupts state; `IntegrityGate` catches it with replayable evidence.
173
+
174
+ ## Public API
175
+
176
+ The committed surface for `0.1.x` is small and explicit:
177
+
178
+ - **Classes:** `StagnationGate`, `IntegrityGate`.
179
+ - **Methods on each gate:** `wrap(node_fn)`, `edge(forward, break_to)`, `certificates`, `reset()`. `StagnationGate` additionally exposes the global property `is_stagnant`, the per-thread methods `is_stagnant_for(thread_id)` and `integrals_for(thread_id)`. `IntegrityGate` exposes the global property `is_violated` and the per-thread method `is_violated_for(thread_id)`.
180
+ - **Theorem-name constants:** `STAGNATION_THEOREM` (`"behavioral_stability_windowed"`), `INTEGRITY_THEOREM` (`"langgraph_state_integrity"`). Use these instead of hard-coding strings; the underlying private constants `_THEOREM` / `_WINDOWED_THEOREM` are the SSoT and the public re-exports forward to them.
181
+ - **Module attributes:** `__version__`, `__all__`.
182
+
183
+ Anything underscore-prefixed is **internal** and may change without notice within `0.1.x`. Notable internals callers sometimes touch:
184
+
185
+ - `_THEOREM` / `_WINDOWED_THEOREM` — module-internal SSoT for theorem names; use `STAGNATION_THEOREM` / `INTEGRITY_THEOREM` instead.
186
+ - `EPHEMERAL_THREAD` (in `_common.py`) — the internal fallback thread-id used whenever no `thread_id` can be extracted from the LangGraph config or runtime at the wrapped node. Confirmed internal in `0.1.0a2` (Roborev #903); see `_common.py:thread_id()` for exact semantics.
187
+ - `_observe`, `_emit_certificate`, `_make_certificate`, `_thread_state` — internal gate machinery; touching these from a caller breaks the binding contract in *Scope (normative)*.
188
+
189
+ **Stability commitment:**
190
+
191
+ - `0.1.x` is an alpha series — **breaking changes are still possible**. Each will be documented in `CHANGELOG.md` and (for renamed theorem names) will go through a deprecation cycle wired through `operon-ai`'s theorem registry.
192
+ - The first non-breaking promise lands at `0.1.0` stable. Patches above that (`0.1.1`, `0.1.2`, ...) preserve the public surface above.
193
+ - Breaking changes thereafter increment to `0.2.0` per [SemVer](https://semver.org/).
194
+ - The cross-repo binding to `operon-ai`'s A2A codec is enforced by `tests/test_a2a_round_trip.py` against the pinned range in `pyproject.toml`; widening that pin requires re-running the test against the new range.
195
+
196
+ ## Status
197
+
198
+ **Beta — `0.1.0`.** First stable release. Public surface is documented in the section above; `0.1.x` patches preserve it, breaking changes increment to `0.2.0` per [SemVer](https://semver.org/). The cross-repo A2A binding is enforced under the pinned `operon-ai>=0.36.1,<0.40` range. Feedback welcome via Issues.
199
+
200
+ ## License
201
+
202
+ MIT — see [LICENSE](./LICENSE).