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

Improve ingest follow-up review generation

nash_su4a278a917422
diff --git a/src/lib/ingest-source-path-collision.test.ts b/src/lib/ingest-source-path-collision.test.ts
index a2febf28..a8aa7c54 100644
--- a/src/lib/ingest-source-path-collision.test.ts
+++ b/src/lib/ingest-source-path-collision.test.ts
@@ -12,6 +12,9 @@ vi.mock("@/commands/fs", () => realFs)
let sourceMarkers: string[] = []
let failLongChunksOnce = new Set<number>()
+let extraReviewResponse = ""
+let generationSuffix = ""
+let abortDuringReview: AbortController | null = null
vi.mock("./llm-client", () => ({
streamChat: vi.fn(async (_cfg, messages, cb) => {
@@ -65,6 +68,16 @@ vi.mock("./llm-client", () => ({
return
}
+ if (systemPrompt.startsWith("You are identifying high-value follow-up research items")) {
+ if (abortDuringReview) {
+ abortDuringReview.abort()
+ throw new Error("AbortError")
+ }
+ cb.onToken(extraReviewResponse)
+ cb.onDone()
+ return
+ }
+
const targetMatch = systemPrompt.match(
/source summary page at \*\*(wiki\/sources\/[^*]+)\*\*/,
)
@@ -89,6 +102,7 @@ vi.mock("./llm-client", () => ({
"",
`Configuration details for ${marker}.`,
"---END FILE---",
+ generationSuffix,
].join("\n"))
cb.onDone()
}),
@@ -105,6 +119,9 @@ describe("autoIngest source summary paths", () => {
beforeEach(async () => {
sourceMarkers = []
failLongChunksOnce = new Set()
+ extraReviewResponse = ""
+ generationSuffix = ""
+ abortDuringReview = null
mockStreamChat.mockClear()
tmp = await createTempProject("same-basename-sources")
@@ -371,6 +388,101 @@ describe("autoIngest source summary paths", () => {
await expect(fs.readdir(progressDir)).resolves.toEqual([])
})
+ it("adds follow-up research reviews from the dedicated review stage", async () => {
+ if (!tmp) throw new Error("missing temp project")
+ sourceMarkers = ["project-a config"]
+ generationSuffix = [
+ "",
+ "---FILE: wiki/concepts/nitrification-inhibition.md---",
+ "---",
+ 'title: "Nitrification inhibition"',
+ "---",
+ "",
+ "# Nitrification inhibition",
+ "",
+ "X".repeat(10_500),
+ "---END FILE---",
+ ].join("\n")
+ extraReviewResponse = [
+ "---REVIEW: suggestion | Research nitrification inhibition signals---",
+ "Add follow-up research on early-warning indicators for nitrification inhibition.",
+ "OPTIONS: Create Page | Skip",
+ "SEARCH: nitrification inhibition early warning wastewater | ammonia oxidation inhibition signals | wastewater nitrification process upset indicators",
+ "---END REVIEW---",
+ ].join("\n")
+
+ await autoIngest(
+ tmp.path,
+ `${tmp.path}/raw/sources/project-a/config.yaml`,
+ useWikiStore.getState().llmConfig,
+ undefined,
+ "project-a",
+ )
+
+ const reviews = useReviewStore.getState().items
+ expect(reviews).toHaveLength(1)
+ expect(reviews[0]).toMatchObject({
+ type: "suggestion",
+ title: "Research nitrification inhibition signals",
+ })
+ expect(reviews[0].searchQueries).toEqual([
+ "nitrification inhibition early warning wastewater",
+ "ammonia oxidation inhibition signals",
+ "wastewater nitrification process upset indicators",
+ ])
+ })
+
+ it("parses generation and dedicated review-stage blocks separately", async () => {
+ if (!tmp) throw new Error("missing temp project")
+ sourceMarkers = ["project-a config"]
+ generationSuffix = [
+ "",
+ "---REVIEW: missing-page | Truncated Orphan---",
+ "Partial description that got cut off",
+ ].join("\n")
+ extraReviewResponse = [
+ "---REVIEW: suggestion | Real Follow-up---",
+ "Real description that should not be swallowed by the generation orphan.",
+ "OPTIONS: Create Page | Skip",
+ "SEARCH: real follow up query | second query",
+ "---END REVIEW---",
+ ].join("\n")
+
+ await autoIngest(
+ tmp.path,
+ `${tmp.path}/raw/sources/project-a/config.yaml`,
+ { ...useWikiStore.getState().llmConfig, maxContextSize: 128_000 },
+ undefined,
+ "project-a",
+ )
+
+ const reviews = useReviewStore.getState().items
+ expect(reviews).toHaveLength(1)
+ expect(reviews[0]).toMatchObject({
+ type: "suggestion",
+ title: "Real Follow-up",
+ })
+ expect(reviews[0].description).not.toContain("Truncated Orphan")
+ })
+
+ it("propagates cancellation that happens during the dedicated review stage", async () => {
+ if (!tmp) throw new Error("missing temp project")
+ sourceMarkers = ["project-a config"]
+ generationSuffix = `${"\n"}${"X".repeat(10_500)}`
+ const controller = new AbortController()
+ abortDuringReview = controller
+
+ await expect(
+ autoIngest(
+ tmp.path,
+ `${tmp.path}/raw/sources/project-a/config.yaml`,
+ { ...useWikiStore.getState().llmConfig, maxContextSize: 128_000 },
+ controller.signal,
+ "project-a",
+ ),
+ ).rejects.toThrow("AbortError")
+ })
+
it("canonicalizes interactive source summary paths and sources frontmatter", async () => {
if (!tmp) throw new Error("missing temp project")
diff --git a/src/lib/ingest.prompt.test.ts b/src/lib/ingest.prompt.test.ts
index 3d29009e..0de0172f 100644
--- a/src/lib/ingest.prompt.test.ts
+++ b/src/lib/ingest.prompt.test.ts
@@ -2,6 +2,8 @@ import { describe, it, expect, beforeEach } from "vitest"
import {
buildAnalysisPrompt,
buildGenerationPrompt,
+ computeIngestGenerationMaxTokens,
+ computeIngestReviewMaxTokens,
computeIngestSourceBudget,
splitSourceIntoSemanticChunks,
} from "./ingest"
@@ -100,6 +102,14 @@ describe("analysis + generation prompt consistency", () => {
})
describe("long-source ingest planning", () => {
+ it("scales generation output tokens with the configured context window", () => {
+ expect(computeIngestGenerationMaxTokens(64_000)).toBe(8_192)
+ expect(computeIngestGenerationMaxTokens(128_000)).toBe(16_384)
+ expect(computeIngestGenerationMaxTokens(256_000)).toBe(24_576)
+ expect(computeIngestGenerationMaxTokens(1_000_000)).toBe(32_768)
+ expect(computeIngestReviewMaxTokens(1_000_000)).toBe(8_192)
+ })
+
it("scales source budget from the configured context window instead of a fixed 50k cap", () => {
const small = computeIngestSourceBudget(64_000, 8_000)
const large = computeIngestSourceBudget(1_000_000, 8_000)
diff --git a/src/lib/ingest.ts b/src/lib/ingest.ts
index 65e6e020..a45ecb17 100644
--- a/src/lib/ingest.ts
+++ b/src/lib/ingest.ts
@@ -31,6 +31,12 @@ const LONG_SOURCE_CHUNK_MIN = 12_000
const LONG_SOURCE_CHUNK_MAX = 60_000
const LONG_SOURCE_DIGEST_MAX = 15_000
const LONG_SOURCE_CHUNK_ANALYSIS_MAX = 40_000
+const INGEST_GENERATION_TOKENS_DEFAULT = 8_192
+const INGEST_GENERATION_TOKENS_128K = 16_384
+const INGEST_GENERATION_TOKENS_256K = 24_576
+const INGEST_GENERATION_TOKENS_512K = 32_768
+const REVIEW_STAGE_MIN_SIGNAL_CHARS = 10_000
+const REVIEW_STAGE_MIN_FILE_BLOCKS = 4
interface SourceChunk {
id: string
@@ -688,7 +694,11 @@ async function autoIngestImpl(
},
},
signal,
- { temperature: 0.1, reasoning: { mode: "off" }, max_tokens: 8192 },
+ {
+ temperature: 0.1,
+ reasoning: { mode: "off" },
+ max_tokens: computeIngestGenerationMaxTokens(llmConfig.maxContextSize),
+ },
)
const generationActivity = useActivityStore.getState().items.find((i) => i.id === activityId)
@@ -696,6 +706,53 @@ async function autoIngestImpl(
throw new Error(generationActivity.detail || "Generation stream failed")
}
+ let reviewSuggestionOutput = ""
+ if (!signal?.aborted && shouldRunDedicatedReviewStage(generation)) {
+ let reviewStageHadError = false
+ try {
+ await streamChat(
+ llmConfig,
+ [
+ {
+ role: "system",
+ content: buildReviewSuggestionPrompt(
+ purpose,
+ index,
+ sourceIdentity,
+ analysis,
+ sourceContext,
+ generation,
+ llmConfig.maxContextSize,
+ ),
+ },
+ {
+ role: "user",
+ content: "Emit only high-value REVIEW blocks for follow-up research or unresolved knowledge gaps. Output nothing if there are none.",
+ },
+ ],
+ {
+ onToken: (token) => { reviewSuggestionOutput += token },
+ onDone: () => {},
+ onError: (err) => {
+ reviewStageHadError = true
+ console.warn(`[ingest] Review suggestion generation failed for "${sourceIdentity}": ${err.message}`)
+ },
+ },
+ signal,
+ {
+ temperature: 0.1,
+ reasoning: { mode: "off" },
+ max_tokens: computeIngestReviewMaxTokens(llmConfig.maxContextSize),
+ },
+ )
+ } catch (err) {
+ if (signal?.aborted) throw err
+ console.warn(`[ingest] Review suggestion generation failed for "${sourceIdentity}":`, err)
+ }
+ if (signal?.aborted) throw new Error("Ingest cancelled")
+ if (reviewStageHadError) reviewSuggestionOutput = ""
+ }
+
// ── Step 3: Write files ───────────────────────────────────────
activity.updateItem(activityId, { detail: "Writing files..." })
await migrateLegacySourceSummaryIfSafe(pp, sourceIdentity, sourceSummaryPath)
@@ -775,7 +832,10 @@ async function autoIngestImpl(
}
// ── Step 4: Parse review items ────────────────────────────────
- const reviewItems = parseReviewBlocks(generation, sp)
+ const reviewItems = [
+ ...parseReviewBlocks(generation, sp),
+ ...parseReviewBlocks(reviewSuggestionOutput, sp),
+ ]
if (reviewItems.length > 0) {
useReviewStore.getState().addItems(reviewItems)
}
@@ -1195,6 +1255,16 @@ function parseReviewBlocks(
return items
}
+function countFileBlocks(text: string): number {
+ return (text.match(/---FILE:\s*[^-]+---/g) ?? []).length
+}
+
+function shouldRunDedicatedReviewStage(generation: string): boolean {
+ return generation.length >= REVIEW_STAGE_MIN_SIGNAL_CHARS
+ || countFileBlocks(generation) >= REVIEW_STAGE_MIN_FILE_BLOCKS
+ || /---REVIEW:\s*[\w-]+\s*\|[\s\S]*$/i.test(generation)
+}
+
/**
* Step 1 prompt: AI reads the source and produces a structured analysis.
* This is the "discussion" step — the AI reasons about the source before writing wiki pages.
@@ -1402,6 +1472,65 @@ export function buildGenerationPrompt(
].filter(Boolean).join("\n")
}
+function buildReviewSuggestionPrompt(
+ purpose: string,
+ index: string,
+ sourceIdentity: string,
+ analysis: string,
+ sourceContext: string,
+ generation: string,
+ maxContextSize: number | undefined,
+): string {
+ const { maxCtx } = computeContextBudget(maxContextSize)
+ const sectionCap = Math.max(4_000, Math.floor(maxCtx * 0.15))
+ const indexCap = Math.max(3_000, Math.floor(sectionCap * 0.8))
+ return [
+ "You are identifying high-value follow-up research items for a personal wiki.",
+ "Do not output chain-of-thought, hidden reasoning, or explanatory preamble.",
+ "",
+ languageRule(sourceContext),
+ "",
+ "Your job is NOT to generate wiki pages. The wiki page generation already happened.",
+ "Output only REVIEW blocks for unresolved knowledge gaps that deserve human attention or Deep Research.",
+ "",
+ "Create REVIEW blocks only for genuinely useful follow-up work:",
+ "- missing-page: an important entity/concept is referenced but still lacks a dedicated page",
+ "- suggestion: a research question, source type, or comparison that would materially improve the wiki",
+ "- contradiction: a conflict or tension that requires user judgment",
+ "- duplicate: likely duplicate pages/names that need user review",
+ "",
+ "Prefer 1-5 high-signal reviews. If there is nothing worth reviewing, output nothing.",
+ "For suggestion and missing-page reviews, include a SEARCH line with 2-3 keyword-rich web search queries separated by ` | `.",
+ "Use only these options: OPTIONS: Create Page | Skip",
+ "",
+ "REVIEW block template:",
+ "```",
+ "---REVIEW: suggestion | Precise title---",
+ "Concise description of the gap and why it matters.",
+ "OPTIONS: Create Page | Skip",
+ "PAGES: wiki/page1.md, wiki/page2.md",
+ "SEARCH: query 1 | query 2 | query 3",
+ "---END REVIEW---",
+ "```",
+ "",
+ "Return REVIEW blocks only. Do not output FILE blocks. Do not wrap the response in markdown fences.",
+ "",
+ purpose ? `## Wiki Purpose\n${purpose}` : "",
+ index ? `## Current Wiki Index\n${trimLongText(index, indexCap)}` : "",
+ "",
+ `## Source\n${sourceIdentity}`,
+ "",
+ "## Stage 1 Analysis",
+ trimLongText(analysis, sectionCap),
+ "",
+ "## Source Context",
+ trimLongText(sourceContext, sectionCap),
+ "",
+ "## Generated Wiki Output",
+ trimLongText(generation, sectionCap),
+ ].filter(Boolean).join("\n")
+}
+
function getStore() {
return useChatStore.getState()
}
@@ -1430,6 +1559,18 @@ export function computeIngestSourceBudget(
return clampNumber(Math.floor(available), LONG_SOURCE_MIN_BUDGET, upper)
}
+export function computeIngestGenerationMaxTokens(maxContextSize: number | undefined): number {
+ const { maxCtx } = computeContextBudget(maxContextSize)
+ if (maxCtx >= 512_000) return INGEST_GENERATION_TOKENS_512K
+ if (maxCtx >= 256_000) return INGEST_GENERATION_TOKENS_256K
+ if (maxCtx >= 128_000) return INGEST_GENERATION_TOKENS_128K
+ return INGEST_GENERATION_TOKENS_DEFAULT
+}
+
+export function computeIngestReviewMaxTokens(maxContextSize: number | undefined): number {
+ return Math.min(8_192, Math.max(4_096, Math.floor(computeIngestGenerationMaxTokens(maxContextSize) / 2)))
+}
+
function splitOversizedBlock(block: string, targetChars: number): string[] {
if (block.length <= targetChars * 1.25) return [block]