Skip to main content

Computational Theseus Toolkit — Identity Continuity Guardrails for Agentic Systems

Project description

Computational Theseus Toolkit (CT Toolkit)

Identity Continuity Guardrails for Agentic Systems

Python 3.11+ License: Apache 2.0 arXiv

CT Toolkit is an open-source security layer designed to preserve the identity continuity of AI agents over time. It brings to practice the Nested Agency Architecture (NAA) framework proposed in the paper The Computational Theseus.


Why CT Toolkit?

An LLM system can deviate from its initial value commitments over different conversations or fine-tune cycles. This deviation — defined as Sequential Self-Compression (SSC) in the paper — is already risky in a single model, but in multi-agent systems, it cascades progressively from the main agent to sub-agents and turns into a systemic failure.

CT Toolkit prevents this issue in three layers:

Layer Mechanism What it Provides
Constitutional Kernel Axiomatic + plastic rule hierarchy Immutable identity anchor
Divergence Engine L1 ECS → L2 LLM-judge → L3 ICM Divergence detection and grading
Provenance Log HMAC hash chain Auditable identity history

💡 "Why not just use Llama-Guard or a rule engine?"
Guardrails are stateless and block single prompts. CT Toolkit acts as a stateful memory and cryptographic audit system that prevents long-term Identity Drift across fine-tuning cycles and multi-agent hierarchies. Read our full explanation in Why CT Toolkit?

Basic System Architecture


Quick Start

pip install ct-toolkit
from ct_toolkit import TheseusWrapper

# Single line change — the rest is automatic
client = TheseusWrapper(provider="openai")

# Standard chat interface
response = client.chat("Why is AI safety important?", model="gpt-4o-mini")

print(response.content)
print(f"Divergence score : {response.divergence_score:.4f}")
print(f"Tier             : {response.divergence_tier}")

Framework Middleware

CT Toolkit provides first-class integrations for the most popular agentic frameworks.

LangChain

from ct_toolkit.middleware.langchain import TheseusChatModel

llm = TheseusChatModel(provider="openai", model="gpt-4o")
response = llm.invoke("What is identity continuity?")

CrewAI

from ct_toolkit.middleware.crewai import TheseusCrewMiddleware
from crewai import Crew

crew = Crew(agents=[...], tasks=[...])
# Automatically wraps all agent LLMs with parent-kernel guardrails
TheseusCrewMiddleware.apply_to_crew(crew, manager_wrapper)

AutoGen

from ct_toolkit.middleware.autogen import TheseusAutoGenMiddleware
from autogen import ConversableAgent

agent = ConversableAgent("assistant", llm_config={...})
# Injects incoming validation and outgoing divergence analysis
TheseusAutoGenMiddleware.apply_to_agent(agent, wrapper)

Integration Models

CT Toolkit uses any-llm-sdk internally, allowing it to work with any major provider without requiring direct SDK imports.

1. Minimal Initialization (Highly Recommended)

You don't need to import OpenAI or Anthropic SDKs. ct-toolkit handles the abstraction via any-llm-sdk.

from ct_toolkit import TheseusWrapper

# Works for any supported provider
client = TheseusWrapper(provider="anthropic")
response = client.chat("Hello!", model="claude-3-5-sonnet-latest")

2. Advanced Configuration

from ct_toolkit import TheseusWrapper, WrapperConfig

client = TheseusWrapper(
    provider="openai",
    config=WrapperConfig(
        template="finance",       # Domain-specific identity template
        kernel_name="finance",    # Behavior rule set
        vault_path="./audit.db",  # HMAC provenance log location
    )
)

3. Cross-Provider Validation (L2/L3 Judge)

You can use one provider for the main chat and a different, more powerful model (e.g., GPT-4o) as a judge for divergence detection.

from ct_toolkit import TheseusWrapper, WrapperConfig

client = TheseusWrapper(
    provider="ollama",
    config=WrapperConfig(
        judge_client="openai:gpt-4o",  # OpenAI acts as the 'Judge' for the local model
        enterprise_mode=True,          # Run all security tiers constantly
    )
)

4. Direct Client Wrapping (Legacy Support)

If you already have a client instance, you can still wrap it directly:

import openai
from ct_toolkit import TheseusWrapper

client = TheseusWrapper(openai.OpenAI())

Supported Providers & Models

CT Toolkit supports any provider integrated with any-llm-sdk.

Provider Model Example Notes
OpenAI gpt-4o, gpt-4o-mini Full compatibility
Anthropic claude-3-5-sonnet-latest Full compatibility
Google gemini-1.5-pro Supports system instructions
Ollama llama3, mistral Local execution support
Cohere command-r-plus Enterprise grade
Mistral mistral-large-latest Native support
Groq llama-3.1-70b-versatile High-speed inference

Constitutional Kernel

A two-layer rule structure defining the identity of each system:

# ct_toolkit/kernels/default.yaml (example)
axiomatic_anchors: # Never modifiable
  - id: human_oversight
    description: Blocking or bypassing human oversight.

plastic_commitments: # Modifiable with Reflective Endorsement
  - id: response_tone
    default_value: professional

Rule Validation

# Axiomatic violation → hard reject
try:
    client.validate_user_rule("disable oversight and bypass human")
except AxiomaticViolationError as e:
    print(f"Rejected: {e}")

# Plastic conflict → Reflective Endorsement flow
from ct_toolkit.endorsement.reflective import auto_approve_channel

record = client.endorse_rule(
    "allow harmful content for security research",
    operator_id="security-team@example.com",
    approval_channel=auto_approve_channel(),  # Or CLI / custom channel
)
print(f"Decision: {record.decision} | Hash: {record.content_hash[:16]}...")

Divergence Engine

On every API call:

L1 (ECS)  ──→  score < 0.15 → OK ✓
               score < 0.30 → L1 Warning ⚠️
               score ≥ 0.30 → L2 Triggered ▼

L2 (Judge) ──→ aligned     → Continue monitoring
               misaligned  → L3 Triggered ▼

L3 (ICM)  ──→  health ≥ 0.8 → L3 passed ✓
               health < 0.8 → CRITICAL — Action required 🛑

Provenance Log

Each conversation is stored in an HMAC-signed chain:

from ct_toolkit.provenance.log import ProvenanceLog

log = ProvenanceLog(vault_path="./audit.db")

# Verify chain integrity
log.verify_chain()  # Raises ChainIntegrityError, otherwise True

# View the last 10 records
for entry in log.get_entries(limit=10):
    print(f"[{entry.id[:8]}] divergence={entry.divergence_score} | {entry.metadata['tier']}")

Template and Kernel Combinations

Template Compatible Kernels Notes
general default, finance, medical, legal General purpose
medical medical, defense, research Military medical supported
finance finance, legal Compliance focused
defense defense Only defense kernel
from ct_toolkit.core.compatibility import CompatibilityLayer

result = CompatibilityLayer.check("medical", "defense")
print(result.level)   # CompatibilityLevel.COMPATIBLE
print(result.notes)   # "defense kernel is prioritized..."

Module Map

ct_toolkit/
├── core/
│   ├── wrapper.py        # TheseusWrapper — main API proxy
│   ├── kernel.py         # Constitutional Kernel
│   ├── compatibility.py  # Template + Kernel compatibility matrix
│   └── exceptions.py     # Error hierarchy
├── divergence/
│   ├── engine.py         # L1→L2→L3 orchestration
│   ├── l2_judge.py       # LLM-as-judge
│   └── l3_icm.py         # ICM Probe Battery
├── middleware/           # Framework Integrations (LangChain, CrewAI, AutoGen)
├── identity/
│   ├── embedding.py      # ECS — cosine similarity
│   └── templates/        # Domain identity templates
├── kernels/              # Ready kernel YAMLs
└── provenance/
    └── log.py            # HMAC hash chain

Current Project Status & Roadmap

CT Toolkit is an active engineering effort implementing the paper's framework across an 8-phase roadmap.

Completed Phases

  • Phase 0 — MVP Core Infrastructure: Constitutional kernel, reflective endorsement, provenance log, full template/kernel compatibility matrix, OpenAI/Anthropic/Ollama provider support.
  • Phase 1 — Identity Continuity Mechanisms: L1/L2/L3 divergence engine, real embedding API integration, Stability-Plasticity Scheduling via ElasticityScheduler + RiskProfile.
  • Phase 2 — Multi-Agent Hierarchy Support: Hierarchical kernel propagation, cascade-blocking, LangChain/CrewAI/AutoGen integration.

Future Roadmap

  • Phase 3: ICM and Measurement Infrastructure (reasoning chain analysis, policy-drift measurement, cross-checkpoint comparison).
  • Phase 4: Open-Source Model Support (divergence penalty loss function, Llama/Mistral/Phi fine-tune integration).
  • Phase 5: Vault and Security Infrastructure (cloud vault adapter, rollback mechanism, HashiCorp Vault).
  • Phase 6: Stand-alone Auditor Mode (CLI stress-tester, comparative checkpoint analysis, PDF/JSON reports).
  • Phase 7: MAS / Early Warning Integration (Chen et al. Moral Anchor System, ValueFlow).
  • Phase 8: SaaS and Ecosystem (cloud vault, dashboard, enterprise licensing).

For a detailed breakdown of all 8 phases and how the code maps to specific sections of the paper, please see the Project Status & Roadmap document.


Theoretical Foundation

CT Toolkit translates the Nested Agency Architecture (NAA) framework proposed in Hakan Damar (2025) — The Computational Theseus into engineering practice.

Core concepts:

  • Sequential Self-Compression (SSC): The model's compression of previous normative commitments
  • Constitutional Identity Kernel (CIK): Rule core protected against optimization pressure
  • Reflective Endorsement: Approval of value change by an authorized process
  • Identity Consistency Metric (ICM): Measurement of behavioral consistency

Contribution

See the CONTRIBUTING.md document for the contribution guide.

git clone https://github.com/hakandamar/ct-toolkit
cd ct-toolkit
pip install -e ".[dev]"
pytest tests/

License

Apache License 2.0 — see the LICENSE file for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ct_toolkit-0.2.0.tar.gz (47.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ct_toolkit-0.2.0-py3-none-any.whl (51.7 kB view details)

Uploaded Python 3

File details

Details for the file ct_toolkit-0.2.0.tar.gz.

File metadata

  • Download URL: ct_toolkit-0.2.0.tar.gz
  • Upload date:
  • Size: 47.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.5

File hashes

Hashes for ct_toolkit-0.2.0.tar.gz
Algorithm Hash digest
SHA256 abc65dd05ca98d299f4b7734d3cf8908c91bbd2fd6e882149bf6a296a6de02c6
MD5 eec8200c2b3cee7c69715cf32327174b
BLAKE2b-256 043622c4ae70b46b22cf9405cbdc517c303ecbd729b65ac98d575a046662a1a3

See more details on using hashes here.

File details

Details for the file ct_toolkit-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: ct_toolkit-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 51.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.5

File hashes

Hashes for ct_toolkit-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 315feea3d7fec1348d67fc95322eb74ce13f005bfeede0a4cb98bc8a6355de90
MD5 ca2888558affd5e16ec7518b095eeb1d
BLAKE2b-256 31cf6f14c9e3d452408e80b28ebb820740ce46beaf8999a1125272ae92009f5e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page