Metadata-Version: 2.4
Name: srbn
Version: 0.1.0
Summary: Stabilized Recursive Barrier Network: stability primitives for long-horizon LLM workflows
Project-URL: Homepage, https://codeberg.org/insanai/srbn-python
Project-URL: Documentation, https://codeberg.org/insanai/srbn-python#readme
Project-URL: Issues, https://codeberg.org/insanai/srbn-python/issues
Author: Vikrant Rathore, Ronak Rathore
License:                    GNU LESSER GENERAL PUBLIC LICENSE
                               Version 3, 29 June 2007
        
         Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
         Everyone is permitted to copy and distribute verbatim copies
         of this license document, but changing it is not allowed.
        
        
          This version of the GNU Lesser General Public License incorporates
        the terms and conditions of version 3 of the GNU General Public
        License, supplemented by the additional permissions listed below.
        
          0. Additional Definitions.
        
          As used herein, "this License" refers to version 3 of the GNU Lesser
        General Public License, and the "GNU GPL" refers to version 3 of the GNU
        General Public License.
        
          "The Library" refers to a covered work governed by this License,
        other than an Application or a Combined Work as defined below.
        
          An "Application" is any work that makes use of an interface provided
        by the Library, but which is not otherwise based on the Library.
        Defining a subclass of a class defined by the Library is deemed a mode
        of using an interface provided by the Library.
        
          A "Combined Work" is a work produced by combining or linking an
        Application with the Library.  The particular version of the Library
        with which the Combined Work was made is also called the "Linked
        Version".
        
          The "Minimal Corresponding Source" for a Combined Work means the
        Corresponding Source for the Combined Work, excluding any source code
        for portions of the Combined Work that, considered in isolation, are
        based on the Application, and not on the Linked Version.
        
          The "Corresponding Application Code" for a Combined Work means the
        object code and/or source code for the Application, including any data
        and utility programs needed for reproducing the Combined Work from the
        Application, but excluding the System Libraries of the Combined Work.
        
          1. Exception to Section 3 of the GNU GPL.
        
          You may convey a covered work under sections 3 and 4 of this License
        without being bound by section 3 of the GNU GPL.
        
          2. Conveying Modified Versions.
        
          If you modify a copy of the Library, and, in your modifications, a
        facility refers to a function or data to be supplied by an Application
        that uses the facility (other than as an argument passed when the
        facility is invoked), then you may convey a copy of the modified
        version:
        
           a) under this License, provided that you make a good faith effort to
           ensure that, in the event an Application does not supply the
           function or data, the facility still operates, and performs
           whatever part of its purpose remains meaningful, or
        
           b) under the GNU GPL, with none of the additional permissions of
           this License applicable to that copy.
        
          3. Object Code Incorporating Material from Library Header Files.
        
          The object code form of an Application may incorporate material from
        a header file that is part of the Library.  You may convey such object
        code under terms of your choice, provided that, if the incorporated
        material is not limited to numerical parameters, data structure
        layouts and accessors, or small macros, inline functions and templates
        (ten or fewer lines in length), you do both of the following:
        
           a) Give prominent notice with each copy of the object code that the
           Library is used in it and that the Library and its use are
           covered by this License.
        
           b) Accompany the object code with a copy of the GNU GPL and this license
           document.
        
          4. Combined Works.
        
          You may convey a Combined Work under terms of your choice that,
        taken together, effectively do not restrict modification of the
        portions of the Library contained in the Combined Work and reverse
        engineering for debugging such modifications, if you also do each of
        the following:
        
           a) Give prominent notice with each copy of the Combined Work that
           the Library is used in it and that the Library and its use are
           covered by this License.
        
           b) Accompany the Combined Work with a copy of the GNU GPL and this license
           document.
        
           c) For a Combined Work that displays copyright notices during
           execution, include the copyright notice for the Library among
           these notices, as well as a reference directing the user to the
           copies of the GNU GPL and this license document.
        
           d) Do one of the following:
        
               0) Convey the Minimal Corresponding Source under the terms of this
               License, and the Corresponding Application Code in a form
               suitable for, and under terms that permit, the user to
               recombine or relink the Application with a modified version of
               the Linked Version to produce a modified Combined Work, in the
               manner specified by section 6 of the GNU GPL for conveying
               Corresponding Source.
        
               1) Use a suitable shared library mechanism for linking with the
               Library.  A suitable mechanism is one that (a) uses at run time
               a copy of the Library already present on the user's computer
               system, and (b) will operate properly with a modified version
               of the Library that is interface-compatible with the Linked
               Version.
        
           e) Provide Installation Information, but only if you would otherwise
           be required to provide such information under section 6 of the
           GNU GPL, and only to the extent that such information is
           necessary to install and execute a modified version of the
           Combined Work produced by recombining or relinking the
           Application with a modified version of the Linked Version. (If
           you use option 4d0, the Installation Information must accompany
           the Minimal Corresponding Source and Corresponding Application
           Code. If you use option 4d1, you must provide the Installation
           Information in the manner specified by section 6 of the GNU GPL
           for conveying Corresponding Source.)
        
          5. Combined Libraries.
        
          You may place library facilities that are a work based on the
        Library side by side in a single library together with other library
        facilities that are not Applications and are not covered by this
        License, and convey such a combined library under terms of your
        choice, if you do both of the following:
        
           a) Accompany the combined library with a copy of the same work based
           on the Library, uncombined with any other library facilities,
           conveyed under the terms of this License.
        
           b) Give prominent notice with the combined library that part of it
           is a work based on the Library, and explaining where to find the
           accompanying uncombined form of the same work.
        
          6. Revised Versions of the GNU Lesser General Public License.
        
          The Free Software Foundation may publish revised and/or new versions
        of the GNU Lesser General Public License from time to time. Such new
        versions will be similar in spirit to the present version, but may
        differ in detail to address new problems or concerns.
        
          Each version is given a distinguishing version number. If the
        Library as you received it specifies that a certain numbered version
        of the GNU Lesser General Public License "or any later version"
        applies to it, you have the option of following the terms and
        conditions either of that published version or of any later version
        published by the Free Software Foundation. If the Library as you
        received it does not specify a version number of the GNU Lesser
        General Public License, you may choose any version of the GNU Lesser
        General Public License ever published by the Free Software Foundation.
        
          If the Library as you received it specifies that a proxy can decide
        whether future versions of the GNU Lesser General Public License shall
        apply, that proxy's public statement of acceptance of any version is
        permanent authorization for you to choose that version for the
        Library.
License-File: LICENSE
Keywords: agents,control,llm,srbn,stability
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries
Requires-Python: >=3.12
Description-Content-Type: text/markdown

# SRBN

> **Stabilized Recursive Barrier Networks** — a small, dependency-free Python
> library that turns flaky long-horizon LLM workflows into stable, observable
> control loops.

Authored by Vikrant Rathore and Ronak Rathore, authors of the paper
*Stability Is All You Need I: Lyapunov-Guided Hierarchies for Long-Horizon LLM
Reliability*. SRBN is the practical, black-box instantiation of the control loop
proved stable in that paper.

```python
import srbn

def generate(prompt: str, feedback: str | None) -> str:
    # Call your favourite LLM here. The library makes no assumptions.
    ...

result = srbn.run(
    "Draft a polite reply",
    generate=generate,
    checks=[srbn.contains("please"), srbn.min_length(20)],
)

print(result.ok, result.output, result.num_attempts)
```

That's the whole interface. No agents, no orchestrators, no hidden state.

---

## Install

```bash
pip install srbn
# or, with uv:
uv add srbn
```

Python 3.12+. The core has **zero runtime dependencies**.

## The idea in one picture

An LLM left to its own devices *drifts*: small errors correlate and compound
over a long task until the output leaves the set of valid states. SRBN treats
generation not as "sampling text" but as **steering a dynamical system** back
onto a *safe manifold* — the set of outputs that satisfy your barriers (checks).

Each attempt measures how far the current output is from valid, turns that
distance into actionable *feedback*, and feeds it back into the next generation.
The loop stops when the output is provably inside tolerance, when it stops
improving, or when the attempt budget is spent.

## Mathematical foundation

SRBN is the engineering reduction of a control-theoretic result. The notation
below is rendered as Unicode so it displays identically on Codeberg and on
PyPI (neither relies on a math renderer).

**1. Sheaf consistency → a Lyapunov energy.** A long-horizon task is a hierarchy
of sub-tasks (a DAG). A global state is *valid* when every parent task `U` and
child task `V` agree under a restriction map `ρ_VU` (the high-level plan and the
low-level output must be consistent). The total disagreement is summarized by a
single non-negative **energy function**:

```
V(x) = Σ_{U,V}  ‖ ρ_VU(x_U) − x_V ‖²        (Lyapunov energy; V(x) = 0 ⇔ valid)
```

In this library, `V(x)` is exactly the **instability score** returned on every
attempt (`attempt.score`): the aggregate residual of your barriers. `score = 0`
means the state sits on the safe manifold `M_safe = { x : V(x) = 0 }`.

**2. The control law.** Rather than re-sampling blindly, SRBN applies a
correction in the descent direction of the energy — gradient flow on `V`:

```
v(x) = −α ∇V(x)          ẋ = f(x) + v(x)
```

`f(x)` is the agent's reasoning *drift*; `v(x)` is the barrier's *correction*.
In the open-weight setting `v(x)` is a steering vector added to the residual
stream; in the black-box setting it is projected to a **feedback prompt** — a
lossy but effective approximation. This library implements the black-box case:
`attempt.feedback` is the discrete stand-in for `v(x)`.

**3. The stability guarantee.** Under the paper's assumptions — the barrier is
stronger than the drift (`β < α`), the energy is well-conditioned
(Polyak–Łojasiewicz constant `μ > 0`), and the safe set is reached without
overshoot — the error energy **decays exponentially** toward zero:

```
continuous time:   V(x(t)) ≤ V(x₀) · e^(−λ t),         λ = 2μ(α − β) > 0
discrete steps:    V(x_k)  ≤ (1 − 2η c μ)^k · V(x₀),    0 < step η < η_max
```

Real LLMs have *persistent* noise `δ` (confident hallucination), so convergence
is not to exactly zero but to a bounded floor whose size topology suppresses:

```
limsup_{t→∞} V(x(t)) ≤ δ² / ( 2 (α − β)² μ )           (error floor)
```

**4. What the library enforces.** SRBN does not have model gradients, so it
enforces the *discrete* analogue of the descent condition `V̇ < 0` directly: with
`Policy(require_descent=True, min_descent=δ)` the loop demands that the score
strictly decrease between attempts and aborts early when it stalls — a practical
guard that the system is actually descending the energy, not thrashing.

| Paper | Library |
|:------|:--------|
| Lyapunov energy `V(x)` | `attempt.score` (`0.0` = stable) |
| Safe manifold `M_safe = {V = 0}` | every check passes within `score_tolerance` |
| Correction flow `v(x) = −α∇V(x)` | `attempt.feedback` fed into the next `generate` |
| Descent condition `V̇ < 0` | `Policy(require_descent=True, min_descent=…)` |
| Attempt budget / step bound | `Policy(max_attempts=…)` |

See *Stability Is All You Need I* for the assumptions, proofs (Theorems 5.1,
5.2, 12.1), and the TLA+ safety model.

## 30-second tour

```python
import srbn

result = srbn.run(
    "Write a SQL query for active users",
    generate=my_llm,
    checks=[srbn.contains("SELECT"), srbn.not_contains("DROP")],
    policy=srbn.Policy(max_attempts=4),
)

for attempt in result.trace:
    print(attempt.index, attempt.ok, attempt.score, attempt.feedback)
```

## API at a glance

| Symbol | What it is |
|:-------|:-----------|
| `srbn.run(prompt, *, generate, checks, policy=None)` | One-call stabilization. |
| `srbn.stabilize(initial_state, *, barrier, update, policy=None)` | Generic SRBN barrier loop over arbitrary state. |
| `srbn.Client(generate, checks=(), policy=Policy())` | Reusable session. |
| `srbn.Policy(...)` | Control parameters (`max_attempts`, `score_tolerance`, `require_descent`, `min_descent`). |
| `srbn.contains`, `not_contains`, `matches`, `min_length`, `max_length`, `json_valid`, `predicate` | Built-in checks (barriers). |
| `srbn.all_of`, `srbn.any_of` | Compose checks. |

The full public surface is curated in
[`src/srbn/__init__.py`](https://codeberg.org/insanai/srbn-python/src/branch/main/src/srbn/__init__.py).

## Examples and benchmarks

Runnable [examples](https://codeberg.org/insanai/srbn-python/src/branch/main/examples)
cover the quickstart, descent policies, check plugins, and structured barrier
plugins — none require API keys. Deterministic control-behaviour
[benchmarks](https://codeberg.org/insanai/srbn-python/src/branch/main/benchmarks):

```bash
python -m benchmarks.srbn_benchmark --tasks 50 --max-attempts 6
```

## Development

```bash
uv sync
uv run pytest tests
uv run ruff check .
```

## License

GNU Lesser General Public License v3.0 only (**LGPL-3.0-only**).
© Vikrant Rathore, Ronak Rathore. See
[`LICENSE`](https://codeberg.org/insanai/srbn-python/src/branch/main/LICENSE).

As an LGPL library, SRBN can be imported by software under any license; changes
to SRBN's own source must be shared under the LGPL.

## Citing

If you use SRBN in research, please cite:

```bibtex
@article{rathore2025stability,
  title   = {Stability Is All You Need I: Lyapunov-Guided Hierarchies
             for Long-Horizon LLM Reliability},
  author  = {Rathore, Vikrant and Rathore, Ronak},
  year    = {2025}
}
```
