Generated banner for Mini Context Graph
Generated logo for Mini Context Graph

Mini Context Graph

GitHubOfficialFirst committed by fizznixDistributed by GitHub

  • Skill
  • Tool integration
  • Data and AI
  • MIT
  • Low risk
  • Has scripts

From the author

A persistent, compounding knowledge base combining Karpathy's LLM Wiki pattern with a structured knowledge graph. Ingest documents once — the LLM writes wiki pages, extracts entities/relations into the graph, and stores raw content for evidence retrieval. Knowledge accumulates and cross-references; it is never re-derived from scratch.
— the description by fizznix

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

Mini Context Graph implements a persistent knowledge management system designed to overcome the limitations of standard RAG. Instead of re-deriving knowledge from scratch, it maintains three synchronized layers: a wiki for human-readable synthesis, a knowledge graph for structural traversal, and an immutable raw source store for provenance. The agent acts as the curator, ingesting documents, extracting entities and relations, and continuously updating the wiki and graph to ensure knowledge accumulates and cross-references over time.

What it does

  • Ingests documents to extract entities and relations into a structured knowledge graph.
  • Maintains a persistent markdown wiki that synthesizes information and cross-references entities.
  • Stores raw source content immutably to provide verifiable evidence for every graph node and edge.
  • Supports structural graph traversal to answer complex queries without re-reading source documents.
  • Provides a linting workflow to identify contradictions, orphans, and stale claims within the knowledge base.
  • Enables fast-path retrieval by searching the wiki before performing deeper graph analysis.

When to use it

  • When you need a long-term, evolving knowledge base that grows more accurate with every document ingested.
  • When you require strict provenance and citations for every claim made by the agent.
  • When you need to perform structural analysis or relationship mapping across a large set of documents.
  • When you want to avoid the computational overhead of re-processing raw data for every query.
  • When you need to maintain a clean, human-readable wiki alongside a machine-navigable graph.

Advantages

  • Compounding knowledge: The system gets smarter and more interconnected as more data is added.
  • Verifiable: Every graph connection is linked to specific source text for auditability.
  • Hybrid retrieval: Combines the speed of wiki search with the depth of graph traversal.
  • Self-maintaining: Includes built-in linting to detect and resolve data inconsistencies.
  • Persistent: Knowledge is stored and refined, not generated from scratch on every request.

Usage examples

“Ingest the provided incident report and update the knowledge base.”
The agent extracts entities and relations, updates the graph, writes a summary wiki page, and links the new information to existing entity pages.
“Why does the system crash? Provide evidence.”
The agent searches the wiki for relevant context and performs a graph traversal to identify the cause, returning the answer with direct citations from the source documents.
“Run a health check on the wiki.”
The agent executes the linting workflow to identify and report on orphan pages, broken links, or potential contradictions in the knowledge base.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/github/mini-context-graph/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip mini-context-graph.zip -d .agents/skills

Documentation by fizznix

Mini Context Graph Skill

The Core Idea

Standard RAG re-discovers knowledge from scratch on every query. This skill is different:

  1. Wiki layer — The LLM writes and maintains persistent markdown pages (summaries, entity pages, topic syntheses). Cross-references are already there. The wiki gets richer with every ingest.

  2. Graph layer — Entities and relations are extracted once and stored as a navigable knowledge graph. BFS traversal answers structural queries without re-reading sources.

  3. Raw source layer — Original documents are stored immutably with chunks. Provenance links tie every graph node and edge back to the exact text that supports it.

The LLM writes; the Python tools handle all bookkeeping.


Three Layers

LayerWhereWhat the LLM doesWhat Python does
Raw Sourcesdata/documents.jsonReads (never modifies)Stores chunks + metadata
Wikiwiki/ (markdown)Writes/updates pagesManages index.md + log.md
Graphdata/graph.jsonExtracts entities + relationsPersists, deduplicates, traverses

⚡ Quick Start for Agents

A complete runnable version of this workflow is in scripts/template_agent_workflow.py — copy and adapt it.

from scripts.contextgraph import ContextGraphSkill
from scripts.tools import wiki_store

skill = ContextGraphSkill()

# ===== INGEST WITH FULL RAG + WIKI =====
# 1. Read references/ingestion.md and references/ontology.md first
# 2. Extract entities and relations (LLM reasoning step)
entities = [
    {"name": "memory leak",   "type": "issue",  "supporting_text": "memory leaks cause crashes"},
    {"name": "system crash",  "type": "issue",  "supporting_text": "system crashes due to memory leaks"},
]
relations = [
    {"source": "memory leak", "target": "system crash", "type": "causes",
     "confidence": 1.0, "supporting_text": "System crashes due to memory leaks."},
]

result = skill.ingest_with_content(
    doc_id="doc_001",
    title="System Crash Analysis",
    source="/docs/incident_report.pdf",
    raw_content="System crashes due to memory leaks. Memory leaks occur when objects are not released.",
    entities=entities,
    relations=relations,
)
# result = {"doc_id": "doc_001", "chunk_count": 1, "nodes_added": 2, "edges_added": 1}

# 3. Write a wiki summary page for this document
wiki_store.write_page(
    category="summary",
    title="System Crash Analysis Summary",
    content="""---
title: System Crash Analysis
source_document: doc_001
tags: [summary, incident]
---

# System Crash Analysis

**Source:** incident_report.pdf

## Key Claims

- [[memory-leak]] causes [[system-crash]] (confidence: 1.0)

## Entities

- [[memory-leak]] (issue)
- [[system-crash]] (issue)
""",
    summary="Incident report: memory leaks cause system crashes.",
)

# ===== QUERY WITH EVIDENCE =====
result = skill.query_with_evidence("Why does the system crash?")
# Returns: {"query": ..., "subgraph": ..., "supporting_documents": [...], "evidence_chain": ...}

# ===== WIKI SEARCH (read wiki before answering) =====
pages = wiki_store.search_wiki("memory leak")
# Returns: [{slug, category, path, snippet}, ...]

Operations

Ingest

When a user provides a new document:

  1. Read references/ingestion.md — entity/relation extraction rules.

  2. Read references/ontology.md — type normalization rules.

  3. Extract entities and relations using your LLM reasoning.

  4. Call skill.ingest_with_content(...) — stores raw content + chunks + graph nodes + provenance.

  5. Write a wiki summary page using wiki_store.write_page(category="summary", ...).

  6. Update entity pages — for each new/updated entity, write or update wiki_store.write_page(category="entity", ...).

  7. Update topic pages if the document touches an existing synthesis topic.

  8. A single document ingest will typically touch 3–10 wiki pages.

Query

When a user asks a question:

  1. Check the wiki first — wiki_store.search_wiki(query) to find relevant pages. Read them.

  2. If the wiki has a good answer, synthesize from wiki pages (fast path).

  3. If deeper graph traversal is needed, call skill.query_with_evidence(query).

  4. Return the answer with evidence citations from supporting_documents.

  5. If the answer is valuable, file it back as a new wiki topic page.

Lint

Periodically health-check the wiki:

from scripts.tools import wiki_store
issues = wiki_store.lint_wiki()
# Returns: {orphan_pages, missing_pages, broken_wikilinks, isolated_pages}

Ask the LLM to review and fix: broken links, orphan pages, stale claims, missing cross-references. See references/lint.md for full lint workflow.


Ingestion Constraints

  • ❌ Do NOT hallucinate entities not present in the text

  • ❌ Do NOT add relations without explicit textual evidence

  • ❌ Do NOT add edges with confidence < 0.6

  • ✅ Provide supporting_text for every entity and relation — this enables provenance

  • ✅ Write a wiki summary page for every ingested document

  • ✅ Update existing entity pages when new information arrives

  • ✅ Flag contradictions in wiki pages when new data conflicts with old claims


Retrieval Constraints

  • 🔒 Traversal depth MUST NOT exceed 2 (config: MAX_GRAPH_DEPTH)

  • 🔒 Only edges with confidence ≥ 0.6 (config: MIN_CONFIDENCE)

  • 🔒 Maximum 50 nodes returned (config: MAX_NODES)

  • ❌ Do NOT fabricate nodes or edges not in the graph


Full Python API Reference

MethodPurposeWhen to Use
skill.ingest_with_content(doc_id, title, source, raw_content, entities, relations)Full RAG ingest: raw docs + graph + provenanceEvery new document
skill.add_node(name, node_type)Add single entity (no provenance)Quick additions without a source doc
skill.add_edge(source_name, target_name, relation, confidence)Add single relationQuick additions without a source doc
skill.query(query)Graph-only retrieval → subgraphStructural queries
skill.query_with_evidence(query)Graph + provenance → subgraph + source chunksQueries requiring citations
wiki_store.write_page(category, title, content, summary)Write/update a wiki pageAfter every ingest; after answering queries
wiki_store.read_page(category, title)Read a wiki pageBefore answering; for cross-referencing
wiki_store.search_wiki(query)Keyword search across wikiFast path before graph traversal
wiki_store.list_pages(category)List all wiki pagesGetting an overview
wiki_store.get_log(last_n)Read recent operationsUnderstanding wiki history
wiki_store.lint_wiki()Health checkPeriodic maintenance
documents_store.list_documents()List all ingested raw sourcesAudit / provenance checking
documents_store.search_chunks(query)Chunk-level searchFinding specific evidence

Design Philosophy

"The wiki is a persistent, compounding artifact. The cross-references are already there. The synthesis already reflects everything you've read." — Karpathy

LayerWhat HappensWho Owns It
LLM ReasoningExtraction, synthesis, writing wiki pagesAgent (.md guidance files)
Wiki PersistenceIndex, log, file I/Owiki_store.py
Graph PersistenceDedup, index, BFS traversegraph_store.py, retrieval_engine.py
Raw Source StorageImmutable docs + chunks + provenancedocuments_store.py

The human curates sources and asks questions. The LLM writes the wiki, extracts the graph, and answers with citations. Python handles all bookkeeping.

Files

scripts/contextgraph.py

"""
contextgraph.py — Main interface for the Context Graph Skill.

This file is orchestration-only. All LLM reasoning lives in the .md files.
Python here only wires together the deterministic storage and retrieval tools.

Agent usage:
- ingest(): agent reads ingestion.md + ontology.md, extracts entities/relations,
            then calls the tool methods directly.
- query():  agent reads retrieval.md, calls index_store.search + retrieval_engine.retrieve,
            then calls graph_store.get_subgraph and returns the result.
"""
from __future__ import annotations

import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent))

import config
from tools import graph_store, index_store, ontology_store, retrieval_engine, documents_store


class ContextGraphSkill:

    def ingest(self, documents: list[str]) -> None:
        """
        Orchestration entry point for ingesting documents into the context graph.

        The agent (Copilot) MUST:
          1. Read ingestion.md to understand entity/relation extraction rules.
          2. Read ontology.md to apply type normalization.
          3. For each document, produce a JSON with entities + relations.
          4. For each entity:
             - ontology_store.add_type(entity["type"])
             - node_id = graph_store.add_node(entity["name"], entity["type"])
             - index_store.add_entity(entity["name"], node_id)
          5. For each relation (if confidence >= MIN_CONFIDENCE):
             - ontology_store.add_relation(relation["type"])
             - source_id = graph_store.find_node_by_name(relation["source"])
             - target_id = graph_store.find_node_by_name(relation["target"])
             - graph_store.add_edge(source_id, target_id, relation["type"], relation["confidence"])

        This method does NOT call any LLM. It documents the agent contract only.
        """
        raise NotImplementedError(
            "ingest() must be driven by the Copilot agent following ingestion.md. "
            "Call the tool methods directly after LLM extraction."
        )

    def query(self, query: str) -> dict:
        """
        Orchestration entry point for retrieving a subgraph for a query.

        The agent (Copilot) MUST:
          1. Read retrieval.md to understand the retrieval strategy.
          2. Call index_store.search(query) to get seed node_ids.
          3. Call retrieval_engine.retrieve(seed_ids, depth=MAX_GRAPH_DEPTH) to expand.
          4. Call graph_store.get_subgraph(node_ids) to build the result.
          5. Return the subgraph dict.

        This method does NOT call any LLM. It documents the agent contract only.
        Returns an empty subgraph if called directly.
        """
        seed_ids = index_store.search(query)
        if not seed_ids:
            return {"nodes": {}, "edges": []}

        node_ids = retrieval_engine.retrieve(
            seed_ids,
            depth=config.MAX_GRAPH_DEPTH,
            min_confidence=config.MIN_CONFIDENCE,
            max_nodes=config.MAX_NODES,
        )
        return graph_store.get_subgraph(node_ids)

    # ------------------------------------------------------------------
    # Convenience wrappers — agents may call these directly
    # ------------------------------------------------------------------

    def add_node(self, name: str, node_type: str) -> str:
        """Add a node to the graph and index. Returns node_id."""
        canonical_type = ontology_store.normalize_type(node_type)
        ontology_store.add_type(canonical_type)
        node_id = graph_store.add_node(name, canonical_type)
        index_store.add_entity(name, node_id)
        return node_id

    def add_edge(
        self, source_name: str, target_name: str, relation: str, confidence: float
    ) -> None:
        """Add an edge between two nodes (by name) if both exist and confidence qualifies."""
        if confidence < config.MIN_CONFIDENCE:
            return

        source_id = graph_store.find_node_by_name(source_name)
        target_id = graph_store.find_node_by_name(target_name)
        if source_id is None or target_id is None:
            return

        canonical_relation = ontology_store.normalize_relation(relation)
        ontology_store.add_relation(canonical_relation)
        graph_store.add_edge(source_id, target_id, canonical_relation, confidence)

    # ------------------------------------------------------------------
    # LLM Wiki + RAG methods — store raw content & provenance
    # ------------------------------------------------------------------

    def ingest_with_content(
        self,
        doc_id: str,
        title: str,
        source: str,
        raw_content: str,
        entities: list[dict],
        relations: list[dict],
    ) -> dict:
        """
        Full RAG ingestion: stores raw document + chunks, then wires provenance
        links from each graph node/edge back to source chunks.

        The agent MUST:
          1. Read the raw_content.
          2. Read ingestion.md and ontology.md for extraction rules.
          3. Extract entities and relations (LLM reasoning step).
          4. Call this method with the results.

        Args:
            doc_id:      Stable document identifier (e.g. "doc_001").
            title:       Human-readable document title.
            source:      Origin path or URL (immutable, never modified).
            raw_content: Full text of the document.
            entities:    List of dicts: [{name, type, supporting_text?}, ...]
            relations:   List of dicts: [{source, target, type, confidence,
                                          supporting_text?, chunk_hint?}, ...]

        Returns:
            Summary dict: {doc_id, chunk_count, nodes_added, edges_added}
        """
        # Step 1: Store raw document and auto-chunk
        doc = documents_store.add_document(doc_id, title, source, raw_content)
        chunks = doc["chunks"]

        def _find_best_chunk(text: str) -> str | None:
            """Find the chunk whose text most overlaps with the given span."""
            if not text or not chunks:
                return None
            text_lower = text.lower()
            best_chunk_id = None
            best_score = 0
            for chunk in chunks:
                if text_lower in chunk["text"].lower():
                    return chunk["chunk_id"]
                # Fallback: count overlapping words
                words_text = set(text_lower.split())
                words_chunk = set(chunk["text"].lower().split())
                score = len(words_text & words_chunk)
                if score > best_score:
                    best_score = score
                    best_chunk_id = chunk["chunk_id"]
            return best_chunk_id

        nodes_added = 0
        # Step 2: Ingest entities with provenance
        for entity in entities:
            supporting = entity.get("supporting_text", "")
            chunk_id = _find_best_chunk(supporting)
            chunk_ids = [chunk_id] if chunk_id else []

            canonical_type = ontology_store.normalize_type(entity["type"])
            ontology_store.add_type(canonical_type)
            node_id = graph_store.add_node(
                entity["name"],
                canonical_type,
                source_document=doc_id,
                source_chunks=chunk_ids,
            )
            index_store.add_entity(entity["name"], node_id)
            nodes_added += 1

        edges_added = 0
        # Step 3: Ingest relations with provenance
        for rel in relations:
            if rel.get("confidence", 0) < config.MIN_CONFIDENCE:
                continue

            supporting = rel.get("supporting_text", "")
            chunk_id = _find_best_chunk(supporting) or rel.get("chunk_hint")

            source_id = graph_store.find_node_by_name(rel["source"])
            target_id = graph_store.find_node_by_name(rel["target"])
            if source_id is None or target_id is None:
                continue

            canonical_relation = ontology_store.normalize_relation(rel["type"])
            ontology_store.add_relation(canonical_relation)
            graph_store.add_edge(
                source_id,
                target_id,
                canonical_relation,
                rel["confidence"],
                source_document=doc_id,
                supporting_text=supporting or None,
                chunk_id=chunk_id,
            )
            edges_added += 1

        return {
            "doc_id": doc_id,
            "chunk_count": len(chunks),
            "nodes_added": nodes_added,
            "edges_added": edges_added,
        }

    def query_with_evidence(self, query: str) -> dict:
        """
        Query the graph and return the subgraph together with supporting
        source documents and chunks (evidence chain).

        Returns:
            {
              "query": str,
              "subgraph": {"nodes": {...}, "edges": [...]},
              "supporting_documents": [
                {
                  "doc_id": str,
                  "doc_title": str,
                  "supporting_chunks": [{"chunk_id": str, "text": str}, ...]
                }
              ],
              "evidence_chain": str   # human-readable summary path
            }
        """
        subgraph = self.query(query)
        if not subgraph["nodes"]:
            return {
                "query": query,
                "subgraph": subgraph,
                "supporting_documents": [],
                "evidence_chain": "No matching nodes found.",
            }

        # Collect all provenance pointers from nodes and edges
        docs_chunks: dict[str, list[str]] = {}  # doc_id -> [chunk_ids]

        for node in subgraph["nodes"].values():
            doc_id = node.get("source_document")
            if doc_id:
                docs_chunks.setdefault(doc_id, [])
                docs_chunks[doc_id].extend(node.get("source_chunks") or [])

        for edge in subgraph["edges"]:
            doc_id = edge.get("source_document")
            if doc_id:
                docs_chunks.setdefault(doc_id, [])
                if edge.get("chunk_id"):
                    docs_chunks[doc_id].append(edge["chunk_id"])

        # Resolve chunk texts from documents_store
        supporting_documents = []
        for doc_id, chunk_ids in docs_chunks.items():
            doc = documents_store.get_document(doc_id)
            if doc is None:
                continue
            seen = set()
            chunks_out = []
            for cid in chunk_ids:
                if cid in seen:
                    continue
                seen.add(cid)
                chunk = documents_store.get_chunk(cid)
                if chunk:
                    chunks_out.append({"chunk_id": cid, "text": chunk["text"]})
            if chunks_out:
                supporting_documents.append({
                    "doc_id": doc_id,
                    "doc_title": doc["title"],
                    "supporting_chunks": chunks_out,
                })

        # Build a simple evidence chain string
        chain_parts = []
        for edge in subgraph["edges"]:
            src_node = subgraph["nodes"].get(edge["source"], {})
            tgt_node = subgraph["nodes"].get(edge["target"], {})
            src_name = src_node.get("name", edge["source"])
            tgt_name = tgt_node.get("name", edge["target"])
            chain_parts.append(f"{src_name} --[{edge['type']}]--> {tgt_name}")
        evidence_chain = " | ".join(chain_parts) if chain_parts else "No edges in subgraph."

        return {
            "query": query,
            "subgraph": subgraph,
            "supporting_documents": supporting_documents,
            "evidence_chain": evidence_chain,
        }

Requirements and compatibility

Written for: GitHub Copilot

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs Python, Needs Node.js

Security

What our scanner noticed· Low risk

  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

First committed by
GitHub avatar of fizznixfizznix
Publisher
GitHub (Official)
Distributed by
GitHub
Source
github/awesome-copilot · skills/mini-context-graph · commit 797337f
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced
Contributors
fizznix, stbenjam

AutoGineer is not affiliated with or endorsed by fizznix or GitHub.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download mini-context-graph.zip