---
name: knowledge-graph-memory
description: >
  Constructs a durable, typed property graph from unstructured documents and agent conversations to serve as persistent, cross-session shared memory for multi-agent systems. Uses schema-constrained LLM calls (not a trained NLP pipeline) to extract typed entities and subject-predicate-object relations, then resolves aliases into canonical entities using contextual description rather than string matching. Every node and edge carries provenance, and resolution is additive and reversible rather than destructive. Use this whenever the user wants agents to share facts across sessions without re-reading every source document, build a persistent world model, deduplicate entities across documents or conversations, or let independent agents publish findings to a common structure instead of each rebuilding context from scratch. Trigger on phrases like "build a knowledge graph," "give agents shared memory," "resolve these entities/aliases," "persist facts across sessions," "turn these documents into a graph," or "stop agents from rebuilding the world every time." The natural companion to swarm-orchestration (workers publish structured graph updates as their evidence contract) and ratchet-loop (the extraction prompt and resolution policy are themselves valid ratchet-loop targets, optimized against entity/relation F1 and resolution precision/recall).
---

# Knowledge Graph Memory Skill

## Overview
A loop externalizes iteration. A swarm externalizes parallel search. This skill externalizes **shared memory**: a durable, typed graph that lets independent agents — across sessions, across context windows, across a whole swarm — read and write a common world model instead of each rebuilding it from scratch out of raw transcripts.

The core move is replacing a classical NLP pipeline (trained NER, trained relation classifiers) with schema-constrained LLM calls. A Pydantic schema is the only "training data" required: one model call extracts typed entities and relations from a document, a second call resolves surface-form aliases into canonical entities, and the result assembles into a property graph that a third call can query without ever seeing the full source corpus again.

The phrase worth holding onto: **the agent forgets, the graph does not.** Persistence is what enables long-running investigations, cross-session planning, incremental document ingestion, contradiction tracking, and recovery after a failed run.

## When to Use
- Multiple agents (or the same agent across sessions) need to share facts without re-reading every prior document or transcript
- The domain has real, evolving relationships between entities that get queried more than once (who supplied what, which claim supports which conclusion, which entity relates to which)
- Provenance matters — you need to know which source backs which fact, not just what the fact is
- A swarm or long-running loop needs a place to publish findings that outlives any single worker's context

## When Not to Use
- Tasks are independent and no cross-session state is required — don't build a graph merely because the system happens to have agents in it
- One document answers every query — a graph adds resolution and traversal overhead with nothing to traverse
- Relations are fixed and simple — a relational table or a flat list answers every query as well as a graph would
- Provenance genuinely isn't needed and never will be asked for
- Extraction/resolution errors would outweigh what traversal buys you — a bad graph is worse than no graph, because it looks authoritative

## Core Operating Rules

### 1. Extraction — Schema-Constrained, Not a Trained Pipeline
Define typed Entity and Relation schemas (e.g., `Entity{name, type, description}`, `Relation{source, predicate, target}`) and extract via a single structured-output call per document, using a cheap/fast model. The schema is the only "training data" needed — there is no separate NER or relation-classifier model to train or maintain.
- Extraction produces **surface forms**, not a clean graph. Do not treat extraction output as final — resolution is a required next stage, not optional cleanup.
- Track schema-valid response rate as a first-class metric; a high failure rate here means the schema or prompt needs work before anything downstream can be trusted.

### 2. Resolution — Contextual, Additive, Reversible (default ON)
This is the highest-risk stage in the whole pipeline, and the one place this skill is opinionated rather than flexible.
- **Resolve by contextual description, not string similarity.** "Edwin Aldrin" and "Buzz Aldrin" should merge despite zero character overlap; two different people who happen to share a name should not merge despite total string overlap. Group candidates by entity type first, then use a stronger model to propose canonical clusters from context — never a pure string-distance heuristic as the final arbiter.
- **Resolution must be additive and inspectable, never destructive.** A canonical entity retains every alias it absorbed, its source documents, the resolution rationale, a confidence score, and which run performed the merge. A wrong merge must be reversible without reconstructing the graph from scratch.
- **Treat a false merge as a cascade failure, not a minor error.** Collapsing two distinct entities into one node means every downstream query can silently combine their attributes, relationships, and claims. Because of this, resolution confidence and rationale are not optional metadata — they are what makes a bad merge findable and reversible after the fact.
- Track compression ratio (raw surface forms / canonical entities) as a health signal, but never as a target to maximize — a high compression ratio is not automatically good; over-merging produces a graph that is connected but false.

### 3. Assembly — Property Graph With Provenance Built In, Not Bolted On
Every node carries: canonical id, type, description, source document(s), and the aliases it absorbed. Every edge carries: predicate, source document, and confidence. Provenance is a required field on every write, not an afterthought added when someone asks "where did this come from."

### 4. Querying — Bounded Traversal, Cited Edges, Explicit Gaps
Never serialize the whole graph into a model's context. A query resolves the entities mentioned in the task, expands a bounded number of hops over allowed edge types, prioritizes recent or verified claims, and serializes only that subgraph — within a stated token budget.
- Every answer must cite the specific edge identifiers used to support it
- Every answer must distinguish stated fact from inference
- If a claim isn't supported by a path in the graph, say so explicitly and name the missing edge — a fluent unsupported answer is worse than an answer that admits the gap

### 5. Four Non-Negotiable Invariants
Every write to the graph satisfies all four, with no exceptions:
1. Every claim has a source, or is explicitly marked as inference
2. Every artifact has an authoring run and a version
3. Every evaluation identifies the rubric or criteria it used
4. Nothing is silently deleted — a superseded object stays addressable, marked superseded, not removed

### 6. Graph vs. DAG — Complementary, Not Interchangeable
A commit DAG (as in `ratchet-loop` or a swarm's work history) answers "what changed, and which experiment produced it" — it represents **work lineage**. A knowledge graph answers "which entities exist, how are they related, which claims conflict" — it represents **domain knowledge**. Don't collapse the two: a system that needs both should keep them as separate, cross-linked structures (a claim can point to the run that produced it; a run can point to the entities it touched) rather than forcing one to do the other's job.

### 7. Output Requirements
Always deliver, in this order:
1. The entity/relation schema used for extraction
2. The resolution policy: how contextual clustering worked, and the compression ratio achieved
3. A sample of the assembled graph (node/edge counts by type, or a small representative subgraph)
4. For any query answered: the bounded subgraph traversed, the cited edges, and any explicitly flagged missing evidence
5. Monitoring signals worth tracking going forward: extraction schema-failure rate, resolution compression ratio, isolated-node count (a sudden rise can signal resolution regression; a sudden drop can signal over-merging), and stale-entity count

## Worked Example

**Input**: "We have 40 vendor contracts and 15 incident reports. Build a graph so agents can answer 'which vendors are linked to which incidents' without re-reading every document."

**Setup**:
- Schema: `Entity{name, type: [Vendor, Component, Incident], description}`, `Relation{source, predicate: [supplied, involved_in, caused], target}`
- Extraction: one structured-output call per document (55 total), cheap model
- Resolution: cluster by type (all Vendor mentions together, all Component mentions together), resolve by contextual description — "Acme Corp" and "Acme Corporation" merge; "Acme Corp" (the vendor) and "Acme Devices" (a different company, similar name) do not, flagged for human review at low confidence instead of auto-merged
- Assembly: property graph, each node tagged with its source documents, each edge tagged with source + confidence
- Query: "Is Vendor X linked to Incident Y?" → traverse from Vendor X, 2 hops, check for a path through a Component to Incident Y. If no path exists, the evaluator returns a structured "no supported path" result naming the missing edge, rather than guessing.

**Output**: graph with node/edge counts by type, resolution compression ratio (e.g., 130 raw mentions → 42 canonical vendors), 3 low-confidence merges flagged for review, and a worked query showing a cited 2-hop path for one true positive and an explicit "unsupported" result for one absent claim.

## Advanced Techniques
- **Graph autoresearch**: the extraction prompt, resolution policy, and query serializer are themselves valid `ratchet-loop` targets — optimize the extraction prompt against entity/relation F1 on a gold set, or the resolution policy against pairwise precision/recall, with the usual reversible-commit, hard-metric discipline. The artifact being optimized is the pipeline, not the graph's content.
- **Swarm workers publishing to the graph**: instead of a swarm's synthesizer receiving raw findings from each worker, have each worker publish a structured `GraphUpdate` (nodes + edges) as its evidence contract — this satisfies `swarm-orchestration`'s evidence-contract requirement and turns the graph into the swarm's shared memory layer, so a synthesizer traverses the graph rather than reading every worker's transcript.
- **Grounding claims against the graph**: an evaluator can check a generated claim against the graph directly — if the claim implies an edge path that doesn't exist, return structured feedback naming the specific missing or contradictory edge, rather than a free-form "this seems wrong."
- **Adversarial resolution cases**: when validating a resolution policy, deliberately construct cases with misleading aliases, contradictory dates, and disconnected paths — these are where contextual resolution earns its keep over string matching.

## Quality Checklist (run before treating the graph as reliable)
- [ ] Entity/relation schema defined and extraction schema-failure rate tracked
- [ ] Resolution uses contextual description, not string similarity, as the final arbiter
- [ ] Resolution is additive and reversible: aliases, sources, rationale, confidence, and originating run retained on every canonical entity
- [ ] Every node and edge carries provenance (source doc, confidence) — not optional metadata
- [ ] All four invariants hold: sourced-or-marked-inference, versioned artifacts, named rubrics, no silent deletion
- [ ] Queries traverse a bounded subgraph, cite specific edges, and explicitly flag unsupported claims
- [ ] Compression ratio and isolated-node count are being tracked as health signals, not ignored until something breaks
- [ ] The decision to use a graph at all was deliberate, not automatic just because agents are involved
