Documentation
Ejentum API Reference
A developer reference for querying Ejentum verification rules mid-execution. Right before your agent runs code or modifies data, query these endpoints to return focused safety checklists and catch errors before they reach production.
Production Base URL
https://api.ejentum.com
Quick-Copy Integration Snippets
Test an invariant query right now from your terminal or editor. Select your preferred environment to copy:
curl -X POST https://api.ejentum.com/logicv1/ \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"query":"50M-row database migration","mode":"reasoning"}'
Authentication
All API requests must include your API key in an authorization header. Ejentum supports standard Bearer token formatting as well as backward-compatible gateway headers:
# Supported Authentication Headers
Authorization: Bearer YOUR_API_KEY
X-API-Key: YOUR_API_KEY
Endpoint: Evaluate Action & Get Checklist
/logicv1/
(Alias: /webhook/logicv1)
Request Parameters
| Field | Type | Required | Description |
|---|---|---|---|
| query | string | Yes | The task, user prompt, or agent action being evaluated. |
| mode | string | No | Execution topology or cognitive domain filter: reasoning / single (default), stack, graph, adaptive (Go/Super), or a specific domain filter (causal, temporal, spatial, simulation, abstract, metacognitive). |
| model_family | string | No | Target compiler syntax formatting: claude (default XML tags), openai (Markdown directives), or gemini (System instructions). |
| depth | integer | No | Graph traversal depth (1 default, 2 for multi-hop prerequisites/successors when mode="graph"). |
Example Request (cURL)
curl -X POST https://api.ejentum.com/logicv1/ \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"query": "Review pull request refactoring payment processing state machine",
"mode": "single",
"model_family": "claude"
}'
Response Payload
{
"status": "success",
"retrieval_engine": "hybrid_vector_bm25",
"relevance_score": 0.884,
"domain": "Causal",
"ability_id": "CA-023",
"ability_name": "Precisionist",
"single_ability": "### SYSTEM OVERRIDE ACTIVE ###\nOPERATION: [DEFINE_TERMS]\nINSTRUCTION: ...\nCOGNITIVE DIRECTIVES:\nAMPLIFY: Semantic Disambiguation...\nSUPPRESS: Implicit Assumptions...",
"prompt_override": "Step 1: Scan the input for terms lacking explicit definitions...",
"graph_payload": {
"amplification": ["semantic_disambiguation", "quantified_definition_demand"],
"suppression": ["allowing_processing_without_measurable_definitions"],
"cognitive_style": "semantic_precision_enforcement"
}
}
Endpoint: Rule Dependency Graph (Chained Rules)
/logicv1/graph
(Also available via POST /logicv1/ with "mode": "graph")
Traverses rule dependencies across the catalog to build a multi-step checklist of prerequisite checks (requires), extra precautions (enhances), and fallback contingencies (fallback). Setting depth=2 returns a coordinated 4-stage execution plan.
Example Request (cURL)
curl -X GET "https://api.ejentum.com/logicv1/graph?query=distributed+consensus+deadlock&depth=2" \ -H "Authorization: Bearer YOUR_API_KEY"
Endpoint: Instant Keyword Rule Search
/logicv1/search/fts
Executes BM25 full-text keyword search directly against the pre-compiled SQLite database across all 311 rules in under 1ms.
Example Request (cURL)
curl -X GET "https://api.ejentum.com/logicv1/search/fts?query=circuit+breaker+fault+tolerance&limit=3" \ -H "Authorization: Bearer YOUR_API_KEY"
Endpoint: Multi-Agent Handshake & Coordination Gate
/logicv1/handshake/evaluate
(List presets: GET /logicv1/handshake/presets)
Evaluates peer-to-peer agent handshakes across multi-agent swarms. Enforces coordination topologies (Planner-Implementer-Auditor, Maker-Checker, Quorum Consensus) to prevent sycophantic rubber-stamping, unverified plan deviations, and destructive payloads before execution.
Request Parameters
| Field | Type | Required | Description |
|---|---|---|---|
| source_role | string | Yes | Role producing the proposal (e.g. planner, implementer, auditor, maker). |
| target_role | string | Yes | Role receiving the handoff (e.g. implementer, auditor, checker). |
| source_output | string | object | Yes | The payload, plan, code diff, or verification critique submitted by the source agent. |
| preset | string | No | Coordination topology: planner_implementer_auditor (default), maker_checker, or quorum_consensus. |
| contract_name | string | No | Contract transition identifier (e.g. plan_approval_gate, code_audit_gate). |
| required_evidence | object | No | Key-value evidence criteria that must appear in the source output. |
| max_rejections | integer | No | Maximum rejection iterations before escalating (default: 3). |
Example Request (cURL)
curl -X POST https://api.ejentum.com/logicv1/handshake/evaluate \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"preset": "planner_implementer_auditor",
"source_role": "auditor",
"target_role": "executor",
"source_output": "Audit findings: Passed all 14 integration test assertions with zero regression.",
"required_evidence": {"test_status": "passed"}
}'
Response Payload
{
"status": "accepted",
"passed": true,
"source_role": "auditor",
"target_role": "executor",
"transition_name": "code_audit_gate",
"violations": [],
"missing_evidence": [],
"rejection_count": 0,
"attestation": {
"receipt_id": "att_8f7b2c9e10a4",
"decision": "PROCEED",
"timestamp": 1729342800,
"signature": "3a8c1f4e..."
}
}
Endpoints: Multi-Modal Visual & Layout Invariants
/logicv1/visual/verify-spatial
| /verify-diagram | /verify-sequence
Deterministic spatial layout, diagram topology, and temporal frame guards for Vision-Language Models (VLMs), automated UI generators, and chart generation agents.
Spatial Layout Verifier
Checks bounding box collisions, text-over-control overlaps, and directional constraints (e.g. header above content).
Diagram Artifact Trap
Verifies referential integrity in Mermaid, DOT, or JSON flowcharts. Catches severed edges, phantom nodes, and cycle bugs.
Frame Sequence Drift Guard
Detects visual teleportation, bounding box jitter, and temporal flickering across generated animation or video frames.
Example Request: Spatial Layout Check (cURL)
curl -X POST https://api.ejentum.com/logicv1/visual/verify-spatial \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"elements": [
{"x1": 10, "y1": 10, "x2": 150, "y2": 50, "label": "submit_button"},
{"x1": 20, "y1": 20, "x2": 140, "y2": 45, "label": "error_text"}
],
"max_overlap_iou": 0.20
}'
Example Response: Collision Detected
{
"status": "success",
"result": {
"is_valid": false,
"collision_count": 1,
"violations": [
"SpatialCollisionViolation: Elements submit_button and error_text overlap with IoU 0.65 exceeding threshold 0.20"
]
}
}
Endpoints: Distributed Session Checkpoints & Rollback
/logicv1/checkpoint/save
| /checkpoint/rollback | GET /checkpoint/{id}
State preservation and automatic rollback engine for long-horizon agent loops. When an invariant fails or an auditor rejects a plan, restores state to the last verified checkpoint before corruption occurs. Compatible with Memory, File, Redis, AWS S3, and Google Cloud Storage (GCS) backends.
Example Request: Save Checkpoint (cURL)
curl -X POST https://api.ejentum.com/logicv1/checkpoint/save \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"thread_id": "session_user_8912",
"state": {"step": 3, "status": "code_compiled", "files_modified": ["api.py"]},
"metadata": {"source_node": "implementer"}
}'
Example Request: Rollback 1 Step on Violation (cURL)
curl -X POST https://api.ejentum.com/logicv1/checkpoint/rollback \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"thread_id": "session_user_8912",
"steps": 1
}'
Endpoint: Self-Serve Free Trial Key Provisioning
/api/trial/request
(Alias: /trial/claim-key)
Instantly provisions an idempotent Free Trial API key (ej_trial_*) with a 1,000-call dynamic retrieval quota (100 req/day) and 30-day validity window. No credit card required. Rate-limited per IP (max 3 new trial keys per 24 hours).
Example Request (cURL)
curl -X POST https://api.ejentum.com/api/trial/request \
-H "Content-Type: application/json" \
-d '{"email": "developer@company.com"}'
Response Payload
{
"status": "success",
"key": "ej_trial_a1b2c3d4e5f6...",
"tier": "Trial",
"daily_limit": 100,
"total_quota": 1000,
"calls_used": 0,
"calls_remaining": 1000,
"expires_in_days": 30,
"already_issued": false
}
Endpoint: Consumer Intake Chat Gateway
/api/chat
Directly routes consumer and user inquiries to specialized domain intake skills, retrieves sub-2ms in-memory cognitive invariants, constructs an uncompromised 3-tier prompt, and returns an objective, honest synthesis.
Request Parameters
| Field | Type | Required | Description |
|---|---|---|---|
| query | string | Yes | The consumer prompt or inquiry being evaluated and synthesized. |
| model | string | No | Target model identifier (default: claude-sonnet-4.5). |
| provider | string | No | Provider: openrouter (default), anthropic, or openai. |
| mode | string | No | Reasoning mode (default: auto). |
| skill_override | string | No | Optional skill filename to bypass lexical routing (e.g. technical_troubleshooting.md). |
Example Request (cURL)
curl -X POST https://api.ejentum.com/api/chat \
-H "Content-Type: application/json" \
-d '{
"query": "Draft an aggressive, threatening email demanding an immediate refund for my broken sofa delivery.",
"model": "claude-sonnet-4.5"
}'
Response Payload
{
"status": "success",
"query": "Draft an aggressive, threatening email demanding an immediate refund for my broken sofa delivery.",
"skill_selected": "professional_composition.md",
"skill_domain": "Professional Composition",
"match_score": 12,
"ability_id": "CM-012",
"ability_name": "Conflict De-escalation Protocol",
"injected_invariants": ["CM-012", "MC-051", "CA-031"],
"engine_mode": "ejentum_offline_engine",
"model_used": "claude-sonnet-4.5",
"retrieval_latency_ms": 1.45,
"total_latency_ms": 4.12,
"response": "Subject: Formal Notice: Damaged Merchandise Delivery - Order #48291...",
"assembled_prompt": {
"system_prompt": "You are Ejentum Ask, a high-rigor consumer advisory agent...",
"user_prompt": "Draft an aggressive, threatening email demanding an immediate refund for my broken sofa delivery."
}
}
Endpoint: Skills Catalog Discovery
/api/skills
Returns all available modular consumer intake skills, their triggering keyword patterns, and associated cognitive invariant operations. No authentication required.
Example Request (cURL)
curl -X GET https://api.ejentum.com/api/skills
Model Context Protocol (MCP) Integration
Ejentum is natively compatible with Claude Desktop, Cursor, Windsurf, and any client supporting Anthropic's Model Context Protocol. Connect your client directly to our MCP endpoint:
{
"mcpServers": {
"ejentum": {
"url": "https://api.ejentum.com/mcp",
"headers": {
"Authorization": "Bearer YOUR_API_KEY"
}
}
}
}
LangGraph & Multi-Agent Swarm Guards
Drop-in nodes for LangGraph state machines. Automatically intercepts state transitions, evaluates evidence and handshake invariants, and rolls back state upon contract violation:
from langgraph.graph import StateGraph, START, END from ejentum import ( Ejentum, create_checkpoint_store, EjentumHandshakeNode, EjentumVisualGuardNode, ) # 1. Initialize distributed checkpointer (Redis, S3, GCS, or in-memory) checkpointer = create_checkpoint_store("redis", redis_url="redis://localhost:6379/0") # 2. Add Handshake Guard Node with automatic rollback on rejection handshake_node = EjentumHandshakeNode( preset="planner_implementer_auditor", contract_name="plan_approval_gate", checkpointer=checkpointer, auto_rollback_state=True ) # 3. Add Multi-Modal Visual Guard Node visual_node = EjentumVisualGuardNode( checkpointer=checkpointer, enforce_spatial=True, max_overlap_iou=0.20 ) workflow = StateGraph(dict) workflow.add_node("plan_step", planner_agent) workflow.add_node("handshake_guard", handshake_node) workflow.add_node("visual_guard", visual_node) workflow.add_edge("plan_step", "handshake_guard") workflow.add_edge("handshake_guard", "visual_guard") app = workflow.compile()
Embedded Local Engine (Sub-Millisecond Zero WAN)
Run the entire 311-ability cognitive engine completely in-process. With local=True, queries execute directly against the bundled precompiled SQLite FTS5 database with zero network overhead.
from ejentum import Ejentum # In-process zero-network client: sub-millisecond local SQLite FTS5 index client = Ejentum(local=True, cache_size=2048, cache_ttl=600.0) # Ultra-fast local retrieval: 0.005ms warm cache, <1.2ms cold search scaffold = client.scaffold("audit postgres migration lock contention") print(client.get_cache_stats()) # {'hits': 1, 'misses': 1, 'hit_ratio': 0.50}
@guard_tool Pre-Execution Interception Decorator
Wrap sensitive Python tool functions before execution to enforce temporal ordering constraints and runtime prerequisites. When an autonomous agent attempts a tool invocation, @guard_tool intercepts the call, validates state prerequisites against an in-process invariant graph, and halts unverified executions in under 2ms.
| Parameter | Type | Default | Behavior & Governance Rule |
|---|---|---|---|
| action | str | None | func.__name__ | Canonical action identifier recorded in the execution trace ledger. |
| requires_prior | str | None | None | Mandatory prerequisite action. Raises EjentumSecurityError if not already executed. |
| forbid_following | str | None | None | Prohibits tool execution if the specified action was previously recorded in the session. |
| raise_on_violation | bool | True | When True, raises an exception on invariant failure. When False, returns an invalid verdict object. |
| guard | TemporalGuard | None | default_guard | Optional isolated guard instance, recipe-based guard, or session-scoped state engine. |
from ejentum import guard_tool, TemporalGuard, get_temporal_recipe, EjentumSecurityError # 1. Enforce temporal prerequisites with zero runtime latency (<2ms) @guard_tool(action="validate_target_schema") def validate_schema(table_name: str) -> bool: # Verify indexes, row-level locks, and replication headroom return True @guard_tool(action="apply_schema_migration", requires_prior="validate_target_schema") def apply_migration(ddl: str) -> str: # Safe execution: only runs if validate_schema succeeded in this session return "Migration successfully applied" # 2. Unauthorized direct execution is blocked immediately before execution: try: apply_migration("ALTER TABLE users ADD COLUMN verified boolean;") except EjentumSecurityError as err: print(f"Blocked by Ejentum Pre-Flight Guard: {err}") # 3. Following invariant order clears execution gate: validate_schema("users") result = apply_migration("ALTER TABLE users ADD COLUMN verified boolean;") print(result) # 'Migration successfully applied'
DeadEndTracker & Session Memory (Negative-Constraint Trapping)
Multi-turn autonomous agents frequently fall into repetition traps: when a tool or endpoint fails, the LLM hallucinates slight variations of the same broken strategy, burning API tokens and looping endlessly. DeadEndTracker stores failed paths, error summaries, and invalid states in lightweight session memory, dynamically injecting a focused [PROHIBITED DEAD-END PATHS] block into prompt scaffolds to prune invalid search branches without context bloat.
Loop Prevention
Suppresses repetitive tool calls and attention drift by placing negative constraints directly in the agent reasoning window.
Zero Context Bloat
Retains only compact operational summaries (action identifier and error cause) rather than full multi-megabyte chat transcripts.
Zero Data Retention (ZDR)
No sensitive customer payloads or PII stored. Dead-end memory is ephemeral and bound strictly to active session IDs.
| Method / Property | Scope | Description |
|---|---|---|
| record(failed_action, error_summary, context=None) | DeadEndTracker | Logs a failed action and error reason into the active session negative ledger. |
| client.record_dead_end(session_id, failed_action, error_summary) | Ejentum | Direct client invocation to record a prohibited path for any arbitrary session. |
| client.scaffold(query, session_id=session_id) | Ejentum | Appends active [PROHIBITED DEAD-END PATHS] block directly to the cognitive scaffold. |
| clear() / client.clear_dead_ends(session_id) | Both | Resets the negative constraint ledger once target task or recovery state succeeds. |
from ejentum import Ejentum, DeadEndTracker client = Ejentum() tracker = DeadEndTracker(client=client, session_id="incident_triage_88") # 1. Agent attempts an action that fails at runtime try: # Simulated failed restart that cascaded connection exhaustion raise RuntimeError("Connection pool exhausted: 120 zombie client handles active") except RuntimeError as err: # Record negative constraint immediately in under 0.05ms tracker.record( failed_action="restart_pgbouncer", error_summary=str(err), context="high_connection_spike" ) # 2. Subsequent scaffold requests automatically inject prohibited constraints scaffold = client.scaffold( "Resolve database connection pool saturation", session_id="incident_triage_88" ) print(scaffold) # Output contains: # [PROHIBITED DEAD-END PATHS - DO NOT REPEAT] # - Action 'restart_pgbouncer' failed: Connection pool exhausted: 120 zombie client handles active # [END PROHIBITED PATHS]
ISO 42001 & SOC2 Audit Evidence Export
Enterprise production swarms require verifiable governance trails for ISO/IEC 42001 (Artificial Intelligence Management Systems) and SOC 2 Type II trust principles. Ejentum generates cryptographically signed attestation bundles that prove cognitive guardrails, handshake agreements, and dead-end memory were applied during agent execution while maintaining strict Zero Data Retention (ZDR).
| Bundle Field | Type | Audit Verification Role |
|---|---|---|
| schema_version | string | SDK bundle schema version (e.g. "1.9.0"). |
| compliance_framework | string | Target compliance standard specification ("ISO-42001-SOC2"). |
| summary | object | Aggregate counts of total_audit_events, guardrails_applied, and dead_ends_recorded. |
| audit_events | array | Chronological execution telemetry recording invariant checks, latency (ms), and pass/block status. |
| dead_end_ledger | object | Session-indexed ledger of recorded dead paths and negative constraints. |
| bundle_attestation | object | Cryptographic HMAC-SHA256 signature sealing summary, timestamp, and framework payload with your secret key. |
import hmac import hashlib import json from ejentum import Ejentum client = Ejentum(api_key="ej_live_production_key") # 1. Export signed compliance evidence bundle to disk bundle = client.export_audit_evidence( output_path="./audit/q4_iso42001_evidence.json", framework="ISO-42001-SOC2" ) print(f"Compliance Framework: {bundle['compliance_framework']}") print(f"Guardrails Enforced: {bundle['summary']['guardrails_applied']}") print(f"Dead-Ends Trapped: {bundle['summary']['dead_ends_recorded']}") # 2. Verify tamper-evident HMAC-SHA256 signature independently: canonical_payload = json.dumps( { "summary": bundle["summary"], "generated_at": bundle["generated_at"], "framework": bundle["compliance_framework"], }, sort_keys=True, separators=(",", ":") ).encode("utf-8") expected_sig = hmac.new( b"ej_live_production_key", canonical_payload, hashlib.sha256 ).hexdigest() is_valid = hmac.compare_digest(bundle["bundle_attestation"]["signature"], expected_sig) print(f"Cryptographic Signature Valid: {is_valid}") # True
Rate Limits, Status Codes & Reliability SLA
Ejentum is engineered for high-throughput autonomous agent swarms. Server-side lookups execute in <2ms using in-memory vector embeddings and binary SQLite FTS5 indexes (~90-150ms cross-region WAN).
| Status Code | Meaning | Production Recommendation |
|---|---|---|
| 200 OK | Successful cognitive scaffold retrieval. | Inject single_ability into model system prompt or agent context. |
| 401 Unauthorized | Missing or invalid API key. | Check EJENTUM_API_KEY environment variable or claim key via Stripe receipt. |
| 429 Too Many Requests | Tier rate limit reached (e.g. >120 req/min on standard tiers). | Implement exponential backoff with jitter or use the Python SDK's built-in fail_open=True fallback. |
| 500 / 502 / 503 | Temporary upstream or gateway unavailability. | Fail-Open: In mission-critical production loops, set a 1.5s-3.0s WAN timeout (or 150ms VPC timeout); if unreachable, log an alert and let the agent proceed un-augmented. |
from ejentum import Ejentum
client = Ejentum(timeout=3.0, fail_open=True) # Never blocks agent if network partitions
Production Resilience: Latency & Fail-Open Design
To prevent introducing a Single Point of Failure (SPOF) or compounding network round-trip latency into multi-step agent loops, adhere to these three production standards:
1. Fail-Open Timeouts
Set a strict client timeout (150ms for local VPC containers, or 1.5s-3.0s for cross-region WAN). With fail_open=True, if the network blinks, your agent proceeds un-augmented without crashing.
2. Local Container Option
For 30+ step agent chains where WAN round-trips (~90-150ms) accumulate, deploy the self-hosted SQLite FTS5 container for true <2ms local engine lookups.
3. Injection Demarcation
Wrap injected scaffolds in explicit boundary tags ([COGNITIVE SCAFFOLD]) to prevent untrusted downstream user input from overriding instructions.