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/template_agent_workflow.py

"""
template_agent_workflow.py — Template agent script for ingesting + querying the context graph.

This script demonstrates the complete workflow an agent should follow:
1. Read markdown guidance files
2. Extract entities/relations via LLM reasoning
3. Call Python methods to persist
4. Query the graph
5. Handle errors gracefully

Copy and adapt this template for your agent implementation.
"""

import json
import sys
from pathlib import Path

# Add tools to path
sys.path.insert(0, str(Path(__file__).parent))

from contextgraph import ContextGraphSkill


def ingest_document(skill: ContextGraphSkill, document: str) -> dict:
    """
    Step 1: Agent reads ingestion.md and ontology.md
    Step 2: Agent uses LLM to extract entities and relations
    Step 3: Call Python methods to persist (mimicked here with static extraction)

    In a real agent, replace the static extraction with LLM calls.
    """
    print(f"\n[INGEST] Processing document:\n{document}\n")

    # --- STEP 1 & 2: LLM EXTRACTION PHASE (Guided by ingestion.md + ontology.md) ---
    # In a real agent, this would use LLM reasoning.
    # For now, we'll mock an extraction result:

    extraction_result = {
        "entities": [
            {"name": "memory leak", "type": "issue"},
            {"name": "system crash", "type": "issue"},
            {"name": "object", "type": "component"},
        ],
        "relations": [
            {
                "source": "memory leak",
                "target": "system crash",
                "type": "causes",
                "confidence": 1.0,
            },
            {
                "source": "object",
                "target": "memory leak",
                "type": "contributes to",
                "confidence": 0.9,
            },
        ],
    }

    print(f"[LLM] Extracted entities + relations:")
    print(json.dumps(extraction_result, indent=2))

    # --- STEP 3: PERSIST PHASE (Call Python methods) ---
    errors = []
    added_nodes = {}

    for entity in extraction_result["entities"]:
        try:
            node_id = skill.add_node(entity["name"], entity["type"])
            added_nodes[entity["name"]] = node_id
            print(f"  ✓ Added node: {entity['name']} (id: {node_id}, type: {entity['type']})")
        except Exception as e:
            errors.append(f"Failed to add node {entity['name']}: {e}")
            print(f"  ✗ Error adding node {entity['name']}: {e}")

    for relation in extraction_result["relations"]:
        # Validate both endpoints exist
        if relation["source"] not in added_nodes or relation["target"] not in added_nodes:
            error_msg = f"Cannot add edge: source or target missing"
            errors.append(error_msg)
            print(f"  ✗ Skip edge {relation['source']} → {relation['target']}: {error_msg}")
            continue

        # Validate confidence threshold
        if relation["confidence"] < 0.6:
            error_msg = f"Confidence {relation['confidence']} < 0.6 (minimum threshold)"
            errors.append(error_msg)
            print(f"  ✗ Skip edge {relation['source']} → {relation['target']}: {error_msg}")
            continue

        try:
            skill.add_edge(
                source_name=relation["source"],
                target_name=relation["target"],
                relation=relation["type"],
                confidence=relation["confidence"],
            )
            print(
                f"  ✓ Added edge: {relation['source']} "
                f"--[{relation['type']}]→ {relation['target']} "
                f"(confidence: {relation['confidence']})"
            )
        except Exception as e:
            errors.append(f"Failed to add edge {relation['source']} → {relation['target']}: {e}")
            print(f"  ✗ Error adding edge: {e}")

    return {
        "success": len(errors) == 0,
        "nodes_added": len(added_nodes),
        "edges_added": len(extraction_result["relations"]) - len(
            [e for e in errors if "skip edge" in e.lower()]
        ),
        "errors": errors,
    }


def query_graph(skill: ContextGraphSkill, query: str) -> dict:
    """
    Query the graph for context to answer the user's question.

    Step 1: Read retrieval.md
    Step 2: Call skill.query() which internally handles BFS + subgraph extraction
    Step 3: Return structured context
    """
    print(f"\n[QUERY] {query}\n")

    try:
        subgraph = skill.query(query)

        if not subgraph["nodes"]:
            print("  ℹ No relevant entities found in graph.")
            return {
                "success": True,
                "query": query,
                "subgraph": subgraph,
                "nodes_found": 0,
                "edges_found": 0,
            }

        print(f"  ✓ Retrieved subgraph with {len(subgraph['nodes'])} nodes, {len(subgraph['edges'])} edges")
        print(f"\n  Nodes:")
        for node_id, node in subgraph["nodes"].items():
            print(f"    - {node['name']} (type: {node['type']}, id: {node_id})")

        print(f"\n  Edges:")
        for edge in subgraph["edges"]:
            source_name = subgraph["nodes"][edge["source"]]["name"]
            target_name = subgraph["nodes"][edge["target"]]["name"]
            print(
                f"    - {source_name} --[{edge['type']}]→ {target_name} "
                f"(confidence: {edge['confidence']})"
            )

        return {
            "success": True,
            "query": query,
            "subgraph": subgraph,
            "nodes_found": len(subgraph["nodes"]),
            "edges_found": len(subgraph["edges"]),
        }

    except Exception as e:
        error_msg = f"Query failed: {e}"
        print(f"  ✗ {error_msg}")
        return {"success": False, "query": query, "error": error_msg}


def main():
    """Demo: ingest a document, then query the graph."""
    skill = ContextGraphSkill()

    # ===== INGESTION =====
    document = """
    System crashes due to memory leaks.
    Memory leaks occur when objects are not released.
    """

    result = ingest_document(skill, document)
    print(f"\n[INGEST RESULT] Nodes added: {result['nodes_added']}, " f"Edges added: {result['edges_added']}")
    if result["errors"]:
        print(f"Errors: {result['errors']}")

    # ===== RETRIEVAL =====
    queries = [
        "Why does the system crash?",
        "What causes memory leaks?",
    ]

    for query in queries:
        result = query_graph(skill, query)
        if result["success"]:
            print(f"  Nodes found: {result['nodes_found']}, Edges found: {result['edges_found']}")
        else:
            print(f"  Error: {result['error']}")


if __name__ == "__main__":
    main()

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