VeriWiki
Health Gecti
- License — License: MIT
- Description — Repository has a description
- Active repo — Last push 0 days ago
- Community trust — 116 GitHub stars
Code Gecti
- Code scan — Scanned 12 files during light audit, no dangerous patterns found
Permissions Gecti
- Permissions — No dangerous permissions requested
Bu listing icin henuz AI raporu yok.
VeriWiki: Provenance-Bound Incremental Epistemic Knowledge Compiler & Submodular Context Engine for AI Agents (Tarjan-SCC Merkle DAG, Contradiction Verifier, Submodular Context Packager & Zero-Dep Stdio MCP)
VeriWiki
Provenance-Bound Incremental Epistemic Knowledge Compiler & Submodular Context Engine for AI Agents
English · 简体中文 · Live Knowledge Graph (Quartz) · Architecture Spec · Benchmarks
VeriWiki transforms plain, Git-versioned Markdown repositories from loose note folders into a deterministic, provenance-verified knowledge compiler and budgeted context runtime for AI agents (Claude Code, Codex, OpenCode, Cursor, Windsurf, and custom MCP pipelines) alongside human IDEs (Obsidian and Quartz).
While Karpathy's LLM Wiki pattern rightly shifts agent memory from stateless query-time chunk rediscovery to persistent Markdown synthesis ("Obsidian is the IDE; the LLM is the programmer; the wiki is the codebase"), prompt-only LLM Wikis and naive RAG pipelines break down as knowledge bases scale past a few hundred pages. VeriWiki supplies the missing compiler middle-end and runtime: Tarjan-SCC Merkle dependency tracking, signed contradiction and supersession verification, hub-penalized typed Personalized PageRank, monotone submodular context optimization, and a zero-dependency JSON-RPC 2.0 Stdio MCP server.
Table of Contents
- Diagnosed Bottlenecks in Naive LLM Wikis & RAG
- Core Architecture: Four-Stage Epistemic Compiler
- Comparison with Existing Knowledge Systems
- Empirical Benchmarks on Live 1,063-Page Corpus
- 60-Second Quickstart
- Native MCP Server Integration (Claude Code, Codex, Cursor, OpenCode)
- CLI & Progressive Context Tiers (
L0–L3) - Python SDK Usage
- Repository Layout & Live Dogfooding Corpus
- Configuration & Epistemic Governance
Diagnosed Bottlenecks in Naive LLM Wikis & RAG
- Silent Cascade Drift & Unbound Provenance:
In prompt-only LLM Wikis, editing a primaryraw/document or foundationalconceptpage leaves downstreamanalysis,comparison, andsynthesispages silently stale. Without transitive Merkle digests or live content-hash rebinding, agents cite outdated prose while triple-duplicated JSON caches bloat Git repositories (e.g., 32 MB full-body dumps). - Hub Flood & Contradiction Blindness:
Treating all[[wikilinks]]as uniform untyped edges lets generic navigation hubs (index,home, collection roots) monopolize 1-hop graph expansion. Meanwhile, opposing claims across notes, unbalanced signedsupports/contradictstriangles, and uncollapsedA → B → Csupersession chains accumulate without static verification. - Redundant Top-$K$ Context Collapse & OS Coupling:
Independent top-$K$ BM25 or cosine ranking packs near-duplicate introductory sections from related notes into the prompt window, wasting 60%+ of token budgets while starving tail aspects and counterpoints. Worse, trusting cached metadata without live SHA-256 rebinding risks leaking local workstation paths or private files.
Core Architecture: Four-Stage Epistemic Compiler
Stage 1: Provenance-Bound Epistemic IR & Merkle Compiler (ir.py, compiler.py, codegraph.py)
- Physical Confinement & Pre-Ingest Scrubbing: Non-following
os.scandirtraversal strictly confines compilation to publicwiki/*.md, rejecting symlinks, junctions, and..path escapes whileveriwiki scrubblocks API keys (sk-*,ghp_*,AKIA*), PEM keys, and workstation user paths. - Structured
PageIR: Extracts heading-scopedSectionSpanline bounds + SHA-256 hashes, structuredClaimRecordstatements (EXTRACTED,INFERRED,AMBIGUOUS,UNVERIFIED, subject entities, $\pm 1$ polarity, quantitative metrics), resolvedTypedEdgerelations (extends,supports,contradicts,compares,supersedes,depends-on,derived-from), tiered Obsidian/Quartz symbol resolution (id > stem > alias/title), and 5-field BM25F term vectors (title,tags,headings,claims,bodywith Unicode + CJK bigram tokenization). - Cycle-Safe Tarjan-SCC Merkle DAG: Mutual concept cross-references are condensed via Tarjan's Strongly Connected Components ($O(V + E)$) before computing transitive digests:
$$H_{\text{merkle}}(u) = \operatorname{SHA256}!\Big(h_{\text{self}}(u) ;|; \bigoplus_{r \in \text{Raw}(u)} h(r) ;|; \bigoplus_{v \in \text{Deps}(u)} \big(\operatorname{rel}(u,v) : H_{\text{merkle}}(v)\big)\Big)$$ - Compact Catalog v3 & Dirty Wavefronts: Normalized serialization with a cryptographic
pages_sha256tamper seal shrinkswiki/catalog.jsonby 80.1% (from ~30–32 MB down to 5.93 MB), whileveriwiki compile --planemits topological rebuild wavefronts (Wave 1 → Wave 2 → ...) in ~480 ms (12.4× faster than cold builds).
Stage 2: Epistemic Verifier & Belief Lifecycle Engine (verifier.py, crystallizer.py)
- Signed Tension & Claim Polarity Auditor: Detects unacknowledged
contradictsedges, dual-sign edges, unbalanced signed triangles ($u \xrightarrow{+} w$, $v \xrightarrow{+} w$, $u \xleftrightarrow{-} v$), and opposing-polarityEXTRACTED/INFERREDclaims sharing topical terms on the same entity. - Supersession & Strict Freshness Gate: Audits
superseded_bycycles, uncollapsed multi-hop chains ($A \to B \to C$), stale active citations to superseded pages, missing## Counterpoints and Gapson debatable types, and stale on-disk catalogs (--strict-catalog). - Hub-Penalized Typed Personalized PageRank: Suppresses structural hubs and discounts high-in-degree generic nodes while amplifying typed epistemic conductance:
$$w(u \to v) = \frac{\rho(\operatorname{rel}(u, v))}{\big(\log_2(2 + d_{\text{in}}(v))\big)^\gamma}, \qquad \gamma = 0.85,; \alpha_{\text{ppr}} = 0.20$$ - Multi-Source Corroboration Retention: Models belief decay using both qualitative/numeric confidence priors $c_0(p)$ (
EXTRACTED: 0.95,INFERRED: 0.80,AMBIGUOUS: 0.55,UNVERIFIED: 0.35) and corroboration-expanded half-life:
$$R(p, t) = c_0(p)\cdot 2^{-\Delta t / \tau_{\text{eff}}(p)}, \qquad \tau_{\text{eff}}(p) = \tau_{\text{type}}(p)\Big(1 + \alpha\ln(1 + k_{\text{ind}}(p)) + \beta\ln(1 + d_{\text{cite}}(p))\Big)$$
Stage 3: Submodular Budgeted Context Compiler (packager.py)
- Hybrid Candidate Generation: Combines 5-field BM25F (
3.5t + 2.5g + 2.0h + 1.8c + 1.0b) with round-robin seed-balanced Typed-PPR discoveries via Reciprocal Rank Fusion, discounting superseded nodes. - Cost-Normalized Submodular Marginal-Gain Selection: Selects heading-scoped spans $s \in \mathcal{S}$ under strict character budgets $(B_{\text{total}}, B_{\text{source}})$ by greedily maximizing coverage minus pairwise Jaccard overlap:
$$\Delta F(s \mid S) = \operatorname{Rel}(q, s) + \lambda_c !!\sum_{t \in (\mathcal{T}(q)\cap s)\setminus \operatorname{Cov}(S)}!! \operatorname{idf}(t) ;-; \lambda_r \max_{s' \in S} J(s, s'), \qquad u(s \mid S) = \frac{\Delta F(s \mid S)}{|s|^\eta}$$ - Fail-Closed Cryptographic Rebinding (
[W1..Wk]): Re-reads livewiki/*.mdfiles at query time, verifies physical confinement and canonical ID match, computespage_sha256§ion_sha256, redacts unsafe local paths or URL query tokens, and attachesepistemic_warnings(contradicts,superseded_by).
Stage 4: Protocol-Native Agent & Publishing Runtime (mcp_server.py, cli.py, obsidian.py, site/)
- Zero-Dependency Stdio MCP Server: Auto-detects both newline-delimited JSON-RPC 2.0 (MCP 2024-11-05+) and
Content-Lengthframed transports using pure Python stdlib. - Closed-Loop Crystallization:
veriwiki crystallizeruns secret scrubbing, routes durable syntheses intowiki/, updateswiki/index.mdandwiki/log.md, and triggers incremental Merkle compilation. - Dual-Stack Human Publishing: Generates
.obsidian/vault configs, Architecture Canvas (wiki/canvases/veriwiki-architecture.canvas), and Quartz static sites deployed via GitHub Actions.
Comparison with Existing Knowledge Systems
| Dimension | Chunk Vector RAG | Prompt-Only LLM Wiki (karpathy-llm-wiki, claude-obsidian) |
Entity GraphRAG (GraphRAG, LightRAG) |
Temporal Memory Graphs (Graphiti, Cognee) |
VeriWiki |
|---|---|---|---|---|---|
| Source of Truth | Opaque vector store | Plain Markdown + Git | Parquet / KV / Neo4j | Graph DB (Neo4j/FalkorDB) | Plain Markdown + Git + Sealed IR v3 |
| Incremental Dirty-DAG | Per-file re-chunk | None (manual LLM pass) | Costly LLM re-extraction | Append-only episodes | Tarjan-SCC Merkle DAG + Wavefronts |
| Contradiction & Drift Audit | None | Prompt-only instruction | Community summary | Edge timestamp invalidation | Signed Triangles + Claim Polarity + Supersession |
| Context Optimization | Top-$K$ cosine | Read index.md + full files |
Community + token cap | Hybrid BFS + rerank | BM25F + Hub-Penalized PPR + Submodular Gain |
| Citation Integrity | Chunk ID only | Unverified [[links]] |
Extracted entity IDs | Episode UUID | Fail-Closed Live SHA-256 Rebinding ([W1..Wk]) |
| Runtime Dependencies | Embedding API + DB | None (no engine) | Heavy LLM API + DB | Graph DB + LLM API | Zero External Deps (Python 3.10+ Stdlib) |
| Agent + Human Interfaces | Python SDK / REST | Agent Skill + Obsidian | Python CLI / API | MCP + Graph DB | Stdio MCP + Unified CLI + Obsidian + Quartz |
Empirical Benchmarks on Live 1,063-Page Corpus
Reproduce every metric locally in seconds with veriwiki benchmark (src/veriwiki/benchmark.py):
1. Compiler Footprint & Incremental Merkle Speedup
| Metric | Legacy Full-Body Catalog (v2) | VeriWiki Compact Catalog (v3) | Gain |
|---|---|---|---|
wiki/catalog.json Size |
29.76 MB (32.0 MB pre-curation) | 5.93 MB | −80.1% (−81.5% vs. raw v2) |
| Cold Full Compile (1,063 pages, 1,940 claims, 5,675 edges) | — | 5,967 ms | Full IR + Tarjan-SCC Merkle + Seal |
| Warm Incremental Merkle Compile | — | 482 ms | 12.4× speedup |
2. Budgeted Context Assembly (max_chars = 3,600, top_k = 5, 8 Multi-Aspect Synthesis Queries)
| Method | Aspect Coverage ↑ | Pairwise Jaccard Redundancy ↓ | Off-Query Hub Pollution ↓ | Unique Terms / 1k Chars ↑ |
|---|---|---|---|---|
| B1: Naive Top-K Lexical | 62.5% | 0.2500 | 18.8% | 46.1 |
| B2: BM25 + Uniform 1-Hop (v2) | 72.9% | 0.1334 | 10.0% | 57.9 |
| VeriWiki (BM25F + Typed-PPR + Submodular) | 85.4% | 0.0372 | 12.5% | 82.5 |
Submodular marginal-gain selection lifts multi-aspect coverage by +22.9 pp over Naive Top-$K$ (
62.5% → 85.4%), cuts inter-citation redundancy by 6.7× (0.2500 → 0.0372), and increases conceptual density by +78.9% (46.1 → 82.5unique terms / 1k chars). Across all 7 structural, epistemic, and privacy fault-injection classes,veriwiki verify+veriwiki scrubachieve 7 / 7 (100%) recall.
60-Second Quickstart
VeriWiki ships with its own zero-dependency PEP 517/660 build backend (_veriwiki_build.py), so editable installation works even in offline or air-gapped environments without setuptools or internet access:
git clone https://github.com/appleweiping/VeriWiki.git
cd VeriWiki
# Zero-dependency editable install (works online or completely offline)
pip install -e . --no-build-isolation
# 1. Inspect corpus telemetry & catalog freshness
veriwiki status
# 2. Incremental Merkle compilation -> Compact Catalog v3 (wiki/catalog.json)
veriwiki compile
veriwiki compile --plan # Preview dirty-propagation rebuild wavefronts
# 3. Run full static, privacy, contradiction & supersession verification
veriwiki verify --strict-catalog
# 4. Hybrid BM25F + Hub-Penalized Typed-PPR search
veriwiki search "calibrated uncertainty recommendation" --graph
# 5. Compile a budgeted, submodular, SHA-256 rebound L2 evidence pack
veriwiki context L2 --query "LLM wiki incremental merkle contradiction" --graph --max-chars 4000
veriwiki context L2 --query "LLM wiki incremental merkle contradiction" --graph --json
# 6. Run the reproducible benchmark suite
veriwiki benchmark
Native MCP Server Integration (Claude Code, Codex, Cursor, OpenCode)
VeriWiki includes a preconfigured .mcp.json at the repository root. Any MCP-compatible coding agent can launch veriwiki mcp directly over stdio with zero third-party pip packages.
Claude Code / Cursor / Windsurf (.mcp.json)
{
"mcpServers": {
"veriwiki": {
"command": "veriwiki",
"args": ["--root", "/path/to/VeriWiki", "mcp"]
}
}
}
(Or without installation: "command": "python3", "args": ["-m", "veriwiki", "--root", ".", "mcp"] with "PYTHONPATH": "src".)
Codex (.codex/config.toml)
[mcp_servers.veriwiki]
command = "veriwiki"
args = ["--root", "/path/to/VeriWiki", "mcp"]
Exposed MCP Surface
| Kind | Name | Description |
|---|---|---|
| Tool | veriwiki_context_pack |
Compile budgeted submodular [W1..Wk] evidence packs with live SHA-256 digests and epistemic_warnings. |
| Tool | veriwiki_search |
Hybrid BM25F + Hub-Penalized Typed-PPR search across compiled pages. |
| Tool | veriwiki_verify |
Audit broken/ambiguous links, privacy leaks, signed contradiction triangles, claim polarity conflicts, and supersession chains. |
| Tool | veriwiki_compile_plan |
Compute Merkle dependency diffs, upstream temporal lag, and topological rebuild wavefronts. |
| Tool | veriwiki_crystallize |
Scrub secrets and promote verified Q&A, analyses, or comparisons into wiki/ with index/log/catalog updates. |
| Tool | veriwiki_graph_neighbors |
Inspect global graph topology, $k$-hop semantic neighborhoods, or shortest paths. |
| Tool | veriwiki_scrub |
Scan raw text for API keys, credentials, PEM blocks, and workstation/private paths. |
| Tool | veriwiki_status |
Return corpus telemetry, quality score, claim/edge counts, and health diagnostics. |
| Resource | veriwiki://overview |
Architecture & domain overview (wiki/overview.md). |
| Resource | veriwiki://index |
Human-readable master catalog (wiki/index.md). |
| Resource | veriwiki://schema |
Epistemic object & relation specification (.wiki-schema.md). |
| Resource | veriwiki://page/{id} |
Full Markdown source of any public compiled page (L3 tier). |
CLI & Progressive Context Tiers (L0–L3)
| Tier / Command | Purpose | Example |
|---|---|---|
L0 Orientation |
Compact reader profile, purpose, overview, and recent log headings | veriwiki context L0 |
L1 Navigation |
Master human-readable index (wiki/index.md), optionally paired with L2 |
veriwiki context L1 |
L2 Evidence Pack |
Submodular budgeted [W1..Wk] section excerpts with live SHA-256 provenance |
veriwiki context L2 -q "ReAct tool agents" --graph --json |
L3 Full Source |
Verified full Markdown page confined inside wiki/ |
veriwiki context L3 --page concepts/veriwiki-architecture |
compile |
Incremental or --full Merkle IR build, or --plan dirty-wavefront preview |
veriwiki compile / veriwiki compile --plan |
verify |
Static + epistemic verification (--strict-catalog, --json) |
veriwiki verify --strict-catalog |
lifecycle |
Corroboration-weighted belief retention & staleness audit | veriwiki lifecycle --json |
crystallize |
Route durable notes into wiki/ + update index, log, and catalog |
veriwiki crystallize --title "..." --type analysis --from-file memo.md |
scrub |
Non-destructive secret & workstation-path redaction (--apply) |
veriwiki scrub raw/inbox/draft.md --apply |
graph |
Knowledge graph stats, neighbors, path, or export |
veriwiki graph path sources/2026-04-21-llm-wiki-pattern concepts/veriwiki-architecture |
codegraph |
Static Python/JS/TS AST symbol & blast-radius analyzer | veriwiki codegraph blast-radius src/veriwiki/ir.py |
obsidian |
Refresh .obsidian/, Canvas, and Vault Dashboard (export, report, backlinks, tags) |
veriwiki obsidian export |
health |
Quality score distribution and non-destructive self-healing (--fix) |
veriwiki health --fix --dry-run |
Python SDK Usage
from veriwiki import (
compile_wiki,
verify_wiki,
build_context_pack,
plan_incremental_rebuild,
)
# 1. Compile or incrementally update the Epistemic IR catalog
catalog, report = compile_wiki(".", incremental=True)
print(f"Compiled {report.page_count} pages and {report.claim_count} claims in {report.elapsed_ms} ms")
# 2. Audit structural invariants, signed contradiction triangles & supersession chains
verification = verify_wiki(".", require_fresh_catalog=True)
assert verification.ok, verification.to_dict()
# 3. Assemble a submodular budgeted evidence pack with live SHA-256 rebinding
pack = build_context_pack(
".",
catalog,
query="submodular context packaging merkle provenance",
top=5,
max_chars=4000,
use_graph=True,
)
for item in pack["citations"]:
print(f"[{item['citation_id']}] {item['title']} ({item['path']} @ {item['page_sha256'][:12]})")
Repository Layout & Live Dogfooding Corpus
VeriWiki/
├── src/veriwiki/ # Zero-dependency Python 3.10+ compiler & runtime
│ ├── config.py # Portable TOML/JSON/env VeriWikiConfig
│ ├── ir.py # PageIR, SectionSpan, ClaimRecord, TypedEdge, confinement
│ ├── compiler.py # Tarjan-SCC Merkle DAG, dirty wavefronts, Compact Catalog v3
│ ├── verifier.py # Contradiction, polarity, supersession, Typed-PPR & retention
│ ├── packager.py # BM25F + Typed-PPR + Submodular L0-L3 context compiler
│ ├── mcp_server.py # JSON-RPC 2.0 Stdio MCP server (NDJSON + Content-Length)
│ ├── crystallizer.py # Routed page crystallization & self-healing
│ ├── codegraph.py # Static Python/TS/JS AST causal graph & blast radius
│ ├── obsidian.py # Obsidian vault, Canvas & dashboard exporter
│ ├── benchmark.py # Multi-baseline retrieval & fault-injection benchmark
│ └── cli.py # Unified `veriwiki` CLI
├── wiki/ # 1,063-page compiled public AI & systems showcase corpus
│ ├── concepts/ # Compiler architecture, LLM-Wiki, uncertainty & agent patterns
│ ├── comparisons/ # Side-by-side architectural tradeoff matrices
│ ├── analyses/ # Taxonomies, research maps & live benchmark reports
│ ├── queries/ # Crystallized technical Q&A
│ ├── entities/ # Systems, frameworks & researcher nodes
│ ├── topics/ # Domain cluster maps
│ ├── sources/ # Compiled Karpathy, Shunyu Yao, OpenAI Cookbook, Codex & Web corpora
│ ├── home.md / index.md # Command Center & human-readable Master Catalog
│ └── catalog.json # Tamper-sealed Normalized Compact Catalog v3
├── raw/ # Immutable public-safe primary source manifests
├── skills/veriwiki/SKILL.md # Universal Agent Skill (+ .claude/ & .codex/ adapters)
├── site/ # Quartz v4 static graph & GitHub Pages adapter
├── scripts/ # Compatibility CLI shims, safety gate & diagram generator
├── tests/ # Unit, security, MCP stdio & Merkle DAG test suite
├── assets/ # Vector & high-DPI architecture diagrams
├── AGENTS.md / .wiki-schema.md # Canonical agent operating contract & epistemic schema
└── pyproject.toml # PEP 621 package metadata + offline PEP 517/660 backend
Configuration & Epistemic Governance
Optional repository-level settings can be placed in veriwiki.toml (or .veriwiki.json) and overridden via environment variables (VERIWIKI_ROOT, VERIWIKI_SEMANTIC_URL):
[veriwiki]
default_max_chars = 12000
default_max_source_chars = 2400
default_top_k = 6
ppr_alpha = 0.20
hub_degree_exponent = 0.85
submodular_coverage_weight = 2.40
submodular_redundancy_weight = 3.20
drift_lag_days = 30
stale_retention_threshold = 0.35
Verification & CI Quality Gates
Every push and pull request runs two automated pipelines:
wiki-quality.yml(Ubuntu + Windows): Compiles all Python packages, runs unit/security/MCP/Merkle test suites (tests/+scripts/test_context_pack.py), enforcesveriwiki verify --strict-catalog(0broken/ambiguous links,0unindexed pages,0private leaks), smoke-tests[W1..Wk]SHA-256 provenance rebinding, and runsscripts/check_safety.py.deploy.yml&pages-health.yml: Builds the publicwiki/tree via Quartz and verifies live GitHub Pages availability with zero private-layer leakage.
License
Released under the MIT License.
Yorumlar (0)
Yorum birakmak icin giris yap.
Yorum birakSonuc bulunamadi