rmic-guard
Role-boundary preservation and identity-drift detection for autonomous LLM agents.
rmic-guard gives an agent a contract — an explicit statement of its role,
allowed/forbidden tools, and data-access scope — and enforces it at runtime
with two layers:
- Hard rules: exact-match checks on tool names, parameter bounds, and data scope.
- IDS (Identity Drift Score): an embedding-based signal (role distance, semantic grounding, trajectory curvature) that flags gradual drift a hard-rule check alone would miss.
Install
pip install rmic-guard
This installs core enforcement plus the local fastembed embedding backend —
no LLM provider SDKs. To also plan tool calls with a real LLM:
pip install "rmic-guard[anthropic]" # Claude, via LiteLLM
pip install "rmic-guard[groq]" # Groq/Llama, via LiteLLM
pip install "rmic-guard[llm]" # both
If your platform can't run fastembed's ONNX backend, install the
PyTorch-based fallback instead:
pip install "rmic-guard[torch]"
Quickstart
from rmic_guard import Guard
guard = Guard("contracts/bank_bot.json") # load + validate + seal + verify
@guard.tool
def transfer_funds(amount: float, to: str):
return {"sent": amount, "to": to}
result = guard.check("transfer_funds", amount=500, to="4321", message="pay rent")
print(result.allowed, result.decision, result.reason, result.output)
Guard loads the contract (a file path, a dict, or an RMICContract), seals
it in memory if it isn't sealed yet, and verifies the hash if it is
(ContractIntegrityError on tampering). guard.check(...) enforces one tool
call and runs your function only if it is allowed.
Semantic mode is experimental and off by default.
Guardenforces the contract's hard rules (forbidden tools, parameter bounds, data scope) unless you passsemantic=True. On the current scoring, the semantic identity-drift score (IDS) does not separate attacks from legitimate requests: across the 4 bundled contracts, attacks score lower than legitimate prompts (ROC AUC 0.35–0.49) and no warn/block threshold catches more than 3 of 25 attacks while flagging at most 1 of 15 legitimate requests. See the calibration report. Enable it only for evaluation. To collect IDS data on real traffic without affecting any decision, usesemantic="monitor": the IDS is computed and written toGuardResult(ids_score,ids_decision= whatsemantic=Truewould have decided) and to the audit log, while the hard rules alone decide.
GuardResult field |
Meaning |
|---|---|
allowed |
True for PASS / PREEMPTIVE_WARN |
decision |
PASS, BLOCK, NEEDS_RECOVERY or PREEMPTIVE_WARN |
reason |
hard-rule violation (forbidden_tool, parameter_constraint:amount:above_max, ...) or IDS reason |
ids_score |
Identity Drift Score (0 in hard-rules-only mode) |
output |
your tool's return value, or None if it didn't run |
recovery_attempted, contract_hash |
recovery flag and the contract that was enforced |
Pass the data categories a call touches with data=["ssn"]. Per-session IDS
and tool-call history is kept for you: guard.reset() clears it, and
guard.session("user-42").check(...) gives each conversation its own history.
Fully offline: hard rules only
guard = Guard({"agent_id": "bot", "role_name": "Bot", "sector": "demo",
"semantic_anchors": ["I check balances."],
"allowed_actions": ["check_balance"], "forbidden_actions": ["admin_login"]},
semantic=False) # the default; shown for clarity
guard.register("check_balance", lambda: {"balance": 100})
print(guard.check("check_balance")) # allowed=True, decision=PASS
print(guard.check("admin_login")) # allowed=False, decision=BLOCK, reason=forbidden_tool
semantic=False (the default) enforces forbidden tools, parameter bounds and
data scope with no embedding model and no network. With the experimental
semantic=True, the first use downloads the BAAI/bge-small-en-v1.5
embedding model once (then it's cached locally).
Let an LLM plan the call
pip install "rmic-guard[groq]" # or [anthropic]
result = guard.run("Transfer $500 to 4321 for rent", llm="groq/llama-3.3-70b-versatile")
With semantic=True (experimental), if the plan lands in the IDS warn zone (NEEDS_RECOVERY), run() re-plans
once with re-anchoring instructions (max_recovery=1) and enforces again; if
it still isn't allowed, the result is blocked and the tool never runs.
Signed audit log
guard = Guard("contracts/bank_bot.json", audit_log="audit.jsonl")
...
guard.verify_log() # False if any entry was edited, deleted, inserted or reordered
Every decision is appended to audit.jsonl with an Ed25519 signature, and
each line stores the SHA-256 of the line before it, so deleted or reordered
lines break the chain. (Cutting lines off the end leaves a shorter valid
chain: record AuditLedger.head_hash("audit.jsonl") elsewhere to detect that.) The
signing key comes from audit_key=..., else RMIC_AUDIT_KEY, else
audit.jsonl.key (created with 0600 permissions on first use). The public
key is written to audit.jsonl.pub, so AuditLedger.verify_file("audit.jsonl")
works after a restart or on another machine.
Contract hard-rule extensions
Optional contract fields, validated at load and covered by the contract hash:
argument_rules: per-toolallowed_args(for fixed-schema tools) and full-matchpatternsfor argument values →BLOCK argument_not_allowed:<tool>:<arg>/argument_pattern:<tool>:<arg>.confirm_aboveinparameter_constraints: larger values returnNEEDS_CONFIRMATION(tool not run);guard.confirm(result.confirmation_id)runs it exactly once and logs it. Ids expire afterconfirmation_ttl_seconds(default 600; a contract value is a ceiling theGuardcan only shorten) and at most 100 can be pending;guard.pending_confirmations()lists them andguard.cancel(id)withdraws one (audited).deny_patterns(opt-in): phrase packsrole_reassignment,objective_override,guardrail_removal, your own regexes andprohibited_terms, matched against the user's message →BLOCK deny_pattern:<pack>:<id>or a warning. These are heuristics: rewordings evade them.session_limits(0.4.1): a running total of one argument perguard.session(...), e.g.{"transfer_funds": {"param": "amount", "max_total": 50000}}, so split transfers →BLOCK session_limit:<tool>:<param>.
See the README on GitHub
for examples, and load_example_contract("financial_agent_hardened") for a contract using them.
Evaluation (v0.4). One run, no tuning, on an external public set (primary: AgentDojo banking, InjecAgent, AgentHarm; 80 attacks and 65 legitimate items over 4 contracts) and a model-generated, context-isolated set (secondary: 45 attacks and 42 legitimate items, one contract).
- External set: attacks blocked 72/80 (90%, 95% CI 81–95) with or without the v0.4 extensions. The contracts' tool lists did that work, and they also blocked 56/65 legitimate items whose tools are outside the allowed lists.
- Generated set: deny patterns raised attacks blocked from 37/45 to 40/45 with 0/42 legitimate items blocked.
- Deny patterns are wording heuristics. Semantic mode is monitor-only: the IDS did not separate attacks from legitimate requests (ROC AUC 0.48 and 0.59).
Full results.
AgentHarm is MIT-licensed with an additional clause (safety and security use only, evaluation
not training); the repository keeps only its behaviour IDs and downloads the prompts with
scripts/fetch_agentharm.py.
Sealing: the contract hash covers anchor_embedding, which depends on the machine and
fastembed version, so seal a contract once (rmic seal contract.json) and distribute the
sealed file. Guard warns when it seals an unsealed contract in memory; such hashes are
stable across loads but machine-specific in semantic mode.
Writing contracts in code
RMICContract.create(...) validates the contract, computes its semantic-anchor
embedding (unless require_embedding=False), hashes it, and seals it — all in
one call. Invalid contracts raise InvalidContractError listing every problem
found, not just the first:
Invalid RMIC contract (RMICContract.create(...)):
- role_name: missing required field (expected a non-empty string)
- semantic_anchors: must contain at least one sentence
Advanced / low-level API
Guard is a layer over these classes, which remain fully supported:
from rmic_guard import (
ClaudeReasoning, EnforcementEngine, PlannedToolCall, ToolRegistry, load_contract,
)
contract = load_contract("contracts/financial_agent.json") # verifies contract_hash by default
reasoning = ClaudeReasoning() # reads ANTHROPIC_API_KEY from the environment
plan = reasoning.plan_tool_call(
"What's my current account balance?", contract=contract, condition="C",
)
engine = EnforcementEngine(contract=contract, tools=ToolRegistry(), ledger=None)
outcome = engine.evaluate_and_maybe_execute(
plan,
recent_ids=[], # pass prior IDS scores for trajectory tracking across a session
drift_type=None,
execute_tool=True,
enforcement_mode="full", # "full" | "hard_rules_only" | "ids_only"
)
print(outcome.decision) # "PASS" | "BLOCK" | "NEEDS_RECOVERY" | "PREEMPTIVE_WARN"
Groq (Llama) is supported as a drop-in alternative to Claude:
from rmic_guard import GroqReasoning
reasoning = GroqReasoning(model_name="groq/llama-3.3-70b-versatile")
Configuration
The SDK uses each contract's own ids_warn_threshold / ids_block_threshold.
It reads a YAML config file only when you name one explicitly, via the
RMIC_CONFIG environment variable; a config.yaml that happens to sit in
your working directory is ignored.
CLI
rmic init research-agent # scaffold a new agent project (sealed contract + quickstart)
rmic validate contract.json # check a contract against the schema, no sealing
rmic seal contract.json # compute anchor_embedding + contract_hash, write back to the file
rmic verify contract.json # check a sealed contract's hash is still intact
Writing a contract
A contract is a JSON file describing the agent's role, its allowed and
forbidden tools, parameter constraints, and data-access scope. The full
schema ships inside the package at rmic_guard/schema/contract.schema.json,
and is also readable directly on GitHub:
https://github.com/Arshu-1104/RMIC/blob/main/schema/contract.schema.json
See contracts/ in the GitHub repo
for real examples across financial, support, healthcare-research, and
legal-review agent roles.
Status
This is an early (0.4.x) release from an active research project on role-boundary preservation in autonomous agents. APIs may change between minor versions until 1.0. Issues and contributions welcome on GitHub.
License
MIT
Metadata
Release files for rmic-guard 0.4.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| rmic_guard-0.4.1.tar.gz | 123.4 kB | With provenance | Details for rmic_guard-0.4.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| rmic_guard-0.4.1-py3-none-any.whl | Python 3 | none | any | Details for rmic_guard-0.4.1-py3-none-any.whl |
Total release size: 222.8 kB
Release files / rmic_guard-0.4.1.tar.gz
| Download URL | rmic_guard-0.4.1.tar.gz |
|---|---|
| Size | 123.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
b3ab026efc1c0634f6b56ce6d0ad0307abf25d1f981296cb346afcd134532fbf
|
|
BLAKE2b-256 checksum How to use checksums |
736a3b36b580ab21a665e2b66d71635ade1f623cc2e7cd6b0a578442046f58dc
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 22, 2026.
Transparency logRelease files / rmic_guard-0.4.1-py3-none-any.whl
| Download URL | rmic_guard-0.4.1-py3-none-any.whl |
|---|---|
| Size | 99.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
d18de636de104eec3e7c5578a85803ffccd28a051ede7fd32982c4ff21671895
|
|
BLAKE2b-256 checksum How to use checksums |
331688bb220e17125d1e041e9935e0608ca89c894c33d27ee60aa07e050538e8
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 22, 2026.
Transparency logSecurity for rmic-guard 0.4.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for rmic_guard-0.4.1.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 22, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.