---
name: project-llm-wiki
description: Use to build and maintain a compounding, navigable knowledge base of durable domain and codebase knowledge. Triggers on "add to wiki", "what do I know about", "ingest into the wiki", "query the wiki", "lint the wiki", any mention of "LLM wiki"; and automatically as work progresses — query the wiki before re-deriving a fact, and ingest durable knowledge when a piece of work closes.
---

# Project LLM Wiki

Build and maintain a persistent, compounding knowledge base with the LLM as
author and maintainer. You manage two directories at the repo root: `raw/`
(immutable source material — you read, never modify) and `wiki/` (compiled
knowledge articles — you own fully). Knowledge goes in once and pays back every
time an agent would otherwise re-derive it.

> Adapted from the MIT-licensed **karpathy-llm-wiki** skill by Yuhan Lei
> (`Astro-Han/karpathy-llm-wiki`). See `LICENSE`. Karpathy's framing: *"the LLM
> writes and maintains the wiki; the human reads and asks questions,"* and *"the
> wiki is a persistent, compounding artifact."*

## Where this sits in the PRD Plugin method

The wiki is **durable domain and codebase knowledge** — how the system works, why
it works that way, the gotchas, the settled decisions. It is deliberately
distinct from, and complementary to, the ID-tracked state:

- `.prd_plugin/state/*` (`REQ-*`/`TRK-*`/`EV-*`/`CHG-*`) — the project's tracked
  work and evidence. Bookkeeping, not a knowledge base.
- `project-memory` — session-to-session lessons and preferences with provenance.
- the traceability graph — machine-first ID relationships.
- **`wiki/`** — the human- and agent-readable knowledge base you *query before
  re-deriving a fact*, and *ingest into when work closes*.

Cross-link when useful: a wiki article may cite the `REQ-*`/`DEC-*`/`EV-*` that
produced or proved its knowledge. Do not duplicate tracked state into the wiki;
capture the *understanding*, not the ticket.

## Automatic use — the point of adopting this

Do not wait to be told "add to wiki". As work progresses:

- **Query first.** Before re-deriving a non-trivial fact about this system —
  architecture, an interface contract, a measured number, a known gotcha — read
  `wiki/index.md` and the relevant article. Querying the wiki is part of
  "resolve before you ask" (`.prd_plugin/method/self-service.md`).
- **Ingest on close.** When a meaningful piece of work closes — a feature landed,
  a bug root-caused, a decision settled, a cross-repo exchange resolved — ingest
  the durable knowledge it produced. `project-session-close` and
  `project-verification-before-completion` call for this; do it as part of
  closeout, not as a separate chore.
- **Lint periodically.** Run a Lint pass at session close or after a burst of
  ingests, so links and the index stay consistent.

Honor the config switch: if `.prd_plugin/config.json` sets
`knowledge.llm_wiki.enabled` to `false`, do none of the automatic behavior (still
respond to explicit "add to wiki" requests). The wiki is initialized lazily — the
first Ingest creates it; an empty repo stays empty until there is something worth
recording.

## Architecture

Three layers, all under the repo root:

**raw/** — Immutable source material. Read, never modify. Organized by topic
subdirectories (e.g., `raw/deployment/`).

**wiki/** — Compiled knowledge articles. Full ownership. One level of topic
subdirectories only: `wiki/<topic>/<article>.md`. Two special files:
- `wiki/index.md` — Global index. One row per article, grouped by topic, with
  link + summary + Updated date.
- `wiki/log.md` — Append-only operation log.

Templates live in `references/` relative to this file — read them for the exact
format of raw files, articles, archive pages, and the index.

### Initialization

Triggers only on the first Ingest. Check whether `raw/` and `wiki/` exist. Create
only what is missing; never overwrite existing files:

- `raw/` directory (with `.gitkeep`)
- `wiki/` directory (with `.gitkeep`)
- `wiki/index.md` — heading `# Knowledge Base Index`, empty body
- `wiki/log.md` — heading `# Wiki Log`, empty body

If Query or Lint cannot find the wiki structure, tell the user: "Run an ingest
first to initialize the wiki." Do not auto-create on Query or Lint.

---

## Ingest

Bring a source into `raw/`, then compile it into `wiki/`. Always both steps.

A "source" is any durable knowledge: a fetched document or spec, a resolved
cross-repo exchange, an as-built summary of a feature you just shipped, a
root-cause writeup, a measured benchmark. When the source is knowledge you
produced (not a fetched document), still record it into `raw/` so the wiki
article has a citable origin.

### Fetch (raw/)

1. Get the source content with whatever web or file tools are available. If
   nothing can reach it, ask the user to paste it.
2. Pick a topic directory. Reuse an existing `raw/` subdirectory if the topic is
   close; create a new one only for genuinely distinct topics.
3. Save as `raw/<topic>/YYYY-MM-DD-descriptive-slug.md`.
   - Slug from the title, kebab-case, max 60 characters.
   - Published date unknown → omit the date prefix; set the Published field to
     `Unknown`.
   - Name collision → append a numeric suffix (`slug-2.md`).
   - Include the metadata header (source, collected date, published date).
   - Preserve original text. Clean formatting noise. Do not rewrite opinions.

   See `references/raw-template.md`.

### Compile (wiki/)

Decide where the content belongs:

- **Same core thesis as an existing article** → merge into it; add the source to
  Raw/Sources; update affected sections.
- **New concept** → create a new article in the most relevant topic directory.
  Name the file after the concept, not the raw file.
- **Spans topics** → place in the most relevant directory; add See Also
  cross-references.

Not mutually exclusive — one source may merge into one article and spawn another.
Check for factual conflicts: if the new source contradicts existing content,
annotate the disagreement with source attribution and cross-link. Where the
knowledge was produced or proven by tracked work, cite the `REQ-*`/`DEC-*`/`EV-*`.

See `references/article-template.md`. Relative paths from `wiki/<topic>/` reach
raw as `../../raw/<topic>/<file>.md`.

### Cascade Updates

After the primary article, check for ripple effects:

1. Scan articles in the same topic directory for affected content.
2. Scan `wiki/index.md` entries in other topics for related concepts.
3. Update every materially-affected article; refresh its Updated date.

Archive pages are never cascade-updated (point-in-time snapshots).

### Post-Ingest

Update `wiki/index.md`: add or update an entry for every touched article; new
topic sections get a one-line description. The Updated date reflects when the
article's knowledge last changed, not the filesystem timestamp. See
`references/index-template.md`.

**Stamp the commit.** Set each touched article's `Commit:` metadata field to the
repo's current short SHA (`git rev-parse --short HEAD`), or `unknown` when the repo
is not under git. This records the repo state the knowledge reflects, so a later
reader can tell how current the article is relative to HEAD.

Append to `wiki/log.md` (include the commit):

```
## [YYYY-MM-DD] ingest | <primary article title> @ <short-sha>
- Updated: <cascade-updated article title>
```

Omit `- Updated:` lines when no cascade updates occur.

---

## Backfill

A one-time deep pass to seed a wiki for a repo that already holds knowledge —
typically an established repo that just updated into the wiki-capable plugin
version. Lazy init (first Ingest) suits fresh repos; an established repo's
understanding should be captured in one deliberate, broad pass instead of
accreting slowly.

**Trigger.** `prd-install` drops `.prd_plugin/local/wiki-backfill-needed` when it
adds the wiki to an established repo that has none yet; the session-start nudge
and `prd_status` surface it. You may also backfill on explicit request ("backfill
the wiki", "seed the wiki from the codebase").

**Procedure.**

1. **Survey (grounded, not from memory).** Run
   `python .prd_plugin/scripts/prd_wiki_backfill.py --plan` (or `scripts/…` in the
   hub). It inventories, read-only, the repo's code modules, docs, README,
   `.prd_plugin` state (requests/decisions/changelog/evidence), git-history
   themes, and memory, and proposes one-level topics. This is the work-list; it
   keeps the backfill complete and prevents inventing coverage.
2. **Initialize** the wiki if absent (see Initialization).
3. **Compile broadly.** Work the proposed topics. For each, record raw sources
   (fetch/reference existing docs into `raw/`, or write a short as-built raw note
   for knowledge that lives only in code) and compile an article per
   `references/article-template.md`, stamping its `Commit:` field with the plan's
   `head_commit`. Aim for full coverage of the repo's real subsystems — the goal is
   a wiki that answers substantive questions, not five.
4. **Ground every claim.** State only what the code, docs, and state actually
   show; do not assert behavior you have not read. Cite the `REQ-*`/`DEC-*`/`EV-*`
   that produced or proved a piece of knowledge. Where sources conflict, annotate
   it.
5. **Index + log.** Build `wiki/index.md` across all topics; append a
   `## [YYYY-MM-DD] backfill | <N> articles across <M> topics` entry to
   `wiki/log.md`.
6. **Lint.** Run a full Lint pass (below) and fix what it auto-fixes.
7. **Clear the marker.** Delete `.prd_plugin/local/wiki-backfill-needed` so the
   nudge stops surfacing it.

Scope the depth to the repo: a small repo may be a handful of articles, a large
one many across several topics. Rate the effort with complexity/confidence, never
a time estimate.

## Export and the page contract

The UTCP `wiki` tool's `list`/`read` actions are the page contract (v1):
enumerate canonical pages and read one as exact UTF-8 Markdown with title,
safe export filename, sha256, and Commit/Updated provenance — hard boundaries
reject traversal, non-Markdown, non-UTF-8, and paths outside `wiki/`.
`python .prd_plugin/scripts/wiki_html_export.py` emits a self-contained
offline HTML viewer (copy/download buttons on every page); `--all` builds the
workspace super index with a combined changelog across every convention wiki.

## Query

Search the wiki and answer. Triggers: "what do I know about X", "summarize
everything on Y", "compare A and B from my wiki" — and, automatically, whenever
you are about to re-derive a fact this wiki may already hold.

1. Discover the configured Substrate policy. When `knowledge` or `federation`
   recall is active, query `knowledge_search` through `prd_substrate_call` (or
   use a workflow's `substrate.enrich` step) before local lookup. Treat results
   as derived pointers; repository Markdown remains canonical. The configured
   `knowledge_browse_url` is an optional human HTML view.
2. Read `wiki/index.md` to locate relevant local articles or to fall back when
   the runtime is disabled, unavailable, stale, or empty.
3. Read the grounded source articles and synthesize.
4. Prefer checked wiki content over training knowledge. Cite with markdown links:
   `[Article Title](wiki/topic/article.md)` (repo-root-relative in conversation;
   file-relative inside wiki files).
5. Output the answer. Do not write files unless asked.

### Optional delegated synthesis

Wiki lookup remains deterministic and source-led. When
`reporting.delegation.enabled` allows `wiki_synthesis`, use `prd_reporting.py`
to build the source-referenced bundle. When the configured AI-Collab Substrate
adapter is available, dispatch `wiki_synthesis` with `prd_substrate_runtime`;
the result must return through `prd_reporting_validate` before presentation.
Every material claim
must reference a bundle source, and delegated output never edits `wiki/`,
`raw/`, or project state. Apply the configured `main`, `deterministic_only`, or
`fail` fallback if delegation is unavailable or invalid.

### Archiving

When the user explicitly asks to archive an answer:

1. Write it as a new wiki page (`references/archive-template.md`). Rewrite
   conversation citations to file-relative paths.
2. Always a new page — never merge (archive content is a synthesized answer, not
   raw material).
3. Update `wiki/index.md`; prefix the Summary with `[Archived]`.
4. Append to `wiki/log.md`:
   ```
   ## [YYYY-MM-DD] query | Archived: <page title>
   ```

---

## Lint

Quality checks, two authority levels.

### Deterministic Checks (auto-fix)

**Inline Markdown navigation** — every resolvable reference in `wiki/**/*.md`
to another local `.md` file must be an inline link, including Sources metadata
and code-styled filenames. Run:

```bash
# hub
python scripts/prd_wiki_backfill.py --lint-links --fix --format json
# downstream
python .prd_plugin/scripts/prd_wiki_backfill.py --lint-links --fix --format json
```

The fixer rewrites only references with one deterministic local target. It never guesses.
Missing or ambiguous targets are reported and must be resolved deliberately.
Fenced code examples and existing Markdown links are ignored. The PRD
gate enforces this by default through
`knowledge.llm_wiki.require_inline_md_links`; disable that setting only when the
repository intentionally does not want the policy.

**Index consistency** — compare `wiki/index.md` against actual `wiki/` files
(excluding index.md/log.md):
- File exists but missing from index → add entry with `(no summary)`; Updated from
  the article's metadata Updated date, else file mtime.
- Index entry → nonexistent file → mark `[MISSING]`; do not delete.

**Internal links** — every markdown link in article files (body + Sources),
excluding Raw links and index.md/log.md:
- Target missing → search `wiki/` for a same-named file. One match → fix. Zero or
  many → report.

**Raw references** — every Raw-field link must point to an existing `raw/` file:
- Target missing → search `raw/`. One match → fix. Zero or many → report.

**See Also** — within each topic directory, add obviously-missing cross-refs;
remove links to deleted files.

### Heuristic Checks (report only)

Judgment calls — report, do not auto-fix:
- Factual contradictions across articles
- Outdated claims superseded by newer sources
- Missing conflict annotations where sources disagree
- Orphan pages with no inbound links
- Missing cross-topic references
- Concepts mentioned often but lacking a dedicated page
- Archive pages whose cited articles changed substantially since archival
- Articles whose `Commit:` is many commits behind HEAD (`git rev-list --count
  <commit>..HEAD`) — the knowledge may have drifted since it was compiled; a
  candidate for re-ingest

### Post-Lint

Append to `wiki/log.md`:

```
## [YYYY-MM-DD] lint | <N> issues found, <M> auto-fixed
```

---

## Conventions

- Standard markdown, relative links throughout.
- Whenever wiki prose names another local Markdown file, use an inline link;
  never leave a navigable `.md` reference as a bare filename or code span.
- `wiki/` supports one level of topic subdirectories only. No deeper nesting.
- Today's date for log entries, Collected, and Archived dates. Updated dates
  reflect when the article's knowledge last changed. Published comes from the
  source (`Unknown` when unavailable).
- The `Commit:` field records the repo's short SHA (`git rev-parse --short HEAD`)
  the article's knowledge was compiled/verified against; `unknown` when the repo
  is not under git. Refresh it whenever the article is materially updated.
- Inside wiki files, links are relative to the current file. In conversation, use
  repo-root-relative paths.
- Ingest updates `wiki/index.md` and `wiki/log.md`. Archive updates both. Lint
  updates `wiki/log.md` (and `wiki/index.md` only when auto-fixing index entries).
  Plain queries write nothing.
- Do not give time/duration estimates; use complexity/confidence (and risk). See
  `.prd_plugin/method/estimation.md`.

## Staleness Responsibility

Apply the shared policy in `.prd_plugin/method/staleness-rules.md`. A wiki article
carries knowledge that can go stale: when an ingest or a piece of work supersedes
an article's claim, update the article and refresh its Updated date rather than
leaving two contradictory statements. The Lint pass's heuristic checks
(contradictions, outdated claims, archive pages whose sources have moved on)
exist to surface stale knowledge — act on what they report.
