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

test: scenario framework for ingest + search

nash_suc855b968ffe9
diff --git a/src/lib/ingest.scenarios.test.ts b/src/lib/ingest.scenarios.test.ts
new file mode 100644
index 00000000..221d7888
--- /dev/null
+++ b/src/lib/ingest.scenarios.test.ts
@@ -0,0 +1,198 @@
+/**
+ * Scenario-driven tests for autoIngest.
+ *
+ * Each scenario materializes an initial project, a source document, and two
+ * canned LLM responses (stage 1 analysis, stage 2 generation with FILE +
+ * REVIEW blocks). The runner mocks streamChat to emit them sequentially.
+ *
+ * After ingest runs, the runner asserts:
+ * - expected files exist on disk with expected substrings
+ * - expected review items were injected into the review store
+ */
+import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from "vitest"
+import path from "node:path"
+import fs from "node:fs/promises"
+import { realFs, createTempProject, readFileRaw, fileExists } from "@/test-helpers/fs-temp"
+import { materializeScenario, copyDir } from "@/test-helpers/scenarios/materialize"
+import { ingestScenarios } from "@/test-helpers/scenarios/ingest-scenarios"
+import type { IngestScenario } from "@/test-helpers/scenarios/types"
+
+vi.mock("@/commands/fs", () => realFs)
+
+// Sequenced streamChat: stage-1 returns analysisResponse, stage-2 returns
+// generationResponse. Any further calls return empty (shouldn't happen in a
+// typical autoIngest run).
+let pendingResponses: string[] = []
+vi.mock("./llm-client", () => ({
+ streamChat: vi.fn(async (_cfg, _msgs, cb) => {
+ const resp = pendingResponses.shift() ?? ""
+ cb.onToken(resp)
+ cb.onDone()
+ }),
+}))
+
+import { autoIngest } from "./ingest"
+import { useWikiStore } from "@/stores/wiki-store"
+import { useReviewStore } from "@/stores/review-store"
+import { useActivityStore } from "@/stores/activity-store"
+import { useChatStore } from "@/stores/chat-store"
+
+const FIXTURES_ROOT = path.join(
+ process.cwd(),
+ "tests",
+ "fixtures",
+ "scenarios-ingest",
+)
+
+beforeAll(async () => {
+ await fs.rm(FIXTURES_ROOT, { recursive: true, force: true })
+ await fs.mkdir(FIXTURES_ROOT, { recursive: true })
+ for (const s of ingestScenarios) {
+ await materializeScenario(s, FIXTURES_ROOT)
+ }
+})
+
+beforeEach(() => {
+ pendingResponses = []
+ useReviewStore.setState({ items: [] })
+ useActivityStore.setState({ items: [] })
+ useChatStore.setState({
+ conversations: [],
+ messages: [],
+ activeConversationId: null,
+ mode: "chat",
+ ingestSource: null,
+ isStreaming: false,
+ streamingContent: "",
+ })
+})
+
+interface Ctx {
+ tmp: { path: string; cleanup: () => Promise<void> }
+}
+let ctx: Ctx | undefined
+
+async function setup(scenario: IngestScenario): Promise<Ctx> {
+ const tmp = await createTempProject(
+ `ingest-${scenario.name.replace(/\//g, "-")}`,
+ )
+ const initialWikiDir = path.join(FIXTURES_ROOT, scenario.name, "initial-wiki")
+ await copyDir(initialWikiDir, tmp.path)
+
+ useWikiStore.setState({
+ project: {
+ name: "t",
+ path: tmp.path,
+ createdAt: 0,
+ purposeText: "",
+ fileTree: [],
+ } as unknown as ReturnType<typeof useWikiStore.getState>["project"],
+ })
+ useWikiStore.getState().setLlmConfig({
+ provider: "openai",
+ apiKey: "test-key",
+ model: "gpt-4",
+ ollamaUrl: "",
+ customEndpoint: "",
+ maxContextSize: 128000,
+ })
+
+ // Queue up the two sequenced LLM responses
+ const analysis = await fs.readFile(
+ path.join(FIXTURES_ROOT, scenario.name, "llm-analysis.txt"),
+ "utf-8",
+ )
+ const generation = await fs.readFile(
+ path.join(FIXTURES_ROOT, scenario.name, "llm-generation.txt"),
+ "utf-8",
+ )
+ pendingResponses = [analysis, generation]
+
+ return { tmp }
+}
+
+afterEach(async () => {
+ if (ctx) {
+ await ctx.tmp.cleanup()
+ ctx = undefined
+ }
+})
+
+// ── Assertions ──────────────────────────────────────────────────────────────
+
+async function assertOutcome(
+ scenario: IngestScenario,
+ tmpPath: string,
+): Promise<void> {
+ const expected = scenario.expected
+
+ // 1. Expected files exist
+ for (const p of expected.writtenPaths) {
+ const full = path.join(tmpPath, p)
+ const exists = await fileExists(full)
+ if (!exists) {
+ // eslint-disable-next-line no-console
+ console.error(
+ `\n[ingest: ${scenario.name}] expected file not written: ${p}`,
+ )
+ }
+ expect(exists, `file not written: ${p}`).toBe(true)
+ }
+
+ // 2. File contents contain expected substrings
+ if (expected.fileContains) {
+ for (const [relPath, substrs] of Object.entries(expected.fileContains)) {
+ const full = path.join(tmpPath, relPath)
+ const content = await readFileRaw(full)
+ for (const sub of substrs) {
+ expect(content, `${relPath} missing substring "${sub}"`).toContain(sub)
+ }
+ }
+ }
+
+ // 3. Review store has the expected items
+ const expectedReviews = expected.reviewsCreated ?? []
+ const actualReviews = useReviewStore.getState().items
+ for (const e of expectedReviews) {
+ const match = actualReviews.find(
+ (r) => r.type === e.type && r.title.includes(e.titleContains),
+ )
+ if (!match) {
+ // eslint-disable-next-line no-console
+ console.error(
+ `\n[ingest: ${scenario.name}] no review matching ${JSON.stringify(e)}. Actual:\n` +
+ JSON.stringify(
+ actualReviews.map((r) => ({ type: r.type, title: r.title })),
+ null,
+ 2,
+ ),
+ )
+ }
+ expect(match, `review missing: ${JSON.stringify(e)}`).toBeTruthy()
+ }
+
+ // 4. If the scenario declared no reviews, store must be empty.
+ if (expectedReviews.length === 0) {
+ expect(actualReviews).toHaveLength(0)
+ }
+}
+
+// ── Tests ───────────────────────────────────────────────────────────────────
+
+describe("ingest scenarios (fixture-driven)", () => {
+ it.each(ingestScenarios.map((s) => [s.name, s]))(
+ "%s",
+ async (_name, scenario) => {
+ ctx = await setup(scenario)
+
+ const sourceFullPath = path.join(ctx.tmp.path, scenario.source.path)
+ await autoIngest(
+ ctx.tmp.path,
+ sourceFullPath,
+ useWikiStore.getState().llmConfig,
+ )
+
+ await assertOutcome(scenario, ctx.tmp.path)
+ },
+ )
+})
diff --git a/src/lib/search.scenarios.test.ts b/src/lib/search.scenarios.test.ts
new file mode 100644
index 00000000..19c85a63
--- /dev/null
+++ b/src/lib/search.scenarios.test.ts
@@ -0,0 +1,136 @@
+/**
+ * Scenario-driven tests for searchWiki.
+ *
+ * Each scenario materializes a wiki dir + a query string, then asserts
+ * the ranked result list from searchWiki.
+ */
+import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from "vitest"
+import path from "node:path"
+import fs from "node:fs/promises"
+import { realFs, createTempProject } from "@/test-helpers/fs-temp"
+import { materializeScenario, copyDir } from "@/test-helpers/scenarios/materialize"
+import { searchScenarios } from "@/test-helpers/scenarios/search-scenarios"
+import type { SearchScenario } from "@/test-helpers/scenarios/types"
+
+vi.mock("@/commands/fs", () => realFs)
+
+import { searchWiki } from "./search"
+import { useWikiStore } from "@/stores/wiki-store"
+
+const FIXTURES_ROOT = path.join(
+ process.cwd(),
+ "tests",
+ "fixtures",
+ "scenarios-search",
+)
+
+beforeAll(async () => {
+ await fs.rm(FIXTURES_ROOT, { recursive: true, force: true })
+ await fs.mkdir(FIXTURES_ROOT, { recursive: true })
+ for (const s of searchScenarios) {
+ await materializeScenario(s, FIXTURES_ROOT)
+ }
+})
+
+beforeEach(() => {
+ // Disable embedding/vector search — we only want to exercise the
+ // BM25-style text search path.
+ useWikiStore.getState().setEmbeddingConfig({
+ enabled: false,
+ endpoint: "",
+ apiKey: "",
+ model: "",
+ })
+})
+
+interface Ctx {
+ tmp: { path: string; cleanup: () => Promise<void> }
+}
+let ctx: Ctx | undefined
+
+async function setup(scenario: SearchScenario): Promise<Ctx> {
+ const tmp = await createTempProject(
+ `search-${scenario.name.replace(/\//g, "-")}`,
+ )
+ const initialWikiDir = path.join(FIXTURES_ROOT, scenario.name, "initial-wiki")
+ await copyDir(initialWikiDir, tmp.path)
+ return { tmp }
+}
+
+afterEach(async () => {
+ if (ctx) {
+ await ctx.tmp.cleanup()
+ ctx = undefined
+ }
+})
+
+describe("search scenarios (fixture-driven)", () => {
+ it.each(searchScenarios.map((s) => [s.name, s]))(
+ "%s",
+ async (_name, scenario) => {
+ ctx = await setup(scenario)
+
+ const results = await searchWiki(ctx.tmp.path, scenario.query)
+
+ // Helper: does a scenario-relative path (e.g. "wiki/attention.md")
+ // match any result in the list?
+ function resultFor(relPath: string) {
+ // Results have absolute paths; compare by suffix-ending-in-relPath
+ return results.find((r) =>
+ r.path.endsWith("/" + relPath) || r.path.endsWith(relPath),
+ )
+ }
+
+ try {
+ // 1. Top results in the expected order
+ for (let i = 0; i < scenario.expected.topResultPaths.length; i++) {
+ const expectedPath = scenario.expected.topResultPaths[i]
+ const actual = results[i]
+ expect(
+ actual,
+ `result #${i} missing (expected ${expectedPath}); got ${results.length} results`,
+ ).toBeTruthy()
+ expect(
+ actual.path.endsWith("/" + expectedPath) ||
+ actual.path.endsWith(expectedPath),
+ `result #${i} path mismatch — expected ending with ${expectedPath}, got ${actual.path}`,
+ ).toBe(true)
+ }
+
+ // 2. Excluded paths
+ if (scenario.expected.excludedPaths) {
+ for (const excluded of scenario.expected.excludedPaths) {
+ expect(
+ resultFor(excluded),
+ `excluded path found in results: ${excluded}`,
+ ).toBeFalsy()
+ }
+ }
+
+ // 3. Paths that must have titleMatch=true
+ if (scenario.expected.titleMatchPaths) {
+ for (const p of scenario.expected.titleMatchPaths) {
+ const r = resultFor(p)
+ expect(r, `title-match page ${p} missing from results`).toBeTruthy()
+ expect(r!.titleMatch, `${p} should have titleMatch=true`).toBe(true)
+ }
+ }
+ } catch (err) {
+ // eslint-disable-next-line no-console
+ console.error(
+ `\n[search: ${scenario.name}] query="${scenario.query}" — actual results:\n` +
+ JSON.stringify(
+ results.map((r) => ({
+ path: r.path,
+ titleMatch: r.titleMatch,
+ score: r.score,
+ })),
+ null,
+ 2,
+ ),
+ )
+ throw err
+ }
+ },
+ )
+})
diff --git a/src/test-helpers/scenarios/ingest-scenarios.ts b/src/test-helpers/scenarios/ingest-scenarios.ts
new file mode 100644
index 00000000..2966d26b
--- /dev/null
+++ b/src/test-helpers/scenarios/ingest-scenarios.ts
@@ -0,0 +1,270 @@
+import type { IngestScenario } from "./types"
+
+/**
+ * Ingest scenarios drive autoIngest end-to-end. Two LLM responses per
+ * scenario (stage 1 analysis, stage 2 generation with FILE + REVIEW blocks).
+ *
+ * FILE block format (what stage 2 must emit to write a wiki file):
+ * ---FILE: wiki/path/to/page.md---
+ * (file content, usually with YAML frontmatter)
+ * ---END FILE---
+ *
+ * REVIEW block format (what stage 2 emits to inject a review item):
+ * ---REVIEW: missing-page | Short title---
+ * Description.
+ * OPTIONS: Approve | Skip
+ * PAGES: page1.md, page2.md
+ * ---END REVIEW---
+ *
+ * Stage 2 may emit arbitrary prose around blocks — the parser only
+ * cares about the delimited blocks.
+ */
+
+const BASIC_PURPOSE = `# Purpose
+
+This wiki tracks deep-learning research concepts.
+`
+
+const BASIC_INDEX = `# Index
+
+## Concepts
+- [[attention]]
+`
+
+const BASIC_SCHEMA = `# Schema
+
+## wiki/sources/
+Each ingested source has a summary page here.
+
+## wiki/concepts/
+Each concept gets its own page.
+`
+
+export const ingestScenarios: IngestScenario[] = [
+ // 1. basic-new-source — new concept wiki page + source summary, no reviews
+ {
+ name: "basic-new-source",
+ description:
+ "Stage 2 emits a single concept page + a source summary page. No " +
+ "REVIEW blocks. The runner must see both files on disk and zero " +
+ "reviews in the store.",
+ initialWiki: {
+ "purpose.md": BASIC_PURPOSE,
+ "schema.md": BASIC_SCHEMA,
+ "wiki/index.md": BASIC_INDEX,
+ },
+ source: {
+ path: "raw/sources/rope-paper.md",
+ content: [
+ "# Rotary Position Embedding",
+ "",
+ "Rotary Position Embedding (RoPE) encodes positional information by",
+ "rotating pairs of dimensions in query and key vectors. It naturally",
+ "supports variable-length contexts and is now standard in LLMs.",
+ ].join("\n"),
+ },
+ analysisResponse: [
+ "## Key Concepts",
+ "- Rotary Position Embedding (RoPE): rotates pairs of dimensions",
+ "",
+ "## Main Arguments",
+ "- RoPE naturally supports variable-length contexts",
+ "",
+ "## Recommendations",
+ "- Create wiki/concepts/rope.md",
+ "- Create wiki/sources/rope-paper.md",
+ ].join("\n"),
+ generationResponse: [
+ "I'll create one concept page and the source summary.",
+ "",
+ "---FILE: wiki/concepts/rope.md---",
+ "---",
+ "title: Rotary Position Embedding",
+ "tags: [positional-encoding]",
+ "sources: [rope-paper.md]",
+ "---",
+ "",
+ "# Rotary Position Embedding",
+ "",
+ "RoPE rotates pairs of dimensions in [[attention]] queries and keys",
+ "to encode absolute position while preserving relative-position invariance.",
+ "---END FILE---",
+ "",
+ "---FILE: wiki/sources/rope-paper.md---",
+ "---",
+ "title: \"Source: rope-paper.md\"",
+ "sources: [rope-paper.md]",
+ "---",
+ "",
+ "# Source: rope-paper.md",
+ "",
+ "Paper introducing [[Rotary Position Embedding]].",
+ "---END FILE---",
+ ].join("\n"),
+ expected: {
+ writtenPaths: [
+ "wiki/concepts/rope.md",
+ "wiki/sources/rope-paper.md",
+ ],
+ fileContains: {
+ "wiki/concepts/rope.md": [
+ "title: Rotary Position Embedding",
+ "[[attention]]",
+ ],
+ "wiki/sources/rope-paper.md": ["rope-paper.md"],
+ },
+ reviewsCreated: [],
+ },
+ },
+
+ // 2. generates-review-items — REVIEW blocks in generation become store items
+ {
+ name: "generates-review-items",
+ description:
+ "Stage 2 emits one FILE and two REVIEW blocks (missing-page + " +
+ "suggestion). Both reviews must appear in the store after ingest.",
+ initialWiki: {
+ "purpose.md": BASIC_PURPOSE,
+ "schema.md": BASIC_SCHEMA,
+ "wiki/index.md": BASIC_INDEX,
+ },
+ source: {
+ path: "raw/sources/flash-attention.md",
+ content:
+ "# FlashAttention\n\nFlashAttention is an IO-aware exact attention algorithm.\n",
+ },
+ analysisResponse: "## Key Concepts\n- FlashAttention\n",
+ generationResponse: [
+ "---FILE: wiki/sources/flash-attention.md---",
+ "---",
+ "title: \"Source: flash-attention.md\"",
+ "sources: [flash-attention.md]",
+ "---",
+ "",
+ "# Source: flash-attention.md",
+ "",
+ "FlashAttention is mentioned here.",
+ "---END FILE---",
+ "",
+ "---REVIEW: missing-page | FlashAttention---",
+ "The source introduces FlashAttention but no dedicated page exists.",
+ "OPTIONS: Create page | Skip",
+ "PAGES: wiki/sources/flash-attention.md",
+ "---END REVIEW---",
+ "",
+ "---REVIEW: suggestion | Add IO-aware algorithms survey---",
+ "Consider a survey page grouping IO-aware attention variants.",
+ "---END REVIEW---",
+ ].join("\n"),
+ expected: {
+ writtenPaths: ["wiki/sources/flash-attention.md"],
+ reviewsCreated: [
+ { type: "missing-page", titleContains: "FlashAttention" },
+ { type: "suggestion", titleContains: "IO-aware" },
+ ],
+ },
+ },
+
+ // 3. references-existing-wikilinks — generated pages link to existing pages
+ {
+ name: "references-existing-wikilinks",
+ description:
+ "The generated wiki page must include [[attention]] — linking back " +
+ "to a page that already exists in the wiki. Runner asserts substring.",
+ initialWiki: {
+ "purpose.md": BASIC_PURPOSE,
+ "schema.md": BASIC_SCHEMA,
+ "wiki/index.md": BASIC_INDEX,
+ "wiki/attention.md":
+ "---\ntitle: Attention\n---\n\n# Attention\n\nThe attention mechanism.\n",
+ },
+ source: {
+ path: "raw/sources/multi-head.md",
+ content: "# Multi-Head Attention\n\nParallel attention heads.\n",
+ },
+ analysisResponse:
+ "## Connections to Existing Wiki\n" +
+ "- Multi-head attention is a variant of attention — existing [[attention]] page should be linked.\n",
+ generationResponse: [
+ "---FILE: wiki/concepts/multi-head-attention.md---",
+ "---",
+ "title: Multi-Head Attention",
+ "---",
+ "",
+ "# Multi-Head Attention",
+ "",
+ "Multi-head [[attention]] runs several attention layers in parallel.",
+ "---END FILE---",
+ "",
+ "---FILE: wiki/sources/multi-head.md---",
+ "---",
+ "title: \"Source: multi-head.md\"",
+ "---",
+ "",
+ "# Source: multi-head.md",
+ "",
+ "Source for multi-head [[attention]].",
+ "---END FILE---",
+ ].join("\n"),
+ expected: {
+ writtenPaths: [
+ "wiki/concepts/multi-head-attention.md",
+ "wiki/sources/multi-head.md",
+ ],
+ fileContains: {
+ "wiki/concepts/multi-head-attention.md": ["[[attention]]"],
+ },
+ },
+ },
+
+ // 4. chinese-source — Chinese content flows through to Chinese wiki pages
+ {
+ name: "chinese-source",
+ description:
+ "Chinese-language source document; LLM responses in Chinese. " +
+ "UTF-8 round-trip through file write must be clean.",
+ initialWiki: {
+ "purpose.md": "# 用途\n\n深度学习研究笔记。\n",
+ "schema.md": BASIC_SCHEMA,
+ "wiki/index.md": "# 索引\n\n- [[注意力机制]]\n",
+ },
+ source: {
+ path: "raw/sources/transformer-survey.md",
+ content: "# Transformer 综述\n\nTransformer 是一种基于注意力机制的神经网络架构。\n",
+ },
+ analysisResponse: "## 核心概念\n- Transformer:基于注意力机制的架构\n",
+ generationResponse: [
+ "---FILE: wiki/concepts/transformer.md---",
+ "---",
+ "title: Transformer",
+ "---",
+ "",
+ "# Transformer",
+ "",
+ "Transformer 是一种基于 [[注意力机制]] 的神经网络架构。",
+ "---END FILE---",
+ "",
+ "---FILE: wiki/sources/transformer-survey.md---",
+ "---",
+ "title: \"Source: transformer-survey.md\"",
+ "---",
+ "",
+ "# Source: transformer-survey.md",
+ "",
+ "关于 [[Transformer]] 的综述。",
+ "---END FILE---",
+ ].join("\n"),
+ expected: {
+ writtenPaths: [
+ "wiki/concepts/transformer.md",
+ "wiki/sources/transformer-survey.md",
+ ],
+ fileContains: {
+ "wiki/concepts/transformer.md": [
+ "title: Transformer",
+ "[[注意力机制]]",
+ ],
+ },
+ },
+ },
+]
diff --git a/src/test-helpers/scenarios/materialize.ts b/src/test-helpers/scenarios/materialize.ts
index d319a29c..17fcf058 100644
--- a/src/test-helpers/scenarios/materialize.ts
+++ b/src/test-helpers/scenarios/materialize.ts
@@ -20,6 +20,10 @@ type AnyScenario = {
// optional per-domain fields
reviews?: unknown
pageToEnrich?: string
+ source?: { path: string; content: string }
+ analysisResponse?: string
+ generationResponse?: string
+ query?: string
}
export async function materializeScenario(
@@ -67,6 +71,45 @@ export async function materializeScenario(
)
}
+ // Ingest scenarios emit TWO LLM responses (stage 1 analysis + stage 2 generation).
+ if (scenario.analysisResponse !== undefined) {
+ await fs.writeFile(
+ path.join(scenarioPath, "llm-analysis.txt"),
+ scenario.analysisResponse,
+ "utf-8",
+ )
+ }
+ if (scenario.generationResponse !== undefined) {
+ await fs.writeFile(
+ path.join(scenarioPath, "llm-generation.txt"),
+ scenario.generationResponse,
+ "utf-8",
+ )
+ }
+
+ // Source doc for ingest scenarios — materialize it under initial-wiki/
+ // at the scenario-declared path.
+ if (scenario.source !== undefined) {
+ const sourceFull = path.join(scenarioPath, "initial-wiki", scenario.source.path)
+ await fs.mkdir(path.dirname(sourceFull), { recursive: true })
+ await fs.writeFile(sourceFull, scenario.source.content, "utf-8")
+ // Also record the path for the runner to read
+ await fs.writeFile(
+ path.join(scenarioPath, "source-path.txt"),
+ scenario.source.path,
+ "utf-8",
+ )
+ }
+
+ // Search scenarios record the query
+ if (scenario.query !== undefined) {
+ await fs.writeFile(
+ path.join(scenarioPath, "query.txt"),
+ scenario.query,
+ "utf-8",
+ )
+ }
+
// expected.json — what the operation should produce
await fs.writeFile(
path.join(scenarioPath, "expected.json"),
diff --git a/src/test-helpers/scenarios/search-scenarios.ts b/src/test-helpers/scenarios/search-scenarios.ts
new file mode 100644
index 00000000..ceb15e68
--- /dev/null
+++ b/src/test-helpers/scenarios/search-scenarios.ts
@@ -0,0 +1,109 @@
+import type { SearchScenario } from "./types"
+
+function page(title: string, body: string): string {
+ return `---\ntitle: ${title}\n---\n\n# ${title}\n\n${body}\n`
+}
+
+export const searchScenarios: SearchScenario[] = [
+ // 1. title-exact-match — a page whose title exactly contains the query
+ // should rank first and have titleMatch=true.
+ {
+ name: "title-exact-match",
+ description:
+ "Query 'attention'. attention.md has 'attention' in its title and in " +
+ "content. Should rank first with titleMatch=true.",
+ initialWiki: {
+ "wiki/attention.md": page("Attention", "The attention mechanism weights sequence tokens."),
+ "wiki/other.md": page("Other Page", "Discusses something unrelated entirely."),
+ "wiki/transformer.md": page("Transformer", "Uses attention across many heads."),
+ },
+ query: "attention",
+ expected: {
+ topResultPaths: ["wiki/attention.md"],
+ titleMatchPaths: ["wiki/attention.md"],
+ excludedPaths: ["wiki/other.md"],
+ },
+ },
+
+ // 2. content-match — query not in title, still found via body text
+ {
+ name: "content-match",
+ description:
+ "Query 'rotary' appears only in the body of embeddings.md, not in " +
+ "any title. Should still be returned, but with titleMatch=false.",
+ initialWiki: {
+ "wiki/embeddings.md": page(
+ "Embeddings",
+ "Rotary position embeddings inject positional information via rotation.",
+ ),
+ "wiki/other.md": page("Other", "Unrelated content here."),
+ },
+ query: "rotary",
+ expected: {
+ topResultPaths: ["wiki/embeddings.md"],
+ excludedPaths: ["wiki/other.md"],
+ },
+ },
+
+ // 3. cjk-bigram — Chinese query via bigram tokenization
+ {
+ name: "cjk-bigram",
+ description:
+ "Query '注意力机制' is tokenized into bigrams ('注意', '意力', '力机', '机制'). " +
+ "The page whose content contains '注意力机制' should rank top.",
+ initialWiki: {
+ "wiki/attention-zh.md": page(
+ "注意力机制",
+ "注意力机制是 Transformer 架构的核心组件之一。",
+ ),
+ "wiki/unrelated-zh.md": page(
+ "无关页面",
+ "这个页面讨论别的话题,比如天气和足球。",
+ ),
+ },
+ query: "注意力机制",
+ expected: {
+ topResultPaths: ["wiki/attention-zh.md"],
+ excludedPaths: ["wiki/unrelated-zh.md"],
+ },
+ },
+
+ // 4. multi-token-ranking — more matches ranks higher
+ {
+ name: "multi-token-ranking",
+ description:
+ "Query 'attention transformer'. The page mentioning BOTH terms " +
+ "should outrank pages mentioning only one.",
+ initialWiki: {
+ "wiki/combined.md": page(
+ "Attention and Transformer",
+ "The transformer architecture is built around attention. " +
+ "Attention weights tokens; transformer stacks attention layers.",
+ ),
+ "wiki/only-attn.md": page("Attention", "Attention is a weighting mechanism."),
+ "wiki/only-trans.md": page("Transformer", "Stacks of layers form the transformer."),
+ },
+ query: "attention transformer",
+ expected: {
+ topResultPaths: ["wiki/combined.md"],
+ },
+ },
+
+ // 5. stop-word-filtered — 'the' filtered, only meaningful tokens used
+ {
+ name: "stop-word-filtered",
+ description:
+ "Query 'the attention' should be tokenized to ['attention'] since " +
+ "'the' is a stop-word. The page about attention should still match.",
+ initialWiki: {
+ "wiki/attention.md": page("Attention", "Attention over keys and values."),
+ "wiki/other.md": page("Other", "This page uses the word 'the' often but " +
+ "otherwise covers cats, dogs, weather, and the sky."),
+ },
+ query: "the attention",
+ expected: {
+ topResultPaths: ["wiki/attention.md"],
+ // 'other' uses "the" a lot but should be filtered out and not rank top
+ },
+ },
+]
diff --git a/src/test-helpers/scenarios/types.ts b/src/test-helpers/scenarios/types.ts
index 95a4c771..8e3501cc 100644
--- a/src/test-helpers/scenarios/types.ts
+++ b/src/test-helpers/scenarios/types.ts
@@ -95,6 +95,65 @@ export interface EnrichScenario {
}
}
+/**
+ * Ingest scenarios exercise autoIngest end-to-end: a source document plus
+ * existing project state, through two LLM calls (analysis + generation),
+ * to the files written on disk and the review items injected into the store.
+ */
+export interface IngestScenario {
+ name: string
+ description: string
+ /** Project state before ingest runs (purpose.md, schema.md, wiki/*.md). */
+ initialWiki: Record<string, string>
+ /** The source document being ingested. */
+ source: {
+ /** Project-relative path, e.g. "raw/sources/paper.md" */
+ path: string
+ content: string
+ }
+ /** Raw LLM response for stage 1 (analysis). */
+ analysisResponse: string
+ /** Raw LLM response for stage 2 (generation — contains FILE + REVIEW blocks). */
+ generationResponse: string
+ expected: {
+ /** File paths (relative to project root) that must be written. */
+ writtenPaths: string[]
+ /** Substring matches for specific files (path → list of substrings to find). */
+ fileContains?: Record<string, string[]>
+ /**
+ * Expected review items (subset match). Each entry matches if an injected
+ * review has the same type and a title containing titleContains.
+ */
+ reviewsCreated?: Array<{
+ type: "contradiction" | "duplicate" | "missing-page" | "suggestion" | "confirm"
+ titleContains: string
+ }>
+ }
+}
+
+/**
+ * Search scenarios exercise searchWiki: a wiki directory plus a query text
+ * produces a ranked list of SearchResult entries.
+ */
+export interface SearchScenario {
+ name: string
+ description: string
+ /** Project state (must include wiki/). */
+ initialWiki: Record<string, string>
+ query: string
+ expected: {
+ /**
+ * File paths (under wiki/, relative to project root) expected in the top
+ * results, IN ORDER. Extra results beyond this prefix are allowed.
+ */
+ topResultPaths: string[]
+ /** Paths that must NOT appear anywhere in the results. */
+ excludedPaths?: string[]
+ /** Paths for which the result's `titleMatch` field must be true. */
+ titleMatchPaths?: string[]
+ }
+}
+
export interface SweepScenario {
/**
* Path-like name used as the scenario's folder under