Skip to content
Projekte

Über uns

Agentic memory for CTI in Python — STIX knowledge graphs, threat-actor alias resolution, offline-first RAG, MCP server for Claude Code and LangChain agents

Entwicklerwerkzeuge

So werden diese Zahlen gemessen

Gemessener Sternzuwachs

in 24h
0
in 7 days
+1
in 15 days
+2
in 1 month
Verlauf wird gesammelt

Nettoänderungen in überlappenden Zeiträumen, keine Tagessummen. Fehlende Messwerte bleiben leer. Sterne zeigen Interesse, nicht Qualität.

README.md

Original

ZettelForge

The only agentic memory system built for cyber threat intelligence.

When a senior analyst leaves, two or three years of context walks out with them — customer environments, prior investigations, actor TTPs, false-positive patterns, every hard-won "wait, we've seen this before." ZettelForge is an agentic memory system built so that context stays with the team.

It extracts CVEs, threat actors, IOCs, and ATT&CK techniques from analyst notes and threat reports, resolves aliases (APT28 = Fancy Bear = STRONTIUM = Sofacy), builds a STIX 2.1 knowledge graph, and serves every past investigation back to your analysts — and to Claude Code via MCP — in natural language. Runs entirely in-process. No API keys. No cloud. No data leaves the host.

PyPI Downloads/month Python 3.11+ License: MIT CI Open Issues Ask DeepWiki

Star · pip install zettelforge · Docs · ThreatRecall (hosted) · Changelog

v2.9.0 (2026-12-02): Ships RFC-008 Memory Salience, Spacing Effects & Tiered Decay (Von Restorff salience scoring, spacing reinforcement, HOT/WARM/COLD/FROZEN tiers), Spec 002 CTI Hardening (end-to-end TLP 2.0 filtering + fail-closed cloud-LLM egress guard, 3-way Vector + Graph + SQLite FTS5 BM25 hybrid retrieval, 106 bundled MITRE ATT&CK/MISP aliases, non-mutating IOC refanging + IPv6/CIDR/ASN/YARA extractors, temporal edge validity, crash-safe enrichment replay, and strict citation verification), an opt-in Neo4j path-query backend (pip install zettelforge[neo4j]), a zero-config npm MCP wrapper (npx --yes zettelforge), typed DetectionMeta + Sigma rule ID extraction, and Python 3.11+ security updates. Full changelog

ZettelForge demo -- CTI agentic memory in action

If ZettelForge fits a CTI workflow you run, a star is the fastest signal that this category is worth continuing to invest in.

Upgrading to 2.9.0

Use Python 3.11 or newer and a fresh virtual environment. No manual database migration is required — new SQLite columns and the CTI-friendly FTS5 index backfill automatically on open. This security update temporarily disables Maigret username discovery until upstream supports patched dependencies; other OSINT collectors remain available. See the security and upgrade notes.

The problem

Every SOC loses analysts. When they leave, investigation context, actor attribution, and environment-specific false-positive patterns go with them. Their replacements re-open the same tickets, re-read the same reports, and re-build the same mental models from scratch.

General-purpose AI memory systems don't fix this for security teams. They can't tell APT28 from Fancy Bear, don't know that CVE-2024-3094 is the XZ Utils backdoor, can't parse Sigma or YARA, and have no concept of MITRE ATT&CK technique IDs or TLP sharing boundaries. When a CTI analyst gives them a year of intel reports, they get back fuzzy semantic search over chat history.

ZettelForge was built for analysts who think in threat graphs. It extracts CVEs, threat actors, IOCs (including defanged indicators), and ATT&CK techniques automatically, resolves aliases across naming conventions, builds a temporally validated STIX 2.1 knowledge graph with causal relationships, enforces TLP 2.0 boundaries, and retrieves memories using 3-way intent-aware hybrid search -- all in-process, with no external API dependency.

Memory augmentation closes 33% of the gap between small and large models on CTI tasks (CTI-REALM, Microsoft 2026, using GPT-4 as the large-model baseline). See full benchmark report for methodology and comparisons.

Capability ZettelForge Mem0 Graphiti Cognee
CTI entity extraction & IOC refanging (24 types) Yes No No No
STIX 2.1 ontology & temporal edge validity Yes No Partial No
Threat actor alias resolution Yes (106 bundled MITRE/MISP aliases) No No No
3-way hybrid search (Vector + Graph + CTI FTS5 BM25) Yes No No No
TLP 2.0 read filtering & fail-closed cloud egress guard Yes No No No
Knowledge graph with causal triples Yes No Yes Yes
Intent-classified retrieval (5 types) Yes No No No
In-process / no external API required Yes No No No
Audit logs in OCSF schema Yes No No No
MCP server (Claude Code / Desktop) Yes No No No

Data Pipeline

ZettelForge architecture -- neural recall loop: ingest, enrich, retrieve, synthesize, backed by SQLite + LanceDB

Features

Entity Extraction & IOC Refanging -- Automatically identifies 24 entity types across regex (18 CTI/IOC types) and LLM NER (6 conversational types): CVEs, intrusion sets, threat actors, tools, campaigns, ATT&CK techniques, Sigma rule IDs (sigma_rule), YARA rules (yara_rule), IOCs (ipv4, ipv6, cidr, asn, domain, url, md5, sha1, sha256, email), people, locations, organizations, events, activities, and temporal references. Common defanged observables (hxxp://, [.], [@], [:]) are refanged during extraction without mutating raw note text, and STIX 2.1 types are preserved throughout.

TLP 2.0 Governance & Fail-Closed Synthesis Egress Guard -- Enforces Traffic Light Protocol ceilings (TLP:CLEAR through TLP:RED, fail-closed on unknown markings or ceilings) across recall(), recall_entity(), recall_actor(), get_context(), synthesize(), traverse_graph(), get_entity_relationships(), provenance_chain(), and MCP tools. Synthesis responses carry high-water-mark TLP annotations, and TLPEgressViolationError blocks TLP:AMBER+STRICT and TLP:RED notes from being sent during synthesize() to cloud LLM providers (including fallback providers such as litellm) unless explicitly overridden via ZETTELFORGE_CLOUD_MAX_TLP (for strict zero-cloud-egress handling across ingestion, remember(evolve=True), remember_report(), and background enrichment, configure a local LLM provider with no cloud fallback).

Knowledge Graph, Temporal Validity & Opt-in Neo4j Path-Finding -- Entities become nodes, co-occurrence becomes edges, and non-routable IP/CIDR ranges (RFC 1918, loopback, link-local, documentation) are suppressed so internal addresses never become cross-incident hubs. Edges carry TLP provenance and enforce temporal validity (valid_from, valid_until, revoked) across standard and causal traversals. SQLite is the zero-config system of record; optionally enable Neo4j (pip install zettelforge[neo4j], ZETTELFORGE_NEO4J_PATHFINDING=true) with the standalone sync job (python -m zettelforge.scripts.neo4j_sync) for ~20x faster undirected shortest-path queries.

Bundled MITRE ATT&CK / MISP Alias Resolution -- Ships with 106 bundled threat-actor and tool alias mappings (src/zettelforge/data/cti_aliases.json) so APT28, Fancy Bear, Sofacy, and STRONTIUM resolve to the same canonical node automatically on store and recall in zero-config SQLite mode. Customize or override locally via ~/.amem/entity_aliases.json.

3-Way Hybrid Retrieval + Salience, Spacing & Tiered Decay (RFC-008) -- Fuses three retrieval channels weighted by 5-type intent classification (factual, temporal, relational, causal, exploratory): 768-dim fastembed vector similarity (ONNX), BFS knowledge-graph traversal, and a synchronized CTI-friendly SQLite FTS5 BM25 index (unicode61 tokenchars '._-:/\' preserving Windows registry paths, mutexes, CLI flags, filenames, and hashes, with automatic local FTS5 fallback when vector retrieval stalls or errors). Results are ranked with Von Restorff salience scoring, spacing-effect reinforcement (reinforce_note()), HOT/WARM/COLD/FROZEN lifecycle tiers (refresh_memory_tiers()), and cross-encoder reranking. Authoritative/durable CTI notes (Tier A, CISA KEV, detection rules, and knowledge semantics) are capped at COLD and never auto-frozen.

Memory Evolution -- With evolve=True, new intel is compared to existing memory. LLM decides ADD, UPDATE, DELETE, or NOOP. Stale intel gets superseded. Contradictions get resolved. Duplicates get skipped.

Write-Time, Prompt-Injection & Citation Defenses -- CTI-calibrated deterministic prompt-injection guardrails (AGE-127) across remember/recall/synthesis boundaries (allowing legitimate analyst prose like bypass firewall/Sigma rules and TTP playbooks while blocking adversarial injections), MemSAD-inspired write-time memory anomaly defense (audit / block / quarantine), optional Microsoft Presidio PII detection (pip install zettelforge[pii]), and opt-in synthesis citation grounding via validate_synthesis() / SynthesisValidator.verify_citations() checking both structured source lists and inline [note_...] text citations.

Crash-Safe Enrichment Ledger -- Background causal extraction, LLM NER, and neighbor evolution jobs are tracked in the SQLite RFC-018 enrichment ledger (enrichment_jobs). On startup, replay_orphaned_enrichment_jobs() recovers abandoned queued/running jobs with atomic durable worker ownership claims (preventing duplicate execution across concurrent managers), oldest-first paging across large backlogs, bounded retries (dead_lettered / cancelled), and live ledger health in get_stats().

Passive & Live OSINT Enrichment -- Opt-in RFC-016 OSINT executor (pip install zettelforge[osint]) enriches domains, IPs, ASNs, netblocks, emails, aliases, and crypto wallets into the knowledge graph with canonical entity resolution.

RAG Synthesis -- Synthesize answers across all stored memories with direct_answer, synthesized_brief, timeline_analysis, or relationship_map formats, high-water-mark TLP markings, and opt-in source citation verification via validate_synthesis().

In-process by architecture -- fastembed (ONNX) for embeddings, llama-cpp-python or onnxruntime-genai for optional local LLM inference, SQLite (WAL + FTS5) + LanceDB for storage, and Ollama on localhost by default (or 100+ providers via pip install zettelforge[litellm]). No external API keys are required. Outbound network access may occur on first run when embedding/LLM models are downloaded; after models are preloaded, it can run fully offline (including on air-gapped hosts).

Audit logging in OCSF schema -- Every operation emits a structured event in the Open Cybersecurity Schema Framework format. What you do with the log stream (SIEM, WORM store, nothing) is up to you.

Quick Start

30-second hello world (no LLM required)

pip install zettelforge
from zettelforge import MemoryManager
from zettelforge.note_schema import Metadata

mm = MemoryManager()

# Store CTI -- entities (CVEs, actors, ATT&CK IDs, defanged IOCs) extracted via regex
mm.remember("APT28 uses Cobalt Strike for lateral movement via T1021 and C2 hxxps://c2[.]example[.]org/stage2")
mm.remember("APT28 (Fancy Bear) targets NATO defense contractors with spear-phishing")
mm.remember(
    r"Implant creates mutex Global\CobaltMutex_9f2 before beacon check-in",
    domain="cti",
    metadata=Metadata(domain="cti", tlp="TLP:GREEN"),
)

# 3-way hybrid recall (vector + graph + FTS5 BM25) with alias resolution and TLP filtering
for note in mm.recall("What tools does Fancy Bear use?", k=3, max_tlp="TLP:AMBER"):
    print(f"[{note.metadata.tier} | {note.metadata.tlp}] {note.content.raw}")

# Exact CTI artifact lookup powered by synchronized SQLite FTS5 BM25
for note in mm.recall(r"Global\CobaltMutex_9f2", k=3):
    print(note.content.raw)

That works on a fresh pip install with no external services. Embeddings run in-process via fastembed (~80MB ONNX model downloaded on first call). MemoryManager() writes to ~/.amem/ by default; override with AMEM_DATA_DIR or via config. A runnable copy lives at examples/quickstart.py.

Add an LLM for synthesis and richer extraction

ollama pull qwen3.5:9b && ollama serve
# With Ollama running, synthesize() returns a TLP-annotated summary across stored notes
answer = mm.synthesize("Summarize known APT28 TTPs", max_tlp="TLP:AMBER")
print(answer["metadata"]["tlp"], answer["synthesis"]["answer"])
# Background LLM NER also enriches stored notes with additional entities

ZettelForge auto-detects Ollama. To use a different provider (local llama-cpp or onnxruntime-genai, litellm for 100+ providers, mock for tests), see Configuration. Without an LLM, synthesize() still returns a structured response but the answer field is a fallback placeholder -- only remember and recall produce useful results in pip-only mode.

Memory Evolution

# New intel arrives -- evolve=True enables memory evolution:
# LLM extracts facts, compares to existing notes, decides ADD/UPDATE/DELETE/NOOP
mm.remember(
    "APT28 has shifted tactics. They dropped DROPBEAR and now exploit edge devices.",
    domain="cti",
    evolve=True,   # existing APT28 note gets superseded, not duplicated
)

How It Works

Every remember() call triggers a pipeline:

  1. Governance & Security Validation -- input validation, CTI-calibrated AGE-127 prompt-injection guard, optional Presidio PII scan, and MemSAD write-time anomaly scoring
  2. Entity Extraction & IOC Refanging -- non-mutating IOC refanging + regex and LLM NER extract 24 entity types (CVEs, intrusion sets, threat actors, tools, campaigns, ATT&CK techniques, Sigma/YARA rules, IPv4/IPv6/CIDR/ASN, domains, URLs, MD5/SHA1/SHA256, emails, people, locations, organizations, events, activities, temporal references) and resolve aliases against the bundled MITRE/MISP table
  3. Knowledge Graph & Salience Update -- entities become nodes (suppressing non-routable IP/CIDR hubs), edges record TLP provenance and temporal bounds, Von Restorff salience score is computed, and LLM infers causal triples
  4. Vector + Lexical Indexing -- 768-dim fastembed (ONNX, in-process, 7ms/embed) stored in LanceDB alongside an O(1)-maintained CTI-friendly SQLite FTS5 BM25 index
  5. Supersession Check -- entity overlap detection marks stale notes as superseded
  6. Dual-Stream Write & Crash-Safe Ledger -- fast path returns in ~45ms; causal enrichment and LLM NER are recorded with durable worker ownership in the SQLite enrichment ledger, deferred to a background worker, and automatically replayed on startup after crashes (when ZETTELFORGE_ENRICHMENT_ENABLED=true)

Every recall() call blends three retrieval channels:

  1. Vector similarity -- semantic search over fastembed embeddings in LanceDB
  2. Graph traversal -- BFS over knowledge-graph edges filtered by temporal validity (valid_from/valid_until/revoked) and max_tlp, scored by hop distance
  3. Lexical BM25 (SQLite FTS5) -- exact-token CTI artifact matching (mutexes, registry paths, CLI flags, hashes, filenames), with automatic local FTS5 fallback if vector retrieval stalls or fails
  4. Intent routing -- query classified as factual/temporal/relational/causal/exploratory, weights adjusted per channel
  5. Salience, Spacing & Tiered Decay (RFC-008) -- post-fusion salience boost, spacing-effect memory strength, and HOT/WARM/COLD/FROZEN tier multipliers (frozen notes excluded; durable CTI notes capped at COLD)
  6. Cross-encoder reranking & governance filtering -- ms-marco-MiniLM reorders top candidates, with superseded-note exclusion (exclude_superseded=True) and TLP 2.0 ceiling enforcement (max_tlp)

Use ZettelForge in Claude Desktop / Claude Code in 60 seconds

Option A: Zero-config via npm (npx)

Requires uv (recommended) or Python 3.11+ with zettelforge installed. Add to your MCP client configuration (.claude.json, ~/.claude/.claude.json, or Claude Desktop config):

{
  "mcpServers": {
    "zettelforge": {
      "command": "npx",
      "args": ["--yes", "zettelforge"]
    }
  }
}

Option B: Direct Python entrypoint (pip install zettelforge)

pip install zettelforge

Create or edit .claude.json in your project root (or ~/.claude/.claude.json for global access):

{
  "mcpServers": {
    "zettelforge": {
      "command": "python3",
      "args": ["-m", "zettelforge.mcp"]
    }
  }
}

If ZettelForge is installed in a virtual environment, use the full path to that Python interpreter:

{
  "mcpServers": {
    "zettelforge": {
      "command": "/home/user/.venvs/zettelforge/bin/python",
      "args": ["-m", "zettelforge.mcp"]
    }
  }
}

Start Claude Code and verify the tools are available:

claude
# Inside the session, ask: "What tools do you have available from zettelforge?"

Seven tools are exposed: zettelforge_remember, zettelforge_recall (excludes superseded notes by default and returns full provenance metadata), zettelforge_synthesize (returns high-water-mark tlp), zettelforge_entity (21 entity types with alias-aware actor routing), zettelforge_graph, zettelforge_stats, and zettelforge_sync (requires enterprise package). All read and graph tools (zettelforge_recall, zettelforge_entity, zettelforge_synthesize, zettelforge_graph) accept an optional max_tlp ceiling. See the MCP protocol reference for full schemas, JSON-RPC request/response examples, error codes, and the lazy-singleton lifecycle. For troubleshooting, virtualenv paths, and manual tool testing, see set-up-mcp-server.

Benchmarks

Evaluated against published academic benchmarks:

Benchmark What it measures Score
CTI Retrieval (CTIBench subset) Attribution, CVE linkage, multi-hop 75.0%
RAGAS Retrieval quality (keyword presence) 78.1%
LOCOMO (ACL 2024) Conversational memory recall 22.0%

The Score column reports ZettelForge measurements run with Ollama-hosted models, with one exception: the LOCOMO row was re-measured at v2.1.1 using an Ollama cloud judge for evaluation grading (not local generation). See the full benchmark report for benchmark-specific methodology, version history, and per-suite judge configuration.

Detection Rules as Memory (Sigma + YARA)

Sigma and YARA rules are first-class memory primitives. Parse, validate, and ingest a rule and its tags become graph edges: MITRE ATT&CK techniques, CVEs, threat-actor aliases, tools, and malware families resolve against the same ontology as every other note. A shared DetectionRule supertype carries SigmaRule and YaraRule subtypes, so a single rule UUID is addressable across both formats.

Sigma rules are validated against the vendored SigmaHQ JSON schema. YARA rules are parsed with plyara and checked against the CCCS YARA metadata standard (tiers: strict, warn, non_cccs). Ingest is idempotent -- re-ingesting an unchanged rule returns the original note via a content-hashed source_ref.

from zettelforge import MemoryManager
from zettelforge.sigma import ingest_rule as ingest_sigma
from zettelforge.yara import ingest_rule as ingest_yara

mm = MemoryManager()
ingest_sigma("rules/proc_creation_win_office_macro.yml", mm)
ingest_yara("rules/webshell_china_chopper.yar", mm, tier="warn")
# Bulk ingest from SigmaHQ or a private rule repo
python -m zettelforge.sigma.ingest /path/to/sigma/rules/
python -m zettelforge.yara.ingest /path/to/yara/rules/ --tier warn

# CI fixture check -- parse + validate, no writes
python -m zettelforge.sigma.ingest rules/ --dry-run

An LLM rule explainer (zettelforge.detection.explainer.explain) produces a structured JSON summary -- intent, key fields, evasion notes, false-positive hypotheses -- for any DetectionRule. It runs synchronously on demand in v1; async enrichment-queue wiring is v1.1. Rate-limited via ZETTELFORGE_EXPLAIN_RPM (default 60 calls/minute).

References: Sigma spec, SigmaHQ rules, CCCS YARA, YARA docs.

Integrations

ATHF (Agentic Threat Hunting Framework)

Ingest completed ATHF hunts into ZettelForge memory. MITRE techniques and IOCs are extracted and linked in the knowledge graph.

python examples/athf_bridge.py /path/to/hunts/
# 12 hunt(s) parsed
# Ingested 12/12 hunts into ZettelForge

See examples/athf_bridge.py.

ThreatRecall (Hosted)

ThreatRecall is the commercial distribution of ZettelForge with enterprise extensions enabled. It is offered as managed SaaS by default, with optional self-hosted on-prem and air-gapped deployments for classified environments. Enterprise add-ons:

  • TypeDB STIX 2.1 backend -- schema-enforced ontology with inference rules
  • OpenCTI sync -- bi-directional sync with your OpenCTI instance
  • Multi-tenant auth -- OAuth/JWT with per-tenant data isolation
  • Sigma rule generation -- detection rules from extracted IOCs (upcoming)

SaaS deploys in minutes with no infrastructure to maintain. Self-hosted ships as a deployable bundle for environments where outbound network egress is restricted or prohibited.

Join the waitlist -- currently onboarding design partners.

Configuration

Variable Default Description
AMEM_DATA_DIR ~/.amem Data directory
ZETTELFORGE_BACKEND sqlite SQLite community backend. TypeDB available via enterprise extension.
ZETTELFORGE_LLM_PROVIDER ollama ollama (default), local (llama-cpp-python or onnxruntime-genai), litellm, or mock
ZETTELFORGE_CLOUD_MAX_TLP TLP:AMBER Maximum TLP sensitivity allowed for synthesize() calls to cloud LLM providers (TLP:AMBER+STRICT/TLP:RED blocked fail-closed)
ZETTELFORGE_ENRICHMENT_ENABLED true Enable/disable background enrichment worker and startup replay of orphaned ledger jobs
ZETTELFORGE_NEO4J_PATHFINDING false Route find_shortest_path() to Neo4j (pip install zettelforge[neo4j]); storage stays SQLite

See config.default.yaml and the Configuration Reference for all options.

Contributing

See CONTRIBUTING.md for development setup.

License

MIT -- See LICENSE.

Built by Patrick Roland -- LinkedIn | Director of SOC Services, Summit 7 Systems | Navy nuclear veteran | CISSP, CCP (CMMC 2.0 Professional)

Support the Project

ZettelForge is MIT-licensed. Star the repo, open issues, and submit PRs — all contributions are welcome.

Acknowledgments

Ähnliche Projekte entdecken

Wird geladen…