{"id":"3c89c20e-76a3-4f06-b48e-7627a28de2ea","slug":"tng-wiki","kind":"mcp","name":"tng-wiki","summary":"Scaffold an LLM-maintained knowledge base in under 10 minutes. Domain templates, agent-agnostic, QMD-ready.","owner":"thenewguardai","repoUrl":"https://github.com/thenewguardai/tng-wiki","license":"MIT","licenseTier":"permissive","trust":"community","stars":3,"match":null,"fewStars":true,"format":"mcp","createdAt":"2026-04-21T18:39:32.000Z","addedAt":"2026-10-21T17:13:56.185Z","logoUrl":"https://avatars.githubusercontent.com/u/262802036?v=4","linkOnly":false,"collection":null,"skillPath":null,"categories":["memory-knowledge"],"tags":[],"runtime":"node","local":true,"cloudCapable":false,"cloudCapability":"unknown","cloudReadyOnPlatform":false,"needsApiKey":false,"reviewed":false,"syncedAt":"2026-10-25T23:21:17.512Z","sample":false,"url":"https://conduits.dev/tools/tng-wiki","language":"JavaScript","transports":["stdio"],"install":{"npm":"@thenewguard/tng-wiki"},"requirements":{"env":[],"upstreamMayCharge":false},"tools":null,"readme":"# tng-wiki\n\n**Keep your LLM wiki honest.** A per-claim citation lockfile, drift detection, and code-grounding for Karpathy-style knowledge bases, so an agent-maintained wiki stays trustworthy as it grows instead of silently rotting.\n\nBuilt by [The New Guard](https://thenewguard.ai). Inspired by [Karpathy's LLM Wiki pattern](https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f).\n\n```\nnpx @thenewguard/tng-wiki init\n```\n\n## The Problem It Solves\n\nAn LLM-maintained wiki compounds in value, and in risk. Sources update, the agent under-updates on ingest, confidence inflates, and pages quietly drift from what their sources actually say. A wiki you can't trust is worse than no wiki. tng-wiki is the layer that keeps attribution honest as the wiki grows:\n\n- **A per-claim citation lockfile** (`wiki/.tng-wiki.lock.json`) that answers *\"which claims changed since a human last verified them?\"* - not \"which files were touched.\" Content-hashed and move-aware: it tells a citation that merely shifted line numbers (a safe auto-fix) apart from one whose cited content actually changed (re-verify).\n- **A three-layer grounding pipeline** - structural lint (`ground`, zero-LLM), agent-driven semantic re-verification (`⚠️ DRIFT?`), and opt-in authority validation against web sources *or* a local codebase. That last one is built for reverse-engineering / porting / M&A work, where the code is ground truth and the AI-generated PRDs in `raw/` are just hypotheses.\n- **Claim-next-to-evidence review** (`cite show`) - every citation printed beside the exact source lines it points at, so a human can verify without hunting.\n\nIt scaffolds a fresh wiki in one command, or adopts an existing repo as one. **The CLI makes zero LLM calls** - it verifies structure and configures tools; your agent is the intelligence.\n\n## What You Get Out of the Box\n\n- **Verification toolchain** - the citation lockfile, `ground` / `cite`, the marker lint verbs (`drift`, `stale`, `unsourced`, `unverified`, `orphans`), and `rounds` to run the whole maintenance bundle at once.\n- **8 domain templates** - AI Research, Competitive Intel, Publication, Business Ops, Learning, Software Engineering & Architecture, Code Archaeology, or Blank. Each ships a tailored schema, directory layout, and page types.\n- **Agent-agnostic schema** - one canonical `AGENTS.md` (kept lean - ~40 always-on lines plus a hand-authored `## Scope`; procedures, grounding protocol, and marker taxonomy load on demand from `.tng-wiki/doctrine/`) with per-agent aliases (`CLAUDE.md`, `.cursorrules`) for Claude Code, OpenAI Codex, Cursor, opencode, hermes-agent, OpenClaw, Aider, and anything that reads the [agents.md](https://agents.md/) convention.\n- **Multi-wiki registry** - one user, many wikis. Reach any registered wiki from any directory by slug.\n- **Wiki access verbs** - `query`, `read`, `search` (with `--include-raw` deep search), `sources` - plain text by default, `--json` for scripts and MCP.\n- **Claude Code skill** - `tng-wiki install-skill` teaches every session the verbs and when to use them. Zero token cost until invoked.\n- **MCP server** - `tng-wiki-mcp` ships alongside the CLI for shell-less agents (Claude Desktop, ChatGPT Desktop, web UIs).\n- **QMD hybrid search** - optional BM25 + vector + LLM re-rank integration for wikis past ~100 pages.\n- **Git + Obsidian ready** - `git init` with initial commit on scaffold; suggests a default path from common Obsidian vault locations.\n\n## Why This Exists\n\nKarpathy described the pattern; dozens of people built scaffolders and plugins around it. The gap nobody filled is *keeping the wiki trustworthy over time* - the failure mode production users named as the real one: the agent under-updates on ingest, pages silently go stale, and nothing tells you which claims drifted. tng-wiki applies a package-lockfile mindset to knowledge claims, so \"verified against this source, at this version\" becomes a checkable fact instead of a hope.\n\nIts sharpest fit is high-stakes, source-grounded work with fallible inputs - reverse-engineering a codebase, M&A / IP due diligence, porting - where `raw/` holds AI-generated docs that may hallucinate and a real codebase is the ground truth the wiki validates against. It also scaffolds a clean general-purpose research wiki in one command.\n\n## Quick Start\n\n```bash\nnpx @thenewguard/tng-wiki init\n```\n\nThe interactive flow walks you through:\n\n1. **Domain** - AI Research, Competitive Intel, Publication, Business Ops, Learning, Software Engineering & Architecture, Code Archaeology, or Blank\n2. **Agent** - Claude Code, OpenAI Codex, Cursor, or all three\n3. **Location** - where to create the wiki (suggests a default path from common Obsidian locations)\n4. **Wiki name**\n5. **Integrations** - Git and/or QMD hybrid search\n6. **Code authorities** *(Software Engineering, Code Archaeology, and Blank domains)* - register one or more reference codebases as advisory ground truth for [Layer 3B grounding](#3b--code-authorities-local-filesystem). On Code Archaeology the prompt nudges hard, since the whole point of the domain is verifying against real code. Optional; skip on first scaffold and add later by editing `.tng-wiki.json`.\n\n**Non-interactive / agent setup.** Pass `--yes` with flags to scaffold headless (no prompts):\n\n```bash\ntng-wiki init --yes --dir ./my-wiki --domain software-engineering --agent claude-code --name \"My Wiki\" --no-integrations\n```\n\nAdd `--into-existing` to adopt tng-wiki into a non-empty directory (existing files are preserved, `.gitignore` is merged). `tng-wiki init --help` lists every flag. Code authorities are configured by editing `.tng-wiki.json` afterward.\n\nThen it scaffolds everything:\n\n```\nyour-wiki/\n├── raw/              ← Drop sources here (immutable)\n├── wiki/             ← LLM-compiled, LLM-maintained\n│   ├── index.md      ← Master table of contents\n│   ├── log.md        ← Append-only operations log\n│   └── ...           ← Domain-specific directories\n├── output/           ← Query results, drafts, slides\n├── AGENTS.md         ← Canonical agent operating instructions\n├── CLAUDE.md         ← Symlink → AGENTS.md (for Claude Code)\n├── .cursorrules      ← Symlink → AGENTS.md (for Cursor)\n└── .gitignore\n```\n\nOpen in Obsidian. Drop your first sources into `raw/`. Then:\n\n```bash\n# Claude Code\ncd your-wiki && claude \"Read AGENTS.md, then ingest the sources in raw/\"\n\n# OpenAI Codex\ncd your-wiki && codex \"Read AGENTS.md, then ingest the sources in raw/\"\n```\n\nThe agent reads the schema, processes the source, builds wiki pages, updates the index, and logs the operation. The CLI gives you the scaffold; the agent runs the workflow.\n\n## Domain Templates\n\nEach template generates a tailored schema with domain-specific page types, directory structures, and workflows.\n\n| Domain | Page Types | Special Features |\n|--------|-----------|-----------------|\n| **AI / Tech Research** | Entities, protocols, stack layers, opportunities (scored), narratives, timelines, contradictions | Opportunity scoring framework, source quality tiers |\n| **Competitive Intel** | Companies, products, markets, SWOT analyses, signals | Signal type taxonomy, SWOT template |\n| **Publication** | Everything in AI Research + issue tracking | Issue prep workflow, post-publish loop, editorial calendar |\n| **Business Ops** | Projects, decisions, people, processes, retrospectives | Decision tracking, retrospective templates |\n| **Learning** | Concepts, people, connections, open questions | Connection pages for non-obvious links |\n| **Software Engineering & Architecture** | ADRs (with status lifecycle + supersedes chain), components, systems, patterns, incidents (P0-P3 severity), runbooks, tech debt (impact × effort scored) | ADR template, incident template, component template, severity taxonomy, ownership register, tech-debt scoring grid |\n| **Code Archaeology / Reverse Engineering** | Meta pages (glossary, ecosystem, project status, open threads, patterns), frozen deliverables (DISCOVERY / ANALYSIS / DESIGN / NOTES), inbox | Verification-first flow, rejection log, code authorities as ground truth, leads-never-sources firewall |\n| **Blank** | Topics | Minimal - structure emerges from content |\n\n## Agent Support\n\n`AGENTS.md` is the canonical schema file - the [agents.md](https://agents.md/) convention is read natively by Claude Code, OpenAI Codex, Cursor, opencode, hermes-agent, OpenClaw, Aider, and others. `tng-wiki init` always writes `AGENTS.md` and creates per-agent filename aliases (symlinks where the filesystem supports them, file copies otherwise) so each agent finds the file it expects to find.\n\n| Agent | File it reads | How `tng-wiki` provides it |\n|-------|--------------|----------------------------|\n| Claude Code | `CLAUDE.md` | Symlink → `AGENTS.md` |\n| OpenAI Codex | `AGENTS.md` | Direct |\n| Cursor | `.cursorrules` | Symlink → `AGENTS.md` |\n| opencode / hermes-agent / OpenClaw / Aider / others | `AGENTS.md` | Direct |\n\nOne schema, every agent. Edit `AGENTS.md`; every alias sees the change.\n\n## Commands\n\n```bash\n# Scaffolding\ntng-wiki init                       # Scaffold a new wiki (interactive; --yes for headless)\ntng-wiki upgrade    [path] [--wiki <slug> | --all] [--domain <d>] [--dry-run] [--json]\n                                    # Regenerate schema + doctrine after a CLI update\n                                    #   (hand-authored sections survive; see below)\ntng-wiki localize   [path] [--wiki <slug>] [--set <name>=<path>]... [--trust <name>]...\n                                    # Reconcile a shared wiki with this machine:\n                                    #   remap or trust code authorities (see Sharing)\ntng-wiki split      --pages <glob|zone> --into <path> --dry-run [--wiki <slug>] [--json]\n                                    # Analyze extracting a subset into its own wiki:\n                                    #   what moves, which lock entries transplant,\n                                    #   which links go cross-wiki (dry-run only)\n\n# Registry\ntng-wiki join <git-url> [--path <dir>]   # Onboard this machine to a shared wiki repo\ntng-wiki register [path]            # Register an existing wiki\ntng-wiki unregister <slug>          # Remove from the registry (files untouched)\ntng-wiki list                       # List registered wikis (★ marks default)\ntng-wiki set-default <slug>         # Set the default wiki\ntng-wiki librarian  [--wiki <slug>] [--set <host> | --set-here | --clear]\n                                    # The one machine that files this wiki; others capture\n\n# Wiki access (the verbs your agent will call)\ntng-wiki query      [--wiki <slug>] [--json]\ntng-wiki read       <page> [--wiki <slug>] [--json]   # path, [[wikilink]], or unique page stem\ntng-wiki search     <query> [--wiki <slug>] [--regex] [--include-raw] [--json]\ntng-wiki sources    [--wiki <slug>] [--uncompiled] [--json]\ntng-wiki inbox      [--wiki <slug>] [--json]           # pending _inbox/ captures, every registered wiki\n\n# Grounding + lint (keeping the wiki honest)\ntng-wiki ground     [--wiki <slug>] [--page <path>] [--at-ref] [--json]   # structural ground-check\ntng-wiki drift      [--wiki <slug>] [--json]                   # ⚠️ DRIFT?      markers\ntng-wiki unsourced  [--wiki <slug>] [--json]                   # ⚠️ UNSOURCED?  markers\ntng-wiki unverified [--wiki <slug>] [--json]                   # ⚠️ UNVERIFIED? markers\ntng-wiki stale      [--wiki <slug>] [--json]                   # ⚠️ STALE?      markers\ntng-wiki orphans    [--wiki <slug>] [--json]                   # pages with no inbound wikilinks\n\n# Agent integration\ntng-wiki install-skill              # Install the Claude Code skill (~/.claude/skills/tng-wiki)\n                                    #   [--force] overwrite  [--uninstall] remove\n\n# Diagnostics\ntng-wiki status     [path] [--wiki <slug>] [--json]   # Basic wiki health snapshot\ntng-wiki doctor                     # Environment check: agent CLIs, QMD, git\ntng-wiki help\n```\n\n## Agent onboarding\n\ntng-wiki is built to be driven *by* an agent, so the command surface is self-describing - a session shouldn't have to probe verb-by-verb to work out how to set up or use a wiki:\n\n- **`tng-wiki help --json`** emits the full machine-readable manifest: every command with its flags, args, and examples, plus a copy-pasteable `onboarding` block (create / adopt / register / connect recipes). One call, the whole surface.\n- **Every command supports `--help`** (human) and `--help --json` (structured); `tng-wiki help <command>` works too. It's all generated from one spec, so help and the manifest can't drift from what actually runs.\n- **`tng-wiki doctor`** reports the environment, the registry, whether the skill is installed, and - most useful for an agent - the **recommended next command** for the current directory (create a wiki, adopt this dir, register, or query an existing one). `--json` for the structured form.\n- **`tng-wiki init --yes --dir <path> --domain <d>`** scaffolds without a TTY; **`--into-existing`** adopts a non-empty repo.\n- **`tng-wiki install-skill`** teaches every Claude Code session the verbs *and* the setup recipes, so a fresh session never has to probe.\n\n## The Registry - one user, many wikis\n\n`tng-wiki` keeps a user-level registry at `~/.tng-wiki/registry.json` listing every wiki you've scaffolded or registered. `init` adds new wikis automatically; the first becomes the default. Every registered wiki is reachable from any working directory by its slug.\n\n```bash\ntng-wiki list\n#   ★ ai-research    ai-research         ~/Documents/Obsidian/ai-research-wiki\n#     comp-intel     competitive-intel   ~/work/comp-intel-wiki\n```\n\n## Sharing a wiki with your team - `localize`\n\nA wiki is a normal git repo, so handing it to a teammate is `git clone` + `tng-wiki register .`. The content, the schema, the citation lockfile - all portable. The one machine-specific thing is `code_authorities` / `lead_archives`: they point at *your* checkouts (`~/w/vso/foglifter-ng`), which a teammate keeps somewhere else, or doesn't have at all.\n\n`tng-wiki localize` reconciles that per machine, writing a **gitignored `.tng-wiki.local.json`** (the committed `.tng-wiki.json` stays canonical for the team - your teammate's local choices never enter shared history):\n\n```bash\ntng-wiki localize            # walks each authority: I have it (enter path) / trust as-is / skip\n```\n\nFor each authority a teammate doesn't have at your path, they choose:\n\n- **I have it** - point at their local path; full local verification resumes (`ground` re-checks every cite).\n- **Trust as-is** - accept your recorded verification as truth. This is the key one: the citation lockfile already records *what* was verified and *at which commit*, so a teammate without the code still consumes the knowledge with provenance. `ground` reports `ℹ authority \"foglifter-ng\": 34 citations trusted, not verifiable here (verified develop@8d280c2)` instead of erroring - the wiki reads as healthy, because for them it is.\n- **Skip** - leave it unresolved for now.\n\nHeadless / scripted form:\n\n```bash\ntng-wiki localize --set foglifter-ng=~/dev/foglifter-ng --trust kpom-legacy\ntng-wiki localize --yes --json     # report per-authority state without prompting\n```\n\n`tng-wiki doctor` reflects the result: a trusted authority reads healthy (\"verification inherited\"), a remapped one shows \"(local override)\". The upshot: a teammate gets the full *find-answers* value of your wiki immediately - `query` / `read` / `search` never needed the authorities - and re-verification is available for exactly the repos they actually have.\n\n## Wiki Access Verbs\n\nThese are the commands an agent invokes (via its Bash tool) to read and navigate a wiki. They're intentionally plain-text and line-oriented by default so agents can parse them fluently and Unix tools can pipe them. Every verb accepts `--wiki <slug>` and `--json` (machine-readable structured output for scripts and MCP wrappers).\n\n**Resolution order, every verb the same:** an explicit path argument (where the verb takes one) > `--wiki <slug>` > **the wiki the current directory is inside** (git-style - ancestor directories count, and an unregistered wiki still resolves) > the registered default. Standing inside a wiki and running a bare verb always targets *that* wiki, never a different registered default. The MCP server is the one exception: it has no meaningful cwd, so omitting the `wiki` parameter there means the registered default, as its tool descriptions say.\n\n### `query` - read the wiki's index\n\nPrints `wiki/index.md` for the chosen wiki. An agent's first call when answering any question about the wiki.\n\n```bash\n$ tng-wiki query\n# AI Research Wiki - Index\n\n_Last updated: 2026-04-15 | Total pages: 23 | Total sources: 41_\n...\n\n$ tng-wiki query --wiki comp-intel\n# Competitive Intelligence Wiki - Index\n...\n\n$ tng-wiki query --json | jq .wiki\n\"ai-research\"\n```\n\n### `read` - fetch a specific page\n\nPrints the content of a wiki page by its path relative to `wiki/`. Refuses paths that escape the wiki directory.\n\n```bash\n$ tng-wiki read entities/openai.md\n---\ntitle: \"OpenAI\"\ntype: entity\n...\n\n$ tng-wiki read opportunities/wiki-mcp-server.md --wiki ai-research\n...\n```\n\n### `search` - case-insensitive search across wiki pages\n\nPrints `[wiki] path:line: matching text` (grep-compatible). Use `--regex` for regex patterns. By default searches only compiled `wiki/` content - that's the canonical distilled knowledge.\n\nPass `--include-raw` to **search deep** into archival `raw/` sources as well. Use this when verifying claims, consulting originals, or when a detail might live in uncompiled source material. Each hit is tagged `[wiki]` or `[raw]` so you always know which layer it came from.\n\n```bash\n$ tng-wiki search karpathy\n[wiki] wiki/narratives/llm-knowledge-bases.md:12: Karpathy described the pattern\n[wiki] wiki/timelines/llm-tooling-2026.md:8: Karpathy post catalyzes wave of clones\n\n$ tng-wiki search karpathy --include-raw\n[wiki] wiki/narratives/llm-knowledge-bases.md:12: Karpathy described the pattern\n[raw]  raw/announcements/2026-04-04-karpathy-llm-knowledge-bases.md:5: \"There is room here for an incredible new product...\"\n\n$ tng-wiki search \"v\\d+\\.\\d+\\.\\d+\" --regex --wiki ai-research\n[wiki] wiki/entities/anthropic.md:42: Claude 4.6 (released v4.6.0)\n\n$ tng-wiki search karpathy --include-raw --json | jq '.hits | group_by(.source) | map({source: .[0].source, count: length})'\n[{\"source\": \"raw\", \"count\": 3}, {\"source\": \"wiki\", \"count\": 2}]\n```\n\n### `sources` - list raw source files\n\nEnumerates everything under `raw/` with `compiled` status from frontmatter. `--uncompiled` filters to sources the wiki hasn't ingested yet - useful for an agent to drive the ingest loop.\n\n```bash\n$ tng-wiki sources --uncompiled\n[uncompiled] raw/announcements/2026-04-15-openai-new-model.md  - OpenAI announces GPT-6\n[uncompiled] raw/papers/2026-karpathy-followup.md              - Karpathy on LLM knowledge compounding\n\n$ tng-wiki sources --json | jq '.sources | map(select(.compiled == false)) | length'\n2\n```\n\n### `inbox` - pending captures across every wiki\n\nLists what is waiting in each registered wiki's `_inbox/`: path, title (frontmatter or first heading), age in days, the host it was captured on, and any `also:` hints naming other wikis the librarian should consider. This is the triage queue for \"anything waiting anywhere?\", in one call.\n\n```bash\n$ tng-wiki inbox\nprojects 2 pending\n  ● 2026-09-27-webgl-gpu-timer.md - WebGL GPU timers read busy time on laptop GPUs (0d · from laptop)\n  ● 2026-09-27-threejs-compileasync.md - three.js compileAsync must bind the composer target (0d · also: shared)\nshared 0 pending\n```\n\n### `stale` - list pages with `⚠️ STALE?` markers\n\n```bash\n$ tng-wiki stale\nwiki/entities/anthropic.md    (3 markers)\nwiki/opportunities/ide-for-agents.md  (1 marker)\n```\n\n### `orphans` - pages with no inbound wikilinks\n\nLists pages nothing else in the wiki links to (excluding structural pages `wiki/index.md` and `wiki/log.md`). Helpful for linting coverage - a well-connected wiki has few orphans.\n\n```bash\n$ tng-wiki orphans\nwiki/entities/some-forgotten-entity.md\nwiki/opportunities/_scoring-criteria.md\n```\n\n## Grounding - keeping the wiki honest over time\n\nLLM-maintained wikis drift. Claims age, sources update, confidence inflates past the evidence, citations go stale. `tng-wiki` ships a three-layer grounding pipeline to catch and reconcile drift without auto-repairing its way into deeper errors.\n\n**Schema invariant:** every wiki page carries a frontmatter `sources:` list of raw paths, and every factual claim cites one of them inline using footnote syntax:\n\n```markdown\n---\nsources:\n  - raw/announcements/2026-anthropic-series-f.md\n  - raw/papers/anthropic-origins.md\n---\n\nAnthropic raised $8B in Series F.[^raw/announcements/2026-anthropic-series-f.md]\nThe company was founded in 2021.[^raw/papers/anthropic-origins.md]\n```\n\nThe `sources:` list is the trust anchor. Every grounding workflow walks it. The four markers (`⚠️ STALE?`, `⚠️ UNSOURCED?`, `⚠️ UNVERIFIED?`, `⚠️ DRIFT?`) are documented with specific resolution actions inside every generated `AGENTS.md` - agents follow those instructions, not a README.\n\n### Two canonical flows\n\nThere are two honest ways to run a wiki, distinguished by *when* verification happens:\n\n**Ingest-first (the default).** Compile raw sources into wiki pages, then verify over time. Grounding runs after the fact; the `⚠️` marker taxonomy is the **health surface** - markers accumulate where claims age, drift, or outrun their evidence, and rounds burns them down. Fits when sources are reasonably trusted and speed of compounding matters: research feeds, competitive intel, learning notes.\n\n**Verification-first (the inverse).** Treat every lead claim as a hypothesis: refute the premise first, validate against authorities (web or [code](#3b--code-authorities-local-filesystem)), and distill **only what survives** - typically `[confirmed]` claims - into the wiki. This flow produces near-zero markers by construction, so the health surface moves: the audit artifact is the **rejection log**, a NOTES deliverable (`deliverables/*_NOTES_*.md`) listing every rejected, corrected, or downgraded lead claim with its disposition. Its core argument: *\"we verified it\" without a list of what failed verification is evidence nothing was looked for.* Fits when the leads themselves are fallible and rigor beats speed: AI-generated PRDs, reverse-engineering, M&A / IP diligence.\n\nThe two flows share everything else - same schema invariant, same citation forms, same grounding layers. `tng-wiki rounds` reads both surfaces: marker counts for ingest-first health, plus an informational rejection-log count whenever `deliverables/*_NOTES_*.md` files exist.\n\n### Layer 1 - `ground` (structural, zero-LLM)\n\n```bash\n$ tng-wiki ground\nwiki/entities/openai.md\n  empty_sources: empty or missing frontmatter `sources:`\nwiki/entities/anthropic.md\n  missing_raw: cited raw file does not exist → raw/papers/deleted.md (line 12)\n  undeclared_cite: cited inline but not in frontmatter `sources:` → raw/social/tweet.md (line 8)\n  source_updated_after_page: raw source modified after page `updated` (page 2026-02-01, source 2026-04-15)\n\n3 issue(s) across 2 page(s), 47 scanned\n\n$ tng-wiki ground --page entities/openai.md          # scope to one page\n$ tng-wiki ground --at-ref                           # resolve code cites at each authority's pinned ref\n$ tng-wiki ground --json | jq '.issues | group_by(.issue)'    # structured for agents + scripts\n```\n\nDetects structural issues: empty/missing `sources:`, inline citations pointing at non-existent raw files, undeclared citations (inline but not in frontmatter), orphan declarations (frontmatter-only, never cited), raw sources whose last git commit-date (or mtime) is newer than the page's `updated` date, and code-authority problems (`unknown_code_authority`, `missing_code_file`, `excluded_code_file`, `code_line_out_of_range`). Add `--at-ref` to resolve code citations at each authority's pinned git `ref` instead of the working tree - this adds at-ref `missing_code_file`, `code_updated_after_page` (page `updated` predates the file's last commit at the ref), and `code_ref_unresolvable`; default `ground` stays working-tree-based. Skips `wiki/index.md`, `wiki/log.md`, `_`-prefixed template files, and `wiki/meta/*`.\n\nThree findings cover index and convention drift:\n\n- `index_header_drift` - the `wiki/index.md` scaffold header (`_Last updated: <date> | Total pages: <N> | ..._`) disagrees with reality. Page count = all `wiki/**/*.md` except `index.md`, `log.md`, and `_`-prefixed files (`wiki/meta/*` counts); the date drifts when it falls behind the newest page's git last-commit date (mtime fallback). JSON fields: `expected_pages` (header), `actual_pages`, `header_date`, `newest_page_date`, `formula`. Indexes without the scaffold header line are skipped - the check never imposes the header on customized indexes.\n- `frontmatter_updated_stale` *(warn-level)* - the page file changed (git last-commit date, mtime fallback) after its frontmatter `updated`, with a 1-day grace window for same-day/timezone noise. JSON fields: `updated`, `last_commit`.\n- `prose_internal_ref` *(warn-level)* - an internal page is referenced in prose (`` `page.md` `` inline-code token, or a markdown link to a relative `.md` path resolving to a wiki page) instead of a `[[wikilink]]`. Fenced code blocks, citation markers, and `raw/` / `deliverables/` file paths are exempt. JSON fields: `line`, `matched`, `suggest` (the `[[wikilink]]` to use).\n\nWarn-level findings are hygiene signals, not attribution breaks: they render in a distinct color (cyan instead of yellow), never change exit codes, and `tng-wiki rounds` counts them under `convention` instead of `ground`.\n\n### Layer 2 - semantic re-verification (agent-driven)\n\nAgents re-read raw sources, compare against wiki claims, and emit `⚠️ DRIFT?` markers where they diverge:\n\n```markdown\nClaim that may have drifted.[^raw/papers/source.md] ⚠️ DRIFT?\n[source: raw/papers/source.md says \"released Q2 2026\";\n wiki says \"released Q1 2026\";\n suggested: \"released Q2 2026\"]\n```\n\nThe marker is self-contained evidence. Reconcile interactively:\n\n```bash\n$ tng-wiki drift\nwiki/entities/anthropic.md  (2 markers)\nwiki/entities/openai.md  (1 marker)\n```\n\nThe agent walks each marker with the user - **accept / edit / reject / defer** - and removes it on resolution. Never auto-apply.\n\nThe full Layer 2 workflow (triage order, per-claim outcomes, dependency chains between wiki pages, batching etiquette for large runs) is documented in every scaffolded wiki's `.tng-wiki/doctrine/grounding.md`; the always-on `AGENTS.md` carries a compact `## Grounding` summary that points there. Agents follow that guidance directly.\n\n### Layer 3 - authority validation (opt-in)\n\nTwo kinds of authority, same semantics. Disagreement surfaces as `⚠️ DRIFT?` with evidence; human reconciles. Never auto-applied.\n\n#### 3A - Web authorities\n\nAgent uses `WebFetch` / `WebSearch` under strict authority rules - never free-range search, which is where confident-wrong creeps in.\n\n**Authority priority**, highest first:\n\n1. URLs cited within the raw source itself (the primary trust chain).\n2. Domains listed in the wiki's `.tng-wiki.json` under `trusted_authorities`:\n\n   ```json\n   {\n     \"version\": 1,\n     \"name\": \"AI Research Wiki\",\n     \"domain\": \"ai-research\",\n     \"trusted_authorities\": [\"docs.anthropic.com\", \"openai.com\", \"arxiv.org\"]\n   }\n   ```\n3. Explicit sources the user names in the ground-check request.\n\nEmpty `trusted_authorities` (the default on `init`) means Layer 3A can only reach URLs cited in raw sources. Opt in per-wiki when you want your agent to consult specific authorities automatically.\n\n#### 3B - Code authorities (local filesystem)\n\nBuilt for reverse-engineering, porting, and M&A / IP-acquisition workflows where `raw/` holds AI-generated PRDs and overview docs (fallible - they hallucinate APIs, invert precedence, miss edge cases) and the actual implementation is the ground truth. Cheaper and often higher-trust than web authorities - local filesystem, no network, no SEO drift.\n\nConfigure during `init` - when you pick the **Software Engineering** or **Blank** domain, `tng-wiki init` asks whether you have a reference codebase and walks you through registering each authority (path, name, language, optional git ref). You can also edit `.tng-wiki.json` directly:\n\n```json\n{\n  \"code_authorities\": [\n    {\n      \"name\": \"legacy-app\",\n      \"path\": \"../customer-portal-v1\",\n      \"description\": \"Source implementation being ported.\",\n      \"exclude\": [\"**/*.md\", \"docs/**\", \"**/*.test.*\", \"**/node_modules/**\", \"**/dist/**\"],\n      \"language\": \"typescript\",\n      \"ref\": \"v2.1.0\"\n    }\n  ]\n}\n```\n\nThe optional `ref` field pins reads to a specific git ref (branch, tag, or commit SHA) - useful when the source repo is actively evolving and you want grounding to be deterministic. The agent reads via `git show <ref>:<file>` rather than the working tree, so a stashed change or branch switch on the source repo can't contaminate the wiki. Leave `ref` unset (or remove the field) to read the working tree directly.\n\nInline citation form, GitHub-style `#L` anchor (clickable in VS Code, jumps to the line):\n\n```markdown\nThe login flow uses OAuth2 implicit grant - no PKCE parameters sent.[^raw/prd-auth.md][^code:legacy-app/src/auth/oauth.ts#L42-L58]\n```\n\nFrontmatter `sources:` declares the authority alongside raw paths:\n\n```yaml\nsources:\n  - raw/prd-auth.md\n  - code:legacy-app\n```\n\nScope during grounding is implementation-only - the agent disregards comments, docstrings, JSDoc, and any markdown/text files inside the authority tree, even ones the `exclude` globs didn't catch. Comments rot; the AI docs in `raw/` already did; the implementation is what the code *does*.\n\nExtended `⚠️ DRIFT?` marker format when a code authority is involved:\n\n```\n⚠️ DRIFT? [source: raw/prd-auth.md says \"OAuth2 with PKCE\";\n           code: legacy-app/src/auth/oauth.ts#L42-L58 shows \"implicit flow, no code_challenge parameter sent\";\n           wiki says \"OAuth2 with PKCE\";\n           suggested: \"OAuth2 implicit flow - legacy-app does not implement PKCE\"]\n```\n\nCode authorities are **advisory**, not absolute - disagreement always surfaces as `⚠️ DRIFT?` for human reconcile, never auto-applied. Structural checks (`tng-wiki ground`) catch code-authority failure classes: `unknown_code_authority` (cited authority not registered), `missing_code_file` (cited file path doesn't exist), `excluded_code_file` (cite targets a path the authority's `exclude` globs skip), and `code_line_out_of_range` (the `#L` anchor exceeds the file). With `tng-wiki ground --at-ref`, citations resolve at each authority's pinned `ref` instead of the working tree, adding `code_updated_after_page` and `code_ref_unresolvable`.\n\nFull workflow lives in `AGENTS.md → ### Grounding → Layer 3`. The Software Engineering & Architecture template ships a scaffolded example ADR (`wiki/decisions/_adr-code-authority-example.md`) showing the full pattern end-to-end.\n\n### Marker lint verbs\n\n```bash\n$ tng-wiki stale        # ⚠️ STALE?       (time-based, human/agent-written)\n$ tng-wiki unsourced    # ⚠️ UNSOURCED?   (ground Layer 1)\n$ tng-wiki unverified   # ⚠️ UNVERIFIED?  (ground Layer 1)\n$ tng-wiki drift        # ⚠️ DRIFT?       (Layer 2/3)\n```\n\nAll accept `--wiki <slug>` and `--json`. Output shape is `path (N markers)` for parity with the existing `stale`/`orphans` verbs.\n\n### Ongoing care - rounds\n\nThe wiki is *agent-maintained*, so the unit of interaction is one phrase - **\"do your rounds\"** - not six verbs you have to remember. Rounds bundles the maintenance loop:\n\n> **Rounds** = ingest anything pending in `raw/` → run `ground` / `orphans` / `unsourced` / `unverified` / `stale` / `drift` → reconcile what's safe and surface the `⚠️` markers that need you → update `index.md` + append a `log.md` entry → report a short summary.\n\nGive your agent the one-liner:\n\n```bash\nclaude \"Read AGENTS.md, then do your wiki rounds\"\n```\n\n`tng-wiki rounds [--wiki <slug>] [--json]` prints the maintenance dashboard - one count per category, zero-LLM - the anchor cron jobs and agents key off. When [verification-first](#two-canonical-flows) rejection logs exist (`deliverables/*_NOTES_*.md`), it adds an informational count so the audit artifact stays visible. Wikis with an `_inbox/` capture directory get an **inbox items pending triage** row (any file dropped there counts - captures are not markdown-only). The bundle is defined precisely in every scaffolded wiki's `.tng-wiki/doctrine/operations.md` (`## Rounds` - the canonical procedure the schema and the skill both point at) so any session understands the phrase. Wire it to a cadence with the `schedule` skill or cron.\n\nRounds also reports **ritual meta-health** - the maintenance loop itself can lapse while every marker reads clean. A closing line shows the age of the last `log.md` entry and the wiki repo's own uncommitted churn, and turns yellow only when both signals agree (log stale two weeks or more *and* uncommitted changes present):\n\n```\nRitual: last log entry 27d ago · uncommitted: 5 changed + 8 untracked\n```\n\n### Upgrading tng-wiki\n\n```bash\nnpm i -g @thenewguard/tng-wiki@latest   # every machine that uses the wikis\ntng-wiki doctor                          # names what is stale and the next command\ntng-wiki upgrade --all                   # one machine per wiki repo (its librarian host); commit + push\ntng-wiki install-skill                   # every machine\n```\n\nEach release's CHANGELOG entry opens with an \"Upgrading\" section when there is anything beyond these four commands (for 0.15: adopting the multi-machine flow, and the PATH shim).\n\n### Upgrading a wiki's schema - `upgrade`\n\nA wiki's `AGENTS.md` and `.tng-wiki/doctrine/` are generated, and the generator improves between releases - but wikis accumulate hand-written operating rules that a regen must never destroy. `tng-wiki upgrade` regenerates both without clobbering anything you wrote:\n\n```bash\n$ tng-wiki upgrade --dry-run     # report what would change, write nothing\n$ tng-wiki upgrade               # the wiki the cwd is inside, else the registered default\n$ tng-wiki upgrade --wiki research\n$ tng-wiki upgrade --domain code-archaeology   # re-domain while upgrading\n$ tng-wiki upgrade --all --dry-run             # every registered wiki on this machine\n```\n\nHow it preserves your content:\n\n- **Fenced schemas** (any scaffold or upgrade from v0.8.0 on) carry managed markers - `<!-- tng-wiki:schema ... -->` ... `<!-- /tng-wiki:schema -->`. Upgrade replaces only what's between them; anything you added above or below survives byte-for-byte.\n- **Pre-fence schemas** get a heading-based merge: any top-level `##` section the generator never owned (your hand-authored contracts, house rules, filing tables) is carried below the new fenced block, in order. Edits made *inside* generated sections are the one thing this can't detect - the previous schema is always backed up to `.tng-wiki/backup/AGENTS.md`, so `git diff` (or the backup) shows exactly what changed before you commit.\n\nUpgrade also refreshes copy-mode alias files (`CLAUDE.md` / `.cursorrules`; symlinks follow automatically, diverged copies are left alone and reported), converts pre-AGENTS.md wikis to the canonical layout, and stamps `schema_version` in `.tng-wiki.json`. `tng-wiki doctor` compares that stamp against the installed CLI and tells you which registered wikis are running an older schema.\n\n## Ambient Cross-Project Access\n\nOnce your wiki is registered, it's reachable from any project you're working in. How to plumb it into your agent depends on whether the agent has shell access.\n\n### Terminal agents (Claude Code, Codex, opencode, OpenClaw, hermes-agent)\n\nThese can invoke `tng-wiki` directly via their Bash tool. No MCP server, no schema tokens burned per session - the agent pays nothing until it actually uses a verb.\n\n**Claude Code - install the skill (recommended):**\n\n```bash\ntng-wiki install-skill\n# ✓ Installed tng-wiki skill → ~/.claude/skills/tng-wiki/SKILL.md\n```\n\nThis writes a Claude Code skill that teaches every future session the verbs and when to use them. Claude Code picks it up within the current session via live change detection (no restart). You can invoke the skill directly with `/tng-wiki` or let Claude load it automatically when your question matches the skill description. Re-run with `--force` to update after an upgrade, or `--uninstall` to remove.\n\n**Other terminal agents** - drop a one-liner in your project's `AGENTS.md`:\n\n```markdown\n## Knowledge Base\n\nYour long-term memory is a tng-wiki. Start any research task with\n`tng-wiki query` to see the index. Use `tng-wiki search <term>` and\n`tng-wiki read <path>` to navigate. Pass `--wiki <slug>` to target\na specific registered wiki (list them with `tng-wiki list`).\n```\n\n### Connect another repo to a wiki (automated)\n\nWriting that one-liner by hand into every repo is exactly what `tng-wiki connect` automates:\n\n```bash\ntng-wiki connect ~/code/some-app --wiki infra\n# ✓ wrote CLAUDE.local.md (added to .git/info/exclude)\n```\n\nIt writes a managed nudge block into a local agent file (`CLAUDE.local.md` for Claude Code) telling sessions in that repo to **search the wiki before re-deriving** domain knowledge and to **hand keepable output back** to it. The file is added to the repo's `.git/info/exclude` - **not** the tracked `.gitignore` - so it stays per-machine and never enters shared git history (it matters when the repo belongs to a client or team). Re-running updates the block in place; `--remove` deletes it. Set a `description` in the wiki's `.tng-wiki.json` and the nudge will say what the wiki actually covers.\n\n### Shell-less / chat-app agents (Claude Desktop, ChatGPT Desktop, web UIs)\n\nThese can only call MCP servers - no Bash. `tng-wiki-mcp` ships alongside `tng-wiki` (same `npm i -g @thenewguard/tng-wiki` installs both) and exposes seven MCP tools: `list_wikis`, `query`, `read`, `search`, `sources`, `stale`, `orphans`. Each tool routes through the registry so every wiki you've registered is reachable by slug.\n\n**Claude Desktop** - edit `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS) or `%APPDATA%\\Claude\\claude_desktop_config.json` (Windows):\n\n```json\n{\n  \"mcpServers\": {\n    \"tng-wiki\": {\n      \"command\": \"tng-wiki-mcp\",\n      \"args\": []\n    }\n  }\n}\n```\n\nRestart Claude Desktop. The tools appear under the server name `tng-wiki`.\n\n**Claude Code** (you'd only enable this if you want MCP specifically rather than the direct CLI, which is usually more token-efficient) - `~/.claude/mcp.json`:\n\n```json\n{\n  \"mcpServers\": {\n    \"tng-wiki\": { \"command\": \"tng-wiki-mcp\" }\n  }\n}\n```\n\n**Codex / opencode / OpenClaw** - each has its own MCP config file (`~/.codex/mcp.json`, `~/.config/opencode/mcp.json`, `~/.openclaw/openclaw.json → mcp.servers`). Same shape.\n\n**Docker MCP Toolkit** - add a custom server pointing at your installed binary. See [Docker's MCP Toolkit CLI docs](https://docs.docker.com/ai/mcp-catalog-and-toolkit/cli/).\n\n> **Why you'd use CLI over MCP when you have the choice:** MCP tool schemas are injected into the agent's context every session. Typical cost is 3-10K tokens for a 7-tool server, paid whether you use it or not. The CLI path pays zero tokens until you invoke a verb. So: use CLI in shell-capable environments, MCP only where CLI isn't reachable.\n\n### Cross-machine (wiki on one box, agent on another)\n\n- **Git sync with roles (recommended)** - see [Multi-machine wikis](#multi-machine-wikis-capture-and-the-librarian-seat) below: one librarian host per wiki, captures from anywhere, `sync` everywhere.\n- **SSH + CLI** - `ssh wiki-host \"tng-wiki search karpathy --wiki ai-research\"` for ad-hoc queries without a full clone.\n- **Thin HTTP wrapper** - wrap the CLI in ~50 lines of `http.createServer` if you want multiple remote agents hitting one wiki without SSH.\n- **MCP for remote chat-app agents** - same `tng-wiki-mcp` binary; run it on the wiki host and point remote MCP clients at it.\n\n## Multi-machine wikis: capture and the librarian seat\n\nWhen one wiki repo is cloned on several machines and many agent sessions touch it, give each machine one of two seats ([ADR 0001](docs/adr/0001-capture-to-origin-and-home-librarian.md), [design](docs/design/cross-machine-flow.md)):\n\n- **Librarian seat** - the one host named in the wiki's committed `.tng-wiki.json` (`tng-wiki librarian --set-here`). It triages `_inbox/`, files pages, grounds, locks, and publishes with `tng-wiki sync --push`.\n- **Capturer seat** - every other machine. Sessions read and search as usual and add knowledge with `tng-wiki capture`. Compiled-state writes (`ground --update-lock` / `--fix-*`, `graduate`, `dismiss`, `log`, `upgrade`) refuse here unless `--off-host`.\n\n```bash\n# any machine, any session: one command, no commit or push decisions\n$ tng-wiki capture --wiki research --file /tmp/finding.md\n✓ published research/_inbox/2026-09-27-webgl-gpu-timers-lie.md (4f1c2ab)\n  the librarian for \"research\" files it; nothing else to do here\n\n$ tng-wiki capture --file note.md          # no target: prints every wiki's ## Scope and asks\n\n# the librarian host, at the end of rounds\n$ tng-wiki sync --push\n✓ ~/wikis rebased 3 commits onto 2 commits from upstream, pushed\n\n# every machine, at session start (e.g. a Claude Code SessionStart hook)\n$ timeout 20 tng-wiki sync --quiet          # silent unless something arrived or needs attention\n```\n\nHow `capture` stays conflict-free: it builds the commit on the freshly fetched upstream tip with a private git index and pushes that SHA (retrying if another capture wins the race), so the index and working tree other sessions are using are never touched, and a new uniquely named file cannot conflict. The local clone fast-forwards when it can; if it holds unpublished commits, the capture arrives on the next `sync --push`. A repo with no upstream gets a path-only local commit (`--no-push` forces that). If the remote is unreachable, the capture waits in `~/.tng-wiki/outbox/` and the next `capture` or `sync` publishes it.\n\nRouting: capture to ONE best-fit wiki and name others with `--also`; the librarian fans out. `tng-wiki inbox` shows what is waiting in every wiki.\n\nAdding a machine is one command: `tng-wiki join <git-url>` clones the repo (or adopts an existing clone of the same remote), registers the wikis meant for this host (its sharing stamps decide), installs the Claude Code skill, prints the `localize` command for any code authority this machine lacks, and checks that `tng-wiki` resolves in non-interactive shells (`tng-wiki doctor --install-shim` fixes it when it does not).\n\n## QMD Integration\n\n[QMD](https://github.com/tobi/qmd) is a local search engine by Tobi Lütke (Shopify) that combines BM25 + vector search + LLM re-ranking, all on-device. At wiki scale beyond ~100 pages, you want it.\n\nIf you select QMD during `init` and it's installed, `tng-wiki` attempts to:\n- Register your `wiki/` directory as a QMD collection\n- Add context metadata for better search results\n\nYour agent can then use `qmd query \"...\"` via CLI or QMD's MCP server for search.\n\nInstall QMD: `npm i -g @tobilu/qmd`\n\n## The Pattern\n\nThis implements Karpathy's three-layer architecture:\n\n1. **Raw sources** → immutable. Articles, papers, transcripts, images.\n2. **The wiki** → LLM-maintained. Summaries, entity pages, cross-references.\n3. **The schema** → operating instructions. You and the LLM co-evolve this.\n\nThe key operations:\n\n- **Ingest** - process a new source, integrate into existing wiki pages, update index and log\n- **Query** - ask questions, get answers with citations, file valuable outputs back into the wiki\n- **Lint** - health-check for contradictions, stale claims, orphans, missing pages, coverage gaps\n\nThe wiki compounds. Every source and every query makes it richer.\n\n## Guide\n\nFull walkthrough, architecture deep dive, and real-world usage:\n\n**[thenewguard.ai/features/llm-wiki-guide](https://thenewguard.ai/features/llm-wiki-guide)**\n\n## License\n\nMIT\n\n---\n\n*Signal over noise. Built for builders who ship.*\n*[The New Guard](https://thenewguard.ai)*\n"}