Mini Context Graph
GitHubOfficialFirst committed by fizznixDistributed by GitHub
- Skill
- Tool integration
- Data and AI
- MIT
- Low risk
- Has scripts
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
Download the skill as a ZIP:
https://autogineer.com/agent-skills/github/mini-context-graph/downloadUnzip 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:
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.
Graph layer — Entities and relations are extracted once and stored as a navigable knowledge graph. BFS traversal answers structural queries without re-reading sources.
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
| Layer | Where | What the LLM does | What Python does |
|---|---|---|---|
| Raw Sources | data/documents.json | Reads (never modifies) | Stores chunks + metadata |
| Wiki | wiki/ (markdown) | Writes/updates pages | Manages index.md + log.md |
| Graph | data/graph.json | Extracts entities + relations | Persists, 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:
Read
references/ingestion.md— entity/relation extraction rules.Read
references/ontology.md— type normalization rules.Extract entities and relations using your LLM reasoning.
Call
skill.ingest_with_content(...)— stores raw content + chunks + graph nodes + provenance.Write a wiki summary page using
wiki_store.write_page(category="summary", ...).Update entity pages — for each new/updated entity, write or update
wiki_store.write_page(category="entity", ...).Update topic pages if the document touches an existing synthesis topic.
A single document ingest will typically touch 3–10 wiki pages.
Query
When a user asks a question:
Check the wiki first —
wiki_store.search_wiki(query)to find relevant pages. Read them.If the wiki has a good answer, synthesize from wiki pages (fast path).
If deeper graph traversal is needed, call
skill.query_with_evidence(query).Return the answer with evidence citations from
supporting_documents.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_textfor 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
| Method | Purpose | When to Use |
|---|---|---|
skill.ingest_with_content(doc_id, title, source, raw_content, entities, relations) | Full RAG ingest: raw docs + graph + provenance | Every 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 relation | Quick additions without a source doc |
skill.query(query) | Graph-only retrieval → subgraph | Structural queries |
skill.query_with_evidence(query) | Graph + provenance → subgraph + source chunks | Queries requiring citations |
wiki_store.write_page(category, title, content, summary) | Write/update a wiki page | After every ingest; after answering queries |
wiki_store.read_page(category, title) | Read a wiki page | Before answering; for cross-referencing |
wiki_store.search_wiki(query) | Keyword search across wiki | Fast path before graph traversal |
wiki_store.list_pages(category) | List all wiki pages | Getting an overview |
wiki_store.get_log(last_n) | Read recent operations | Understanding wiki history |
wiki_store.lint_wiki() | Health check | Periodic maintenance |
documents_store.list_documents() | List all ingested raw sources | Audit / provenance checking |
documents_store.search_chunks(query) | Chunk-level search | Finding 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
| Layer | What Happens | Who Owns It |
|---|---|---|
| LLM Reasoning | Extraction, synthesis, writing wiki pages | Agent (.md guidance files) |
| Wiki Persistence | Index, log, file I/O | wiki_store.py |
| Graph Persistence | Dedup, index, BFS traverse | graph_store.py, retrieval_engine.py |
| Raw Source Storage | Immutable docs + chunks + provenance | documents_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
- ATTRIBUTION.mdAdded by AutoGineer867 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md8.0 KiB
- references/ingestion.md5.0 KiB
- references/lint.md4.1 KiB
- references/ontology.md3.2 KiB
- references/retrieval.md4.3 KiB
- scripts/config.pyScript893 B
- scripts/contextgraph.pyScript11.5 KiB
- scripts/template_agent_workflow.pyScript6.6 KiB
- scripts/tools/__init__.pyScript0 B
- scripts/tools/documents_store.pyScript5.7 KiB
- scripts/tools/graph_store.pyScript6.0 KiB
- scripts/tools/index_store.pyScript2.8 KiB
- scripts/tools/ontology_store.pyScript4.8 KiB
- scripts/tools/retrieval_engine.pyScript1.6 KiB
- scripts/tools/wiki_store.pyScript9.4 KiB
scripts/tools/wiki_store.py
"""
wiki_store.py — Manages the persistent wiki layer.
Inspired by Karpathy's LLM Wiki pattern: the wiki is a directory of LLM-generated
markdown pages that the agent writes and maintains. This module provides the
deterministic file I/O and index/log management so the agent can focus on
reasoning, not bookkeeping.
Wiki structure (relative to project root):
wiki/
index.md ← content-oriented catalog of all pages
log.md ← chronological append-only operation log
entities/ ← one page per entity (person, concept, system, etc.)
summaries/ ← source document summary pages
topics/ ← cross-cutting synthesis and topic pages
The agent WRITES pages; this module handles the filesystem + index + log.
"""
from __future__ import annotations
import os
import re
import sys
from datetime import datetime, timezone
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent))
import config
_WIKI_DIR = Path(os.environ.get("MINI_CONTEXT_GRAPH_WIKI_DIR", str(config.WIKI_DIR)))
_INDEX_FILE = _WIKI_DIR / "index.md"
_LOG_FILE = _WIKI_DIR / "log.md"
_CATEGORY_DIRS = {
"entity": _WIKI_DIR / "entities",
"summary": _WIKI_DIR / "summaries",
"topic": _WIKI_DIR / "topics",
}
# ---------------------------------------------------------------------------
# Internal helpers
# ---------------------------------------------------------------------------
def _ensure_dirs() -> None:
_WIKI_DIR.mkdir(parents=True, exist_ok=True)
for d in _CATEGORY_DIRS.values():
d.mkdir(parents=True, exist_ok=True)
def _now_iso() -> str:
return datetime.now(timezone.utc).strftime("%Y-%m-%d")
def _slug(title: str) -> str:
"""Convert a title to a filesystem-safe slug."""
slug = title.lower().strip()
slug = re.sub(r"[^a-z0-9]+", "-", slug)
return slug.strip("-")
def _page_path(category: str, slug: str) -> Path:
base = _CATEGORY_DIRS.get(category, _WIKI_DIR)
return base / f"{slug}.md"
# ---------------------------------------------------------------------------
# Index management
# ---------------------------------------------------------------------------
def _load_index() -> list[dict]:
"""Parse index.md into a list of entry dicts."""
if not _INDEX_FILE.exists():
return []
entries = []
for line in _INDEX_FILE.read_text().splitlines():
# Expected table row: | [[slug]] | category | summary | date |
if line.startswith("| [["):
parts = [p.strip() for p in line.split("|") if p.strip()]
if len(parts) >= 3:
link = parts[0] # [[slug]]
category = parts[1] if len(parts) > 1 else ""
summary = parts[2] if len(parts) > 2 else ""
date = parts[3] if len(parts) > 3 else ""
slug = re.sub(r"\[\[|\]\]", "", link)
entries.append({
"slug": slug,
"category": category,
"summary": summary,
"date": date,
})
return entries
def _save_index(entries: list[dict]) -> None:
"""Rewrite index.md from the entries list."""
_ensure_dirs()
lines = [
"# Wiki Index\n",
"_Auto-managed by wiki_store. Do not edit the table manually._\n\n",
"| Page | Category | Summary | Date |\n",
"|------|----------|---------|------|\n",
]
for e in entries:
lines.append(
f"| [[{e['slug']}]] | {e['category']} | {e['summary']} | {e['date']} |\n"
)
_INDEX_FILE.write_text("".join(lines))
def _append_log(operation: str, detail: str) -> None:
"""Append a timestamped entry to log.md."""
_ensure_dirs()
timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%d")
entry = f"\n## [{timestamp}] {operation} | {detail}\n"
with open(_LOG_FILE, "a") as f:
f.write(entry)
# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------
def write_page(
category: str,
title: str,
content: str,
summary: str = "",
) -> str:
"""
Write (or overwrite) a wiki page.
The agent provides the full markdown content. This method handles:
- Writes the .md file to the appropriate category subfolder.
- Updates index.md with a one-line entry.
- Appends an entry to log.md.
Args:
category: One of "entity", "summary", "topic".
title: Human-readable page title (used for slug + index).
content: Full markdown content the agent wrote.
summary: One-line summary for the index (optional; auto-extracted if empty).
Returns:
Relative path from wiki root (e.g. "entities/memory-leak.md").
"""
_ensure_dirs()
slug = _slug(title)
path = _page_path(category, slug)
# Auto-extract first non-heading, non-empty line as summary if not provided
if not summary:
for line in content.splitlines():
stripped = line.strip()
if stripped and not stripped.startswith("#"):
summary = stripped[:100]
break
path.write_text(content)
# Update index
entries = _load_index()
existing = next((e for e in entries if e["slug"] == slug), None)
if existing:
existing["summary"] = summary
existing["date"] = _now_iso()
else:
entries.append({
"slug": slug,
"category": category,
"summary": summary,
"date": _now_iso(),
})
_save_index(entries)
_append_log("write", title)
return str(path.relative_to(_WIKI_DIR))
def read_page(category: str, title: str) -> str | None:
"""Read a wiki page's content. Returns None if not found."""
slug = _slug(title)
path = _page_path(category, slug)
if not path.exists():
return None
return path.read_text()
def read_page_by_slug(slug: str) -> str | None:
"""Read a wiki page by slug, searching across all categories."""
for d in list(_CATEGORY_DIRS.values()) + [_WIKI_DIR]:
path = d / f"{slug}.md"
if path.exists():
return path.read_text()
return None
def search_wiki(query: str) -> list[dict]:
"""
Simple keyword search over all wiki pages.
Returns list of {slug, category, path, snippet} sorted by relevance.
"""
query_tokens = set(re.findall(r"[a-z0-9]+", query.lower()))
if not query_tokens:
return []
results = []
for category, base_dir in _CATEGORY_DIRS.items():
if not base_dir.exists():
continue
for page_path in base_dir.glob("*.md"):
content = page_path.read_text().lower()
content_tokens = set(re.findall(r"[a-z0-9]+", content))
overlap = len(query_tokens & content_tokens)
if overlap > 0:
# Extract a short snippet around first match
first_token = next(iter(query_tokens & content_tokens), "")
idx = content.find(first_token)
snippet = content[max(0, idx - 30):idx + 80].replace("\n", " ").strip()
results.append({
"slug": page_path.stem,
"category": category,
"path": str(page_path.relative_to(_WIKI_DIR)),
"score": overlap,
"snippet": snippet,
})
results.sort(key=lambda x: x["score"], reverse=True)
return results
def list_pages(category: str | None = None) -> list[dict]:
"""List all wiki pages, optionally filtered by category."""
entries = _load_index()
if category:
return [e for e in entries if e["category"] == category]
return entries
def get_log(last_n: int = 20) -> list[str]:
"""Return the last N log entries from log.md."""
if not _LOG_FILE.exists():
return []
lines = _LOG_FILE.read_text().splitlines()
entries = [l for l in lines if l.startswith("## [")]
return entries[-last_n:]
def lint_wiki() -> dict:
"""
Health-check the wiki as described in Karpathy's LLM Wiki pattern.
Checks for:
- Orphan pages (in directory but not in index)
- Missing pages (in index but file deleted)
- Broken wikilinks ([[slug]] pointing to non-existent file)
- Pages with no wikilinks (isolated pages)
Returns:
{
"orphan_pages": [...],
"missing_pages": [...],
"broken_wikilinks": {slug: [broken_links]},
"isolated_pages": [...],
}
"""
index_entries = {e["slug"] for e in _load_index()}
file_slugs: dict[str, Path] = {}
for d in _CATEGORY_DIRS.values():
if d.exists():
for p in d.glob("*.md"):
file_slugs[p.stem] = p
orphans = [s for s in file_slugs if s not in index_entries]
missing = [s for s in index_entries if s not in file_slugs]
broken_wikilinks: dict[str, list[str]] = {}
isolated: list[str] = []
all_slugs = set(file_slugs.keys())
for slug, path in file_slugs.items():
content = path.read_text()
links = re.findall(r"\[\[([^\]]+)\]\]", content)
if not links:
isolated.append(slug)
broken = [lnk for lnk in links if _slug(lnk) not in all_slugs]
if broken:
broken_wikilinks[slug] = broken
return {
"orphan_pages": orphans,
"missing_pages": missing,
"broken_wikilinks": broken_wikilinks,
"isolated_pages": isolated,
}
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
fizznix
- 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