JanYork

LWC — Proactive Memory for AI Agents

Community JanYork
Updated

Agent-driven proactive memory CLI for AI agents — autonomously recall, maintain, and evolve persistent, source-grounded knowledge across sessions.

LWC — Proactive Memory for AI Agents

Agent-driven · Persistent · Source-grounded

English · 简体中文 · 日本語 · Español · Português (Brasil) · Français · Русский

lwc is an agent-driven proactive memory CLI for AI agents. It lets Agentsautonomously recall, maintain, and evolve persistent, source-grounded knowledgeacross sessions.

Works with Claude Code, Codex, Cursor, OpenCode, Gemini CLI, Kiro, Hermes,Antigravity, and pi.

LWC turns curated documents into a durable Wiki. Agents reason and synthesize;lwc preserves sources, pages, citations, links, indexes, and history soknowledge compounds instead of being rediscovered from raw chunks on everyquery.

LWC Is Agent Memory, Not RAG

RAG and LWC can both help an LLM work with external documents, but they keepstate in different places. A typical RAG request retrieves raw chunks and buildsone answer at query time:

query -> retrieve chunks -> generate answer

LWC keeps the useful work between requests:

task -> recall maintained Wiki -> reason from sources and prior synthesis
     -> write durable improvements back

Retrieval is one operation inside LWC, not its organizing principle. The durableartifact is a source-grounded Wiki whose pages, citations, links,contradictions, and history are revised as knowledge changes. LWC thereforedoes not require embeddings or a vector database, and it does not discard eachsynthesis after answering. It can complement RAG, but it is not query-time RAG.

The Agent operates LWC

lwc is a machine interface for Agents, not a human-facing note-taking app. Innormal use, a human selects sources, states goals, asks questions, and reviewsanswers or the projected Markdown. The Agent runs the CLI, manages scope,integrates sources, maintains citations and links, and decides what is worthrecalling or writing back.

Do not manually drive the routine lwc workflow unless you are developing ordebugging the tool. Ask your Agent to activate the bundled canonicalusing-lwc Skill instead—usually as $using-lwc.

Recommended: Ask Your Agent to Set Up LWC

Paste this prompt into the Agent you use. It installs the global CLI, delegatesall supported host configuration to LWC's idempotent AgentTarget installer, anduses native self-configuration only for an unregistered Agent.

Copy the complete setup prompt
Configure LWC completely for this user. Perform and verify the work; do not
merely describe commands for me to run.

Source of truth:
- https://github.com/JanYork/llm-wiki-cli
- https://github.com/JanYork/llm-wiki-cli/tree/main/skills/using-lwc

Requirements:
1. Read this README, `SECURITY.md`, and `skills/using-lwc/SKILL.md`. Install the
   official checksum-verified release if `lwc` is not globally callable; never
   prefix routine commands with a private binary path or `LWC_PROJECT_ROOT`.
2. Run `lwc --version`, initialize global memory once with
   `lwc --scope global init` when missing, then run `lwc agent install --yes`.
   This command detects installed supported Agents and safely installs their
   MCP, Skill, Hook and Instructions using official locations. Do not recreate
   that logic manually or install a native package for the same Agent as well.
3. Inspect `lwc agent status --target all --location global`. Restart affected
   Agents and complete their normal Hook trust review where required. Do not
   initialize a project Wiki or either graph without explicit project consent.
4. If the current runtime is not one of LWC's registered AgentTargets, use its
   official user-level conventions to install the canonical `using-lwc` Skill,
   an additive instruction block, `lwc serve --mcp`, and a bounded session Hook
   only where those surfaces are officially supported. Preserve existing
   configuration, remain idempotent, and report unsupported surfaces instead of
   inventing paths or keys.

Finish with the LWC version, detected and configured Targets, status results,
files changed, unsupported surfaces, and any restart or trust action remaining.

Origin and Acknowledgements

lwc implements the LLM Wikipattern proposed by Andrej Karpathy: an LLM incrementally builds and maintains apersistent, interlinked Wiki instead of reconstructing knowledge from rawdocuments for every query. The CLI architecture and selected implementationdetails also draw inspiration fromnashsu/llm_wiki.

This project adapts those ideas into an agent-first Rust CLI backed by SQLite.

Core Design

The persistent knowledge model has three logical layers:

Layer Contents Contract
Raw sources Immutable snapshots of curated input Add through source; never rewrite source truth.
Wiki Agent-maintained pages, citations, links, and provenance Update through page; cite sources and classify durable non-source knowledge.
Schema and purpose Maintenance rules and project intent Guide every future ingest and revision.

SQLite is canonical. The Markdown tree is a rebuildable projection for peopleand tools such as Obsidian. Agents mutate knowledge through lwc, not by editing.lwc/wiki.db or projected Markdown directly. Successful commands return JSONon stdout; failures return structured JSON on stderr.

Read commands keep current-format stores read-only. When an older writablestore is opened by a newer CLI, its schema is migrated transactionally oncebefore the read proceeds.

Hierarchical Recall and Knowledge Graph

Every current Source and Wiki page is deterministically indexed as passages andsentences. SQLite remains authoritative; span FTS and an optional externaldocument graph are rebuilt indexes. Existing search stays document-onlyunless a granularity is requested:

lwc search "projection consistency" --granularity sentence --type page
lwc search "projection consistency" --granularity passage
lwc search "projection consistency" --granularity all --group-by document
lwc span get <SPAN_ID>
lwc span expand <SPAN_ID> --before 1 --after 1 --children 20

Span locators contain the document fingerprint and segmentation version. Alocator from a replaced body fails with stale_span and reports prior/currentmetadata; LWC never silently remaps it to similar text.

Use the bounded, typed graph API for exploration without requiring keywords:

lwc graph explore                         # representative macro view
lwc graph node page:projection-policy
lwc graph neighbors page:projection-policy --direction outgoing
lwc graph path page:implementation page:policy --max-depth 6
lwc graph impact page:policy --max-depth 4
lwc graph overview
lwc graph status
lwc graph verify

Automatic edges are limited to structural/evidential facts. Semantic claimsmust be explicit and auditable:

lwc graph relation set page:implementation DEPENDS_ON page:policy \
  --provenance source-grounded --source 12 \
  --reason "Source 12 states the required policy" --confidence 0.95
lwc graph relation list --from page:implementation
lwc graph relation retract page:implementation DEPENDS_ON page:policy \
  --reason "The dependency was superseded"

Relation reasons are durable content: never put credentials, secrets, or rawchain-of-thought in them.

SQLite documents remain authoritative. Graph storage is disabled by default;enable exactly one external engine when traversal is needed. Configuration islayered from built-in defaults through global and project files:

lwc config show
lwc config set --graph grafeo
lwc config set --graph surrealdb
lwc config set --graph disabled
lwc config unset --graph

Markdown conversion is a separate opt-in operation. lwc init reports thesame machine-readable setup guidance, but never installs or enables aconverter. Install one adapter, select it explicitly, convert to a new localMarkdown file, review it, and only then ingest it:

# Choose one adapter; both are disabled unless configured.
npm install --global @firecrawl/anydoc
lwc config set --trans anydoc

# Or:
python3 -m pip install 'markitdown[all]'
lwc config set --trans markitdown

lwc trans INPUT --output OUTPUT.md
lwc source add OUTPUT.md

Configuration accepts --trans-timeout 1..900 and repeated--trans-arg=<value> options for the selected adapter. LWC invokes the fixedadapter executable directly, never falls back to the other adapter, acceptslocal files only, caps input and output at 64 MiB, and never overwrites anexisting output. Keep credentials in the adapter's environment rather than inLWC configuration. See the official Anydocand MarkItDown documentation forsupported formats and optional flags.

Grafeo and embedded SurrealDB use disposable sidecars under .lwc/. Eachgraph-project Work commits one current Source/Page and its owned links,citations, and explicit relations before starting the next document. Updatesand deletions enqueue only touched documents; rebuild and resume use the samedocument units. Historical source revisions remain immutable and are neverre-tokenized or projected. Use work list, work status, or work watch toobserve progress and work resume after interruption. graph status reportsthe selected engine and projected document count; graph verify compares itscurrent document keys with SQLite.

Installation

Most users should use the Agent setup prompt above. The manual commands beloware for maintainers, debugging, or Agent environments that cannot install thecompanion Skill.

Install with Homebrew (prebuilt bottles are available for Apple silicon macOSand x86_64 Linux):

brew install JanYork/tap/lwc

Install with npm (Node.js 22+):

npm install --global @i-xor/lwc

Install from crates.io:

cargo install --locked lwc

Install from GitHub:

curl --proto '=https' --tlsv1.2 -fsSL https://github.com/JanYork/llm-wiki-cli/releases/latest/download/install.sh | sh

The installer supports x86_64/aarch64 macOS, glibc Linux, and Windows Git Bash,verifies the release checksum, and installs or updates lwc.It uses ~/.local/bin by default, or updates an existing copy in~/.local/bin or ~/.cargo/bin. To choose another directory:

curl --proto '=https' --tlsv1.2 -fsSL https://github.com/JanYork/llm-wiki-cli/releases/latest/download/install.sh | LWC_INSTALL_DIR="$HOME/bin" sh

Alternatively, build and install from GitHub with Cargo:

cargo install --locked --git https://github.com/JanYork/llm-wiki-cli

Or install a local checkout:

git clone https://github.com/JanYork/llm-wiki-cli.git
cd llm-wiki-cli
cargo install --locked --path .

Companion Agent Skill

The repository includes skills/using-lwc, an Agent Skillthat makes lwc a proactive memory layer for substantive sessions. Install itfrom skills.sh:

npx skills add JanYork/llm-wiki-cli --skill using-lwc -g

Or copy it from a local checkout into the current Agent runtime's user-levelSkills directory. For Codex:

mkdir -p "$HOME/.agents/skills"
cp -R skills/using-lwc "$HOME/.agents/skills/"

The canonical invocation is $using-lwc.

When triggered, the Skill:

  • finds a compatible CLI or installs the official checksum-verified release;
  • initializes global memory in ~/.lwc/ once;
  • recalls bounded global and project context before repeated investigation;
  • initializes the active project on explicit invocation, otherwise asks first;
  • refuses project writes outside the current authorized workspace root;
  • separates project facts from reusable global knowledge;
  • integrates sources and writes durable answers back into the Wiki.

SKILL.md is a short router rather than a monolithic manual. It links onefocused teaching document for basic memory, trigger timing, active memory,physical document graph, bounded Word Graph, CodeGraph, strong tags, documentconversion, Agent onboarding, and recovery/maintenance. Each document stateswhen to use and skip the capability, its minimum workflow, consent boundary, andcompletion evidence.

The Skill normally discovers the active project from the current directory andinvokes the globally installed lwc command directly. LWC_PROJECT_ROOT is anexplicit boundary for a deliberately targeted project, not a prefix to exportfor routine commands in the project you are already working in.

Set LWC_AUTO_INSTALL=0 to disable automatic CLI installation. Automaticinstallation executes the reviewed installer bundled in the Skill, trusts thisrepository and its GitHub Release publishing boundary, and verifies thedownloaded archive against SHA256SUMS; the checksum is integrity protection,not publisher code signing. Release binaries cover x86_64/aarch64 macOS, glibcLinux, and Windows through Git Bash. SKILL.md follows the Agent Skillsresource layout, whileagents/openai.yaml supplies OpenAI/Codex metadata. The CLI itself isruntime-neutral: any Agent that can execute it and load or adapt the Skill'sinstructions can use LWC. Skill commands, global instructions, and Hooks remainruntime-specific, so the setup prompt detects and configures the current host.

Native Agent setup

LWC can detect supported Agents and install one unified read-only LWC MCP.All 12 registered AgentTargets are strong adapters: each installs everyofficial file-based MCP, Skill, Hook, and Instructions surface available forthat host and scope, while UI-owned, preview, or unsupported surfaces arereported explicitly.

lwc agent install --yes
lwc agent status --target all --location global
lwc agent install --print-config codex
lwc agent refresh --target codex,claude
lwc agent uninstall --target codex,claude --yes

--yes selects detected Agents, global scope, and each target's defaultlifecycle/prompt Hooks. Use --no-prompt-hook to omit Claude's per-prompt Hook. The installedentry is lwc -> serve --mcp; its single lwc_exploretool defaults to bounded Wiki memory and accepts explicit code/all modes.The requested projectPath must stay inside the workspace where the MCP hoststarted LWC. It never downloads or initializes CodeGraph. Repeated install and refresh arebyte-idempotent; uninstall restores only owned state and leaves project indexesintact. Optional Codex, Claude Code, and Pi packages live under integrations/;installing a package does not grant or bypass native trust. Do not combine thedirect installer and native package for the same Agent. Each native packagebundles the complete using-lwc Skill, so installation does not depend on athird-party Skill manager or any maintainer-specific environment.

Pi exposes LWC MCP through its official extension bridge because Pi has nobuilt-in MCP. Other Targets register only lwc serve --mcp; CodeGraph stays aninternal LWC code-context plane and is never registered as a second Agent MCP.Officially UI-owned trust and permission settings remain user-managed. Previewsurfaces are labeled as such, and partial project scopes install the supportedsurfaces instead of weakening or rejecting the whole Target. Kiro global pathshonor KIRO_HOME.

The target interface, registry order, detection rules, and MCP paths followCodeGraph's MIT-licensed installer adapter design; LWC adds the unified LWC MCP,per-surface capability reporting, Skills and Hooks, shared-file ownership, andexact rollback.See THIRD_PARTY_NOTICES.md.

Fresh project lwc init output and session/compaction Hooks expose boundedLWC_READINESS facts for the Wiki, physical document graph, CodeGraph runtimeand project index, plus Agent integration commands. Physical graph readinessdistinguishes configured consent from a pending or failed projection. Detectionis read-only and never enables or initializes a graph. When both graphs needauthorization, the portable baseline is plain text, so Agents without checkboxsupport behave the same way:

1. Enable physical document graph and CodeGraph (recommended)
2. Enable physical document graph only
3. Enable CodeGraph only
4. Later

After explicit choice 1, the Agent initializes a missing project Wiki, enablesGrafeo, waits for and verifies its projection Work, initializes CodeGraph, andchecks both results independently. Later changes nothing and does not blockthe primary task. Native plugins may render the same choice IDs with their ownUI, but checkbox support is never required.

Strong tags provide bounded full-page loading for core rules and runbooks:

lwc tag set "operations" incident-response --priority 100 --reason "primary runbook"
lwc load tag "operations" --limit 3
lwc tag autoload "operations" --enable --priority 100 --limit 3 \
  --max-chars 50000 --reason "required at session boundaries"

This is an explicit strong-load mechanism, not token-derived search: limits andcharacter budgets are applied before complete pages enter Agent context.

Quick Start

This section documents the CLI protocol that the Agent executes. Humans do notneed to run these commands during normal use.

1. Initialize a project Wiki

cd your-project
lwc init
printf '# Schema\nEvery page declares provenance; source-grounded claims cite sources.\n' | lwc schema set -
printf '# Purpose\nBuild a durable project Wiki.\n' | lwc purpose set -

Project initialization adds the project-relative .lwc/ path to Git's localinfo/exclude file when needed, without changing the repository .gitignore.Use lwc init --no-git-exclude only when the Wiki is intentionally versioned.

2. Add source material

lwc source add-dir docs/

Files without an explicit title use their source origin as a stable,human-readable fallback. Identical bytes are deduplicated by SHA-256.Project sources that resolve outside the active Wiki root require--allow-external-source. High-confidence credential markers are rejectedunless the reviewed source is explicitly acknowledged with--acknowledge-sensitive-source.

Each successful add also records the observed file path and its currentimmutable snapshot. Check only the sources relevant to the task before relyingon file-backed evidence:

lwc source status 7 12

The command streams each live file through SHA-256 and reports path lineage(current or superseded) separately from filesystem state (current,modified, missing, unreadable, oversized, or unstable). It isread-only. Use source status --all only for explicit maintenance because itscost is proportional to the bytes in all tracked files. Inspect a modified pathbefore updating knowledge:

lwc source diff 7
lwc source refs 7 --limit 1000

source diff compares the immutable source with its live file, or with anothersnapshot via --to-source. It returns a bounded unified diff: at most 8 MiB and200,000 lines per side, 20,000 Unicode output characters by default, and100,000 with --max-chars. If one source was observed at multiple paths, selectan exact --path. A truncated diff is only a preview. source refs listsdirectly citing review candidates; it does not prove which pages aresemantically affected. Re-run source add only after review when the same pathcontains a meaningful new revision. An A -> B -> A sequence remains three pathobservations even though content A reuses its original source ID. External livepaths require --allow-external-source again; flagged live text also requires--acknowledge-sensitive-source after inspection.

Sources migrated from older stores remain explicitly untracked because LWC doesnot guess historical paths; re-add the intended file once to establish itsfirst tracked revision. If a file or path head changes during the check, LWCreturns source_status_unstable; retry instead of trusting a mixed-time result.

For a curated atomic import, paths in a JSON manifest resolve from themanifest's directory:

{
  "sources": [
    {"path": "ARCHITECTURE.md", "title": "Architecture contract"},
    {"path": "src/store.rs", "title": "SQLite store"}
  ]
}
lwc source add-manifest lwc-sources.json

3. Analyze and integrate one source

lwc ingest next --context-limit 50 --source-max-chars 100000
lwc ingest analyze 1 --file analysis.md

Use lwc ingest claim 7 when a manifest or scheduler already selected an exactpending source ID.

If source_window.has_more is true, continue reading fromsource_window.next_offset_chars:

lwc source show 1 --offset-chars 100000 --max-chars 100000

Create a cited source-summary page and integrate its contribution into at leastone non-source page before completing the ingest task:

lwc page put source-1 \
  --title "Source 1 Summary" \
  --kind source \
  --summary "What this source contributes" \
  --file source-summary.md \
  --source 1

lwc page put durable-concept \
  --title "Durable Concept" \
  --kind concept \
  --summary "How this source changes shared knowledge" \
  --file concept.md \
  --source 1

lwc ingest complete 1

Both layers are required: the source page is a navigation and provenance aid;the non-source page makes knowledge compound. If a source genuinely changes noshared page, complete it with a specific audited explanation:

lwc ingest complete 1 \
  --no-derived-pages-reason "Duplicate evidence; existing synthesis already covers every supported claim"

Source citations automatically expose source-grounded provenance. Fordurable knowledge that comes from the user, an Agent observation, or anexplicit hypothesis, repeat --provenance as needed instead of inventing asource:

lwc page put architecture-decision \
  --title "Architecture decision" \
  --kind query \
  --summary "Accepted constraint and remaining uncertainty" \
  --file decision.md \
  --provenance user-provided \
  --provenance hypothesis

page put replaces the complete citation and explicit-provenance sets. Readthe existing page first, then repeat every still-valid --source andnon-source --provenance value. Do not pass source-grounded explicitly; it isderived from citations. Provenance is returned by page reads, context, search,source references, and Markdown projection, but does not change search ranking.

4. Query the accumulated Wiki

lwc context --limit 50
lwc search "question keywords" --limit 20
lwc search "question keywords" --limit 20 --explain
lwc search "concept only" --type page --kind concept
lwc search "exact evidence" --type source
lwc page show source-1

Agent Workflow

The intended workflow is:

  1. Collect immutable sources.
  2. Claim one ingest task with bounded lwc ingest next, or ingest claim <ID>when the source was selected explicitly.
  3. Read every returned source window, plus the schema, purpose, and bounded context.
  4. Analyze before generating pages.
  5. Write or revise a source summary and shared durable pages with explicit --source citations.
  6. Complete only after both integration gates pass, or record why no shared page should change.
  7. Put a multi-command ingest or broad revision in one changeset, validate thedraft, then publish it atomically.
  8. Use search, context, graph, and lint to keep the Wiki coherent over time.

See docs/agent-workflow.md for the full operating contract.Run lwc --help or lwc <command> --help for Agent-oriented preconditions,state transitions, side effects, and next actions.

Atomic Multi-command Changes

A single source or page command is transactional. Use a changeset when onelogical update needs several commands and must not expose a partial Wiki:

lwc --scope project changeset begin architecture-refresh
lwc --scope project --changeset architecture-refresh source add-manifest sources.json
lwc --scope project --changeset architecture-refresh ingest claim 1
# Analyze, write cited pages, and complete ingest with the same selector.
lwc --scope project --changeset architecture-refresh lint
lwc --scope project --changeset architecture-refresh search "expected answer" --limit 5
lwc --scope project changeset show architecture-refresh
lwc --scope project changeset commit architecture-refresh

Draft reads see staged writes, while live SQLite and Markdown stay unchanged.The draft database starts as a small sparse overlay; it does not copy orcheckpoint the live Wiki. changeset show reports staged operations, revisions,and readiness without running lint. Commit validates and applies onlytouched entities, so unrelated live writes survive; a same-entity revision conflictfails without overwriting either side. Commit rejects empty drafts and lintissues; there is no force or automatic merge. Use--allow-lint-issues --reason "reviewed pre-existing debt" only for auditeddebt that the changeset did not introduce. After commit, rerun the same fixedretrieval checks against live state. Commit freezes the reviewed draft beforepublication; changeset_frozen blocks any later staged write. Retry the samecommit for recovery, or discard after a reported conflict—never add more workto a frozen draft.

lwc --scope project changeset discard architecture-refresh
lwc --scope project changeset rollback <CHANGESET_ID>

Discard touches only an uncommitted draft. Commit writes a checksummed inversepatch containing only touched entities and returns the exact rollback ID;rollback restores only those entities and refuses if one changed again. Projectand global changesets are separate, --scope all is invalid, and init,maintenance, checkpoint, and nested changeset commands reject--changeset. Drafts never create a second Markdown projection. If a structurederror reports committed=true with cleanup or materialization work remaining,do not repeat the knowledge changes; run the returned recovery action.

Sparse commit currently has exact patches for Source add/ingest, Pageput/remove, schema, purpose, and recorded search operations. Retrieval-weightand explicit semantic-relation mutations fail before checkpointing or taking alive write lock with changeset_sparse_unsupported; apply those as directsingle-entity transactions until their sparse inverse patches are available.

Scopes

lwc supports three scopes:

Scope Store Use
project Nearest ancestor .lwc/wiki.db Default, project-specific knowledge
global ~/.lwc/wiki.db Reusable cross-project knowledge
all Project and global stores Combined search and context only

Examples:

lwc --scope global init
lwc --scope global source add shared.md
lwc --scope all search "shared term"
lwc --scope all context

Knowledge writes are explicit. all does not create implicit cross-store citationsor links; search --record only appends the query operation to each selected store.

Search and CJK

Search is lexical and deterministic.

  • Search terms are plain text, not raw FTS syntax.
  • --type auto is the default: compiled pages rank first, paired raw sourcesare hidden, and raw sources provide fallback recall.
  • Use --type page, --type source, or --type all to select a layer.Repeat --kind to restrict page results, such as--kind concept --kind synthesis.
  • Multi-character CJK query terms use adjacent bigrams; the index also retainsnon-stopword unigrams so one-character queries remain searchable.
  • Latin text is tokenized into lowercased alphanumeric terms.
  • Ranking keeps title, source filename, path/slug, summary, and body evidencedistinct. Exact/partial title and path matches receive bounded boosts.
  • README/index/overview documents and explicit navigation hubs arequery-conditionally downweighted in favor of specific feature documents;asking for the README or overview disables that penalty.
  • Page candidates may receive a bounded direct-link or shared-source graphboost. Common-neighbor-only relationships cannot change search order, and abroad navigation hub receives a bounded graph penalty.
  • --explain returns the exact score arithmetic, including lexical, generic,graph, manual-weight, and query-feedback signals. It does not record thequery; --record remains the only search-history opt-in.
  • Fixed coefficients and lower-is-better ranks keep project and global resultscomparable under --scope all.

This is intentionally dictionary-free. The goal is stable behavior for product names, code names, mixed-language terms, and emerging vocabulary without depending on a word-segmentation dictionary.

Explicit retrieval weights and feedback

Use a document weight for a durable, query-independent judgment about a pageor source. Use feedback for one exact ordered-token query fingerprint:

lwc weight set page payment-rules \
  --value 2 \
  --reason "Canonical payment rules specification" \
  --provenance agent-observed
lwc weight list page payment-rules

lwc weight feedback page payment-rules \
  --query "payment reconciliation rules" \
  --signal relevant \
  --reason "Verified against the expected answer" \
  --provenance agent-observed

lwc weight feedback-clear page payment-rules \
  --query "payment reconciliation rules" \
  --provenance agent-observed
lwc weight clear page payment-rules --provenance agent-observed

Document values are -2, -1, 1, or 2; use clear for zero. Bothmechanisms only rerank lexical candidates and cannot make a nonmatchingdocument appear. A user-provided row takes precedence over anagent-observed row while both remain auditable. Feedback stores the SHA-256fingerprint, not the raw query, and does not transfer to paraphrases withdifferent tokens. Reasons and operation records are durable, so never copy asensitive query into --reason. Mutations require an explicit project orglobal scope; --scope all is rejected.

Read-only Viewer and CodeGraph

lwc view starts a foreground, loopback-only project inspector and opens thebrowser. It serves one embedded TS + Lit application—no CDN and no Node runtimeat use time—and exposes GET/HEAD APIs only. Pages, sources, Markdown, theknowledge graph, and the optional code graph are read from the current projectwithout migration, refresh, or graph construction:

lwc view
lwc view --port 4173 --no-open

The viewer starts in English. Use the 中文 / EN control to switch languages;the browser remembers the selection while Wiki content remains in its authoredlanguage. Graphs use a single Obsidian-inspired 3D relationship view with smallnodes, persistent labels, thin links, rotation, and zoom.

Code indexing is project-only and disabled until explicitly initialized. Thepinned LWC CodeGraph fork is downloaded once from its GitHub Release, verifiedwith SHA-256, and cached under ~/.lwc/runtime/codegraph/<PIN>/<TARGET>/; eachproject keeps only its index under .lwc/codegraph. Telemetry is always off andno .codegraph state is used.

lwc cg status
lwc cg init                 # download once, then index one complete file at a time
lwc cg sync
lwc cg query UserService
lwc cg node UserService
lwc cg callers UserService
lwc cg callees UserService
lwc cg impact UserService
lwc cg files

The pinned runtime recognizes these languages and code-oriented formats:TypeScript, TSX, JavaScript, JSX, ArkTS, Python, Go, Rust, Java, C, C++, C#,Razor, PHP, Ruby, Swift, Kotlin, Dart, Svelte, Vue, Astro, Liquid, Pascal,Scala, Lua, Luau, Objective-C, R, Solidity, Nix, YAML, Twig, XML,.properties, CFML, CFScript, CFQuery, COBOL, VB.NET, Erlang, and Terraform.YAML, Twig, and .properties are tracked at file level; framework resolvers maystill add relationships. XML is recognized for MyBatis mapper extraction.

All CodeGraph query capabilities are forwarded by lwc cg. Global lifecyclecommands (install, uninstall, upgrade, telemetry, daemon, daemons)are blocked. The exact lwc cg serve --mcp bridge remains for legacy manualcompatibility; new Agent integrations use lwc serve --mcp, which fusesbounded Wiki and CodeGraph exploration behind one read-only tool. LWC owns theruntime and enforces the project boundary. Initial,incremental, full, update, delete, reference-resolution, and recovery writescommit one owner file completely before the next; the current graph remainsreadable and historical document revisions are never refreshed.

Maintenance and Projection

Useful maintenance commands:

lwc lint
lwc maintenance reindex
lwc maintenance materialize
lwc maintenance compact
lwc work list
lwc work status <WORK_ID>
lwc work watch <WORK_ID>
lwc work cancel <WORK_ID>
lwc work resume <WORK_ID>
lwc checkpoint create before-large-update
lwc checkpoint list
lwc log --limit 20

Notes:

  • Maintenance commands return a durable work immediately. Read progress withwork status, or use work watch and inspect work.result after success.Schema v10 to v11 migration uses the same mechanism automatically, so normalcommands never perform that migration inline.
  • lint is read-only by default. Add --record only when the lint pass belongsin durable operation history.
  • maintenance reindex rebuilds derived search artifacts from SQLite.
  • maintenance materialize rebuilds the projected Markdown tree from SQLite.
  • maintenance compact only attempts a WAL truncate checkpoint; it does nothide a full FTS optimization. Run it while the Wiki is idle and inspectbusy plus after_bytes. A busy reader returns promptly without changingcanonical content.
  • Search queries are private by default; add --record only when you want the query wording stored in the durable operation log.

lwc checkpoint create <NAME> uses SQLite's online backup API. Restore withlwc checkpoint restore <NAME>; LWC first creates a pre-restore-* safetycheckpoint and then rebuilds the projection. Use source remove <ID> andpage remove <SLUG> for guarded deletion: sources with citations and pageswith inbound links are refused. Removing the current source for a tracked pathstops tracking that path instead of silently exposing an older revision ascurrent.

For a multi-source ingest or broad page replacement, prefer a changeset over amanual checkpoint: successful commit writes a sparse inverse patch, publishesonly touched canonical entities in one transaction, and incrementallymaterializes changed Markdown. Commit attempts a WAL truncate after publication;wal_checkpointed=false means an active reader prevented it and does not meanthe canonical commit failed.

For an external filesystem backup, stop active lwc commands and copy thecomplete .lwc/ directory. Do not copy only wiki.db while a writer may stillbe using its WAL files.

Benchmark Suite

The opt-in benchmark imports a local UTF-8 corpus into a temporary Wiki andreports import time, search P50/P95, Recall@5/10, MRR, and storage before/aftercompaction. Ground truth is a JSONL file of queries and expectedcorpus-relative paths:

cargo build --release
LWC_BENCH_CORPUS=/path/to/sanitized-corpus \
LWC_BENCH_QUERY_SET=/path/to/query-set.jsonl \
LWC_BENCH_BINARY="$PWD/target/release/lwc" \
cargo test --test search_benchmark -- --ignored --nocapture

Normal cargo test --all-targets covers page-first search, type/kind filters,UTF-8 source windows, ingest completion gates, graph precision, migrations,lint, and WAL compaction. See benchmarks/README.md forthe workload contract and fair before/after comparison rules.

Limits and Non-Goals

Current design constraints:

  • single-machine, single-user knowledge base;
  • UTF-8 text workflow;
  • bounded input size of 64 MiB per schema, purpose, source, or page body;
  • lexical search, not semantic vector retrieval.

Deliberate non-goals for this CLI:

  • no built-in LLM calls;
  • no vector database;
  • no daemon or background service;
  • no web UI or desktop UI;
  • no direct database editing contract.

If the projected Markdown drifts, rebuild it. If the SQLite schema is wrong, fix it through the CLI and migrations, not by hand.

Contributing

Issues and pull requests are welcome, especially around:

  • agent workflow ergonomics;
  • deterministic projection behavior;
  • durable citation and page maintenance contracts;
  • search quality for multilingual technical corpora.

Please read CONTRIBUTING.md before opening a pull request.Report security issues according to SECURITY.md.

License

Licensed under the Apache License 2.0.

MCP Server · Populars

MCP Server · New

    JanYork

    LWC — Proactive Memory for AI Agents

    Agent-driven proactive memory CLI for AI agents — autonomously recall, maintain, and evolve persistent, source-grounded knowledge across sessions.

    Community JanYork
    mixelpixx

    Konnect *BETA Release

    AI-assisted PCB design for KiCAD 10. Native KiCAD plugin — a single Rust binary exposing 171 schematic, layout, routing, design-review, and manufacturing tools to Claude, or the LLM of your choosing

    Community mixelpixx
    mixelpixx

    Nimrod

    Web research for Claude over MCP: quality-scored Google search, clean extraction, deep research. Hosted connector for claude.ai/Desktop/Code + Nimrod Desktop toolkit (skills, agent, hooks).

    Community mixelpixx
    Minima-AI-Inc

    minima

    On-premises conversational RAG with configurable containers

    Community Minima-AI-Inc
    Minima-AI-Inc

    minima MCP server

    On-premises conversational RAG with configurable containers

    Community Minima-AI-Inc