clawmaster icon indicating copy to clipboard operation
clawmaster copied to clipboard

LLM Wiki: wire LLM into core operations (ingest, query, evolve)

Open webup opened this issue 7 months ago • 3 comments

Problem

The LLM Wiki module has solid infrastructure (filesystem vault, frontmatter schema, hybrid search, freshness decay, lint, REST API, React UI) but is missing the core of the Karpathy LLM Wiki pattern: the LLM that reads, understands, cross-references, and writes. Without LLM calls, the wiki is a structured file store — not a compounding knowledge base.

Reference: Karpathy's LLM Wiki concept

Gaps (priority order)

1. Ingest touches 1 page, not 10–15

Karpathy: "A single source might touch 10–15 wiki pages. The LLM reads the source, writes a summary page, updates the index, updates relevant entity and concept pages across the wiki."

Current ingestWikiSource creates or updates exactly one page per source. It never extracts entities, never updates existing entity/concept pages with new information, never cross-references with existing content.

Fix: After writing the primary source page, call the LLM to:

  • Extract key entities/concepts from the source
  • Find existing wiki pages that should be updated
  • Write or update entity/concept pages with new information
  • Flag contradictions with existing claims
  • Add [[wikilink]] cross-references

2. Query returns search results, not a synthesized answer

Karpathy: "The LLM searches for relevant pages, reads them, and synthesizes an answer with citations."

Current queryWiki returns a numbered list of page titles + snippets. This is search, not synthesis.

Fix: After retrieving matching pages, call the LLM to produce a synthesized answer with inline [[wikilink]] citations. The offerToSave flag is already there — once the answer is good enough, save it back as a synthesis page.

3. Evolve is mechanical, not intelligent

Current evolveWiki recalculates freshness scores and updates link maps. Karpathy's evolve would have the LLM re-read and revise stale pages.

Fix: For pages that turned stale, call the LLM to:

  • Re-examine the page against current sources
  • Suggest updates or mark as superseded
  • Detect contradictions between related pages

4. No contradiction detection

Lint checks structural health (orphans, missing links, stale scores) but never examines content. Two pages can directly contradict each other and lint won't notice.

Fix: Add an LLM-backed lint pass that samples page pairs sharing [[wikilink]] references and checks for factual contradictions.

5. No schema co-evolution

SCHEMA.md is a one-line placeholder. Karpathy: the schema "is the key configuration file — it's what makes the LLM a disciplined wiki maintainer."

Fix: Populate SCHEMA.md with current conventions and add a mechanism for the user + LLM to co-evolve it over time.

6. Smaller gaps

  • No git integration — version history, branching, collaboration for free
  • No query logging — log.md only records ingests/evolves, not queries
  • No rich output formats — comparison tables, Marp slides, charts (only markdown pages)
  • No incremental re-ingest — re-ingest either skips or overwrites; no diff propagation to related pages
  • Tauri/desktop unavailable — adapter returns "not available" for all wiki calls

What's already good

These parts are solid and should be preserved:

  • Three-layer vault layout (raw/, pages/, .meta/, SCHEMA.md)
  • Markdown + YAML frontmatter with full provenance
  • [[wikilink]] bidirectional link extraction
  • index.md + log.md auto-updated on writes
  • Fingerprint-based ingest dedup with URL confirmation flow
  • Ebbinghaus freshness decay with importance weighting
  • PowerMem managed memory integration (semantic + keyword hybrid search)
  • Structural lint (orphan, missing-link, duplicate-title, stale, schema)
  • Full REST API + React UI with i18n

Proposed approach

  1. Define an LLM call abstraction in wikiService.ts (provider-agnostic, pluggable)
  2. Wire LLM into ingestWikiSource for multi-page updates (gap 1)
  3. Wire LLM into queryWiki for answer synthesis (gap 2)
  4. Wire LLM into evolveWiki for stale page revision (gap 3)
  5. Add LLM-backed contradiction lint (gap 4)
  6. Populate and maintain SCHEMA.md (gap 5)

webup avatar May 01 '26 07:05 webup

Execution Plan

Architecture constraint

ClawMaster does not make direct LLM inference calls. All chat completions go through the OpenClaw gateway (port 18789). The only direct API call in the codebase is the ERNIE image plugin (/images/generations). The wiki service must follow the same pattern: call the OpenClaw gateway's chat completions endpoint, using the user's configured provider and model from openclaw.json.


Phase 1 — LLM abstraction layer

Goal: A single, testable wikiLlm module that the wiki service can call without knowing provider details.

Files to create/modify:

  • packages/backend/src/services/wikiLlm.ts — new module
  • packages/backend/src/services/wikiService.ts — import from wikiLlm

What it does:

  1. Read provider config from openclaw.json via readConfigJson() (already in configJson.ts)
  2. Resolve the default model from agents.defaults.model.primary
  3. Call the OpenClaw gateway at http://localhost:{GATEWAY_PORT}/v1/chat/completions (or fall back to direct provider API using stored credentials)
  4. Expose two functions:
    • wikiLlmComplete(messages, opts?) — single-turn completion, returns string
    • wikiLlmCompleteStructured(messages, schema, opts?) — returns parsed JSON matching a schema (for entity extraction, lint results, etc.)
  5. Both functions accept { maxTokens, temperature, signal } options
  6. Include a wikiLlmEnabled() guard that returns false if no provider is configured — all wiki operations fall back to current behavior (search-only, no LLM)
  7. Token/cost guard: maxWikiLlmTokensPerOperation config (default 4096) to prevent runaway LLM spend

Tests: Mock the gateway HTTP call; verify config resolution, fallback, and token limits.

Why gateway-first: The gateway already has the user's API keys, model routing, and streaming infrastructure. We don't duplicate credential management.


Phase 2 — LLM-powered ingest (multi-page)

Goal: One source touches multiple wiki pages, as Karpathy describes.

Files to modify:

  • packages/backend/src/services/wikiService.ts — ingestWikiSource()
  • packages/backend/src/services/wikiService.test.ts — new test cases

What changes in ingestWikiSource():

After the current logic writes the primary source page:

  1. Extract entities/concepts — call wikiLlmCompleteStructured with the source content and a prompt like:

    Given this source, extract:
    - Named entities (people, orgs, products, technologies) that deserve their own wiki page
    - Concepts (ideas, methods, patterns) that deserve their own wiki page
    - For each: a 1-2 sentence summary of what this source says about it
    - For each: whether an existing wiki page likely covers this (given the page titles: ...)
    

    Schema: { entities: [{ name, summary, existingPageId?, isNew }], concepts: [{ name, summary, existingPageId?, isNew }] }

  2. Update/create entity and concept pages — for each extracted item:

    • If existingPageId exists: call wikiLlmComplete to merge the new information into the existing page body, preserving [[wikilinks]] and frontmatter
    • If isNew: create a new page in pages/entities/ or pages/concepts/ with the summary, a [[wikilink]] back to the source page, and proper frontmatter
    • Each new/updated page also gets a PowerMem managed memory record
  3. Cross-reference — ensure the source page body gets [[wikilinks]] added for all extracted entities/concepts

  4. Update index + log — already handled by existing writeIndex and appendLog calls

Fallback: If wikiLlmEnabled() is false, ingest works exactly as today (single page, no entity extraction).

Token budget: Ingest operations are the most expensive. Cap at ~6000 input + 2000 output tokens per source. Skip entity extraction for sources > 12000 chars (truncate with a note).

Tests:

  • Ingest with LLM disabled → same behavior as today
  • Ingest with LLM enabled + mock response → verify entity/concept pages created, source page updated with wikilinks
  • Ingest with LLM error → graceful fallback to single-page ingest + warning

Phase 3 — LLM-powered query (answer synthesis)

Goal: Query returns a synthesized answer with citations, not a list of snippets.

Files to modify:

  • packages/backend/src/services/wikiService.ts — queryWiki()
  • packages/backend/src/services/wikiService.test.ts — new test cases

What changes in queryWiki():

After searchWiki() returns results:

  1. Load top pages — read the full content of the top 3-5 matching pages (already done partially for citations)

  2. Build synthesis prompt:

    You are answering a question using the local Wiki knowledge base.
    
    Question: {query}
    
    Wiki pages:
    {for each page}
    ---
    ## [[{title}]] (freshness: {status}, updated: {date})
    {content}
    ---
    {/for}
    
    Synthesize a concise answer. Cite claims with [[Page Title]] wikilinks.
    If pages contradict each other, note the contradiction.
    If the wiki doesn't cover the question well, say so.
    
  3. Call wikiLlmComplete with the prompt, temperature: 0.3, maxTokens: 1024

  4. Return the LLM answer as answer in WikiQueryPayload, with offerToSave: true if the answer synthesizes 2+ pages

  5. Append wikilinks found in the LLM answer to the results list (so the UI can render them as clickable links)

Fallback: If LLM is disabled, return the current snippet-based answer (no behavior change).

Tests:

  • Query with LLM disabled → current behavior
  • Query with LLM enabled + mock → verify synthesized answer, citations preserved
  • Query with no results → same "no relevant article" message
  • Query with LLM error → fallback to snippet-based answer + warning

Phase 4 — LLM-powered evolve (stale page revision)

Goal: Stale pages get LLM-reviewed and revised, not just score-recalculated.

Files to modify:

  • packages/backend/src/services/wikiService.ts — evolveWiki()
  • packages/backend/src/services/wikiService.test.ts — new test cases

What changes in evolveWiki():

After the current freshness recalculation, for each page that turned stale (score < 0.35):

  1. Collect related context — load the stale page + its backlinked pages + its source pages (via [[wikilinks]] and frontmatter source refs)

  2. Build revision prompt:

    This wiki page has gone stale (last updated {date}, freshness score {score}).
    
    Current page: [[{title}]]
    {content}
    
    Related pages:
    {for each related page}
    ## [[{title}]] (freshness: {status})
    {snippet}
    {/for}
    
    Review and revise the page if needed:
    - Update claims that may be outdated
    - Add new information from related pages
    - Note contradictions
    - If the page is still accurate, respond with "NO_CHANGE"
    - Otherwise, provide the revised body (keep the same structure, update facts)
    
  3. Call wikiLlmComplete — if the response is not "NO_CHANGE", write the revised body back to the page file, update frontmatter (evolveChangedAt, evolveChangeSummary, evolveSource: 'llm-revision'), and bump freshness score

  4. Rate limit — process at most 5 stale pages per evolve call to control LLM spend. Log how many were skipped.

Fallback: If LLM is disabled, evolve works exactly as today (mechanical freshness recalculation only).

Tests:

  • Evolve with no stale pages → no LLM calls
  • Evolve with stale pages + LLM disabled → mechanical-only
  • Evolve with stale pages + LLM enabled + mock "NO_CHANGE" → page unchanged, freshness updated
  • Evolve with stale pages + LLM enabled + mock revision → page body updated, frontmatter updated
  • Evolve with LLM error → stale page gets mechanical freshness only + warning

Phase 5 — LLM-backed lint (contradiction detection)

Goal: Lint detects content contradictions, not just structural issues.

Files to modify:

  • packages/backend/src/services/wikiService.ts — lintWiki(), computeWikiLintIssues()
  • packages/backend/src/services/wikiService.test.ts — new test cases

What changes:

Add a new lint pass after the existing structural checks:

  1. Collect candidate pairs — find pages that share [[wikilinks]] (i.e., page A links to page B, or both link to page C). These are most likely to contain related claims.

  2. Sample pairs — limit to 10 pairs per lint call (cost control)

  3. Build contradiction prompt:

    Do these two wiki pages contain any factual contradictions?
    
    Page 1: [[{title1}]]
    {content1}
    
    Page 2: [[{title2}]]
    {content2}
    
    Respond with JSON: { "contradictions": [{ "claim1": "...", "claim2": "...", "explanation": "..." }] }
    If no contradictions, respond: { "contradictions": [] }
    
  4. Call wikiLlmCompleteStructured with the schema

  5. Emit lint issues of kind 'contradiction' with severity 'warning' for each found contradiction

  6. New WikiLintIssue.kind: add 'contradiction' to the union type

Fallback: If LLM is disabled, lint runs the existing structural checks only (no contradiction detection).

Tests:

  • Lint with LLM disabled → no contradiction issues
  • Lint with LLM enabled + mock contradictions → verify kind: 'contradiction' issues emitted
  • Lint with LLM enabled + mock no contradictions → no new issues
  • Lint with LLM error → structural checks still run, contradiction check skipped + warning

Phase 6 — Schema co-evolution + SCHEMA.md

Goal: SCHEMA.md becomes a living document that the LLM helps maintain.

Files to modify:

  • packages/backend/src/services/wikiService.ts — ensureWikiVault(), add updateWikiSchema()
  • packages/backend/src/services/wikiService.test.ts — new test cases

What changes:

  1. Populate SCHEMA.md — replace the one-line placeholder with a real schema document describing:

    • Page types and their directory structure
    • Frontmatter fields and conventions
    • [[wikilink]] syntax
    • Ingest/query/evolve/lint workflows
    • Freshness model
  2. Schema review on evolve — at the end of each evolveWiki() call (if LLM enabled), sample 5 random pages and ask the LLM:

    Here is the current wiki schema:
    {schemaContent}
    
    Here are sample pages:
    {pages}
    
    Are the pages following the schema conventions? Suggest schema updates if conventions have drifted.
    Respond with JSON: { "suggestions": [{ "field": "...", "current": "...", "proposed": "...", "reason": "..." }] }
    

    Log suggestions to log.md but do NOT auto-update SCHEMA.md (user review required).

  3. Add POST /api/wiki/schema endpoint — returns current SCHEMA.md content; accepts PUT to update it

Fallback: If LLM is disabled, SCHEMA.md stays static after initial population.


Phase 7 — Smaller gaps

These can be done in any order after Phase 1:

Gap Approach Effort
Query logging Add appendLog(paths, ...) call in queryWiki() and assistWithWiki() with prefix ## [{date}] query | {query} S
Incremental re-ingest When fingerprint differs, call LLM to diff old vs new content and propagate changes to entity/concept pages M (depends on Phase 2)
Tauri/desktop Implement wiki command handlers in src-tauri/ that call the backend API (same as web adapter) M
Git integration git init in vault root on ensureWikiVault(), auto-commit on ingest/evolve with meaningful messages S
Rich output formats Add format param to queryWiki (markdown, table, slides). LLM prompt variant per format. M (depends on Phase 3)

Dependency graph

Phase 1 (LLM abstraction)
  ├── Phase 2 (ingest multi-page)
  ├── Phase 3 (query synthesis)
  ├── Phase 4 (evolve revision)
  └── Phase 5 (lint contradictions)
       └── Phase 6 (schema co-evolution)
Phases 2-5 can run in parallel after Phase 1.
Phase 6 depends on Phase 5 (uses LLM in evolve context).
Phase 7 items are independent.

Estimated effort

Phase Scope Estimate
1 LLM abstraction 2-3 days
2 Ingest multi-page 3-4 days
3 Query synthesis 1-2 days
4 Evolve revision 2-3 days
5 Lint contradictions 1-2 days
6 Schema co-evolution 1-2 days
7 Smaller gaps 2-3 days
Total 12-19 days

Risk mitigation

  • LLM cost: Every LLM call goes through wikiLlmComplete which enforces token limits. All LLM-dependent features have graceful fallbacks to current behavior. wikiLlmEnabled() guard means zero cost if no provider configured.
  • LLM latency: Ingest and evolve are async-friendly (user doesn't block on them). Query synthesis should target < 5s response time with streaming support in future.
  • LLM errors: Every LLM call is wrapped in try/catch with fallback to non-LLM behavior + warning in response payload.
  • Quality: LLM-generated page content always includes evolveSource: 'llm-ingest' / 'llm-revision' / 'llm-synthesis' in frontmatter so it's traceable. Schema review suggestions require human approval.

webup avatar May 01 '26 08:05 webup

Implemented the gateway-first wiki LLM plan for #137 on feat/wiki-llm-core-137.

What is now in place:

  • Added a dedicated backend wiki LLM helper that reads openclaw.json, resolves agents.defaults.model.primary, respects gateway auth, and calls the OpenClaw gateway chat completions endpoint only.
  • Extended wiki ingest provenance so one source can manage one primary page plus multiple derived pages with tracked primaryPageId, derivedPageIds, memoryIds, and per-derived-page fingerprints.
  • Added deterministic multi-page ingest for source pages: structured entity/concept extraction, generated per-source contribution blocks, re-ingest replacement, and cleanup of no-longer-derived pages.
  • Upgraded queryWiki() to use LLM synthesis when enabled while keeping it read-only and preserving the existing durable save flow through synthesizeWiki().
  • Split maintenance into the existing mechanical /api/wiki/evolve path plus a new explicit /api/wiki/evolve/deep path for bounded LLM stale-page review.
  • Added LLM-backed contradiction linting with the new contradiction issue kind.
  • Replaced the placeholder schema bootstrap with a fuller SCHEMA.md template.
  • Updated the web wiki UI to render clickable wikilinks in synthesized answers and expose the deep-evolve action.

Verification completed:

  • npm run test --workspace=@openclaw-manager/backend
  • npm test --workspace=@openclaw-manager/web -- --run src/modules/wiki/__tests__/WikiPage.test.tsx
  • npm run build --workspace=@openclaw-manager/backend
  • npm run build --workspace=@openclaw-manager/web

Not included in this pass:

  • Tauri/desktop wiki parity remains deferred.
  • No direct provider inference fallback was added; gateway remains the only wiki LLM path.

webup avatar May 01 '26 09:05 webup

Updating the execution plan/status for #137 to match the revised gateway-first implementation and the proof pass.

Implemented shape:

  • OpenClaw gateway remains the only wiki inference path through packages/backend/src/services/wikiLlm.ts.
  • Multi-page ingest is provenance-safe: each source now tracks a primary page plus derived pages, memory ids, and per-derived-page fingerprints in .meta/ingest-state.json.
  • Derived entity/concept updates are deterministic in v1: generated per-source contribution blocks are replaceable on re-ingest, and outdated derived artifacts are cleaned up.
  • queryWiki() stays read-only and now uses LLM synthesis when enabled, while durable persistence still flows only through synthesizeWiki().
  • Mechanical evolve stays on /api/wiki/evolve; bounded opt-in LLM maintenance is separated into /api/wiki/evolve/deep and never runs from auto-evolve-on-write.
  • Contradiction lint is now supported as a bounded LLM check with WikiLintIssue.kind = 'contradiction'.
  • Vault bootstrap now writes a real SCHEMA.md template, while schema drift is still documentation/logging first.
  • Web wiki rendering now supports linked synthesized answers; desktop/Tauri wiki parity remains deferred for this issue.

Proof follow-up fix:

  • During workflow proofing, I found that durable synthesis pages could accidentally absorb internal generated wiki blocks/comments from source pages, which could create malformed wikilinks and false missing-link lint issues.
  • Fixed by sanitizing generated blocks and internal maintenance sections before snippet generation, query synthesis prompting, and durable synthesis rendering.
  • Added backend regression coverage for the contaminated-source case so saved synthesis output stays clean and lint-safe.

Verification:

  • npm test --workspace=@openclaw-manager/backend -- --run src/services/wikiService.test.ts
  • npm run build --workspace=@openclaw-manager/backend

webup avatar May 01 '26 10:05 webup