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://mp-staging.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/tools/documents_store.py

"""
documents_store.py — Persistent storage for raw documents and chunks (RAG layer).

Inspired by Karpathy's LLM Wiki pattern: raw sources are immutable and stored
as the ground truth. Chunks are the retrieval unit; provenance links tie graph
nodes/edges back to specific chunks.

Handles:
- Storing raw documents with metadata
- Chunking documents into overlapping text windows
- Retrieving chunks by id or by keyword search
- Persisting to data/documents.json
"""
from __future__ import annotations

import json
import os
import re
import sys
import uuid
from datetime import datetime, timezone
from pathlib import Path

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

_DATA_DIR = Path(os.environ.get("MINI_CONTEXT_GRAPH_DATA_DIR", str(config.DATA_DIR)))
_DOCS_FILE = _DATA_DIR / "documents.json"

_CHUNK_SIZE = 500       # characters per chunk
_CHUNK_OVERLAP = 100    # overlap between consecutive chunks

_STOPWORDS = frozenset([
    "a", "an", "the", "is", "are", "was", "were", "be", "been", "being",
    "have", "has", "had", "do", "does", "did", "will", "would", "could",
    "should", "may", "might", "shall", "can", "to", "of", "in", "on",
    "at", "by", "for", "with", "from", "and", "or", "but", "not", "it",
    "its", "this", "that", "these", "those", "i", "you", "he", "she",
    "we", "they", "what", "which", "who", "how", "why", "when", "where",
])


def _load() -> dict:
    if _DOCS_FILE.exists():
        with open(_DOCS_FILE, "r") as f:
            return json.load(f)
    return {"documents": {}}


def _save(store: dict) -> None:
    _DATA_DIR.mkdir(parents=True, exist_ok=True)
    with open(_DOCS_FILE, "w") as f:
        json.dump(store, f, indent=2)


def _tokenize(text: str) -> list[str]:
    tokens = re.findall(r"[a-z0-9]+", text.lower())
    return [t for t in tokens if t not in _STOPWORDS and len(t) > 1]


def _chunk_text(content: str, chunk_size: int = _CHUNK_SIZE, overlap: int = _CHUNK_OVERLAP) -> list[str]:
    """Split content into overlapping character windows."""
    chunks = []
    start = 0
    while start < len(content):
        end = start + chunk_size
        chunks.append(content[start:end].strip())
        if end >= len(content):
            break
        start += chunk_size - overlap
    return [c for c in chunks if c]


# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------

def add_document(
    doc_id: str,
    title: str,
    source: str,
    content: str,
) -> dict:
    """
    Store a raw document and auto-generate chunks.

    Args:
        doc_id:  Caller-supplied stable identifier (e.g. "doc_001" or a filename).
        title:   Human-readable title.
        source:  Origin path/URL (immutable provenance pointer).
        content: Full raw text to store and chunk.

    Returns:
        The stored document dict including generated chunk_ids.
    """
    store = _load()

    # Idempotent: return existing doc if already stored
    if doc_id in store["documents"]:
        return store["documents"][doc_id]

    raw_chunks = _chunk_text(content)
    chunks = []
    for i, text in enumerate(raw_chunks):
        chunks.append({
            "chunk_id": f"{doc_id}_chunk_{i:03d}",
            "index": i,
            "text": text,
        })

    doc = {
        "id": doc_id,
        "title": title,
        "source": source,
        "content": content,
        "chunks": chunks,
        "ingestion_date": datetime.now(timezone.utc).isoformat(),
    }
    store["documents"][doc_id] = doc
    _save(store)
    return doc


def get_document(doc_id: str) -> dict | None:
    """Return the full document record or None if not found."""
    store = _load()
    return store["documents"].get(doc_id)


def get_chunk(chunk_id: str) -> dict | None:
    """Return a specific chunk by its chunk_id (searches across all documents)."""
    store = _load()
    for doc in store["documents"].values():
        for chunk in doc["chunks"]:
            if chunk["chunk_id"] == chunk_id:
                return chunk
    return None


def get_chunks_for_document(doc_id: str) -> list[dict]:
    """Return all chunks for a document."""
    doc = get_document(doc_id)
    if doc is None:
        return []
    return doc["chunks"]


def search_chunks(query: str, top_k: int = 5) -> list[dict]:
    """
    Keyword search over chunk text. Returns top_k matching chunks sorted by
    term overlap (simple TF-style scoring, no embeddings required).

    Returns list of dicts with keys: chunk_id, doc_id, score, text.
    """
    store = _load()
    query_tokens = set(_tokenize(query))
    if not query_tokens:
        return []

    scored: list[tuple[float, dict]] = []
    for doc in store["documents"].values():
        for chunk in doc["chunks"]:
            chunk_tokens = set(_tokenize(chunk["text"]))
            overlap = len(query_tokens & chunk_tokens)
            if overlap > 0:
                score = overlap / len(query_tokens)
                scored.append((score, {
                    "chunk_id": chunk["chunk_id"],
                    "doc_id": doc["id"],
                    "doc_title": doc["title"],
                    "score": round(score, 4),
                    "text": chunk["text"],
                }))

    scored.sort(key=lambda x: x[0], reverse=True)
    return [item for _, item in scored[:top_k]]


def list_documents() -> list[dict]:
    """Return a summary list of all stored documents (no content, no chunks)."""
    store = _load()
    return [
        {
            "id": doc["id"],
            "title": doc["title"],
            "source": doc["source"],
            "chunk_count": len(doc["chunks"]),
            "ingestion_date": doc["ingestion_date"],
        }
        for doc in store["documents"].values()
    ]

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