Python API Reference¶
Top-level exports¶
rulegraph
¶
rulegraph - Natural-language rulebook compiler for game arbitration.
EnforcementSession(incident, status='open', inventory=list(), clearance_token=None, blocked_actions=list(), notes='')
dataclass
¶
Mutable post-incident lockdown session (AgentWard runtime).
Attributes:
| Name | Type | Description |
|---|---|---|
status |
IncidentStatus
|
open/lockdown/cleared/false_alarm. |
inventory |
list[str]
|
Recovered inventory of lost/affected resources. |
clearance_token |
str | None
|
Human/owner clearance id (required to clear). |
blocked_actions |
list[str]
|
High-risk actions attempted while locked. |
IncidentEvent(incident_id, kind, paths=(), summary='', agent_id='', timestamp=0.0)
dataclass
¶
One destructive / loss event that opens enforcement.
ClosedLoopError
¶
Bases: ValueError
Raised when policy gate refuses empty/conflicted/indeterminate graphs.
GateOutcome(ok, verdict, reason, exit_code, rule_count=0, edge_count=0, conflict_count=0, critical_conflict_count=0, tier=None, confidence=None, provenance=(), human_required=False, mean_logprob=None, min_logprob=None, token_count=0, action=None, brittle_spans=())
dataclass
¶
Result of a closed-loop policy or logprob gate.
Attributes:
| Name | Type | Description |
|---|---|---|
ok |
bool
|
True only when the pipeline may continue. |
verdict |
str
|
|
reason |
str
|
Always non-empty. |
exit_code |
int
|
0 PASS, 1 FAIL, 2 FAIL_LOUD. |
rule_count |
int
|
Nodes in the graph. |
edge_count |
int
|
Edges in the graph. |
conflict_count |
int
|
Conflicts detected. |
critical_conflict_count |
int
|
Severity=critical conflicts. |
tier |
str | None
|
Arbitration tier when a query was run. |
confidence |
float | None
|
Arbitration confidence or geometric mean token prob. |
provenance |
tuple[str, ...]
|
Rule ids used for the answer. |
human_required |
bool
|
True when policy needs human arbitration. |
mean_logprob |
float | None
|
Mean token logprob when a logprob gate ran. |
min_logprob |
float | None
|
Minimum token logprob when a logprob gate ran. |
token_count |
int
|
Number of tokens examined by a logprob gate. |
action |
str | None
|
Action / step name gated (logprob path). |
brittle_spans |
tuple[str, ...]
|
Span names that failed logprob thresholds. |
LogprobSummary(token_count, mean_logprob, min_logprob, confidence)
dataclass
¶
Aggregate stats over a sequence of token logprobs (AgentUQ class).
CoverageTracker(arbiter)
¶
Wraps a RuleArbiter to track which rules are invoked.
Source code in src/rulegraph/coverage.py
arbitrate(query)
¶
Delegate to arbiter and record which rules were used.
Source code in src/rulegraph/coverage.py
report()
¶
Generate a coverage report.
Source code in src/rulegraph/coverage.py
ArbitrationResult(query, answer, tier, provenance, confidence, contradictions)
dataclass
¶
The structured answer to a query against the rule graph.
Attributes:
| Name | Type | Description |
|---|---|---|
query |
str
|
The original question posed. |
answer |
str
|
The synthesized answer. |
tier |
str
|
Classification - "determinate" | "indeterminate" | "unknown". |
provenance |
list[str]
|
List of rule_ids that were used to produce the answer. |
confidence |
float
|
Aggregate confidence in [0.0, 1.0]. |
contradictions |
list[str]
|
rule_ids of rules that conflict with the answer. |
to_dict()
¶
Serialize to a JSON-compatible dict.
Source code in src/rulegraph/rule.py
from_dict(d)
classmethod
¶
Deserialize from a dict produced by to_dict().
Source code in src/rulegraph/rule.py
RuleArbiter(graph)
¶
Query engine that arbitrates questions against a RuleGraph.
Given a natural-language question, the arbiter: 1. Finds relevant rules by matching keywords against rule text, tags, and rule_id. 2. Detects contradictions among the found rules. 3. Classifies the query as determinate or indeterminate based on rule types. 4. Returns a structured ArbitrationResult with full provenance.
Attributes:
| Name | Type | Description |
|---|---|---|
graph |
The RuleGraph to search. |
Source code in src/rulegraph/rule.py
query(question)
¶
Arbitrate a natural-language question against the rule graph.
Finds relevant rules by keyword matching, detects contradictions, classifies as determinate/indeterminate, and returns a structured result with provenance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
question
|
str
|
A natural-language question about the rules. |
required |
Returns:
| Type | Description |
|---|---|
ArbitrationResult
|
An ArbitrationResult with the answer, tier, provenance, and |
ArbitrationResult
|
any detected contradictions. |
Source code in src/rulegraph/rule.py
RuleEdge(source_id, target_id, relation, condition='', confidence=1.0)
dataclass
¶
A directed relationship between two rules.
Edges represent how rules interact: one rule may modify, supersede, require, or be an exception to another.
Attributes:
| Name | Type | Description |
|---|---|---|
source_id |
str
|
rule_id of the source RuleNode. |
target_id |
str
|
rule_id of the target RuleNode. |
relation |
str
|
Type of relationship (e.g. "modifies", "supersedes", "requires", "exception-to"). |
condition |
str
|
Optional condition under which the edge applies. |
confidence |
float
|
Certainty that this edge is correct, in [0.0, 1.0]. |
id |
str
|
SHA-256[:16] of "{source_id}|{target_id}|{relation}", auto-set. |
RuleGraph()
¶
An in-memory directed graph of RuleNode objects connected by RuleEdge objects.
The graph supports efficient lookup by rule_id, tag, node_type, and keyword search in the text field.
Source code in src/rulegraph/rule.py
add_node(node)
¶
add_edge(edge)
¶
Add a RuleEdge to the graph.
Duplicate edges (same source_id, target_id, relation) are silently ignored to keep the graph idempotent.
Source code in src/rulegraph/rule.py
get_node(rule_id)
¶
get_edges(source_id=None, relation=None)
¶
Return edges, optionally filtered by source_id and/or relation.
Source code in src/rulegraph/rule.py
find_rules(tag=None, node_type=None, text_contains=None)
¶
Search for rules matching any combination of filters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tag
|
str | None
|
If given, only nodes whose tags list contains this string. |
None
|
node_type
|
str | None
|
If given, only nodes of this type. |
None
|
text_contains
|
str | None
|
If given, only nodes whose text contains this substring (case-insensitive). |
None
|
Returns:
| Type | Description |
|---|---|
list[RuleNode]
|
List of matching RuleNode objects in insertion order. |
Source code in src/rulegraph/rule.py
node_ids()
¶
nodes()
¶
node_count()
¶
RuleNode(rule_id, text, node_type, tags=list(), source='', confidence=1.0)
dataclass
¶
A single rule extracted from a rulebook, content-addressed by rule_id.
Two RuleNode objects with the same rule_id always share the same id, regardless of when they were created.
Attributes:
| Name | Type | Description |
|---|---|---|
rule_id |
str
|
Human-readable identifier (e.g. "PHB.5e.attack_roll"). |
text |
str
|
The full rule text. |
node_type |
str
|
Semantic category (e.g. "mechanic", "definition", "narrative"). |
tags |
list[str]
|
Free-form labels for filtering (e.g. ["combat", "attack"]). |
source |
str
|
Source book or document (e.g. "D&D SRD 5.1"). |
confidence |
float
|
Certainty that this is a deterministic rule, in [0.0, 1.0]. |
id |
str
|
SHA-256[:16] of rule_id, set automatically in post_init. |
RuleStore(path)
¶
SQLite-backed persistence layer for RuleNode, RuleEdge, and ArbitrationResult objects.
Attributes:
| Name | Type | Description |
|---|---|---|
path |
Path to the SQLite database file. |
Source code in src/rulegraph/rule.py
save_node(node)
¶
Persist a RuleNode (upsert by rule_id).
Source code in src/rulegraph/rule.py
save_edge(edge)
¶
Persist a RuleEdge (upsert by id).
Source code in src/rulegraph/rule.py
load_graph()
¶
Load all persisted nodes and edges into a new RuleGraph.
Source code in src/rulegraph/rule.py
save_result(result)
¶
Persist an ArbitrationResult.
Source code in src/rulegraph/rule.py
list_results()
¶
Return all stored ArbitrationResult objects, oldest first.
Source code in src/rulegraph/rule.py
assert_post_incident_ok(session, **kwargs)
¶
Raise :class:ClosedLoopError unless :func:gate_post_incident is ok.
Source code in src/rulegraph/agentward.py
clear_incident(session, *, clearance_token, require_inventory=True)
¶
Attempt to clear lockdown with a human/owner token.
Does not clear if inventory is empty when required - status stays locked.
Source code in src/rulegraph/agentward.py
gate_post_incident(session, *, proposed_action=None, require_session_after_incident=False, incident_signaled=False, require_inventory=True, block_high_risk_while_locked=True, high_risk_extra=None)
¶
Refuse high-risk continue under open AgentWard lockdown.
Rules:
incident_signaledand no session whenrequire_session_after_incident→ FAIL_LOUD (enforcer missing after known destruction)- No session and not required → PASS (nothing to enforce)
- Session open/lockdown + empty inventory when required → FAIL_LOUD
- Session locked + high-risk
proposed_action→ FAIL (record block) - Session cleared with inventory + token → PASS
- Locked + low-risk / no proposed action → PASS with human_required note only when action is None (observe-only); if action is low-risk → PASS
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
EnforcementSession | dict[str, Any] | None
|
Open enforcement session or dict; None if no incident yet. |
required |
proposed_action
|
str | None
|
Next agent action name to gate. |
None
|
require_session_after_incident
|
bool
|
When True and incident_signaled, missing session is FAIL_LOUD. |
False
|
incident_signaled
|
bool
|
External signal that destruction already happened. |
False
|
require_inventory
|
bool
|
Empty inventory while locked → FAIL_LOUD. |
True
|
block_high_risk_while_locked
|
bool
|
High-risk under lockdown → FAIL. |
True
|
Source code in src/rulegraph/agentward.py
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 | |
is_high_risk_action(action, *, extra=None)
¶
True if action name matches default or extra high-risk verbs.
Source code in src/rulegraph/agentward.py
open_incident(incident, *, auto_lockdown=True)
¶
Open an AgentWard session from a destructive incident signal.
Source code in src/rulegraph/agentward.py
record_inventory(session, paths, *, replace=False)
¶
Attach or merge post-incident inventory (what was lost / affected).
Source code in src/rulegraph/agentward.py
assert_arbitration_ok(result, **kwargs)
¶
Raise :class:ClosedLoopError unless arbitration result is ok.
Source code in src/rulegraph/closed_loop.py
assert_logprob_ok(logprobs, **kwargs)
¶
Raise :class:ClosedLoopError unless :func:gate_logprob is ok.
Source code in src/rulegraph/closed_loop.py
assert_policy_ok(graph, **kwargs)
¶
Raise :class:ClosedLoopError unless the policy graph gates clean.
Source code in src/rulegraph/closed_loop.py
compile_farm_policy_graph()
¶
Compile Foundry/farm COI + endorse policy rules into a RuleGraph.
POLICY-ARBITRATION product artifact - not a README list. Rules:
- COI: no self-endorsement when financial interest exists
- COI: disclose material interest before public statements
- Endorse: require owner/review before public endorse
- Endorse: never auto-endorse without HITL
- Legal: never auto-fix legal gates (cross-ref worldoracle LEGAL-NO-AUTOFIX)
Edges encode requires/modifies relationships for arbitration provenance.
Source code in src/rulegraph/closed_loop.py
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 | |
gate_arbitration(result, *, require_determinate=False, require_provenance=True, min_confidence=0.0, refuse_contradictions=True)
¶
Gate an :class:ArbitrationResult for load-bearing policy decisions.
tier=unknownwith require_provenance or require_determinate → FAIL- empty provenance when required → FAIL (POLICY-ARBITRATION)
- contradictions when refuse_contradictions → FAIL
- confidence below min → FAIL
Source code in src/rulegraph/closed_loop.py
gate_logprob(logprobs, *, min_mean_logprob=DEFAULT_MIN_MEAN_LOGPROB, min_token_logprob=DEFAULT_MIN_TOKEN_LOGPROB, require_logprobs=True, high_risk=False, action=None, spans=None)
¶
Block brittle LLM steps using token logprobs (AgentUQ / LOGPROB-GATE).
Public case: AgentUQ (HN Show HN) - single-pass runtime reliability gate from provider logprobs. Does not claim truth; refuses execution when the generation looks ambiguous/brittle, especially on high-risk tools (SQL, shell, paths, tool JSON).
Rules:
require_logprobsand empty/missing logprobs → FAIL_LOUD (cannot gate a phantom confidence signal).- mean logprob <
min_mean_logprob→ FAIL (human_requiredif high_risk). - any token logprob <
min_token_logprob→ FAIL. - optional
spans: each named span (e.g.sql_clause,tool_args) is checked with the same thresholds; failing span names appear inbrittle_spans. - clean tokens → PASS with
confidence = exp(mean_logprob).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logprobs
|
Sequence[float] | None
|
Full-step token logprobs (may be None if only spans given). |
required |
min_mean_logprob
|
float
|
Minimum allowed mean logprob (default -1.5). |
DEFAULT_MIN_MEAN_LOGPROB
|
min_token_logprob
|
float
|
Minimum allowed single-token logprob (default -4.0). |
DEFAULT_MIN_TOKEN_LOGPROB
|
require_logprobs
|
bool
|
If True, missing/empty tokens FAIL_LOUD. |
True
|
high_risk
|
bool
|
If True, failures set |
False
|
action
|
str | None
|
Optional step/tool name for the reason string. |
None
|
spans
|
Mapping[str, Sequence[float]] | None
|
Optional map of span_name → token logprobs for localization. |
None
|
Source code in src/rulegraph/closed_loop.py
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 | |
gate_policy_graph(graph, *, refuse_critical_conflicts=True, min_rules=1)
¶
Gate a rule graph for POLICY-ARBITRATION readiness.
- Empty / below min_rules → FAIL_LOUD
- Critical conflicts (cycles, mutual supersede) → FAIL
- Otherwise PASS (warning-level overlaps do not fail by default)
Source code in src/rulegraph/closed_loop.py
gate_policy_query(graph, query, *, require_determinate=False, require_provenance=True, min_confidence=0.0, refuse_critical_conflicts=True)
¶
End-to-end: graph readiness + arbitrate query + gate the result.
This is the load-bearing closed-loop entry for POLICY-ARBITRATION.
Source code in src/rulegraph/closed_loop.py
list_critical_conflicts(graph)
¶
summarize_logprobs(logprobs)
¶
Compute mean/min logprob and geometric-mean confidence from token logprobs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logprobs
|
Sequence[float]
|
Per-token natural log-probabilities (typically ≤ 0). |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
if logprobs is empty. |
Source code in src/rulegraph/closed_loop.py
detect_conflicts(graph)
¶
Find rules that may contradict or circularly depend on each other.
Source code in src/rulegraph/conflicts.py
find_cycles(graph)
¶
Find circular dependencies in the rule graph using DFS.
Source code in src/rulegraph/conflicts.py
import_from_file(path, source='')
¶
Read a text file and parse it into RuleNodes.
Source code in src/rulegraph/importer.py
import_from_text(text, source='', default_type='mechanic')
¶
Parse plain text into RuleNodes.
Each line starting with '- ', '* ', or a number+dot becomes a RuleNode. Tags are auto-extracted from [bracket] patterns. Rule ID is auto-generated as source + SHA hash of the line text.
Source code in src/rulegraph/importer.py
infer_edges(rules)
¶
Heuristically infer edges by looking for keyword references between rules.
For each rule, scan its text for keywords (modifies, supersedes, requires, exception) and cross-reference against other rules whose rule_id or tags appear in the text.