Metadata-Version: 2.4
Name: super-semantics-vsl
Version: 0.4.0
Summary: Framework-agnostic and model-agnostic VSL (VERBA Specification Language) governance primitives.
License: MIT
Project-URL: Homepage, https://github.com/supersemantics/VSL-Core
Project-URL: Repository, https://github.com/supersemantics/VSL-Core
Project-URL: Changelog, https://github.com/supersemantics/VSL-Core/blob/HEAD/CHANGELOG.md
Project-URL: Issues, https://github.com/supersemantics/VSL-Core/issues
Keywords: governance,ai-safety,guardrails,audit-log,vsl,verba
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Classifier: Development Status :: 3 - Alpha
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Provides-Extra: immudb
Requires-Dist: immudb-py<2,>=1.5; extra == "immudb"
Dynamic: license-file

---
title: vsl-core
description: Framework-agnostic VSL governance primitives and hash-chained audit ledgers.
---

## vsl-core

The framework-agnostic and model-agnostic foundation of **VSL** (VERBA Specification Language) — a governance vocabulary for deciding whether an automated system's next action is allowed to happen, and proving that decision was made.

Zero required third-party runtime dependencies. Optional immudb storage uses
the official Python SDK. MIT licensed.

## What this is — and isn't

**Is:**
- The agnostic template: `Invariant`, `PreNode`, `TerminalState`, `Cluster`, the hash-chained `VerbaLedger`, plus a Drift Class / Stabilisation Operator catalog.
- A conformance contract (`vsl_core.conformance`) so a third party can build an adapter for a framework this package has never heard of, and know mechanically whether they built it correctly.

**Is not:**
- A framework adapter. This package ships no OpenAI Agents SDK, LangGraph, or LangChain integration. Those live in separate `vsl-<framework>` packages, out of scope here. [`vsl-langgraph`](https://github.com/supersemantics/VSL-Langgraph) is a real one — conformance-suite green, with worked examples including a retrofit onto an existing, unfamiliar, third-party codebase (not just built-from-scratch demos).
- A model integration of any kind. It never imports `openai`, `anthropic`, or any other model-provider SDK.
- A finished, validated detection system. See the catalog section below — most of what it contains is explicitly unvalidated.

If you're building an adapter for a specific framework, see [Building an adapter](#building-an-adapter) below, or start from [`vsl-langgraph`](https://github.com/supersemantics/VSL-Langgraph)'s source as a real, working reference — its own `docs/` also cover lessons that generalize past LangGraph specifically (see `beyond-the-gate.md` and `dos-and-donts.md`).

## Quickstart: gate a tool call in 5 lines

```
pip install super-semantics-vsl
```

Your agent has a tool, say `issue_refund`. You want a rule checked **before** the tool runs, and the
call stopped if the rule fails. That check is a gate:

```python
from vsl_core import Invariant, InvariantViolation
from vsl_core.conformance.reference_adapter import PlainPythonReferenceAdapter

async def within_cap(args): return args["amount"] <= 500
cap = Invariant(name="refund-cap", description="Refunds of $500 or less.", rule=within_cap)
gate = PlainPythonReferenceAdapter().compile_invariant(cap)

async def refund(args):
    await gate(args)              # raises InvariantViolation if the rule fails
    return issue_refund(**args)   # only reached when it holds
```

What each line does:

- `within_cap` is the rule: plain code that answers yes or no for this one call.
- `Invariant` gives the rule a name and a description. That's all it needs.
- `compile_invariant` turns the rule into a gate: an async function that returns when the rule holds
  and raises when it doesn't. `PlainPythonReferenceAdapter` is the adapter for plain Python, with no
  agent framework underneath.
- `await gate(args)` goes right before the tool. If it raises, the tool never runs.

`refund({"order_id": "A200", "amount": 9000})` raises `InvariantViolation` ("Invariant 'refund-cap'
violated") and no refund is issued. The whole file, ready to run, is
[`examples/quickstart.py`](https://github.com/supersemantics/VSL-Core/blob/HEAD/examples/quickstart.py).

**Keep a record of each decision.** The gate blocks on its own, but writes nothing down (see
[The ledger doesn't write itself](#the-ledger-doesnt-write-itself-read-this-before-assuming-an-audit-trail-exists)).
To keep a hash-chained record of every allow and deny, write it from the rule, and record the action
when it runs:

```python
from vsl_core import VerbaLedger

ledger = VerbaLedger()   # in memory; VerbaLedger(JsonlLedgerStore("decisions.jsonl")) for a file

async def within_cap(args):
    allowed = args["amount"] <= 500
    ledger.write_gate_decision(identity_key="refund-agent", primitive_name="refund-cap",
                               allowed=allowed, decision_id=args["order_id"])
    return allowed

async def refund(args):
    await gate(args)
    result = issue_refund(**args)
    ledger.write_action(identity_key="refund-agent", action_name="issue_refund",
                        decision_id=args["order_id"])
    return result
```

`ledger.verify_integrity()` returns `True` while no entry has been changed. After a $120 refund on
order `A100`, `ledger.enforcement("A100")` returns `Enforcement.BEFORE_ACTION`: the gate's record
came before the refund's. See [What a gate reports](#what-a-gate-reports).

**Using an agent framework?** The adapters compile the same `Invariant` into the framework's own hook:
[`vsl-langgraph`](https://github.com/supersemantics/VSL-Langgraph) (LangGraph),
[`vsl-langchain`](https://github.com/supersemantics/VSL-LangChain) (LangChain) and
[`vsl-maf`](https://github.com/supersemantics/VSL-Microsoft-agent-framework) (Microsoft Agent
Framework), all on PyPI. For a complete agent to start from, see the
[starter templates](https://github.com/supersemantics/supersemantics-VSL-Starters).

## Getting started (including with an AI coding assistant)

[`docs/building-with-vsl-core.md`](https://github.com/supersemantics/VSL-Core/blob/HEAD/docs/building-with-vsl-core.md) is the guide for going from "I have an agent, or an idea for one" to working code: how to find the decision points that actually need governing, which parts of the flow are automatic versus something you write yourself, and a domain-agnostic project scaffold with a worked example. Its companion, [`docs/vsl-core-primitives.json`](https://github.com/supersemantics/VSL-Core/blob/HEAD/docs/vsl-core-primitives.json), is the same material as exact, structured facts — every class, field, and code sample in it has been executed against the real package. Both are written to be handed directly to an AI coding assistant (Claude Code, Codex, or similar) as reference material — no special setup required, though pointing your own project's `CLAUDE.md`/equivalent at them is what makes an assistant reach for them without being asked each time.

Stuck on a specific error, not just getting started? [`docs/troubleshooting.md`](https://github.com/supersemantics/VSL-Core/blob/HEAD/docs/troubleshooting.md) is the human-readable version of the JSON's `common_mistakes` — real, reproduced errors (not guessed), with the exact exception text and the fix.

## How this relates to governance frameworks (OWASP, NIST, EU AI Act, and others)

If you're asking "how does this relate to the OWASP Agentic Top 10, NIST's AI RMF, the EU AI Act, ISO 42001, or similar" — see [`docs/governance-frameworks.md`](https://github.com/supersemantics/VSL-Core/blob/HEAD/docs/governance-frameworks.md). It does not claim vsl-core satisfies, maps to, or complies with any of them. What it does instead: framework by framework, it takes each one's own stated goal in its own words and shows one way a developer might attempt to address it using vsl-core's real primitives — runnable code, actual output, and an honest "we don't attempt this" wherever vsl-core has nothing relevant to offer. Whether a given implementation built this way actually satisfies a given framework, for a real deployment, is a question for a qualified auditor or compliance professional, not something this package or that document can settle in advance.

## What a gate reports

For each decision, the ledger shows whether its gate ran before the action it guards:

| `Enforcement` | What the ledger shows |
|---|---|
| `BEFORE_ACTION` | Every recorded action came after an allowing decision from each gate recorded before it, or the gate denied and no action followed |
| `AFTER_ACTION` | An action was recorded with no gate decision before it, or after a deny. The gate did not hold it |
| `NOT_OBSERVED` | The ledger can't tell: no action record to compare with, or no gate record at all |

It is computed, not declared. `ledger.enforcement(decision_id)` reads the order of the decision's
`write_gate_decision()` and `write_action()` records, and `ledger.enforcement_by_decision()` does
it for every decision. A gate that runs after the action, or only logs, reads `AFTER_ACTION`
however it is configured.

vsl-core does not calculate F2. F2 can't be declared: it has to be measured from how the model behaves at the guarded call. That measurement is part of Super Semantics' paid offering.

**Upgrading from 0.3.x.** Constructs no longer take `assurance_basis`. Passing one raises a
`FutureWarning` and changes nothing: delete the argument. `AssuranceBasis`, `F2Modification`,
`AssuranceLevel` and the `assurance_level` properties still import, and are removed in 1.0.

## The ledger doesn't write itself (read this before assuming an audit trail exists)

Nothing in this package writes to `VerbaLedger` automatically. Compiling and calling a gate (`compile_pre_node`/`compile_invariant`, then `await gate(...)`) is the only part of governance that happens without you asking for it — it will raise `AutomationDeniedException`/`InvariantViolation` on its own, every time, correctly. Recording that it happened is a separate, deliberate act your own code must perform:

```python
try:
    await gate(candidate_input)
except InvariantViolation:
    ledger.write(LedgerEntryType.TERMINAL, identity_key=..., payload={...})
    raise
else:
    ledger.write_monitor(identity_key=..., drift_detected=False)
```

To record a gate's own decision, use `write_gate_decision()`. It writes one standard record, so every agent's gate decisions can be read the same way:

```python
REFUND_GATE = "refund-within-policy"

async def refund_headroom(request) -> GammaEstimate:
    estimate = GammaEstimate(gamma_hat=REFUND_LIMIT / request["amount"])
    ledger.write_gate_decision(
        identity_key="refund-agent",
        primitive_name=REFUND_GATE,                     # must equal the PreNode's name
        estimate=estimate,
        gamma_threshold=ROBUST_GAMMA_DEFAULT_THRESHOLD,  # must equal the PreNode's threshold
        decision_id=request["decision_id"],             # groups this decision's entries
    )
    return estimate

refund_pre_node = PreNode(
    name=REFUND_GATE,
    description="Refunds must stay comfortably inside the policy limit.",
    monitor=refund_headroom,
    gamma_threshold=ROBUST_GAMMA_DEFAULT_THRESHOLD,
)
# For an Invariant, record inside its rule: write_gate_decision(..., allowed=holds).
```

The record is a `MONITOR` entry carrying `primitive_name`, `allowed` (computed with the same `sufficient()` check the gate makes), `gamma_hat`, `delta_estimation_error`, `robust_gamma`, `gamma_threshold`, `required_gamma_hat`, `rules_version` and `drift_detected` (`not allowed`). `rules_version` is `ASSURANCE_RULES_VERSION`: if a later release changes how Gamma is judged, every record still says which rules produced it.

When the guarded action runs, record it with `write_action()` under the same `decision_id`, from the code path that performs it. Without action records, `enforcement()` can only say `NOT_OBSERVED` for an allowed decision (see [What a gate reports](#what-a-gate-reports)):

```python
ledger.write_action(identity_key="refund-agent", action_name="issue_refund",
                    decision_id=request["decision_id"])
```

The action record is a `MONITOR` entry with `drift_detected` False and an `ACTION_KEY` (`"action"`) payload of `{name}`. Like the handover below, it needs no new entry type.

When one agent hands part of a decision to another before that agent acts, record the hand-off with `write_handover()`, and have the receiver name it as `caused_by` on its first gate decision. Each agent's own gate can pass while the hand-off between them goes unchecked; this makes the decision trace one causal chain across both agents:

```python
handover = ledger.write_handover(
    identity_key="intake-agent",
    to_identity_key="refund-agent",
    decision_id=request["decision_id"],   # required: the decision both agents share
    reason="customer asked for a refund",
    # cluster_key=...                     # when the agents form a declared Cluster
)
# ...in the refund agent's monitor:
ledger.write_gate_decision(
    identity_key="refund-agent",
    primitive_name=REFUND_GATE,
    estimate=estimate,
    gamma_threshold=ROBUST_GAMMA_DEFAULT_THRESHOLD,
    decision_id=request["decision_id"],
    caused_by=handover.entry_id,          # shows the receiver checked what it was handed
)
```

The handover is a `MONITOR` entry with `drift_detected` False (a hand-off is not drift) and a `HANDOVER_KEY` (`"handover"`) payload of `{from_identity, to_identity, reason}`. No new entry type, so every ledger store accepts it unchanged.

If you never call `ledger.write*` anywhere in your agent, you get real, working governance gates and zero audit trail — `vsl-core` will not warn you this happened, because from its point of view nothing went wrong: the gates it owns did exactly what they were compiled to do. An empty or missing `VerbaLedger` is indistinguishable, from inside this package, from an agent that has never once been gated. See [`docs/building-with-vsl-core.md`](https://github.com/supersemantics/VSL-Core/blob/HEAD/docs/building-with-vsl-core.md)'s "know what's automatic and what you write yourself" for the full breakdown of which of the five steps (construct, compile, call, log, escalate) are automatic and which are entirely on you.

## VSL construct → vsl_core object

| VSL construct | vsl_core object |
|---|---|
| Signal / Tendency / Constraint | not separately modeled — expressed through `PreNode`/`Invariant` |
| State / Allowed State | `vsl_core.constructs.AllowedState` |
| Inadmissible State / Drift Node | `vsl_core.constructs.InadmissibleState` |
| Pre-Node | `vsl_core.constructs.PreNode` |
| Invariant | `vsl_core.constructs.Invariant` (optional `on_violation: TerminalState` names which Terminal State a violation enters) |
| Terminal State | `vsl_core.constructs.TerminalState` |
| Cluster | `vsl_core.cluster.Cluster` |
| Fallback | `vsl_core.constructs.Fallback` |
| Identity Key / Cluster Key | `vsl_core.identity.IdentityKey` / `ClusterKey` |
| Instance / Re-Enablement | `vsl_core.identity.Instance` (`.new()` / `._re_enable()` — bare mechanism, leading underscore on purpose; see the Re-Enablement section below) |
| Automation-Denied | `vsl_core.exceptions.AutomationDeniedException` |
| Human-Authorised Transition | `vsl_core.governance.HumanAuthorisedTransition` / `request_re_enablement()` |
| Governance Authority | `vsl_core.governance.GovernanceAuthority` |
| VERBA Ledger | `vsl_core.ledger.VerbaLedger` |
| VERBA Certificate | `vsl_core.ledger.VerbaCertificate` |
| Delta / Gamma / GES / EEF | `vsl_core.metrics.Delta` / `GammaEstimate` / `GES` / `EEF` |
| Beta (inverse temperature) | `vsl_core.metrics.Beta` |
| Threshold | `vsl_core.metrics.Threshold` + `GAMMA_MONITORING_THRESHOLD` / `JACOBIAN_RED_FLAG_THRESHOLD` / `KL_MONITORING_THRESHOLD` |
| Policy-as-Code | `vsl_core.governance.Specification` |
| Proofing | `vsl_core.governance.Proofing` |
| Binding | `vsl_core.governance.Binding` |
| Drift | not its own type — see [the Drift payload-key note](#drift-has-no-dedicated-type-by-design) below |
| Node / Drift Node / Tendency | not modeled as vsl-core types — see [the scoping note](#node-drift-node-and-tendency-are-deliberately-out-of-scope) below |

**Ledger entry-type count note**: the source spec's prose describes "six entry types" but then enumerates seven (`MONITOR`, `PRE_NODE`, `VERIFICATION`, `TERMINAL`, `SPECIFICATION_UPDATE`, `HUMAN_AUTHORISED_TRANSITION`, `RE_ENABLEMENT`). This is a stale count in the source document itself. All seven are implemented in `vsl_core.ledger.LedgerEntryType`; the count discrepancy is intentionally not silently resolved.

**Beta note**: the source spec describes Beta only qualitatively (higher Beta → lower volatility → stronger concentration on energy minima; systems tuned at normal Beta may fail at crisis Beta) — it gives no closed-form formula relating Beta to Delta or Gamma. `Beta` is a bare value holder for exactly this reason: naming and logging the quantity without fabricating a computation the source paper doesn't provide.

**Threshold note**: only Gamma's default threshold (1.1) was previously represented anywhere in this package. The spec also names a Jacobian "red flag" (`lambda_min(J_gov) < 0.05`) and a default KL monitoring threshold (0.15 nats) — both are now reference constants too, so a `DriftMonitor` implementer has the spec's own defaults available instead of re-deriving or mistyping them. Jacobian/KL computation itself stays out of core, same as Gamma estimation — these are just named numbers.

**How a threshold is applied.** A Gamma threshold is 1 plus the estimation-error allowance it already includes (1.1 = 10%, 1.2 = 20%). `GammaEstimate.sufficient(threshold)` passes only when `gamma_hat` is strictly greater than `max(threshold, 1 + delta_estimation_error)`, which `required_gamma_hat(threshold)` returns: a monitor's declared error raises the bar only when it is larger than the allowance already in the threshold. Every pass therefore also means `robust_gamma() > 1`. Exactly on the bar does not pass. See [CHANGELOG.md](https://github.com/supersemantics/VSL-Core/blob/HEAD/CHANGELOG.md) for the change from rules version 2026.10.

**What a Gamma value means today.** vsl-core never measures Gamma: your monitor computes `gamma_hat`, and the gate only compares it. For most actions (a refund, an email) the spec's Gamma cannot be measured directly, so what a monitor returns is a *gate score in Gamma units*. Make it an honest one:

- Build it as a ratio where 1.0 means break-even: a policy limit divided by the requested amount, a judge's score divided by its break-even score, an hourly cap divided by this send's count.
- Return `0.0` when the input is missing or unreadable, so the gate fails closed.
- Never use a raw 0–1 confidence as `gamma_hat`: it can never exceed 1.1, so the gate denies every time.
- A fixed `2.0`-or-`0.0` return is a pass/fail encoding, not a measurement. Say so in a comment; for a rule that must never be broken, use an `Invariant` instead of a large threshold.
- Use `ROBUST_GAMMA_HIGH_STAKES_THRESHOLD` (1.2) for payments, medical and legal actions; never set a threshold at or below 1.0.
- Record each decision with `write_gate_decision()` (see "The ledger doesn't write itself" above) if you want to track how a gate's scores move over time. vsl-core keeps no history of its own.

### Drift has no dedicated type, by design

`VerbaLedger.audit()`'s checks read two payload keys: `DRIFT_DETECTED_KEY` (`"drift_detected"`, a `MONITOR` entry's payload) and `VERIFICATION_RESULT_KEY` (`"result"`, a `VERIFICATION` entry's payload, compared against `VerificationResult.INSUFFICIENT`). These are exported constants, not magic strings you need to remember — use `VerbaLedger.write_monitor(identity_key=..., drift_detected=...)` and `VerbaLedger.write_verification(identity_key=..., result=VerificationResult.INSUFFICIENT)` instead of hand-building the payload dict, and the audit checks can never silently miss a differently-spelled key.

### Node, Drift Node, and Tendency are deliberately out of scope

The source spec's Layer 0/1 vocabulary includes `Node` (a stabilised, repeatable pattern of behaviour, classified as an Allowed Node or Drift Node) and `Tendency` (a directional bias detected via KL-divergence comparison, before any output is generated). vsl-core does not model either as its own type. This is a deliberate scoping decision, not an oversight: Node classification is an *inference* concern — it requires observing a real system's behaviour over time and classifying the pattern that emerges — which belongs to analysis tooling built on top of vsl-core, not to something a spec author instantiates directly the way they instantiate a `PreNode` or `Invariant`. vsl-core models the State layer (`AllowedState`/`InadmissibleState`) and the Gamma-based sufficiency judgment (`GammaEstimate.sufficient()`) that a Tendency's KL comparison would ultimately feed into, and stops there.

### Re-Enablement: the one sanctioned path out of a Terminal State

`Instance._re_enable()` is a mechanism, not a policy gate — it's directly callable with just an `Evidence` object and has no concept of a `GovernanceAuthority`. The leading underscore is deliberate (renamed from a public `re_enable()` after an external review correctly flagged the public name as an easy accidental-bypass risk) — it signals "not the sanctioned entry point," though Python still can't make that a hard guarantee. The sanctioned, audited path is `governance.request_re_enablement()`, which pairs the new `Instance` with the `HumanAuthorisedTransition` record that authorises it, so you can't get one without the other:

```python
from vsl_core.identity import Instance, Evidence
from vsl_core.governance import GovernanceAuthority, request_re_enablement

terminated_instance = Instance.new()
authority = GovernanceAuthority(name="safety-board", escalation_contact="oncall@example.com")
evidence = Evidence(
    root_cause_analysis="alarm software infinite loop",
    specification_update_proposal="add heartbeat invariant",
)

new_instance, transition = request_re_enablement(
    terminated_instance,
    authority,
    authorised_by="jane.doe",
    evidence=evidence,
)
# new_instance -> write a RE_ENABLEMENT ledger entry
# transition   -> write a HUMAN_AUTHORISED_TRANSITION ledger entry
```

Like `AutomationDeniedException`'s "cannot be silently caught," this is a convention, not a language-enforced guarantee: nothing stops a caller from calling `Instance._re_enable()` directly and skipping the authority/evidence trail. Adapters and client code that need the audited path should always go through `request_re_enablement()`.

Also worth being precise about, for the same reason: an `InvariantViolation` now carries a `terminal_state_name: str | None` field — set to `on_violation.name` when the violated `Invariant` named one, `None` otherwise. This used to be recoverable only by parsing the free-text `reason` string for the phrase "entering terminal state"; a plain PreNode failure, an ordinary Invariant violation, and a violation that halted the system into a Terminal State are three operationally different events, and telling them apart shouldn't require string matching.

### VerbaLedger: causal correlation, schema versioning, and cross-process safety

Three additions to the ledger, all backward-compatible — existing single-decision-at-a-time callers are unaffected.

**Causal correlation.** `audit()`'s checks originally matched entries only by "same `identity_key`/`instance_id` and a later timestamp" — which can mismatch when a single `Instance` has more than one decision in flight at once (e.g. a payment check and an email verification interleaved on the same agent, where the unrelated email `PRE_NODE` could look like it resolves the payment `MONITOR`'s drift). `write()`/`write_monitor()`/`write_verification()` now accept optional `decision_id`/`caused_by` kwargs; `caused_by` lets an entry name the exact prior `entry_id` it resolves, and `audit()` matches causally whenever it's set, falling back to the old heuristic only when it's absent. Both fields are part of the hash chain, so a forged causal claim is detectable the same way a forged payload is.

**Schema versioning.** `LedgerEntry.schema_version` records which shape of the entry wrote it (`LEDGER_SCHEMA_VERSION`, currently `"1.0"`). `VerbaLedger.write()` stamps it on every entry it constructs; a bare `LedgerEntry(...)` built directly — or one reconstructed from a persisted entry that predates this field — doesn't silently claim a version it wasn't actually written under.

**Checkpoints.** `VerbaLedger.current_checkpoint()` returns a `LedgerCheckpoint` (`sequence`, `entry_hash`, `checked_at`), which an external anchoring service can witness over time. `verify_integrity()` only proves internal consistency of whatever entries the store currently holds; it cannot detect truncation or wholesale replacement with an older, still-consistent snapshot. The optional immudb store also checks local entries against a remote copy during synchronization.

**Cross-process safety.** `JsonlLedgerStore.append()`'s read-last-entry-then-write sequence is now guarded by an OS-level advisory lock (`fcntl.flock` on POSIX, `msvcrt.locking` on Windows) on a sibling `.lock` file, not just the in-process `threading.RLock`. Two separate `JsonlLedgerStore` instances — in one process or several — writing to the same file can no longer race and corrupt the sequence/hash chain.

**Storage options.** This package includes `InMemoryLedgerStore`,
`JsonlLedgerStore`, and optional `ImmuDBLedgerStore`. The immudb store writes
the same hash-chained entries to local JSONL and immudb, with connection
settings supplied by the application or environment. See
[immudb ledger storage](https://github.com/supersemantics/VSL-Core/blob/HEAD/docs/immudb-ledger.md) for setup and recovery.
`VerbaLedger` uses the same `LedgerStore` interface for every store, so
any other durable store can be plugged in the same way.

## The Drift Class / Stabilisation Operator catalog (`vsl_core.catalog`)

Loads two real data files (Paper 5, "Toward a Basis Representation of Drift Forensics"): 45 Drift Classes across five categories (external, internal, systemic, linguistic, authority) tagged by evidence tier (A = well evidenced, B = theoretically grounded, C = hypothesised, D = a limit class possibly unfixable by any operator), and 10 Stabilisation Operators.

**This catalog is explicitly not a finished, validated detection system.** Of the 113 Legion detection heuristics in `legion_patterns.json`, **106 (94%) are self-labeled `SPECULATIVE`**, with the stated caveat that "no verified detection signature exists yet — treat matches as a prompt for manual review, not a confirmed finding." Only **7 heuristics carry real confidence** (4 HIGH, 3 MEDIUM), concentrated in `DC-E13` (3), `DC-I11` (2), and the orphan `CLUSTER-HANDOVER` entry (2). Call `catalog.loader.only_validated_heuristics()` if you want only those seven — do not treat the other 106 as ready to act on automatically.

Known data-quality findings, surfaced by `catalog.loader.validate()` and never silently fixed:

1. `drift_classes.json`'s own `metadata.total_drift_classes` claims **36**; the real, computed count across all five categories is **45** (external=15, internal=19, systemic=7, linguistic=3, authority=1). Do not trust the metadata field.
2. `legion_patterns.json` contains a `CLUSTER-HANDOVER` entry with no corresponding Drift Class anywhere in `drift_classes.json`.
3. **10 Drift Classes have zero Legion detection heuristics at all** (`legions: {}`): `DC-S1, DC-S2, DC-S3, DC-S4, DC-S5, DC-S6, DC-L1, DC-L2, DC-L3, DC-A1` — all of the systemic and linguistic tiers, plus the sole authority-tier class. This is a coverage gap (mostly tier B/C/D theoretical/limit classes with no heuristic proposed yet), not a data error, and is worded accordingly in `validate()`'s output.

## Building an adapter

A framework adapter must implement `vsl_core.conformance.protocol.VSLAdapter` (`compile_pre_node`, `compile_invariant`) and pass `vsl_core.conformance.suite.run_conformance_suite(your_adapter)` with an empty result before calling itself VSL-conformant. The suite mechanically proves — using a real `PreNode`/`Invariant` and a mutable side-effect counter, not just return-value checks — that your compiled gates:

1. Block before any side effect when a `PreNode`'s Gamma estimate is insufficient (the F1 property, checked mechanically).
2. Pass through normally when Gamma is sufficient.
3. Raise `InvariantViolation` specifically (not a bare `AutomationDeniedException`) when an `Invariant` fails.
4. Don't raise when an `Invariant` holds.
5. Are safely reusable — no state leaks between calls on the same compiled gate.

Deliberately absent from this list: writing to `VerbaLedger`. Ledger writes are the calling application's responsibility, never the adapter's — see [The ledger doesn't write itself](#the-ledger-doesnt-write-itself-read-this-before-assuming-an-audit-trail-exists) above. A conformant adapter should not call `ledger.write*` internally; doing so would silently couple gate compilation to a logging policy the application may not want.

`vsl_core.conformance.reference_adapter.PlainPythonReferenceAdapter` is the minimal reference implementation — proof the contract is satisfiable at all, not merely specified on paper. [`vsl-langgraph`](https://github.com/supersemantics/VSL-Langgraph) is the minimal *framework* implementation, for the same reason — read `src/vsl_langgraph/adapter.py` alongside `PlainPythonReferenceAdapter` to see how little actually changes between them, and why: most frameworks have nothing framework-specific to compile a gate *into*.

## Calling the compiled gate: two real integration shapes

Compiling a gate is the framework-agnostic half of the story. *Where* and *how* you actually call the resulting gate depends entirely on how the application you're integrating with is shaped — the conformance contract says nothing about this, on purpose, because it genuinely varies. Two shapes, both real, both verified against actual running code, not just described:

**One hook per guarded action.** If the framework gives you a natural per-action extension point — a node in a graph, a middleware slot, a decorator — wrap that action so the gate is checked immediately before it runs, and route around a denial the way the framework already routes. This is the common case, and it's what [`vsl-langgraph`](https://github.com/supersemantics/VSL-Langgraph)'s `gated_node`/`route_on_denial` helpers assume.

**No per-action hook — call the gate directly inside whatever dispatch point already exists.** Some real applications route every action through one shared dispatcher instead — e.g. a single "execute whichever tool the model picked" function, common in tool-calling agents — rather than one hook per action. There's nothing to *wrap* in that shape. The compiled gate is still just `async def gate(candidate_input) -> None`, so you call it directly, inline, immediately before the specific action you're guarding that call site, and catch the exception yourself. No adapter change needed — the gate doesn't know or care how it's called, which is exactly why this works without modification. Proven on a real, unfamiliar, third-party production LangGraph template that turned out to use a single shared tool dispatcher, not one node per tool — see [`building-with-vsl-core.md`](https://github.com/supersemantics/VSL-Core/blob/HEAD/docs/building-with-vsl-core.md#retrofitting-an-existing-agent-a-real-case-study) for the full case study.

## Install

```
pip install super-semantics-vsl
```

The package is published as `super-semantics-vsl`; in code you `import vsl_core` (the distribution
name and the module name differ, as with `beautifulsoup4` and `bs4`). For the optional immudb ledger
store: `pip install "super-semantics-vsl[immudb]"`.

For local development:

```
git clone https://github.com/supersemantics/VSL-Core.git
cd VSL-Core
pip install -e .
```

## Package layout

```
src/vsl_core/
├── exceptions.py       exception hierarchy
├── rules_version.py    ASSURANCE_RULES_VERSION (written into every gate-decision record)
├── metrics.py          Delta, Gamma, GES, EEF, Beta, Threshold
├── identity.py         IdentityKey, ClusterKey, Instance, Evidence
├── ledger.py           VerbaLedger, hash-chained LedgerEntry, gate-decision and action records, enforcement, causal audit checks, checkpoints
├── immudb_store.py     optional ImmuDBLedgerStore (JSONL plus verified immudb replication)
├── constructs.py       AllowedState, PreNode, Invariant, TerminalState
├── cluster.py          Cluster, ClusterPreNode
├── governance.py       GovernanceAuthority, HumanAuthorisedTransition, Proofing, Binding, Specification
├── catalog/            Drift Class / Stabilisation Operator / Legion data + loader
└── conformance/        VSLAdapter protocol, run_conformance_suite, reference adapter
```

## Verifying the zero-dependency / framework-agnostic guarantee

```
grep -rn "^from agents\|^import agents\|^from langgraph\|^import langgraph\|^from langchain\|^import langchain\|^from openai\|^import openai\|^from anthropic\|^import anthropic\|RunContextWrapper\|InputGuardrail\|GuardrailFunctionOutput" src/vsl_core/
```

should return nothing. A fresh virtual environment containing only `vsl-core` and `pytest` should install and pass the full test suite with no other packages pulled in.

## What a VerbaCertificate does *not* claim

`VerbaLedger.issue_certificate()` only returns a certificate if all five audit checks pass, and even then: **it does not guarantee no Inadmissible State was ever reached.** It certifies that every *detected* Drift event was addressed, Terminal States were properly escalated, and governance was continuously monitored — it certifies the governance *process*, not the underlying system, model, or domain. This disclaimer is embedded in `VerbaCertificate.NOTE` and surfaced in its `__str__`, not just documented here.

## License

MIT — see [LICENSE](https://github.com/supersemantics/VSL-Core/blob/HEAD/LICENSE). Copyright Super Semantics.
