Skip to content

LLM Wiki is a cross-platform desktop application that turns your documents into an organized, interlinked knowledge base — automatically. Instead of traditional RAG (retrieve-and-answer from scratch every time), the LLM incrementally builds and maintains a persistent wiki from your sources。

TypeScript

feat: real-LLM testing infrastructure + prompt hardening

nash_sub1ceb9ed1b5b
diff --git a/package.json b/package.json
index 9c19a49d..0a508058 100644
--- a/package.json
+++ b/package.json
@@ -7,7 +7,8 @@
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
- "test": "vitest run",
+ "test": "vitest run --exclude='**/*.real-llm.test.ts'",
+ "test:llm": "RUN_LLM_TESTS=1 vitest run real-llm --no-file-parallelism --reporter=verbose",
"tauri": "tauri"
},
"dependencies": {
diff --git a/src/lib/enrich-wikilinks.ts b/src/lib/enrich-wikilinks.ts
index 20b43b73..3efcbbe6 100644
--- a/src/lib/enrich-wikilinks.ts
+++ b/src/lib/enrich-wikilinks.ts
@@ -31,21 +31,28 @@ export async function enrichWithWikilinks(
{
role: "system",
content: [
- "You are a wiki cross-referencing assistant.",
- "Your ONLY job: add [[wikilinks]] to the text where entities or concepts from the wiki index are mentioned.",
+ "You are a wiki cross-referencing assistant. Your ONLY job: add",
+ "[[wikilinks]] around existing words that match entries in the wiki",
+ "index. You do NOT rewrite, summarize, or expand the page.",
"",
buildLanguageDirective(content),
"",
- "Rules:",
- "- Return the COMPLETE text with [[wikilinks]] added.",
- "- Do NOT change any content, only add [[ and ]] around existing words that match wiki pages.",
- "- Do NOT add new text, summaries, or explanations.",
- "- Do NOT remove or modify any existing text.",
- "- Preserve all YAML frontmatter exactly as-is.",
- "- Only link to pages that exist in the wiki index below.",
- "- Each page should be linked only on first mention.",
- "",
`## Wiki Index (link to these pages)\n${index}`,
+ "",
+ "## Output Requirements (STRICT — violations will cause rejection)",
+ "",
+ "1. Return the COMPLETE original text with [[wikilinks]] inserted.",
+ "2. PRESERVE the YAML frontmatter block (--- ... ---) at the top EXACTLY,",
+ " byte-for-byte. Do not modify, reorder, or remove any frontmatter fields.",
+ "3. DO NOT add new sentences, paragraphs, summaries, or explanations.",
+ "4. DO NOT remove or rewrite any existing text.",
+ "5. Only wrap existing words with [[ and ]] where they match a wiki",
+ " index entry. First mention per page only.",
+ "6. Your output length MUST be close to the input length; adding",
+ " [[brackets]] changes length by only a handful of characters.",
+ "",
+ "If you would need to materially change the page to improve it, emit",
+ "the ORIGINAL TEXT UNCHANGED. Rewriting is explicitly forbidden.",
].join("\n"),
},
{
@@ -61,7 +68,25 @@ export async function enrichWithWikilinks(
)
if (!enriched || enriched.length < content.length * 0.5) {
- // LLM returned something too short — probably an error, don't overwrite
+ // LLM returned too little — probably an error, don't overwrite
+ return
+ }
+ if (enriched.length > content.length * 2) {
+ // LLM rewrote the page instead of just adding links — reject to avoid
+ // destroying user content. Adding [[ ]] at most ~4 chars per link, so
+ // a reasonable enrichment stays well under 2× the original length.
+ console.warn(
+ `[enrich-wikilinks] LLM output too long (${enriched.length} vs ${content.length}) — rejecting`,
+ )
+ return
+ }
+
+ // Frontmatter guard: if the input started with YAML frontmatter, the
+ // enriched output MUST too. Otherwise we'd silently lose metadata.
+ if (content.startsWith("---\n") && !enriched.startsWith("---\n")) {
+ console.warn(
+ `[enrich-wikilinks] LLM dropped YAML frontmatter — rejecting`,
+ )
return
}
diff --git a/src/lib/ingest.ts b/src/lib/ingest.ts
index b38c93de..68e0e760 100644
--- a/src/lib/ingest.ts
+++ b/src/lib/ingest.ts
@@ -108,15 +108,25 @@ export async function autoIngest(
{
role: "user",
content: [
- `Based on the following analysis of **${fileName}**, generate the wiki files.`,
+ `Source document to process: **${fileName}**`,
"",
- "## Source Analysis",
+ "The Stage 1 analysis below is CONTEXT to inform your output. Do NOT echo",
+ "its tables, bullet points, or prose. Your output must be FILE/REVIEW",
+ "blocks as specified in the system prompt — nothing else.",
+ "",
+ "## Stage 1 Analysis (context only — do not repeat)",
"",
analysis,
"",
"## Original Source Content",
"",
truncatedContent,
+ "",
+ "---",
+ "",
+ `Now emit the FILE blocks for the wiki files derived from **${fileName}**.`,
+ "Your response MUST begin with `---FILE:` as the very first characters.",
+ "No preamble. No analysis prose. Start immediately.",
].join("\n"),
},
],
@@ -385,15 +395,8 @@ export function buildGenerationPrompt(schema: string, purpose: string, index: st
`The original source file is: **${sourceFileName}**`,
`All wiki pages generated from this source MUST include this filename in their frontmatter \`sources\` field.`,
"",
- "## Output Format",
- "",
- "Output each wiki file in this exact format:",
+ "## What to generate",
"",
- "---FILE: wiki/sources/filename.md---",
- "(complete file content with YAML frontmatter)",
- "---END FILE---",
- "",
- "Generate:",
`1. A source summary page at **wiki/sources/${sourceBaseName}.md** (MUST use this exact path)`,
"2. Entity pages in wiki/entities/ for key entities identified in the analysis",
"3. Concept pages in wiki/concepts/ for key concepts identified in the analysis",
@@ -424,26 +427,18 @@ export function buildGenerationPrompt(schema: string, purpose: string, index: st
"- Follow the analysis recommendations on what to emphasize",
"- If the analysis found connections to existing pages, add cross-references",
"",
- "## Review Items",
- "",
- "After the FILE blocks, output REVIEW blocks for anything that needs human judgment:",
+ "## Review block types",
"",
- "---REVIEW: type | Title---",
- "Description of what needs the user's attention.",
- "OPTIONS: (see allowed options below)",
- "PAGES: wiki/page1.md, wiki/page2.md",
- "SEARCH: search query 1 | search query 2 | search query 3",
- "---END REVIEW---",
+ "After all FILE blocks, optionally emit REVIEW blocks for anything that needs human judgment:",
"",
- "Review types and when to use:",
"- contradiction: the analysis found conflicts with existing wiki content",
"- duplicate: an entity/concept might already exist under a different name in the index",
"- missing-page: an important concept is referenced but has no dedicated page",
"- suggestion: ideas for further research, related sources to look for, or connections worth exploring",
"",
- "## OPTIONS Rules (CRITICAL — only use these predefined options):",
+ "Only create reviews for things that genuinely need human input. Don't create trivial reviews.",
"",
- "For each review type, use ONLY these allowed OPTIONS:",
+ "## OPTIONS allowed values (only these predefined labels):",
"",
"- contradiction: OPTIONS: Create Page | Skip",
"- duplicate: OPTIONS: Create Page | Skip",
@@ -453,18 +448,47 @@ export function buildGenerationPrompt(schema: string, purpose: string, index: st
"The user also has a 'Deep Research' button (auto-added by the system) that triggers web search.",
"Do NOT invent custom option labels. Only use 'Create Page' and 'Skip'.",
"",
- "IMPORTANT for suggestion and missing-page types:",
- "- The SEARCH field must contain 2-3 web search queries optimized for finding relevant papers, articles, or documentation.",
- "- These should be specific, keyword-rich queries suitable for a search engine — NOT titles or sentences.",
- "- Example: for a suggestion about 'automated debt detection in AI-generated code', good SEARCH queries would be:",
+ "For suggestion and missing-page reviews, the SEARCH field must contain 2-3 web search queries",
+ "(keyword-rich, specific, suitable for a search engine — NOT titles or sentences). Example:",
" SEARCH: automated technical debt detection AI generated code | software quality metrics LLM code generation | static analysis tools agentic software development",
"",
- "Only create reviews for things that genuinely need human input. Don't create trivial reviews.",
- "",
purpose ? `## Wiki Purpose\n${purpose}` : "",
schema ? `## Wiki Schema\n${schema}` : "",
index ? `## Current Wiki Index (preserve all existing entries, add new ones)\n${index}` : "",
overview ? `## Current Overview (update this to reflect the new source)\n${overview}` : "",
+ "",
+ // ── OUTPUT FORMAT MUST BE THE LAST SECTION — models weight recent instructions highest ──
+ "## Output Format (MUST FOLLOW EXACTLY — this is how the parser reads your response)",
+ "",
+ "Your ENTIRE response consists of FILE blocks followed by optional REVIEW blocks. Nothing else.",
+ "",
+ "FILE block template:",
+ "```",
+ "---FILE: wiki/path/to/page.md---",
+ "(complete file content with YAML frontmatter)",
+ "---END FILE---",
+ "```",
+ "",
+ "REVIEW block template (optional, after all FILE blocks):",
+ "```",
+ "---REVIEW: type | Title---",
+ "Description of what needs the user's attention.",
+ "OPTIONS: Create Page | Skip",
+ "PAGES: wiki/page1.md, wiki/page2.md",
+ "SEARCH: query 1 | query 2 | query 3",
+ "---END REVIEW---",
+ "```",
+ "",
+ "## Output Requirements (STRICT — deviations will cause parse failure)",
+ "",
+ "1. The FIRST character of your response MUST be `-` (the opening of `---FILE:`).",
+ "2. DO NOT output any preamble such as \"Here are the files:\", \"Based on the analysis...\", or any introductory prose.",
+ "3. DO NOT echo or restate the analysis — that was stage 1's job. Your job is to emit FILE blocks.",
+ "4. DO NOT output markdown tables, bullet lists, or headings outside of FILE/REVIEW blocks.",
+ "5. DO NOT output any trailing commentary after the last `---END FILE---` or `---END REVIEW---`.",
+ "6. Between blocks, use only blank lines — no prose.",
+ "",
+ "If you start with anything other than `---FILE:`, the entire response will be discarded.",
].filter(Boolean).join("\n")
}
diff --git a/src/lib/llm-client.ts b/src/lib/llm-client.ts
index ff2dfe85..ecbcd3ad 100644
--- a/src/lib/llm-client.ts
+++ b/src/lib/llm-client.ts
@@ -23,6 +23,13 @@ export async function streamChat(
messages: import("./llm-providers").ChatMessage[],
callbacks: StreamCallbacks,
signal?: AbortSignal,
+ /**
+ * Extra fields to merge into the request body. Use for provider-specific
+ * knobs like `temperature`, `top_p`, `max_tokens`. Callers that need
+ * strict format adherence (e.g. ingest stage 2 emitting FILE blocks)
+ * should pass `{ temperature: 0.1 }` to reduce sampling variance.
+ */
+ requestOverrides?: Record<string, unknown>,
): Promise<void> {
const { onToken, onDone, onError } = callbacks
const providerConfig = getProviderConfig(config)
@@ -48,10 +55,12 @@ export async function streamChat(
let response: Response
try {
+ const baseBody = providerConfig.buildBody(messages) as Record<string, unknown>
+ const body = requestOverrides ? { ...baseBody, ...requestOverrides } : baseBody
response = await fetch(providerConfig.url, {
method: "POST",
headers: providerConfig.headers,
- body: JSON.stringify(providerConfig.buildBody(messages)),
+ body: JSON.stringify(body),
signal: combinedSignal,
// @ts-ignore — keepalive hint for Tauri webview
keepalive: false,