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

fix: address high-confidence issue regressions

nash_su6ed47592cdb5
diff --git a/src/components/settings/sections/embedding-section.tsx b/src/components/settings/sections/embedding-section.tsx
index 39d4a4a5..77927474 100644
--- a/src/components/settings/sections/embedding-section.tsx
+++ b/src/components/settings/sections/embedding-section.tsx
@@ -46,6 +46,16 @@ const RESERVED_HEADER_NAMES = new Set([
"x-goog-api-key",
])
const HTTP_HEADER_NAME_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/
+const EMBEDDING_MODEL_SUGGESTIONS = [
+ "text-embedding-3-small",
+ "text-embedding-3-large",
+ "gemini-embedding-001",
+ "gemini-embedding-2",
+ "text-embedding-004",
+ "text-embedding-qwen3-embedding-0.6b",
+ "nomic-embed-text",
+ "mxbai-embed-large",
+]
function headersToText(headers: Record<string, string>): string {
return Object.entries(headers)
@@ -205,8 +215,17 @@ export function EmbeddingSection({ draft, setDraft }: Props) {
<Input
value={draft.embeddingModel}
onChange={(e) => setDraft("embeddingModel", e.target.value)}
+ list="embedding-model-suggestions"
placeholder="e.g. text-embedding-qwen3-embedding-0.6b or gemini-embedding-001"
/>
+ <datalist id="embedding-model-suggestions">
+ {EMBEDDING_MODEL_SUGGESTIONS.map((model) => (
+ <option key={model} value={model} />
+ ))}
+ </datalist>
+ <p className="text-xs text-muted-foreground">
+ {t("settings.sections.embedding.modelHint")}
+ </p>
</div>
<div className="space-y-2">
diff --git a/src/i18n/en.json b/src/i18n/en.json
index 0be056c0..82a39268 100644
--- a/src/i18n/en.json
+++ b/src/i18n/en.json
@@ -296,6 +296,7 @@
"apiKey": "API Key (optional)",
"apiKeyPlaceholder": "Leave empty for local models",
"model": "Model",
+ "modelHint": "Common examples are suggested, but custom OpenAI-compatible model IDs are accepted.",
"outputDimensionality": "Output dimensionality (Gemini only)",
"outputDimensionalityHint": "Optional. Sent only for Gemini native embedContent endpoints as `output_dimensionality`; OpenAI-compatible endpoints ignore this field. Leave empty for the model default. Rebuild embeddings after changing model or dimension.",
"extraHeaders": "Custom request headers",
diff --git a/src/i18n/zh.json b/src/i18n/zh.json
index 09f5b3b9..eeb4580c 100644
--- a/src/i18n/zh.json
+++ b/src/i18n/zh.json
@@ -296,6 +296,7 @@
"apiKey": "API Key(可选)",
"apiKeyPlaceholder": "本地模型留空即可",
"model": "Model",
+ "modelHint": "输入框会提示常见模型;OpenAI 兼容 endpoint 的自定义模型 ID 也可以直接填写。",
"outputDimensionality": "输出维度(仅 Gemini)",
"outputDimensionalityHint": "可选。仅对 Gemini 原生 embedContent endpoint 作为 `output_dimensionality` 发送;OpenAI 兼容 endpoint 会忽略此项。留空则使用模型默认值。修改模型或维度后需要重建嵌入。",
"extraHeaders": "自定义请求头",
diff --git a/src/lib/__tests__/llm-providers.test.ts b/src/lib/__tests__/llm-providers.test.ts
index cc56c5a9..385c0d61 100644
--- a/src/lib/__tests__/llm-providers.test.ts
+++ b/src/lib/__tests__/llm-providers.test.ts
@@ -497,7 +497,7 @@ describe("Origin header — local LLM CORS workaround", () => {
expect(cfg.headers["Origin"]).toBe("http://localhost")
})
- it("custom OpenAI-compat endpoint gets the same Origin override (LM Studio / llama.cpp / vLLM)", () => {
+ it("local custom OpenAI-compat endpoint gets the Origin override (LM Studio / llama.cpp / vLLM)", () => {
// For these servers Origin is ignored entirely — but we send
// the value anyway so behavior is uniform across local-LLM
// providers and the rare hardened deployment that does check
@@ -514,6 +514,19 @@ describe("Origin header — local LLM CORS workaround", () => {
expect(cfg.headers["Origin"]).toBe("http://localhost")
})
+ it("public custom OpenAI-compat endpoint does not get the local Origin override", () => {
+ const cfg = getProviderConfig({
+ provider: "custom",
+ apiKey: "key",
+ model: "qwen3",
+ ollamaUrl: "",
+ customEndpoint: "https://gateway.example.com/v1",
+ maxContextSize: 8192,
+ apiMode: "chat_completions",
+ } as RealLlmConfig)
+ expect(cfg.headers["Origin"]).toBeUndefined()
+ })
+
it("commercial provider (OpenAI) does NOT get an explicit Origin override", () => {
// OpenAI's CORS doesn't care about Origin (auth is via API key).
// Setting Origin would just be noise. Pin that we DON'T touch
diff --git a/src/lib/auto-save.ts b/src/lib/auto-save.ts
index fb6bd6c6..b2b21bdd 100644
--- a/src/lib/auto-save.ts
+++ b/src/lib/auto-save.ts
@@ -11,11 +11,11 @@ let chatTimer: ReturnType<typeof setTimeout> | null = null
export function setupAutoSave(): void {
// Auto-save review items (debounced 1s)
useReviewStore.subscribe((state) => {
+ const projectPath = useWikiStore.getState().project?.path
if (reviewTimer) clearTimeout(reviewTimer)
reviewTimer = setTimeout(() => {
- const project = useWikiStore.getState().project
- if (project) {
- saveReviewItems(project.path, state.items).catch(() => {})
+ if (projectPath) {
+ saveReviewItems(projectPath, state.items).catch(() => {})
}
}, 1000)
})
@@ -34,11 +34,11 @@ export function setupAutoSave(): void {
// Auto-save chat conversations and messages (debounced 2s, skip during streaming)
useChatStore.subscribe((state) => {
if (state.isStreaming) return
+ const projectPath = useWikiStore.getState().project?.path
if (chatTimer) clearTimeout(chatTimer)
chatTimer = setTimeout(() => {
- const project = useWikiStore.getState().project
- if (project) {
- saveChatHistory(project.path, state.conversations, state.messages).catch(() => {})
+ if (projectPath) {
+ saveChatHistory(projectPath, state.conversations, state.messages).catch(() => {})
}
}, 2000)
})
diff --git a/src/lib/connection-tests.test.ts b/src/lib/connection-tests.test.ts
index ddbee03b..fcfb708b 100644
--- a/src/lib/connection-tests.test.ts
+++ b/src/lib/connection-tests.test.ts
@@ -1,6 +1,7 @@
import { beforeEach, describe, expect, it, vi } from "vitest"
import type { EmbeddingConfig, LlmConfig } from "@/stores/wiki-store"
import {
+ LLM_PROVIDER_TEST_MAX_TOKENS,
testEmbeddingConnection,
testEmbeddingFunction,
testLlmConnection,
@@ -92,7 +93,24 @@ describe("provider connection tests", () => {
expect.any(Array),
expect.any(Object),
undefined,
- { max_tokens: 32, reasoning: { mode: "off" } },
+ { max_tokens: LLM_PROVIDER_TEST_MAX_TOKENS, reasoning: { mode: "off" } },
+ )
+ })
+
+ it("uses enough output budget for reasoning-heavy local models", async () => {
+ streamChatMock.mockImplementationOnce(async (_cfg, _messages, callbacks) => {
+ callbacks.onToken("OK")
+ callbacks.onDone()
+ })
+
+ await testLlmConnection(llmConfig)
+
+ expect(streamChatMock).toHaveBeenCalledWith(
+ llmConfig,
+ expect.any(Array),
+ expect.any(Object),
+ undefined,
+ expect.objectContaining({ max_tokens: 512 }),
)
})
})
diff --git a/src/lib/connection-tests.ts b/src/lib/connection-tests.ts
index 21e49614..9760e7fa 100644
--- a/src/lib/connection-tests.ts
+++ b/src/lib/connection-tests.ts
@@ -7,6 +7,8 @@ export interface ProviderTestResult {
message: string
}
+export const LLM_PROVIDER_TEST_MAX_TOKENS = 512
+
export async function testEmbeddingConnection(cfg: EmbeddingConfig): Promise<ProviderTestResult> {
if (!cfg.endpoint.trim()) {
return { ok: false, message: "Embedding endpoint is empty." }
@@ -77,7 +79,7 @@ export async function testLlmConnection(cfg: LlmConfig): Promise<ProviderTestRes
onError: (err) => { errorMessage = err.message },
},
undefined,
- { max_tokens: 32, reasoning: { mode: "off" } },
+ { max_tokens: LLM_PROVIDER_TEST_MAX_TOKENS, reasoning: { mode: "off" } },
)
if (errorMessage) return { ok: false, message: errorMessage }
@@ -107,7 +109,7 @@ export async function testLlmFunction(cfg: LlmConfig): Promise<ProviderTestResul
onError: (err) => { errorMessage = err.message },
},
undefined,
- { max_tokens: 32, reasoning: { mode: "off" } },
+ { max_tokens: LLM_PROVIDER_TEST_MAX_TOKENS, reasoning: { mode: "off" } },
)
if (errorMessage) return { ok: false, message: errorMessage }
diff --git a/src/lib/deep-research.ts b/src/lib/deep-research.ts
index a8a73e8b..0cff3ded 100644
--- a/src/lib/deep-research.ts
+++ b/src/lib/deep-research.ts
@@ -123,6 +123,21 @@ function hasAnyTxtSource(searchConfig: SearchApiConfig): boolean {
return sourceMode === "anytxt" || sourceMode === "both"
}
+function isActiveProjectPath(projectPath: string): boolean {
+ const activePath = useWikiStore.getState().project?.path
+ return Boolean(activePath && normalizePath(activePath) === normalizePath(projectPath))
+}
+
+function updateTaskIfActive(
+ projectPath: string,
+ taskId: string,
+ patch: Parameters<ReturnType<typeof useResearchStore.getState>["updateTask"]>[1],
+): boolean {
+ if (!isActiveProjectPath(projectPath)) return false
+ useResearchStore.getState().updateTask(taskId, patch)
+ return true
+}
+
/**
* Process queued tasks up to maxConcurrent limit.
*/
@@ -150,12 +165,12 @@ async function executeResearch(
searchConfig: SearchApiConfig,
) {
const pp = normalizePath(projectPath)
- const store = useResearchStore.getState()
try {
+ if (!isActiveProjectPath(pp)) return
// Step 1: gather research sources — use multiple queries if available,
// merge Web Search and local AnyTXT results, then deduplicate.
- store.updateTask(taskId, { status: "searching" })
+ if (!updateTaskIfActive(pp, taskId, { status: "searching" })) return
const task = useResearchStore.getState().tasks.find((t) => t.id === taskId)
const queries = task?.searchQueries && task.searchQueries.length > 0
@@ -168,21 +183,22 @@ async function executeResearch(
{ webSearch, anyTxtSearch: anyTxtSearchSmart },
{ llmConfig },
)
+ if (!isActiveProjectPath(pp)) return
const webResults = allResults
- store.updateTask(taskId, { webResults })
+ if (!updateTaskIfActive(pp, taskId, { webResults })) return
if (webResults.length === 0) {
- store.updateTask(taskId, {
+ if (!updateTaskIfActive(pp, taskId, {
status: "done",
synthesis: sourceErrors.length > 0 ? sourceErrors.join("\n") : "No research sources found.",
- })
- onTaskFinished(pp, llmConfig, searchConfig)
+ })) return
+ if (isActiveProjectPath(pp)) onTaskFinished(pp, llmConfig, searchConfig)
return
}
// Step 2: LLM synthesis
- store.updateTask(taskId, { status: "synthesizing" })
+ if (!updateTaskIfActive(pp, taskId, { status: "synthesizing" })) return
const searchContext = webResults
.map((r, i) => `[${i + 1}] **${r.title}** (${r.source})\n${r.snippet}`)
@@ -227,12 +243,14 @@ async function executeResearch(
],
{
onToken: (token) => {
+ if (!isActiveProjectPath(pp)) return
accumulated += token
// Update synthesis progressively so UI shows real-time text
useResearchStore.getState().updateTask(taskId, { synthesis: accumulated })
},
onDone: () => {},
onError: (err) => {
+ if (!isActiveProjectPath(pp)) return
useResearchStore.getState().updateTask(taskId, {
status: "error",
error: err.message,
@@ -243,12 +261,13 @@ async function executeResearch(
// Check if errored during streaming
if (useResearchStore.getState().tasks.find((t) => t.id === taskId)?.status === "error") {
- onTaskFinished(pp, llmConfig, searchConfig)
+ if (isActiveProjectPath(pp)) onTaskFinished(pp, llmConfig, searchConfig)
return
}
+ if (!isActiveProjectPath(pp)) return
// Step 3: Save to wiki
- store.updateTask(taskId, { status: "saving", synthesis: accumulated })
+ if (!updateTaskIfActive(pp, taskId, { status: "saving", synthesis: accumulated })) return
const { fileName, date } = makeDeepResearchFileName(topic)
const filePath = `${pp}/wiki/queries/${fileName}`
@@ -285,33 +304,37 @@ async function executeResearch(
await writeFile(filePath, pageContent)
const savedPath = `wiki/queries/${fileName}`
- useResearchStore.getState().updateTask(taskId, {
+ if (!updateTaskIfActive(pp, taskId, {
status: "done",
savedPath,
- })
+ })) return
// Refresh tree
try {
const tree = await listDirectory(pp)
- useWikiStore.getState().setFileTree(tree)
- useWikiStore.getState().bumpDataVersion()
+ if (isActiveProjectPath(pp)) {
+ useWikiStore.getState().setFileTree(tree)
+ useWikiStore.getState().bumpDataVersion()
+ }
} catch {
// ignore
}
// Auto-ingest the research result to generate entities, concepts, cross-references
- autoIngest(pp, `${pp}/${savedPath}`, llmConfig).catch((err) => {
- console.error("Failed to auto-ingest research result:", err)
- })
+ if (isActiveProjectPath(pp)) {
+ autoIngest(pp, `${pp}/${savedPath}`, llmConfig).catch((err) => {
+ console.error("Failed to auto-ingest research result:", err)
+ })
+ }
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
- useResearchStore.getState().updateTask(taskId, {
+ updateTaskIfActive(pp, taskId, {
status: "error",
error: message,
})
}
- onTaskFinished(pp, llmConfig, searchConfig)
+ if (isActiveProjectPath(pp)) onTaskFinished(pp, llmConfig, searchConfig)
}
function onTaskFinished(
diff --git a/src/lib/ingest.prompt.test.ts b/src/lib/ingest.prompt.test.ts
index 83ee323b..8107edd7 100644
--- a/src/lib/ingest.prompt.test.ts
+++ b/src/lib/ingest.prompt.test.ts
@@ -72,6 +72,14 @@ describe("buildGenerationPrompt language directive", () => {
expect(prompt).toContain("my-paper.pdf")
})
+ it("tells the model to keep generated filenames aligned with the output language", () => {
+ useWikiStore.getState().setOutputLanguage("Chinese")
+ const prompt = buildGenerationPrompt("", "", "", "source.pdf")
+
+ expect(prompt).toContain("Derive filenames from the page title in the mandatory output language")
+ expect(prompt).toContain("keep readable CJK characters in the filename")
+ })
+
it("makes project schema routing authoritative over default entity and concept folders", () => {
const prompt = buildGenerationPrompt(
"Use wiki/people/ for people. Use wiki/technologies/ for technical methods.",
diff --git a/src/lib/ingest.ts b/src/lib/ingest.ts
index 47e85bae..6515212f 100644
--- a/src/lib/ingest.ts
+++ b/src/lib/ingest.ts
@@ -1559,6 +1559,7 @@ export function buildGenerationPrompt(
"- Use [[wikilink]] syntax in the BODY for cross-references between pages",
"- If you include images, use wiki-root-relative paths such as `media/source-slug/image.png`; never output absolute filesystem paths.",
"- Use kebab-case filenames",
+ "- Derive filenames from the page title in the mandatory output language. For Chinese/Japanese/Korean titles, keep readable CJK characters in the filename instead of translating the slug to English.",
"- Follow the analysis recommendations on what to emphasize",
"- If the analysis found connections to existing pages, add cross-references",
"",
diff --git a/src/lib/llm-providers.ts b/src/lib/llm-providers.ts
index 3d96629e..1d76ecc1 100644
--- a/src/lib/llm-providers.ts
+++ b/src/lib/llm-providers.ts
@@ -118,6 +118,25 @@ function localLlmOriginHeader(): Record<string, string> {
return { Origin: "http://localhost" }
}
+function isLocalOrPrivateHttpEndpoint(endpoint: string): boolean {
+ try {
+ const url = new URL(endpoint)
+ const host = url.hostname.toLowerCase()
+ if (host === "localhost" || host.endsWith(".localhost")) return true
+ if (host === "127.0.0.1" || host === "::1" || host === "[::1]") return true
+ if (/^10\./.test(host)) return true
+ if (/^192\.168\./.test(host)) return true
+ const m = host.match(/^172\.(\d+)\./)
+ if (m) {
+ const second = Number(m[1])
+ if (second >= 16 && second <= 31) return true
+ }
+ return false
+ } catch {
+ return false
+ }
+}
+
function parseOpenAiLine(line: string): string | null {
if (!line.startsWith("data:")) return null
const data = line.slice(5).trim()
@@ -828,10 +847,11 @@ export function getProviderConfig(config: LlmConfig): ProviderConfig {
? { "api-key": apiKey }
: { Authorization: `Bearer ${apiKey}` }
: {}),
- // Local OpenAI-compatible servers (LM Studio, llama.cpp,
- // vLLM, LocalAI) often share Ollama's CORS sensitivity.
- // Same rationale as the `ollama` branch above.
- ...(azure ? {} : localLlmOriginHeader()),
+ // Only local/LAN OpenAI-compatible servers (LM Studio,
+ // llama.cpp, vLLM, LocalAI) need the Ollama-style Origin
+ // workaround. Public custom gateways may reject unexpected
+ // browser Origin headers, so leave them untouched.
+ ...(!azure && isLocalOrPrivateHttpEndpoint(url) ? localLlmOriginHeader() : {}),
},
buildBody: (messages, overrides) => {
const body = buildOpenAiCompatibleBody(config, messages, overrides)
diff --git a/src/lib/source-lifecycle.test.ts b/src/lib/source-lifecycle.test.ts
index 8fd7e20a..39804d6f 100644
--- a/src/lib/source-lifecycle.test.ts
+++ b/src/lib/source-lifecycle.test.ts
@@ -112,6 +112,41 @@ describe("source-lifecycle path helpers", () => {
])
})
+ it("rejects importing the project folder or folders inside it", async () => {
+ await expect(
+ importSourceFolder(
+ { id: "p1", name: "Project", path: "/project" },
+ "/project",
+ {
+ provider: "openai",
+ endpoint: "https://api.example.com/v1",
+ apiKey: "key",
+ model: "model",
+ customModel: "",
+ reasoning: { enabled: false, effort: "low" },
+ } as never,
+ ),
+ ).rejects.toThrow("Cannot import the project folder")
+
+ await expect(
+ importSourceFolder(
+ { id: "p1", name: "Project", path: "/project" },
+ "/project/raw/sources",
+ {
+ provider: "openai",
+ endpoint: "https://api.example.com/v1",
+ apiKey: "key",
+ model: "model",
+ customModel: "",
+ reasoning: { enabled: false, effort: "low" },
+ } as never,
+ ),
+ ).rejects.toThrow("Cannot import the project folder")
+
+ expect(mocks.listDirectory).not.toHaveBeenCalled()
+ expect(mocks.copyFile).not.toHaveBeenCalled()
+ })
+
it("filters single-file imports using the original source path before copying", async () => {
const copied = await importSourceFiles(
{ id: "p1", name: "Project", path: "/project" },
diff --git a/src/lib/source-lifecycle.ts b/src/lib/source-lifecycle.ts
index 2a82894d..5ba5f774 100644
--- a/src/lib/source-lifecycle.ts
+++ b/src/lib/source-lifecycle.ts
@@ -77,6 +77,22 @@ function parentPath(path: string): string {
return index > 0 ? normalized.slice(0, index) : ""
}
+function stripTrailingSlash(path: string): string {
+ return normalizePath(path).replace(/\/+$/, "")
+}
+
+function isSameOrInside(path: string, parent: string): boolean {
+ const p = stripTrailingSlash(path).toLowerCase()
+ const base = stripTrailingSlash(parent).toLowerCase()
+ return p === base || p.startsWith(`${base}/`)
+}
+
+function isProjectScopedImport(projectPath: string, selectedFolder: string): boolean {
+ const pp = stripTrailingSlash(projectPath)
+ const sourceRoot = stripTrailingSlash(selectedFolder)
+ return isSameOrInside(pp, sourceRoot) || isSameOrInside(sourceRoot, pp)
+}
+
export interface DeleteSourceResult {
deletedWikiPaths: string[]
rewrittenSourcePages: number
@@ -181,6 +197,9 @@ export async function importSourceFolder(
): Promise<string[]> {
const pp = normalizePath(project.path)
const sourceRoot = normalizePath(selectedFolder)
+ if (isProjectScopedImport(pp, sourceRoot)) {
+ throw new Error("Cannot import the project folder or a folder inside the current project.")
+ }
const folderName = getFileName(selectedFolder) || "imported"
const destDir = `${pp}/raw/sources/${folderName}`
const cfg = normalizeSourceWatchConfig(sourceWatchConfig)
diff --git a/src/lib/sources-merge.test.ts b/src/lib/sources-merge.test.ts
index 0dcb4d92..8d7e3e6b 100644
--- a/src/lib/sources-merge.test.ts
+++ b/src/lib/sources-merge.test.ts
@@ -64,6 +64,20 @@ describe("parseSources — inline `sources: [...]`", () => {
"test.md",
])
})
+
+ it("keeps commas inside quoted source filenames", () => {
+ expect(parseSources(WRAP('sources: ["reports/Q1, revised.pdf", "测试,最终版.md"]'))).toEqual([
+ "reports/Q1, revised.pdf",
+ "测试,最终版.md",
+ ])
+ })
+
+ it("round-trips source filenames with quotes and backslashes", () => {
+ const after = writeSources(WRAP("title: X"), ['drafts/"quoted".md', "folder\\note.md"])
+
+ expect(after).toContain('sources: ["drafts/\\"quoted\\".md", "folder\\\\note.md"]')
+ expect(parseSources(after)).toEqual(['drafts/"quoted".md', "folder\\note.md"])
+ })
})
describe("parseSources — multi-line YAML list form", () => {
diff --git a/src/lib/sources-merge.ts b/src/lib/sources-merge.ts
index 01484fa9..fcf1bceb 100644
--- a/src/lib/sources-merge.ts
+++ b/src/lib/sources-merge.ts
@@ -59,10 +59,45 @@ export function parseFrontmatterArray(content: string, fieldName: string): strin
if (!inline) return []
const body = inline[1].trim()
if (body === "") return []
- return body
- .split(",")
- .map((s) => s.trim().replace(/^["']|["']$/g, ""))
- .filter((s) => s.length > 0)
+ return splitInlineArray(body)
+}
+
+function splitInlineArray(body: string): string[] {
+ const out: string[] = []
+ let current = ""
+ let quote: "\"" | "'" | null = null
+ let escaped = false
+
+ for (const ch of body) {
+ if (escaped) {
+ current += ch
+ escaped = false
+ continue
+ }
+ if (quote === "\"" && ch === "\\") {
+ escaped = true
+ continue
+ }
+ if ((ch === "\"" || ch === "'") && quote === null) {
+ quote = ch
+ continue
+ }
+ if (quote === ch) {
+ quote = null
+ continue
+ }
+ if (ch === "," && quote === null) {
+ const value = current.trim()
+ if (value) out.push(value)
+ current = ""
+ continue
+ }
+ current += ch
+ }
+
+ const value = current.trim()
+ if (value) out.push(value)
+ return out
}
/**
@@ -86,7 +121,7 @@ export function writeFrontmatterArray(
const [, openDelim, fmBody, closeDelim] = fmMatch
const escapedName = fieldName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
- const serialized = values.map((s) => `"${s}"`).join(", ")
+ const serialized = values.map(quoteInlineArrayValue).join(", ")
const newLine = `${fieldName}: [${serialized}]`
// Replace inline form in place — preserves field ordering.
@@ -111,6 +146,10 @@ export function writeFrontmatterArray(
return `${openDelim}${rewritten}${closeDelim}${content.slice(fmMatch[0].length)}`
}
+function quoteInlineArrayValue(value: string): string {
+ return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`
+}
+
/**
* Union-merge two array values. Case-insensitive dedup. First-seen
* casing wins (matches sources-merge's historical contract — keeps