# LLM Wiki — Agent Operating Contract

You are working in the **LLM-wiki** memory system — a local, file-based,
git-native knowledge base for multi-agent memory. This file is the canonical
operating contract for any AI agent (Claude Code, OpenCode, Codex, Cursor,
Antigravity) editing this repository. `AGENTS.md` and `CLAUDE.md` are kept
byte-identical so every agent reads the same rules regardless of which file
it loads.

---

## 0. Process rules (mandatory)

### How to talk to the user
- Write in **plain human language**. Short sentences.
- Avoid jargon stacks, audit IDs, severity tables unless the user explicitly
  asked for a technical report.
- After any task: **what happened**, **what it means**, **what (if anything)
  they should do** — in that order.
- If nothing is required from the user, say so explicitly.
- Match the user's language (Russian → Russian, English → English).

### Architecture changes require explicit sign-off
Before changing **structure, paths, env contracts, or runtime location**:
1. Describe the proposed change in plain language (what, why, impact).
2. Get the user's explicit "yes".
3. Record the decision in `knowledge/notes/` (decision page) and update
   `docs/STRUCTURE.md` (the canonical structure reference).
4. Only then write code.
Never improvise architectural decisions mid-task. When unsure, ask.

### Release / docs sync
- Before any release or version bump: **sync `README.md` + `README.ru.md` +
  `README.zh-CN.md` in the same change**.
- Never leave RU/ZH with stale test counts, install URLs, or architecture.
- Run `uv run pytest tests/test_readme_i18n.py -q` after README edits.
- Update `CHANGELOG.md` (Keep-a-Changelog format) and `pyproject.toml`
  `version` in the same change.
- See `CONTRIBUTING.md` → Release checklist.

---

## 1. Three-zone layout (canonical)

The repository is organized into three zones. This layout is enforced by
`tests/test_structure.py` — do not break it.

```
# CODE (tracked in git)
scripts/   tests/   docs/   skills/   rules/   integrations/   benchmark/

# KNOWLEDGE (tracked in git — public examples only in source;
#            full user data lives in the installed vault)
knowledge/
  daily/      # append-only session capture
  notes/      # durable compiled pages (OKF frontmatter, flat slugs)
  projects/   # per-project state.md / context
  raw/        # immutable sources
  inbox/      # unprocessed staging
  feedback/   # correction candidates

# RUNTIME (inside the vault, gitignored)
# Override root via LLM_WIKI_STATE_ROOT (tests use a temp dir).
cache/     # FTS5 / vector / graph indexes; legacy cache/cognee/ is retired
logs/      # lint reports, compile logs, SessionStart debug dumps
run/       # state, transactions, queue results, locks, install ownership
```

**Env contracts:**
- `$LLM_WIKI_ROOT` → vault root (the repository root). Default: resolved from
  `scripts/` location, worktree-aware.
- `$LLM_WIKI_STATE_ROOT` → runtime root. **Default: the vault itself** →
  `cache/`, `logs/`, `run/` at vault root, all gitignored.
  Override for multi-disk setups or hermetic tests.
- `$MEMORY_LLM_PROVIDER` → `fake` (tests), or one of
  `opencode|codex|claude|openai|ollama` (runtime, auto-detected).
- `$LLM_WIKI_DLP_POLICY` → optional absolute external policy path. Invalid or
  digest-mismatched required policy blocks protected work.

**Agent integration boundary:** MCP is the common interface for reads and
actions (12 task-shaped tools, uniform response envelope, health/context
resources). Native hooks, plugins, and wrappers are thin lifecycle adapters
for events MCP cannot observe. Automatic health context is injected only when
`doctor` reports degraded/error findings.

**Approved audit-closure contract (2026-08-15):** Cognee is retired from the
supported product; existing `cache/cognee/` is disposable legacy cache and is not
deleted automatically. First-party model calls use one fail-closed DLP boundary.
Verified local-only mode accepts only literal-loopback Ollama and requires
verifiable Ollama cloud disablement. Coherent encrypted private-vault recovery uses
Restic with the existing maintenance fence, SQLite online backup, manifests, and
staged validation. `run/install/` is the only new runtime directory and owns
resumable install state, exact-release/external-path manifests, verified preimages,
and non-secret scheduler definitions. Windows uses Task Scheduler, macOS uses a
user LaunchAgent, Linux uses a user systemd timer, and cron is explicit degraded
fallback. Blackboard and capture reuse the two Reliability v3 databases. No daemon,
MCP tool, runtime root, or automatic Git operation is added. See
`knowledge/notes/audit-closure-security-recovery-control-plane-decision.md`.

**Superset product contract (approved 2026-07-19):** LLM Wiki is the single
local-first memory, code-intelligence, and agent-control product for one person
managing many agents, sessions, projects, repositories, branches, and worktrees.
Normal Graphify and codebase-memory-mcp workflows must not require a separate
installation. The approved target includes a native code-index kernel,
repository-scoped generations, multi-repository contracts, temporal claims,
episodic/semantic/procedural/prospective memory, one Adaptive Context Compiler,
durable task/execution/artifact/budget control, an exception-driven local
operator console, optional bounded watching, HTTP MCP, and broad ingestion.
These additions remain derived or operational; they do not displace Markdown,
Git, raw episodes, project journals, accepted decisions, or accepted artifacts
as authority. Completion requires real paired task, token, latency, safety, and
operator-attention evidence. A finished subplan or smoke fixture is not product
completion. See `knowledge/notes/solo-operator-superset-product-decision.md`.

**Reliable mutation boundary:** automatic Markdown writes use recoverable
transactions with before/after hashes. Project handoff is projected from an
append-only `journal.md`. `cache/` and `logs/` are disposable; `run/` must not be
deleted while doctor reports a nonterminal, conflicted, or quarantined
transaction, a transaction inside the 30-day undo window, or any retained queue
task or result, or while a project lease, writer, queue worker, or maintenance
owner is live. Deleting eligible committed artifacts loses undo history.

**Stage 2 operational contract:** Markdown remains authoritative; runtime SQLite
is coordination/derived state, never a knowledge source. Operational databases use
rollback-journal, `synchronous=FULL`, and no WAL on the current SQLite runtime. They
require a local filesystem with correct locking. Network/cloud-synchronized runtime
roots are unsupported; cloud detection is best-effort. External editors may briefly
see a mixed tree, and hash/CAS guarantees apply only to cooperating transaction-API
writers. Queue delivery is at least once. Archives keep 90 hot days and preserve
logical evidence in immutable uncompressed BagIt packages. Claims with uncertain
evidence or evaluator disagreement enter quarantine; automatic semantic supersession
and eager backfill remain disabled. Do not delete `run/` while doctor reports a
source failure, any 30-day undo artifact, retained work/result, or live owner. There
is no automatic Git operation, persistent daemon, cloud service, remote queue/cache,
exactly-once promise, or gzip archive tier.

**Approved Reliability v3 target (not implemented):** New
unprocessed lifecycle evidence would be create-only under `run/capture-intents/`
until an immutable terminal record proves committed Markdown, validated
no-durable-content, or operator discard; queue enqueue alone would not permit
deletion. Compile receipts would bind logical path plus digest and a validated
per-source disposition; digest-only v2 receipts would remain historical evidence
only. Queue payload hashes would be checked at every transition, and dedupe would
alias only identical kind, handler version, and payload. All operational actors would
use one canonical fenced admission registry, including capture, project/Markdown
writers, queue, and LSP. Explicit offline adoption would publish versioned v3
databases and replace legacy active paths with JSON tombstones, blocking normal
v2 queue/transaction clients after cutover. Live, expired-but-not-proven-dead, or
unknown owners, unresolved intents, and partial adoption would block `run/` deletion.
Doctor would
report a quiescent snapshot only after complete adoption, and never a durable deletion
permit.
See `knowledge/notes/v4-reliability-contracts-decision.md`.

**Derived evidence generations:** Markdown, Git, and project journals are
authoritative. All graph, FTS, vector, tier, and telemetry generation state is
disposable and derived. `cache/evidence-graph/` is the new target generation layout.
The rollback-journal,
`synchronous=FULL`, no WAL catalog at `cache/evidence-graph/catalog.sqlite3`
selects one active generation under
`cache/evidence-graph/generations/<generation-id>/`.
Each generation is immutable after activation; optional vectors are absent,
complete, or explicitly stale.
These databases require a local filesystem with correct locking. Cache deletion is
regenerable and does not change the existing `run/` deletion contract.
No generation database belongs under `run/`; it remains operational state only.
The design requires no persistent daemon.

Legacy `cache/index.sqlite`, `cache/vectors.npy`, `cache/vectors_meta.json`, and
`cache/lancedb/` remain readable during migration. They are disposable derived
caches, not members of a generation. They must not be removed until installed-vault
migration evidence makes that safe.

**Implemented code-navigation slice:** The current authoritative corpus checkpoint
remains `corpus-generation/v2` with `evidence-graph/v2`. Foundation Tasks 1-5 of the
2026-07-21 Plan A remain implemented, but its one-shot consent/SCIP/publication Tasks
6-16 are superseded. The replacement plan implements the production-quality,
Python 3.10-compatible read-only LSP path through pinned Pyright 1.1.411: paths,
positions, bounded protocol, startup evidence, leased platform-qualified lifecycle
ownership, repository containment, safe log redaction, explicit profile installation,
document synchronization, session-manager capacity, the normalized navigation facade,
deterministic rendering, precise `get_architecture` modes, doctor diagnostics, and
qualification gates. A Windows Job Object owns the assigned server tree. On POSIX,
the process group covers pinned Pyright descendants only while they remain in-group;
hostile `setsid()` escape is unsupported, so this path remains limited to trusted
local repositories and is not an OS sandbox.
It adds no Serena runtime dependency, Rust rewrite, second graph, catalog, active
pointer, runtime root, persistent daemon, or MCP tool. Query-time LSP observations
are not written into active generations. Language servers start lazily inside the
owning MCP process, expose only allowlisted read operations, report readiness and
capability limits, and fall back to existing structural evidence. Installation is
a separate explicit operator action. The managed Pyright artifact lives at
`cache/code-tools/pyright/1.1.411/`; bounded process scratch lives under
`run/lsp/<owner-nonce>/` and follows the existing `run/` deletion contract, which
protects live LSP owners and retained LSP failure evidence. While ownership is live,
`run/lsp/<owner-nonce>/lease.json` is a bounded mutable live lease, refreshed every
10 seconds with a 30 seconds expiry, and remains distinct from immutable create-only
`owner.json` and `failure.json`. Controlled cleanup removes the lease after joining
its heartbeat; abrupt death leaves it to expire. Second-fatal recovery completes
without caller intervention. Incomplete startups enter a bounded module registry;
Pyright sessions adopt returned cleanup owners into session-held normal-exit and
caller-deadline retry, while unadopted owners stay registered. Windows lease refresh
retries only errors 5, 32, and 33 within the previous lease expiry. See
`knowledge/notes/read-only-lsp-navigation-engine-decision.md`,
`knowledge/notes/lsp-live-lease-decision.md`, and
`knowledge/notes/lsp-process-containment-decision.md`.

**Forbidden at vault root:** `wiki/`, `memory/`, `outputs/`, `state/`,
`LLM-wiki-state/` (legacy sibling layout — removed). Runtime lives **inside**
the vault under gitignored `cache/logs/run/`.

---

## 2. Public source vs installed instance

This repository is the **public source** (dev). The **installed, running**
memory system — with real user data — lives at `$LLM_WIKI_ROOT` on the
operator's machine (a separate clone, pull-only).

**These two locations are completely separate entities. Never mix them.**

| Signal | Public source (HERE) | Installed tool (runtime) |
|---|---|---|
| Role | Dev: edit code, run tests, commit, push | Runtime: capture, compile, search |
| Push | `git@github.com:Ekgardt/llm-wiki.git` | `no-push` (blocked) |
| User data | NONE (clean examples + fixtures only) | YOUR memory, daily logs, state |
| `$LLM_WIKI_ROOT` | Does NOT point here | Points here |

If unsure: `git remote get-url --push origin`. Real GitHub URL → public source.
`no-push` → installed instance.

### What you may do here
- Edit source code (`scripts/`, `tests/`, `install.sh`, etc.)
- Edit public docs (`README.md`, `docs/`, `CONTRIBUTING.md`)
- Run tests: `uv run pytest -q`
- Commit and push to `Ekgardt/llm-wiki` (public repo)

### What you must NEVER do here
- **NEVER create personal knowledge pages** in `knowledge/notes/` or
  `knowledge/daily/` — those dirs hold PUBLIC EXAMPLES only (enforced by
  `.gitignore` allowlist). Personal knowledge goes in `$LLM_WIKI_ROOT`.
- **NEVER write daily logs, session state, or project state here.** The
  running system writes those to `$LLM_WIKI_ROOT`, not here.
- **NEVER run `compile_memory.py`, `flush_memory.py`, or any memory pipeline
  script against this folder.** These scripts operate on `$LLM_WIKI_ROOT`.
- **NEVER commit user data** (decisions about your projects, debugging notes,
  personal design rules) to this repo. It is PUBLIC.
- **NEVER commit runtime dirs** (`cache/`, `logs/`, `run/`).
  They are gitignored; keep them out of the index.

### When asked to "work on the memory system"
- "Improve the system" → develop HERE (edit code, run tests, commit, push).
  The installed instance picks up updates via `git pull` at `$LLM_WIKI_ROOT`.
- "Show me my memory / what do I know about X" → that's the INSTALLED
  instance at `$LLM_WIKI_ROOT`, not here.

---

## 3. Knowledge conventions

### Global rules
1. Prefer answering from `knowledge/notes/` first.
2. Read `knowledge/raw/` or `knowledge/inbox/` only when the wiki is missing,
   stale, or contradictory.
3. When durable knowledge appears, update the wiki rather than leaving it
   only in chat.
4. Every important update should touch:
   - the most relevant wiki page(s)
   - `knowledge/index.md`
   - `knowledge/log.md`
5. Preserve provenance. When writing claims, include a `Source:` / Evidence
   line pointing to the relevant file(s).
6. Mark uncertainty explicitly.
7. Track contradictions and superseded claims instead of silently deleting
   history.
8. Use Obsidian-style wikilinks like `[[Concept Name]]` whenever a stable
   concept/entity/page exists.
9. Do not dump raw excerpts into the wiki unless the quote itself matters.
10. Prefer concise pages that link outward over giant pages that try to hold
    everything.

### Wiki page conventions
Every durable wiki page should try to include:
- Title (`# H1`)
- One-sentence summary (`One-sentence summary: ...`)
- Key facts / synthesis
- Open questions (if any)
- Source / Evidence
- Links to related pages

### Special files
@knowledge/index.md
@knowledge/log.md

### Default behavior for new material
When asked to compile or ingest new material:
1. Inspect `knowledge/inbox/` and/or the target source file.
2. Decide whether to create or update pages under `knowledge/notes/`.
3. Update `knowledge/index.md`.
4. Append a concise entry to `knowledge/log.md`.
5. Summarize what changed.

---

## 4. Extended rules (OKF + lifecycle)

11. **Every durable page MUST have YAML frontmatter with at least `type:`.**
    OKF v0.1 conformance. Use `scripts/migrate_to_okf.py --apply` to backfill
    missing frontmatter; `lint_memory.py` flags violations as
    `missing_frontmatter` / `missing_required_type`.

12. **When a new fact conflicts with an existing page, mark the old
    `status: superseded` and add a `superseded_by: [[<new-slug>]]` link —
    never delete.** History outranks tidiness. The old page stays in git, in
    the graph, and in the index, but retrieval excludes it. Decisions are
    immutable: supersede, never edit in place.

13. **Set `confidence` (high|medium|low) and `source_authority`
    (user|ai-derived|web|inferred) when a page makes a claim.** Hierarchy:
    user-stated > web-sourced > ai-derived > inferred. The compile/search
    pipeline uses these fields to rank retrieval results. Without them, pages
    default to medium / inferred and lose ranking.

14. **Track knowledge gaps: when a concept is mentioned but has no page, add
    a stub to `knowledge/notes/`** so the absence is visible, not lost.
    `lint_memory.py::orphan_gaps` flags gap pages with no inbound link from
    outside gaps/. Gaps close when a real page is created and backlinks the gap.

15. **Sessions start with self-awareness: read your knowledge state** (page
    counts, open gaps, last compile timestamp, active threads) before acting.
    The SessionStart hook injects a metacognitive block — read it. If compile
    backlog > 0 or stale pages exist, propose running `/lint` or
    `/knowledge-compile` before doing real work.

16. **Skills and rules are first-class knowledge: they live under the same
    frontmatter schema and are linted alongside wiki and memory.** A skill
    without `type: skill` frontmatter fails `missing_required_type` the same
    way a wiki page does.

---

## 5. Page-type quick reference (OKF)

| Type | Location | Notes |
|------|----------|-------|
| `concept` | `knowledge/notes/<slug>.md` | Mental models. Never archives. |
| `entity` | `knowledge/notes/<slug>.md` | Named things/people/orgs. Never archives. |
| `decision` | `knowledge/notes/<slug>.md` | Dated choice + rationale. Immutable; supersede. |
| `pattern` | `knowledge/notes/<slug>.md` | Recurring approach. 180-day archive. |
| `debugging` | `knowledge/notes/<slug>.md` | Symptom → cause → fix. 60-day archive. |
| `qa` | `knowledge/notes/<slug>.md` | Settled answer to a recurring question. 365-day. |
| `synthesis` | `knowledge/notes/<slug>.md` | Cross-page comparison/connection. Never archives. |
| `raw-source` | `knowledge/notes/<slug>.md` | Excerpted primary source. Archivable. |
| `workflow` | `knowledge/notes/<slug>.md` | Auto-promoted playbook. 365-day. |
| `gap` | `knowledge/notes/<slug>.md` | Not-yet-written knowledge. 90-day. |
| `skill` | `skills/<name>/SKILL.md` | Agent workflow. Never archives. |
| `rule` | `rules/<name>.md` | File-handling policy. Never archives. |
| `project-state` | `knowledge/projects/<slug>/state.md` | Per-project handoff. Never archives. |
| `project-context` | `knowledge/projects/<slug>/` | Per-project context. Never archives. |
| `bootstrap-context` | `knowledge/notes/<slug>.md` | Seed context for new sessions. Never archives. |

Pages live **flat** as `<slug>.md` under `knowledge/notes/` (the compile
pipeline writes flat slugs). Typed subdirectories are optional.

---

## 6. LLM backend

The memory pipeline needs an LLM for classification, compilation,
contradiction checks, and playbook crystallization. Backend is
**auto-detected** via `scripts/llm_client.py` — no API keys required.

Priority: OpenCode → Codex → Claude CLI → OpenAI → Ollama. If none available,
the call is enqueued in `run/queue.sqlite3` and processed at the next active
session. Legacy `run/queue/*.json` files are migration input only.

Override via `MEMORY_LLM_PROVIDER` env var. `fake` returns a canned response
for tests/e2e.

**Zero-cost path:** no paid API beyond existing agent subscriptions. Ollama remains
an optional local backend; the retired Cognee bridge is not a supported feature.

---

## 7. Quick command reference

```bash
uv run pytest -q                              # run the full regression suite
uv run ruff check scripts/ tests/             # Python static analysis
uv run python scripts/lint_memory.py --scope all   # structural lint
uv run python scripts/search_memory.py "query"     # hybrid search
uv run python scripts/compile_memory.py            # compile daily logs → notes
uv run python scripts/lookup_mode.py               # show retrieval tier
# v4.0 optional features (require --extra flags):
uv run python scripts/mcp_server.py                # MCP server (12 tools, stdio)
uv run python scripts/doctor.py                    # local health; --repair is explicit
uv run python scripts/code_graph.py .              # index code graph (tree-sitter)
uv run python scripts/impact_analysis.py           # git diff → stale wiki pages
uv run python scripts/reflection.py --apply        # A-MEM page consolidation
uv run python scripts/access_tracking.py --flush   # flush access counts
uv run python scripts/build_tiers.py --all          # generate L1 overviews
```

Runtime state is gitignored and never committed. `cache/` and `logs/` are
regenerable; `run/` is operational state and follows the deletion contract in
section 1.
