Your data may be wrong.
The agent is still telling you exactly what it says.
A deterministic 5-gate firewall between AI agents and the databases people rely on. Verify math, wording, sources, and write integrity before a single record commits—in TypeScript or directly inside Claude and Cursor via MCP.
Strips prompt injections, invisible Unicode characters, and malicious scripts before text enters your pipeline.
Evaluates formulas and totals deterministically and blocks unsupported or overstated claims before write.
Separates AI drafts from official records, enforces monotonic state transitions, and gates promotions on human sign-off.
Verifies cited identifiers against trusted registries and seals exact source excerpts with SHA-256 hashes.
Reads every record back immediately after write to catch silent storage drift and append an immutable Merkle receipt.
The 5-Gate Governance Simulator
Interactive simulation demonstrating how the 5 gates evaluate incoming documents and mutations: stripping injections, enforcing algebraic consistency, and verifying read-back parity without write drift.
--- id: "trial_codebreak100_sotorasib" label: "ClinicalTrial" status: "PUBLISHED" phase: "Phase 2" drug: "Sotorasib (AMG 510)" target: "KRAS G12C (Switch-II pocket)" dose: "960 mg orally once daily" doi: "10.1038/s41392-021-00780-4" pmcid: "PMC8593166" nct_id: "NCT03600883" evaluable_patients: 124 complete_responses: 3 partial_responses: 43 stable_disease: 54 objective_responses: 46 objective_response_rate: 0.371 disease_control_rate: 0.806 median_pfs_months: 6.8 median_dor_months: 11.1 --- Sotorasib (AMG 510) is a first-in-class small-molecule inhibitor that specifically and irreversibly binds to the Switch-II pocket of KRAS(G12C). In the Phase 2 CodeBreak 100 trial (evaluable n=124 pretreated advanced NSCLC, 126 enrolled; 960 mg QD), confirmed objective response was observed in 46 patients (37.1%, including 3 CR and 43 PR). Disease control was achieved in 100 patients (80.6%), with a median progression-free survival of 6.8 months and median response duration of 11.1 months.
Downstream Agent Query: Accuracy Comparison
What happens when an autonomous agent reads the stored data? See how generic LLMs hallucinate vs. Nesatz's verified invariants.
Model Context Protocol Integration
Empower autonomous agents with deterministic governance over stdio. Connect Claude Code, Claude Desktop, Cursor, Antigravity, or Windsurf with zero external DB setup.
Two-Phase Mutation Protocol
Agents never write directly to the database. Mutations must pass preflight gate validation before receiving an execution token.
- Gate 1: Ingress sanitization & identifier checks passed
- Gate 2: AST semantics & modality rules confirmed
- Gate 3: BiomarkerFinding schema & 8-state lifecycle valid
- Gate 4: Source identifier verified via pluggable hook
blockingErrors + 256-bit proposalToken (.nesatz/ ledger; nesatz-mcp approve for ACTIVE){
"mcpServers": {
"nesatz": {
"command": "npx",
"args": ["-y", "@nesatz/mcp"],
"env": {
"NESATZ_ENABLE_MUTATION_TOOLS": "true",
"NESATZ_CLIENT_LABEL": "research_agent"
}
}
}
}--enable-mutations to unlock gated writes and nesatz-mcp approve for out-of-band sign-off.Built for Any Team Where AI Writes Facts People Rely On
Science and biotech were our first proving ground—but the same 5-gate pattern protects finance, legal, insurance, cybersecurity, supply chains, journalism, and enterprise knowledge bases.
propose_mutation or applyMutation with Gate 4 source hooks.DRAFT → ACTIVE; Gate 5 checks saved parity.Pharma & Biotech R&D
Extract clinical trial results from papers into a governed knowledge graph.
AI extracts: Response rates (ORR = CR + PR), dosing, endpoints, and trial metadata from PubMed & ClinicalTrials.gov.
Nesatz enforces: Gate 2 locks RECIST math (ORR = CR + PR, DCR >= ORR); Gate 4 binds PMCID/NCT IDs and SHA-256 excerpt hashes; medical affairs approves before ACTIVE.
Clinical Decision Support
Gate the curated knowledge base your CDS tool retrieves from—not just chat output.
AI extracts: Guideline summaries, dosing schedules, and drug-label interpretations.
Nesatz enforces: EpistemicAuditor modality rules block overclaiming ('cures', 'proves'); DeclarativeFormulaEvaluator checks dose bounds and unit fields before facts enter the retrieval store.
Investment & Equity Research
Verify earnings figures, segment sums, and accounting identities from filings.
AI extracts: Income statement metrics, segment breakdowns, and balance sheet extractions into analyst models.
Nesatz enforces: DeclarativeFormulaEvaluator checks segment revenues = total, grossProfit = revenue - COGS, and assets = liabilities + equity; span hashes anchor figures to the filing; analysts promote before client notes.
Legal & Contract Extraction
Block phantom case citations and verify contract payment schedules.
AI extracts: Case-law summaries, brief research notes, and extracted payment/obligation schedules.
Nesatz enforces: Gate 4 SourceVerifier hooks reject fabricated case citations; SHA-256 span hashes tie every quote to its passage; Gate 2 verifies payment schedules sum to contract total.
Insurance & Claims
Sanitize untrusted third-party claim files and enforce payout limits.
AI extracts: Claim summaries, line-item damage totals, and policy coverage assessments from PDFs and emails.
Nesatz enforces: Gate 1 strips hidden prompt injections from third-party PDFs/emails; Gate 2 enforces line items = claimed total and payout <= policyLimit; Gate 4 validates policy numbers against your system of record.
Cybersecurity & Threat Intel
Enforce least-privilege graph queries and require analyst sign-off on IOCs.
AI extracts: Threat graphs, attacker TTPs, and vulnerability links extracted from vendor advisories.
Nesatz enforces: Gate 1 sanitizes hostile report text; QueryValidator restricts which labels and relationships agents can traverse; Gate 4 anchors CVE IDs before an analyst promotes indicators to ACTIVE.
Academic Research & PKM
Keep Obsidian or Logseq vaults clean—never mix AI guesses with vetted notes.
AI extracts: Literature notes, YAML frontmatter, and wikilinked claims in local Markdown workspaces.
Nesatz enforces: DocumentStoreAdapter tracks CAS versions with built-in FileSystemDocumentDriver or custom Markdown vault drivers; DOI checks and quote excerpt hashes keep drafts separated until reviewed.
Journalism & Fact-Checking
Anchor dossier quotes to primary sources and flag overstated prose.
AI extracts: Background dossiers, timeline facts, and statistical summaries for reporters.
Nesatz enforces: Gate 2 modality rules flag claims stronger than the source supports; Gate 4 binds quotes to exact source locators and hashes; editors act as designated reviewers before CMS publication.
Supply Chain & Manufacturing
Reconcile invoices, bills of lading, and maintenance logs with zero write drift.
AI extracts: Quantities shipped vs. ordered, line totals, and part maintenance records.
Nesatz enforces: Gate 2 checks shipped <= ordered and line-item totals; Gate 5 read-back parity catches silent type coercion on write. (Use GraphStoreAdapter/DocumentStoreAdapter today; TabularStoreAdapter arrives in v1.1.)
Customer Support & Enterprise KBs
Turn support tickets into vetted help articles—and retire old policies cleanly.
AI extracts: Draft troubleshooting articles and policy summaries mined from user tickets.
Nesatz enforces: Gate 1 treats tickets as untrusted input to block hidden injections; articles land in DRAFT until product owners promote them to ACTIVE; policy updates mark old claims SUPERSEDED or STALE instead of deleting history.
Humanities, Archives & Museum Provenance
Protect exact historical quotes, scholarly nuance, chronology, and artifact ownership history.
AI extracts: Transcribed passages, literary interpretations, archive footnotes, timeline events, and museum provenance chains.
Nesatz enforces: Gate 4 span hashes block even single-word quote edits; EpistemicAuditor flags overstated prose ('suggests' vs. 'proves'); DeclarativeFormulaEvaluator orderings enforce chronology (e.g. letterYear <= deathYear); and auction rumors stay in DRAFT until an archivist approves ACTIVE.
@nesatz/core stays strictly domain-agnostic. Register any async SourceVerifier hook in configureNesatz({ sourceVerifiers, allowedRegistries })—whether you are checking PubMed / ClinicalTrials.gov / DOI, JSTOR / WorldCat / museum catalogs, SEC EDGAR filings, CourtListener case law, NVD CVEs, or your internal insurance policy API.
Where Each Verification Check Runs
A sequential verification pipeline ensuring only structurally sound, mathematically proven, and source-grounded data enters canonical storage.
Descending From Human Common Sense to Cryptographic Bedrock
Data moves from simple, human-understandable perimeter hygiene at the summit down into rigorous mathematical solvers and cryptographic ledger proofs at the foundation.
Strips hidden prompt injection attacks, invisible Unicode characters, and malicious scripts before the agent reads them.
SourceVerifier hooks, PubMed/NCT/DOI resolution, and SHA-256 excerpt hashes.EpistemicAuditor flag unhedged claims, while syntax sanitization, schema constraints, mathematical ASTs, and read-back parity are strictly deterministic with zero ML model dependencies.Ingress & Syntax Sanitization
Perimeter ingress & syntax sanitization — Strips invisible Unicode attacks, control bytes, and prompt injection scripts.
Enforced Safeguards
TypeScript API Usage
// 1. Deterministic Syntax Sanitization & URL Allowlist
const result = InputSanitizer.sanitize(rawDocumentText, 'untrusted');
if (result.blocked) throw new SecurityError('Adversarial syntax detected');
if (!InputSanitizer.isAllowedUrl(citationUrl)) throw new SecurityError('Unallowed domain');
// 2. Cypher AST Validation (Graph Traversal)
QueryValidator.validateCypher(agentQuery, {
bannedLabels: ['RestrictedEntity', 'InternalAudit'],
allowedRelationships: ['INHIBITS', 'TARGETS', 'INDICATES']
});Universal Verified Storage
A domain-agnostic graph substrate. Back verified nodes in Neo4j or zero-infra memory, persist atomic JSON/Markdown vaults locally, or extend cleanly via the EpistemicStore contract.
Verified Graph Store
Content-addressed DAG supporting monotonic revisions, UUIDv5 identifiers, pluggable ReadInterceptor / WriteInterceptor middleware with prototype-preserving RedactedRecord proxying, and bidirectional traversal.
Document Store Adapter
Human-in-the-loop interoperability with built-in FileSystemDocumentDriver and InMemoryDocumentDriver, or custom DocumentDriver bindings for Logseq/Obsidian Markdown vaults.
Tabular Store Adapter
Sibling @nesatz/adapter-tabular package (staged in deferred/v1.1/storage/) for SQLite, DuckDB, and Postgres row projections.
import { InMemoryGraphExecutor, GraphStoreAdapter, Neo4jExecutor, SovereignWriter } from "@nesatz/core";
// 1. Zero-dependency in-memory graph backend (or await Neo4jExecutor.createAsync(...) in production)
const executor = new InMemoryGraphExecutor();
const writer = new SovereignWriter(executor, {
validateNode: () => ({ valid: true, errors: [], warnings: [] })
});
// 2. Or query any graph backend via the universal EpistemicStore CAS contract
const store = new GraphStoreAdapter(executor);
const entity = await store.getEntity("claim:trial-091");
const relations = await store.getRelations("claim:trial-091", "both");Governing LM Studio, Desktop Agents & Free APIs
You don't need a graph database or cloud infrastructure to eliminate prompt injection and hallucinations. Wrap any OpenAI-compatible desktop agent or free cloud API with an offline pre-flight and post-flight safety firewall in 15 lines of code.
Syntax clean: Zero invisible characters, zero prompt injections, clean text structure.
“In the Phase 2 CodeBreaK 100 trial (NSCLC cohort, n=124 evaluable), confirmed ORR was 37.1% (95% CI: 28.6%–46.2%) with 3 complete responses (2.4%) and 43 partial responses (34.7%).”
Modality hedged: Response rates cite primary confidence intervals, math tallies sum consistently (3 + 43 = 46).
import { InputSanitizer, EpistemicAuditor } from "@nesatz/core";
// 1. Point to LM Studio (localhost:1234) or Free Gemini/Groq API (1-line toggle)
const ENDPOINT = "http://localhost:1234/v1/chat/completions";
const API_KEY = "lm-studio";
export async function askGovernedAgent(userPrompt: string) {
// GATE 1: Pre-flight Ingress Filter (Blocks prompt overrides & zero-width unicode)
const ingress = InputSanitizer.sanitize(userPrompt, "untrusted");
if (ingress.blocked) {
return { blocked: true, output: "Blocked: Prompt injection detected." };
}
// DISPATCH: Works identically across LM Studio, Gemini, Groq, or OpenAI
const res = await fetch(ENDPOINT, {
method: "POST",
headers: { "Content-Type": "application/json", Authorization: `Bearer ${API_KEY}` },
body: JSON.stringify({
model: "local-model",
messages: [{ role: "user", content: ingress.sanitized }]
})
});
const data = await res.json();
const rawResponse = data.choices[0].message.content;
// GATE 2: Post-flight Claim & Math Audit (Flags unhedged 'cures' & temporal prophecies)
const auditFailures = await EpistemicAuditor.audit(rawResponse);
return {
blocked: false,
output: rawResponse,
auditBadge: auditFailures.length === 0 ? "[AUDIT PASS]" : "[FLAGGED]"
};
}Architectural Guarantees & Production Triage
How enterprise pipelines enforce mathematical invariance on ingestion while preserving sub-10ms read performance without alert fatigue.
Zero Write Drift
Post-write property parity check immediately compares persisted storage state against authorized mutation payloads, detecting any silent database schema coercion.
Sub-10ms Read Latency
Verification executes fail-closed on the write-path. User-facing dashboards and reports render already-attested cryptographic receipts with zero live query overhead.
Monotonic State Machine
Claims progress strictly through 8 canonical states (DRAFT → UNDER_REVIEW → ACTIVE, guarded downward states NARROWED, STALE, SUSPENDED, and terminal absorbing states REVOKED, SUPERSEDED). State skips are blocked by design.
Cryptographic Provenance
Every assertion binds to an exact text locator and SHA-256 excerpt hash. Tampering with a single punctuation mark immediately trips GATE4_SPAN_HASH_MISMATCH.
When to Gate vs. When to Render Pure Prose
Attaching cryptographic hashes to every metaphor creates false precision and alert fatigue. Nesatz triages content into three pragmatic tiers.
Pivotal response rates (ORR), hazard ratios (HR), survival statistics (PFS, OS), or cohort sizes where clinical or capital bets are made.
Full 5-Gate Trace: Gate 2 deterministic AST solver verifies clinical tallies (nORR = nCR + nPR, DCR ≥ ORR); Gate 4 anchors exact SHA-256 excerpt hash.
Displays the “Grounded by Nesatz” cryptographic receipt sidebar directly adjacent to the quantitative claim.
“Most grounded RAG systems rely on asking an LLM to cite sources faithfully. In practice, models paraphrase quotes, hallucinate PMIDs, or invert clinical fractions (nORR ≠ nCR + nPR). Nesatz shifts monographs from standard editorial essays into cryptographically attested scholarly artifacts. Tampering with even a single punctuation mark immediately trips GATE4_SPAN_HASH_MISMATCH.”
Quickstart in 60 Seconds
Add a zero-drift deterministic firewall to any Node.js, Next.js, or Bun application in just a few lines of TypeScript.
import {
SovereignWriter,
InMemoryGraphExecutor,
InputSanitizer
} from "@nesatz/core";
// 1. Initialize zero-dependency in-memory graph backend & minimal pass-through guard
const backend = new InMemoryGraphExecutor();
const writer = new SovereignWriter(backend, {
validateNode: () => ({ valid: true, errors: [], warnings: [] })
});
// 2. Deterministically sanitize raw text ingress (Gate 1)
const sanitized = InputSanitizer.sanitize("Sotorasib Phase 2 CodeBreak 100 trial outcome");
if (sanitized.blocked) {
throw new Error("Ingress text blocked by syntax sanitizer");
}
// 3. Construct an attested mutation with span-level provenance
const mutation = SovereignWriter.createAttestedSeed({
targetId: "trial:sotorasib-codebreak100",
targetLabel: "ClinicalTrial",
curatorId: "curator:dr-alice",
source: {
registry: "PubMed",
id: "PMC8593166",
doi: "10.1038/s41392-021-00780-4",
locator: "Section 3.2, Table 1",
excerptHash: "sha256:5d8526bb8fdb323b8f7a76e1c4e01e69914f50f8f37e37f25c3001292bb5ec83"
},
properties: {
summary: sanitized.sanitized,
name: "CodeBreak 100 (KRAS G12C)",
evaluablePatients: 124, // 126 enrolled; 124 evaluable per RECIST 1.1
completeResponses: 3,
partialResponses: 43,
objectiveResponseCount: 46, // RECIST invariant: ORR Count = CR (3) + PR (43) = 46
diseaseControlRate: 0.806, // Hierarchy invariant: DCR (80.6%) >= ORR (37.1% = 46/124)
status: "PUBLISHED"
}
});
// 4. Preflight dry-run, atomic commit, and read-back drift detection (Gates 2-5)
const result = await writer.applyMutation(mutation);
if (result.success) {
console.log("Committed to graph with Merkle txHash:", result.txHash, "opLogId:", result.opLogId);
} else {
console.error("Mutation blocked by validation gates:", result.code, result.message, result.gate3Report?.conflicts);
}