Skip to content

A full-featured download manager.

chore(docs): add optional Obsidian plan gateway

Dr_rOot2ca02b0392e9
diff --git a/.dockerignore b/.dockerignore
index 68340baa..b585e576 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -16,6 +16,8 @@ e2e
AGENTS.md
CLAUDE.md
obsidian-docs.config.json
+.obsidian-doc-context.json
+.obsidian-doc-context.json.tmp-*
scripts/obsidian-docs-lib.mjs
scripts/obsidian-docs.mjs
tests/scripts/obsidian-docs.test.ts
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index a35609a1..81ced484 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -141,6 +141,7 @@ jobs:
tests/scripts/electron-package-contract.test.ts
tests/scripts/flatpak-native-host.test.ts
tests/scripts/native-binary-target.test.ts
+ tests/scripts/obsidian-docs.test.ts
tests/scripts/release-metadata.test.ts
tests/scripts/snap-artifact.test.ts
tests/scripts/snap-build-set-release.test.ts
diff --git a/.gitignore b/.gitignore
index 60b8be0a..d8a35e15 100644
--- a/.gitignore
+++ b/.gitignore
@@ -147,6 +147,11 @@ graphify-out/*
.worktrees/
+# Optional local Obsidian documentation gateway
+/obsidian-docs.config.json
+/.obsidian-doc-context.json
+/.obsidian-doc-context.json.tmp-*
+
# Playwright e2e
/e2e/test-results
/e2e/playwright-report
diff --git a/obsidian-docs.config.example.json b/obsidian-docs.config.example.json
new file mode 100644
index 00000000..f5cf8135
--- /dev/null
+++ b/obsidian-docs.config.example.json
@@ -0,0 +1,17 @@
+{
+ "version": 1,
+ "vault": "your-obsidian-vault",
+ "projectRoot": "projects/motrix",
+ "repository": "Motrix",
+ "contextFile": ".obsidian-doc-context.json",
+ "commandTimeoutMs": 30000,
+ "directories": {
+ "activeSpecs": "20-active-specs",
+ "activePlans": "30-active-plans",
+ "decisions": "40-decisions",
+ "evidence": "50-evidence",
+ "publication": "60-publication",
+ "archivePlans": "90-archive/plans",
+ "legacyImport": "90-legacy-import"
+ }
+}
diff --git a/package.json b/package.json
index d41fc2dd..5a1b3ad7 100644
--- a/package.json
+++ b/package.json
@@ -46,6 +46,15 @@
"check:update-artifacts": "node scripts/verify-update-artifacts.mjs",
"check:snap": "node scripts/verify-snap-artifact.mjs",
"check:snap-store": "node scripts/verify-snap-store-channel.mjs",
+ "docs": "node scripts/obsidian-docs.mjs",
+ "docs:clear": "node scripts/obsidian-docs.mjs clear",
+ "docs:context": "node scripts/obsidian-docs.mjs context",
+ "docs:doctor": "node scripts/obsidian-docs.mjs doctor",
+ "docs:list": "node scripts/obsidian-docs.mjs list",
+ "docs:status": "node scripts/obsidian-docs.mjs status",
+ "docs:task": "node scripts/obsidian-docs.mjs task",
+ "docs:use": "node scripts/obsidian-docs.mjs use",
+ "docs:check": "node scripts/obsidian-docs.mjs check",
"lint": "biome check .",
"lint:fix": "biome check --fix .",
"format": "biome format --write .",
diff --git a/scripts/obsidian-docs-lib.mjs b/scripts/obsidian-docs-lib.mjs
new file mode 100644
index 00000000..5ac3a061
--- /dev/null
+++ b/scripts/obsidian-docs-lib.mjs
@@ -0,0 +1,790 @@
+import { spawnSync } from 'node:child_process'
+import { randomUUID } from 'node:crypto'
+import {
+ existsSync,
+ lstatSync,
+ readFileSync,
+ renameSync,
+ unlinkSync,
+ writeFileSync,
+} from 'node:fs'
+import path from 'node:path'
+
+export const TASK_ID_PATTERN = /^[A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+$/
+export const LOCAL_CONTEXT_FILE = '.obsidian-doc-context.json'
+
+const TASK_LINE_PATTERN =
+ /^(\s*-\s+\[)([ xX])(\]\s+\[([A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+)\]\s+)(.+)$/
+
+const OPEN_MIGRATION_STATUSES = new Set([
+ 'bootstrap',
+ 'draft',
+ 'in-progress',
+ 'needs-review',
+])
+
+function stripUnsafeControlCharacters(value) {
+ return [...value]
+ .filter((character) => {
+ const code = character.codePointAt(0)
+ return (
+ character === '\n' ||
+ character === '\r' ||
+ character === '\t' ||
+ (code >= 0x20 && code !== 0x7f)
+ )
+ })
+ .join('')
+}
+
+export function loadDocsConfig(repoRoot, configPath) {
+ if (configPath !== undefined && typeof configPath !== 'string') {
+ throw new Error('--config requires a file path')
+ }
+ const resolvedPath = path.resolve(
+ repoRoot,
+ configPath ?? 'obsidian-docs.config.json'
+ )
+ if (!existsSync(resolvedPath)) {
+ throw new Error(
+ `Obsidian docs config not found: ${resolvedPath}. Copy obsidian-docs.config.example.json to obsidian-docs.config.json and customize the ignored local file.`
+ )
+ }
+ const config = JSON.parse(readFileSync(resolvedPath, 'utf8'))
+ validateDocsConfig(config)
+ return { ...config, configPath: resolvedPath, repoRoot }
+}
+
+export function validateDocsConfig(config) {
+ if (config?.version !== 1) {
+ throw new Error('obsidian docs config version must be 1')
+ }
+ for (const key of ['vault', 'projectRoot', 'repository', 'contextFile']) {
+ if (typeof config[key] !== 'string' || config[key].length === 0) {
+ throw new Error(`obsidian docs config requires ${key}`)
+ }
+ }
+ if (/[^\P{Cc}\t]/u.test(config.vault) || config.vault.length > 200) {
+ throw new Error('vault must not contain control characters')
+ }
+ if (
+ !Number.isInteger(config.commandTimeoutMs) ||
+ config.commandTimeoutMs < 1_000
+ ) {
+ throw new Error('commandTimeoutMs must be an integer of at least 1000')
+ }
+ const requiredDirectories = [
+ 'activeSpecs',
+ 'activePlans',
+ 'decisions',
+ 'evidence',
+ 'publication',
+ 'archivePlans',
+ 'legacyImport',
+ ]
+ for (const key of requiredDirectories) {
+ const value = config.directories?.[key]
+ if (typeof value !== 'string' || value.length === 0) {
+ throw new Error(`obsidian docs config requires directories.${key}`)
+ }
+ assertRelativePath(value, `directories.${key}`)
+ }
+ assertRelativePath(config.projectRoot, 'projectRoot')
+ assertRelativePath(config.contextFile, 'contextFile')
+ if (config.contextFile !== LOCAL_CONTEXT_FILE) {
+ throw new Error(`contextFile must be ${LOCAL_CONTEXT_FILE}`)
+ }
+}
+
+function assertRelativePath(value, label) {
+ if (
+ typeof value !== 'string' ||
+ value.length === 0 ||
+ value.includes('\\') ||
+ value.includes('\0') ||
+ path.posix.isAbsolute(value) ||
+ path.win32.isAbsolute(value) ||
+ value
+ .split('/')
+ .some((part) => part.length === 0 || part === '.' || part === '..')
+ ) {
+ throw new Error(`${label} must be a safe relative path`)
+ }
+}
+
+function isWithinPosixPath(root, candidate) {
+ const relative = path.posix.relative(root, candidate)
+ return (
+ relative.length > 0 &&
+ relative !== '..' &&
+ !relative.startsWith('../') &&
+ !path.posix.isAbsolute(relative)
+ )
+}
+
+export function projectPath(config, directoryKey, filename = '') {
+ const directory = config.directories[directoryKey]
+ if (!directory) throw new Error(`Unknown docs directory: ${directoryKey}`)
+ return [config.projectRoot, directory, filename].filter(Boolean).join('/')
+}
+
+export function assertProjectMarkdownPath(config, vaultPath) {
+ assertRelativePath(vaultPath, 'Vault path')
+ if (
+ !isWithinPosixPath(config.projectRoot, vaultPath) ||
+ !vaultPath.endsWith('.md')
+ ) {
+ throw new Error(
+ `Markdown path must stay under ${config.projectRoot}: ${vaultPath}`
+ )
+ }
+ return vaultPath
+}
+
+export function assertActivePlanMarkdownPath(config, vaultPath) {
+ assertProjectMarkdownPath(config, vaultPath)
+ const activePlansRoot = projectPath(config, 'activePlans')
+ if (!isWithinPosixPath(activePlansRoot, vaultPath)) {
+ throw new Error(
+ `Active plan path must stay under ${activePlansRoot}: ${vaultPath}`
+ )
+ }
+ return vaultPath
+}
+
+export function parseTaskLines(content) {
+ const tasks = []
+ const seen = new Set()
+ const duplicates = new Set()
+ const lines = content.split(/\r?\n/)
+
+ for (let index = 0; index < lines.length; index += 1) {
+ const match = TASK_LINE_PATTERN.exec(lines[index])
+ if (!match) continue
+ const id = match[4]
+ if (seen.has(id)) duplicates.add(id)
+ seen.add(id)
+ tasks.push({
+ id,
+ description: match[5],
+ done: match[2].toLowerCase() === 'x',
+ line: index + 1,
+ text: lines[index],
+ })
+ }
+
+ return { duplicates: [...duplicates].sort(), tasks }
+}
+
+export function deriveProgress(tasks) {
+ const completed = tasks.filter((task) => task.done).length
+ const total = tasks.length
+ const currentTask = tasks.find((task) => !task.done)?.id
+ const implementationStatus =
+ completed === 0
+ ? 'not-started'
+ : completed === total
+ ? 'verification'
+ : 'in-progress'
+ return { completed, currentTask, implementationStatus, total }
+}
+
+export function validatePlanPair(english, chinese, options = {}) {
+ const errors = []
+ const repository = options.repository ?? 'Motrix'
+ const englishParsed = parseTaskLines(english.content)
+ const chineseParsed = parseTaskLines(chinese.content)
+ const englishIds = englishParsed.tasks.map((task) => task.id)
+ const chineseIds = chineseParsed.tasks.map((task) => task.id)
+ const englishStates = englishParsed.tasks.map((task) => task.done)
+ const chineseStates = chineseParsed.tasks.map((task) => task.done)
+
+ if (englishParsed.duplicates.length > 0) {
+ errors.push(
+ `${english.path}: duplicate task IDs ${englishParsed.duplicates.join(', ')}`
+ )
+ }
+ if (chineseParsed.duplicates.length > 0) {
+ errors.push(
+ `${chinese.path}: duplicate task IDs ${chineseParsed.duplicates.join(', ')}`
+ )
+ }
+ if (englishIds.length === 0) {
+ errors.push(`${english.path}: no stable task IDs found`)
+ }
+ if (JSON.stringify(englishIds) !== JSON.stringify(chineseIds)) {
+ errors.push(`${english.path}: bilingual task ID order differs`)
+ }
+ if (JSON.stringify(englishStates) !== JSON.stringify(chineseStates)) {
+ errors.push(`${english.path}: bilingual task completion differs`)
+ }
+
+ const englishProgress = deriveProgress(englishParsed.tasks)
+ const chineseProgress = deriveProgress(chineseParsed.tasks)
+ for (const document of [english, chinese]) {
+ const metadata = document.metadata ?? {}
+ const progress = document === english ? englishProgress : chineseProgress
+ const required = [
+ 'doc_id',
+ 'implementation_status',
+ 'last_verified',
+ 'path_audit',
+ 'progress_schema',
+ 'verified_head',
+ 'verified_repository',
+ 'bilingual_pair',
+ ]
+ for (const key of required) {
+ if (metadata[key] === undefined || metadata[key] === '') {
+ errors.push(`${document.path}: missing ${key}`)
+ }
+ }
+ if (metadata.verified_repository !== repository) {
+ errors.push(`${document.path}: verified_repository must be ${repository}`)
+ }
+ if (metadata.progress_schema !== 'stable-task-ids-v1') {
+ errors.push(`${document.path}: unsupported progress_schema`)
+ }
+ if (metadata.pair_status !== 'paired') {
+ errors.push(`${document.path}: pair_status must be paired`)
+ }
+ if (!String(metadata.lifecycle ?? '').startsWith('active')) {
+ errors.push(`${document.path}: lifecycle must start with active`)
+ }
+ if (metadata.progress_completed !== progress.completed) {
+ errors.push(`${document.path}: progress_completed is stale`)
+ }
+ if (metadata.progress_total !== progress.total) {
+ errors.push(`${document.path}: progress_total is stale`)
+ }
+ if (metadata.implementation_status !== progress.implementationStatus) {
+ errors.push(`${document.path}: implementation_status is stale`)
+ }
+ if ((metadata.current_task ?? undefined) !== progress.currentTask) {
+ errors.push(`${document.path}: current_task is stale`)
+ }
+ }
+
+ if (english.metadata?.doc_id !== chinese.metadata?.doc_id) {
+ errors.push(`${english.path}: bilingual doc_id differs`)
+ }
+ for (const document of [english, chinese]) {
+ if (document.metadata?.document_type !== 'active-plan') {
+ errors.push(`${document.path}: document_type must be active-plan`)
+ }
+ }
+ if (english.metadata?.language !== 'en') {
+ errors.push(`${english.path}: language must be en`)
+ }
+ if (chinese.metadata?.language !== 'zh-CN') {
+ errors.push(`${chinese.path}: language must be zh-CN`)
+ }
+ if (wikilinkPath(english.metadata?.bilingual_pair) !== chinese.path) {
+ errors.push(`${english.path}: bilingual_pair is not reciprocal`)
+ }
+ if (wikilinkPath(chinese.metadata?.bilingual_pair) !== english.path) {
+ errors.push(`${chinese.path}: bilingual_pair is not reciprocal`)
+ }
+ return errors
+}
+
+function wikilinkPath(value) {
+ const target = String(value ?? '').match(/\[\[([^\]|#]+)/)?.[1]
+ if (!target) return undefined
+ return target.endsWith('.md') ? target : `${target}.md`
+}
+
+export function parseEvalJson(output) {
+ const lines = output.trim().split(/\r?\n/)
+ const markerLine = lines.findIndex((line) =>
+ line.trimStart().startsWith('=>')
+ )
+ const payload =
+ markerLine >= 0
+ ? [
+ lines[markerLine].slice(lines[markerLine].indexOf('=>') + 2),
+ ...lines.slice(markerLine + 1),
+ ]
+ .join('\n')
+ .trim()
+ : lines.join('\n').trim()
+ if (!payload) throw new Error('Obsidian eval returned no JSON payload')
+ return JSON.parse(payload)
+}
+
+export function runProcess(command, args, options = {}) {
+ const result = spawnSync(command, args, {
+ cwd: options.cwd,
+ encoding: 'utf8',
+ timeout: options.timeoutMs ?? 30_000,
+ })
+ if (result.error) {
+ throw new Error(`${command} failed: ${result.error.message}`)
+ }
+ if (result.status !== 0) {
+ const rawDetail = [
+ result.stderr,
+ options.includeStdoutOnError ? result.stdout : '',
+ ]
+ .filter(Boolean)
+ .join('\n')
+ .trim()
+ const detail = stripUnsafeControlCharacters(rawDetail).slice(0, 4_000)
+ const displayArgs = options.redactArgs
+ ? '[arguments redacted]'
+ : args.join(' ')
+ throw new Error(
+ `${command} ${displayArgs} exited ${result.status}${
+ detail ? `\n${detail}` : ''
+ }`
+ )
+ }
+ return result.stdout.trim()
+}
+
+export function runObsidian(config, args) {
+ return runProcess('obsidian', [`vault=${config.vault}`, ...args], {
+ cwd: config.repoRoot,
+ redactArgs: true,
+ timeoutMs: config.commandTimeoutMs,
+ })
+}
+
+export function evaluateObsidian(config, code) {
+ return parseEvalJson(runObsidian(config, ['eval', `code=${code}`]))
+}
+
+export function getGitState(config) {
+ const branch = runProcess('git', ['branch', '--show-current'], {
+ cwd: config.repoRoot,
+ })
+ const head = runProcess('git', ['rev-parse', 'HEAD'], {
+ cwd: config.repoRoot,
+ })
+ return { branch, head }
+}
+
+export function resolveGitCommit(config, ref) {
+ return runProcess('git', ['rev-parse', '--verify', `${ref}^{commit}`], {
+ cwd: config.repoRoot,
+ })
+}
+
+export function contextFilePath(config) {
+ if (config.contextFile !== LOCAL_CONTEXT_FILE) {
+ throw new Error(`contextFile must be ${LOCAL_CONTEXT_FILE}`)
+ }
+ const repoRoot = path.resolve(config.repoRoot)
+ const target = path.resolve(repoRoot, config.contextFile)
+ if (path.dirname(target) !== repoRoot) {
+ throw new Error('Local context file must stay at the repository root')
+ }
+ return target
+}
+
+function assertSafeContextFile(target) {
+ if (!existsSync(target)) return false
+ const stats = lstatSync(target)
+ if (stats.isSymbolicLink() || !stats.isFile()) {
+ throw new Error('Local context path must be a regular file, not a symlink')
+ }
+ return true
+}
+
+export function readLocalContext(config) {
+ const target = contextFilePath(config)
+ if (!assertSafeContextFile(target)) return undefined
+ const context = JSON.parse(readFileSync(target, 'utf8'))
+ if (typeof context.planId !== 'string' || context.planId.length === 0) {
+ throw new Error(`${config.contextFile} does not contain planId`)
+ }
+ if (typeof context.planPath !== 'string') {
+ throw new Error(`${config.contextFile} does not contain planPath`)
+ }
+ assertActivePlanMarkdownPath(config, context.planPath)
+ return context
+}
+
+export function clearLocalContext(config) {
+ const target = contextFilePath(config)
+ if (!assertSafeContextFile(target)) return false
+ unlinkSync(target)
+ return true
+}
+
+export function writeLocalContext(config, plan) {
+ if (typeof plan.id !== 'string' || plan.id.length === 0) {
+ throw new Error('Selected plan requires a document ID')
+ }
+ assertActivePlanMarkdownPath(config, plan.path)
+ const context = {
+ planId: plan.id,
+ planPath: plan.path,
+ selectedAt: new Date().toISOString(),
+ }
+ const target = contextFilePath(config)
+ assertSafeContextFile(target)
+ const temporary = `${target}.tmp-${process.pid}-${randomUUID()}`
+ try {
+ writeFileSync(temporary, `${JSON.stringify(context, null, 2)}\n`, {
+ encoding: 'utf8',
+ flag: 'wx',
+ mode: 0o600,
+ })
+ renameSync(temporary, target)
+ } catch (error) {
+ if (existsSync(temporary)) unlinkSync(temporary)
+ throw error
+ }
+ return context
+}
+
+export function listDocuments(config, kind) {
+ const directoryKey =
+ kind === 'plans'
+ ? 'activePlans'
+ : kind === 'specs'
+ ? 'activeSpecs'
+ : undefined
+ if (!directoryKey) throw new Error('Document kind must be plans or specs')
+ const folder = projectPath(config, directoryKey)
+ const code = `(async()=>{const folder=${JSON.stringify(
+ folder
+ )};const files=app.vault.getMarkdownFiles().filter(f=>f.path.startsWith(folder+"/"));const rows=[];for(const file of files){const metadata=app.metadataCache.getFileCache(file)?.frontmatter||{};if(!metadata.language)continue;rows.push({path:file.path,id:metadata.doc_id||file.basename.replace(/\\.zh-CN$/,"") ,language:metadata.language,document_type:metadata.document_type,lifecycle:metadata.lifecycle,implementation_status:metadata.implementation_status,verified_head:metadata.verified_head,bilingual_pair:metadata.bilingual_pair});}rows.sort((a,b)=>a.path.localeCompare(b.path));return JSON.stringify(rows)})()`
+ return evaluateObsidian(config, code)
+}
+
+const DOCUMENT_ROOTS = Object.freeze([
+ ['activePlans', 'active-plan'],
+ ['activeSpecs', 'active-spec'],
+ ['decisions', 'decision'],
+ ['evidence', 'evidence'],
+])
+
+function documentRoot(config, vaultPath) {
+ return DOCUMENT_ROOTS.find(([directoryKey]) =>
+ isWithinPosixPath(projectPath(config, directoryKey), vaultPath)
+ )
+}
+
+function documentIndexCode(config) {
+ const roots = DOCUMENT_ROOTS.map(([directoryKey]) => ({
+ directoryKey,
+ path: projectPath(config, directoryKey),
+ }))
+ return `(async()=>{const roots=${JSON.stringify(
+ roots
+ )};const under=(root,candidate)=>candidate.startsWith(root+"/");const files=app.vault.getMarkdownFiles().filter(file=>roots.some(root=>under(root.path,file.path)));const rows=[];for(const file of files){const cache=app.metadataCache.getFileCache(file)||{};const metadata=cache.frontmatter||{};const pairLink=String(metadata.bilingual_pair||"").match(/\\[\\[([^\\]|#]+)/)?.[1];const pair=pairLink?app.metadataCache.getFirstLinkpathDest(pairLink,file.path):null;const relatedPaths=[];for(const link of [...(cache.links||[]),...(cache.frontmatterLinks||[])]){const target=app.metadataCache.getFirstLinkpathDest(link.link,file.path);if(target&&roots.some(root=>root.directoryKey!=="activePlans"&&under(root.path,target.path)))relatedPaths.push(target.path)}rows.push({path:file.path,basename:file.basename,metadata,pairPath:pair?.path,relatedPaths:[...new Set(relatedPaths)].sort()})}rows.sort((a,b)=>a.path.localeCompare(b.path));return JSON.stringify(rows)})()`
+}
+
+function readDocumentsCode(paths) {
+ return `(async()=>{const paths=${JSON.stringify(
+ paths
+ )};const documents=[];for(const path of paths){const file=app.vault.getAbstractFileByPath(path);if(!file||file.extension!=="md")throw new Error("Allowed Markdown file not found");const cache=app.metadataCache.getFileCache(file)||{};const metadata=cache.frontmatter||{};const pairLink=String(metadata.bilingual_pair||"").match(/\\[\\[([^\\]|#]+)/)?.[1];const pair=pairLink?app.metadataCache.getFirstLinkpathDest(pairLink,file.path):null;documents.push({path:file.path,metadata,pairPath:pair?.path,content:await app.vault.cachedRead(file)})}documents.sort((a,b)=>a.path.localeCompare(b.path));return JSON.stringify(documents)})()`
+}
+
+function assertDocumentPair(config, byPath, candidate, expectedRootKey) {
+ if (!candidate) throw new Error('Selected document is missing')
+ const root = documentRoot(config, candidate.path)
+ if (!root || root[0] !== expectedRootKey) {
+ throw new Error(`Document is outside ${expectedRootKey}: ${candidate.path}`)
+ }
+ if (candidate.metadata?.document_type !== root[1]) {
+ throw new Error(`${candidate.path}: document_type must be ${root[1]}`)
+ }
+ if (!candidate.pairPath) {
+ throw new Error(`${candidate.path}: bilingual pair is missing`)
+ }
+ const pair = byPath.get(candidate.pairPath)
+ if (!pair) throw new Error(`${candidate.path}: bilingual pair is not allowed`)
+ const pairRoot = documentRoot(config, pair.path)
+ if (!pairRoot || pairRoot[0] !== expectedRootKey) {
+ throw new Error(`${candidate.path}: bilingual pair leaves its directory`)
+ }
+ if (pair.metadata?.document_type !== root[1]) {
+ throw new Error(`${pair.path}: document_type must be ${root[1]}`)
+ }
+ const languages = new Set([
+ candidate.metadata?.language,
+ pair.metadata?.language,
+ ])
+ if (!languages.has('en') || !languages.has('zh-CN') || languages.size !== 2) {
+ throw new Error(`${candidate.path}: pair languages must be en and zh-CN`)
+ }
+ const english = candidate.metadata.language === 'en' ? candidate : pair
+ const chinese = english === candidate ? pair : candidate
+ const expectedChinesePath = english.path.replace(/\.md$/, '.zh-CN.md')
+ if (
+ english.path.endsWith('.zh-CN.md') ||
+ chinese.path !== expectedChinesePath
+ ) {
+ throw new Error(
+ `${candidate.path}: bilingual filenames do not match language`
+ )
+ }
+ if (
+ !candidate.metadata?.doc_id ||
+ candidate.metadata.doc_id !== pair.metadata?.doc_id
+ ) {
+ throw new Error(`${candidate.path}: bilingual doc_id differs or is missing`)
+ }
+ if (pair.pairPath !== candidate.path) {
+ throw new Error(`${candidate.path}: bilingual pair is not reciprocal`)
+ }
+ return { english, chinese }
+}
+
+export function selectPlanDocuments(config, index, ref, options = {}) {
+ if (typeof ref !== 'string' || ref.length === 0 || ref.length > 500) {
+ throw new Error('Plan reference must be a non-empty string')
+ }
+ const byPath = new Map()
+ for (const document of index) {
+ if (byPath.has(document.path)) {
+ throw new Error(`Duplicate indexed path: ${document.path}`)
+ }
+ byPath.set(document.path, document)
+ }
+ const activePlans = index.filter(
+ (document) => documentRoot(config, document.path)?.[0] === 'activePlans'
+ )
+ const matches = activePlans.filter(
+ (document) =>
+ document.path === ref ||
+ document.basename === ref ||
+ document.metadata?.doc_id === ref
+ )
+ if (matches.length === 0) throw new Error(`Active plan not found: ${ref}`)
+
+ const resolvedPairs = matches.map((candidate) =>
+ assertDocumentPair(config, byPath, candidate, 'activePlans')
+ )
+ const englishPaths = new Set(resolvedPairs.map((pair) => pair.english.path))
+ if (englishPaths.size !== 1) {
+ throw new Error(`Ambiguous active plan reference: ${ref}`)
+ }
+ const plan = resolvedPairs[0].english
+ const pair = resolvedPairs[0].chinese
+ const selected = new Set([plan.path, pair.path])
+
+ if (options.includeRelated) {
+ for (const source of [plan, pair]) {
+ for (const relatedPath of source.relatedPaths ?? []) {
+ const related = byPath.get(relatedPath)
+ const root = related && documentRoot(config, related.path)
+ if (!related || !root || root[0] === 'activePlans') continue
+ const relatedPair = assertDocumentPair(config, byPath, related, root[0])
+ selected.add(relatedPair.english.path)
+ selected.add(relatedPair.chinese.path)
+ }
+ }
+ }
+ return {
+ pairPath: pair.path,
+ paths: [...selected].sort(),
+ planPath: plan.path,
+ }
+}
+
+export function readPlanBundle(config, ref, options = {}) {
+ const index = evaluateObsidian(config, documentIndexCode(config))
+ const selection = selectPlanDocuments(config, index, ref, options)
+ const documents = evaluateObsidian(config, readDocumentsCode(selection.paths))
+ const byPath = new Map(documents.map((document) => [document.path, document]))
+ for (const document of documents) {
+ const root = documentRoot(config, document.path)
+ if (!root) throw new Error(`Document left allowed roots: ${document.path}`)
+ assertDocumentPair(config, byPath, document, root[0])
+ }
+ const english = byPath.get(selection.planPath)
+ const chinese = byPath.get(selection.pairPath)
+ const errors = validatePlanPair(english, chinese, {
+ repository: config.repository,
+ })
+ if (errors.length > 0) throw new Error(errors.join('\n'))
+ for (const document of documents) delete document.pairPath
+ return { ...selection, documents }
+}
+
+export function resolvePlanReference(config, explicitRef) {
+ if (explicitRef) return explicitRef
+ const context = readLocalContext(config)
+ if (!context) {
+ throw new Error(
+ `No plan selected. Run "pnpm run docs:use -- <plan-id>" first.`
+ )
+ }
+ return context.planPath
+}
+
+export function planSummary(bundle, gitState) {
+ const plan = bundle.documents.find(
+ (document) => document.path === bundle.planPath
+ )
+ const pair = bundle.documents.find(
+ (document) => document.path === bundle.pairPath
+ )
+ if (!plan || !pair) throw new Error('Plan bundle is missing its pair')
+ const parsed = parseTaskLines(plan.content)
+ const progress = deriveProgress(parsed.tasks)
+ const verifiedHead = plan.metadata.verified_head
+ const head = gitState.head
+ const matchesVerifiedHead =
+ Boolean(verifiedHead && head) &&
+ (verifiedHead === head ||
+ verifiedHead.startsWith(head) ||
+ head.startsWith(verifiedHead))
+ return {
+ id: plan.metadata.doc_id ?? path.basename(plan.path, '.md'),
+ path: plan.path,
+ pairPath: pair.path,
+ branch: gitState.branch,
+ head,
+ verifiedHead,
+ requiresRevalidation: !matchesVerifiedHead,
+ lastProgressHead: plan.metadata.last_progress_head,
+ implementationStatus: plan.metadata.implementation_status,
+ progress,
+ tasks: parsed.tasks,
+ }
+}
+
+export function readAllActivePlanDocuments(config) {
+ const index = evaluateObsidian(config, documentIndexCode(config))
+ const paths = index
+ .filter(
+ (document) => documentRoot(config, document.path)?.[0] === 'activePlans'
+ )
+ .map((document) => document.path)
+ return evaluateObsidian(config, readDocumentsCode(paths))
+}
+
+export function validateActivePlanDocuments(config, documents) {
+ const byPath = new Map(documents.map((document) => [document.path, document]))
+ const errors = []
+ const warnings = []
+ let pairCount = 0
+
+ const supportedTypes = new Set([
+ 'active-plan',
+ 'active-plan-index',
+ 'plan-index',
+ ])
+ const identities = new Map()
+ const basenames = new Map()
+ for (const document of documents) {
+ try {
+ assertActivePlanMarkdownPath(config, document.path)
+ } catch (error) {
+ errors.push(error instanceof Error ? error.message : String(error))
+ }
+ const metadata = document.metadata ?? {}
+ if (!supportedTypes.has(metadata.document_type)) {
+ errors.push(`${document.path}: unsupported or missing document_type`)
+ }
+ if (metadata.language !== 'en' && metadata.language !== 'zh-CN') {
+ errors.push(`${document.path}: language must be en or zh-CN`)
+ }
+ if (typeof metadata.doc_id !== 'string' || metadata.doc_id.length === 0) {
+ errors.push(`${document.path}: missing doc_id`)
+ } else if (metadata.language === 'en' || metadata.language === 'zh-CN') {
+ const key = `${metadata.doc_id}\u0000${metadata.language}`
+ const previous = identities.get(key)
+ if (previous) {
+ errors.push(
+ `${document.path}: duplicate doc_id/language also used by ${previous}`
+ )
+ } else {
+ identities.set(key, document.path)
+ }
+ }
+ const basename = path.posix.basename(document.path)
+ const previousBasename = basenames.get(basename)
+ if (previousBasename) {
+ errors.push(
+ `${document.path}: duplicate basename also used by ${previousBasename}`
+ )
+ } else {
+ basenames.set(basename, document.path)
+ }
+ if (
+ (metadata.language === 'en' && document.path.endsWith('.zh-CN.md')) ||
+ (metadata.language === 'zh-CN' && !document.path.endsWith('.zh-CN.md'))
+ ) {
+ errors.push(`${document.path}: filename does not match language`)
+ }
+ }
+
+ const executable = documents.filter(
+ (document) => document.metadata?.document_type === 'active-plan'
+ )
+ for (const english of executable.filter(
+ (document) => document.metadata?.language === 'en'
+ )) {
+ try {
+ const pair = assertDocumentPair(config, byPath, english, 'activePlans')
+ pairCount += 1
+ errors.push(
+ ...validatePlanPair(pair.english, pair.chinese, {
+ repository: config.repository,
+ })
+ )
+ } catch (error) {
+ errors.push(error instanceof Error ? error.message : String(error))
+ }
+ if (OPEN_MIGRATION_STATUSES.has(english.metadata?.migration_status)) {
+ warnings.push(`${english.path}: migration_status is still open`)
+ }
+ }
+
+ for (const document of executable.filter(
+ (candidate) => candidate.metadata?.language === 'zh-CN'
+ )) {
+ const english = executable.find(
+ (candidate) =>
+ candidate.metadata?.language === 'en' &&
+ candidate.metadata?.doc_id === document.metadata?.doc_id
+ )
+ if (!english) errors.push(`${document.path}: English document not found`)
+ }
+ return {
+ documentCount: documents.length,
+ errors,
+ executableDocumentCount: executable.length,
+ indexDocumentCount: documents.length - executable.length,
+ pairCount,
+ warnings,
+ }
+}
+
+export function checkActivePlans(config) {
+ return validateActivePlanDocuments(config, readAllActivePlanDocuments(config))
+}
+
+export function updatePlanTask(config, options) {
+ if (!TASK_ID_PATTERN.test(options.taskId)) {
+ throw new Error(`Invalid task ID: ${options.taskId}`)
+ }
+ const bundle = readPlanBundle(config, options.planRef)
+ const gitState = getGitState(config)
+ const commit = options.done
+ ? resolveGitCommit(config, options.commitRef)
+ : gitState.head
+ const paths = [bundle.planPath, bundle.pairPath]
+ for (const vaultPath of paths) {
+ assertActivePlanMarkdownPath(config, vaultPath)
+ }
+
+ const code = `(async()=>{const paths=${JSON.stringify(
+ paths
+ )};const taskId=${JSON.stringify(options.taskId)};const done=${JSON.stringify(
+ options.done
+ )};const commit=${JSON.stringify(commit)};const branch=${JSON.stringify(
+ gitState.branch
+ )};const timestamp=${JSON.stringify(
+ new Date().toISOString()
+ )};const pattern=new RegExp(${JSON.stringify(
+ TASK_LINE_PATTERN.source
+ )});const parse=(content)=>content.split(/\\r?\\n/).map((text,index)=>{const match=pattern.exec(text);return match?{id:match[4],done:match[2].toLowerCase()==="x",index,text}:null}).filter(Boolean);const entries=[];for(const path of paths){const file=app.vault.getAbstractFileByPath(path);if(!file)throw new Error("Plan file not found: "+path);const content=await app.vault.cachedRead(file);const tasks=parse(content);if(tasks.filter(task=>task.id===taskId).length!==1)throw new Error(path+": expected exactly one "+taskId);entries.push({file,path,content,tasks})}const ids=entries.map(entry=>entry.tasks.map(task=>task.id).join("\\n"));const states=entries.map(entry=>entry.tasks.map(task=>String(task.done)).join("\\n"));if(new Set(ids).size!==1)throw new Error("Bilingual task ID order differs");if(new Set(states).size!==1)throw new Error("Bilingual task completion differs before update");const targetDone=entries[0].tasks.find(task=>task.id===taskId).done;if(targetDone===done)return JSON.stringify({changed:false,paths,taskId,done,commit,branch});try{for(const entry of entries){const lines=entry.content.split(/\\r?\\n/);const task=entry.tasks.find(candidate=>candidate.id===taskId);lines[task.index]=lines[task.index].replace(/^(\\s*-\\s+\\[)[ xX](\\])/,"$1"+(done?"x":" ")+"$2");await app.vault.modify(entry.file,lines.join("\\n"))}for(const entry of entries){const content=await app.vault.cachedRead(entry.file);const tasks=parse(content);const completed=tasks.filter(task=>task.done).length;const total=tasks.length;const next=tasks.find(task=>!task.done)?.id;const status=completed===0?"not-started":completed===total?"verification":"in-progress";await app.fileManager.processFrontMatter(entry.file,fm=>{fm.progress_completed=completed;fm.progress_total=total;fm.implementation_status=status;fm.last_progress_at=timestamp;fm.last_progress_head=commit;fm.work_branch=branch;if(next)fm.current_task=next;else delete fm.current_task;if(done){const commits=Array.isArray(fm.implementation_commits)?fm.implementation_commits:fm.implementation_commits?[String(fm.implementation_commits)]:[];if(!commits.includes(commit))commits.push(commit);fm.implementation_commits=commits}})}return JSON.stringify({changed:true,paths,taskId,done,commit,branch})}catch(error){for(const entry of entries){await app.vault.modify(entry.file,entry.content)}throw error}})()`
+ return evaluateObsidian(config, code)
+}
diff --git a/scripts/obsidian-docs.mjs b/scripts/obsidian-docs.mjs
new file mode 100644
index 00000000..baa90dca
--- /dev/null
+++ b/scripts/obsidian-docs.mjs
@@ -0,0 +1,250 @@
+#!/usr/bin/env node
+
+import path from 'node:path'
+import { pathToFileURL } from 'node:url'
+import {
+ checkActivePlans,
+ clearLocalContext,
+ getGitState,
+ listDocuments,
+ loadDocsConfig,
+ planSummary,
+ readPlanBundle,
+ resolvePlanReference,
+ runObsidian,
+ updatePlanTask,
+ writeLocalContext,
+} from './obsidian-docs-lib.mjs'
+
+const REPO_ROOT = path.resolve(import.meta.dirname, '..')
+
+export function parseArguments(argv) {
+ const positional = []
+ const options = {}
+ for (let index = 0; index < argv.length; index += 1) {
+ const argument = argv[index]
+ if (argument === '--') continue
+ if (!argument.startsWith('--')) {
+ positional.push(argument)
+ continue
+ }
+ const key = argument.slice(2)
+ const value = argv[index + 1]
+ if (!value || value.startsWith('--')) {
+ options[key] = true
+ } else {
+ options[key] = value
+ index += 1
+ }
+ }
+ return { options, positional }
+}
+
+function printHelp() {
+ console.log(`Motrix Obsidian documentation gateway
+
+Optional maintainer tooling. Copy obsidian-docs.config.example.json to the
+ignored obsidian-docs.config.json and customize it before using vault commands.
+
+Usage:
+ pnpm run docs:doctor
+ pnpm run docs:list -- plans|specs [--all] [--include-indexes]
+ pnpm run docs:use -- <plan-id>
+ pnpm run docs:clear
+ pnpm run docs:context -- [plan-id] [--format json]
+ pnpm run docs:status -- [plan-id] [--format json]
+ pnpm run docs:task -- done <task-id> [plan-id] --commit <git-ref>
+ pnpm run docs:task -- todo <task-id> [plan-id]
+ pnpm run docs:check -- [--format json]
+`)
+}
+
+function requireValue(value, label) {
+ if (!value) throw new Error(`${label} is required`)
+ return value
+}
+
+function formatDocumentTable(documents) {
+ const rows = documents.map((document) => [
+ document.id,
+ document.language,
+ document.lifecycle ?? '—',
+ document.implementation_status ?? '—',
+ document.path,
+ ])
+ return [
+ ['ID', 'Lang', 'Lifecycle', 'Status', 'Path'].join('\t'),
+ ...rows.map((row) => row.join('\t')),
+ ].join('\n')
+}
+
+function formatContext(bundle) {
+ return bundle.documents
+ .map(
+ (document) => `<!-- Obsidian: ${document.path} -->\n\n${document.content}`
+ )
+ .join('\n\n---\n\n')
+}
+
+function formatStatus(summary) {
+ const lines = [
+ `Plan: ${summary.id}`,
+ `Path: ${summary.path}`,
+ `Pair: ${summary.pairPath}`,
+ `Git: ${summary.branch}@${summary.head.slice(0, 8)}`,
+ `Verified head: ${summary.verifiedHead ?? '—'}`,
+ `Needs revalidation: ${summary.requiresRevalidation ? 'yes' : 'no'}`,
+ `Last progress head: ${summary.lastProgressHead ?? '—'}`,
+ `Status: ${summary.implementationStatus ?? '—'}`,
+ `Progress: ${summary.progress.completed}/${summary.progress.total}`,
+ `Current task: ${summary.progress.currentTask ?? 'verification'}`,
+ '',
+ ...summary.tasks.map(
+ (task) => `${task.done ? '[x]' : '[ ]'} ${task.id} ${task.description}`
+ ),
+ ]
+ return lines.join('\n')
+}
+
+export function main(argv = process.argv.slice(2)) {
+ const { options, positional } = parseArguments(argv)
+ const [command = 'help', ...args] = positional
+
+ if (command === 'help' || command === '--help') {
+ printHelp()
+ return
+ }
+ const config = loadDocsConfig(REPO_ROOT, options.config)
+ if (command === 'doctor') {
+ const version = runObsidian(config, ['version'])
+ const vault = runObsidian(config, ['vault', 'info=name'])
+ const projectFiles = runObsidian(config, [
+ 'folder',
+ `path=${config.projectRoot}`,
+ 'info=files',
+ ])
+ const git = getGitState(config)
+ console.log(
+ [
+ `Obsidian: ${version}`,
+ `Vault: ${vault}`,
+ `Project root: ${config.projectRoot}`,
+ `Project files: ${projectFiles}`,
+ `Repository: ${config.repository}`,
+ `Git: ${git.branch}@${git.head.slice(0, 8)}`,
+ ].join('\n')
+ )
+ return
+ }
+ if (command === 'list') {
+ const kind = requireValue(args[0], 'plans or specs')
+ let documents = listDocuments(config, kind)
+ if (kind === 'plans' && !options['include-indexes']) {
+ documents = documents.filter(
+ (document) => document.document_type === 'active-plan'
+ )
+ }
+ if (!options.all) {
+ documents = documents.filter((document) => document.language === 'en')
+ }
+ console.log(
+ options.format === 'json'
+ ? JSON.stringify(documents, null, 2)
+ : formatDocumentTable(documents)
+ )
+ return
+ }
+ if (command === 'use') {
+ const ref = requireValue(args[0], 'plan-id')
+ const bundle = readPlanBundle(config, ref)
+ const plan = bundle.documents.find(
+ (document) => document.path === bundle.planPath
+ )
+ if (!plan) throw new Error(`Plan not found in bundle: ${ref}`)
+ const context = writeLocalContext(config, {
+ id: plan.metadata.doc_id ?? path.basename(plan.path, '.md'),
+ path: plan.path,
+ })
+ console.log(`Selected ${context.planId}\nContext: ${config.contextFile}`)
+ return
+ }
+ if (command === 'clear') {
+ console.log(
+ clearLocalContext(config)
+ ? `Cleared ${config.contextFile}`
+ : `No local plan context was selected`
+ )
+ return
+ }
+ if (command === 'context') {
+ const ref = resolvePlanReference(config, args[0])
+ const bundle = readPlanBundle(config, ref, { includeRelated: true })
+ console.log(
+ options.format === 'json'
+ ? JSON.stringify(bundle, null, 2)
+ : formatContext(bundle)
+ )
+ return
+ }
+ if (command === 'status') {
+ const ref = resolvePlanReference(config, args[0])
+ const summary = planSummary(
+ readPlanBundle(config, ref),
+ getGitState(config)
+ )
+ console.log(
+ options.format === 'json'
+ ? JSON.stringify(summary, null, 2)
+ : formatStatus(summary)
+ )
+ return
+ }
+ if (command === 'task') {
+ const action = requireValue(args[0], 'task action')
+ const taskId = requireValue(args[1], 'task-id')
+ if (action !== 'done' && action !== 'todo') {
+ throw new Error('task action must be done or todo')
+ }
+ if (action === 'done' && typeof options.commit !== 'string') {
+ throw new Error('task done requires --commit <git-ref>')
+ }
+ const planRef = resolvePlanReference(config, args[2])
+ const result = updatePlanTask(config, {
+ commitRef: options.commit,
+ done: action === 'done',
+ planRef,
+ taskId,
+ })
+ console.log(JSON.stringify(result, null, 2))
+ return
+ }
+ if (command === 'check') {
+ const result = checkActivePlans(config)
+ if (options.format === 'json') {
+ console.log(JSON.stringify(result, null, 2))
+ } else {
+ console.log(
+ `Active plan pairs: ${result.pairCount}\nExecutable documents: ${result.executableDocumentCount}\nPlan indexes: ${result.indexDocumentCount}`
+ )
+ for (const warning of result.warnings) {
+ console.warn(`WARN: ${warning}`)
+ }
+ for (const error of result.errors) console.error(`ERROR: ${error}`)
+ }
+ if (result.errors.length > 0) process.exitCode = 1
+ return
+ }
+ throw new Error(`Unknown docs command: ${command}`)
+}
+
+if (
+ process.argv[1] &&
+ import.meta.url === pathToFileURL(process.argv[1]).href
+) {
+ try {
+ main()
+ } catch (error) {
+ console.error(error instanceof Error ? error.message : String(error))
+ process.exitCode = 1
+ }
+}
diff --git a/tests/scripts/docker-server-runtime.test.ts b/tests/scripts/docker-server-runtime.test.ts
index 045762c7..964d451b 100644
--- a/tests/scripts/docker-server-runtime.test.ts
+++ b/tests/scripts/docker-server-runtime.test.ts
@@ -119,6 +119,8 @@ describe('Docker Server runtime staging contract', () => {
'**/*.test.ts',
'**/*.test.tsx',
'obsidian-docs.config.json',
+ '.obsidian-doc-context.json',
+ '.obsidian-doc-context.json.tmp-*',
]) {
expect(dockerignore.split('\n')).toContain(entry)
}
diff --git a/tests/scripts/obsidian-docs.test.ts b/tests/scripts/obsidian-docs.test.ts
new file mode 100644
index 00000000..589cb9b6
--- /dev/null
+++ b/tests/scripts/obsidian-docs.test.ts
@@ -0,0 +1,357 @@
+import {
+ lstatSync,
+ mkdtempSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from 'node:fs'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+import { describe, expect, it } from 'vitest'
+// @ts-expect-error -- JavaScript documentation gateway has no declarations
+import { parseArguments } from '../../scripts/obsidian-docs.mjs'
+// @ts-expect-error -- JavaScript documentation gateway has no declarations
+import {
+ assertProjectMarkdownPath,
+ clearLocalContext,
+ deriveProgress,
+ loadDocsConfig,
+ parseEvalJson,
+ parseTaskLines,
+ projectPath,
+ readLocalContext,
+ selectPlanDocuments,
+ validateActivePlanDocuments,
+ validateDocsConfig,
+ validatePlanPair,
+ writeLocalContext,
+} from '../../scripts/obsidian-docs-lib.mjs'
+
+const config = {
+ version: 1,
+ vault: 'example-vault',
+ projectRoot: 'projects/example',
+ repository: 'Motrix',
+ contextFile: '.obsidian-doc-context.json',
+ commandTimeoutMs: 30_000,
+ directories: {
+ activeSpecs: '20-active-specs',
+ activePlans: '30-active-plans',
+ decisions: '40-decisions',
+ evidence: '50-evidence',
+ publication: '60-publication',
+ archivePlans: '90-archive/plans',
+ legacyImport: '90-legacy-import',
+ },
+}
+
+function planDocument(
+ documentPath: string,
+ language: 'en' | 'zh-CN',
+ content: string,
+ overrides: Record<string, unknown> = {}
+) {
+ return {
+ path: documentPath,
+ basename: path.posix.basename(documentPath, '.md'),
+ content,
+ metadata: {
+ doc_id: 'motrix.plan.sample',
+ document_type: 'active-plan',
+ language,
+ lifecycle: 'active',
+ implementation_status: 'in-progress',
+ current_task: 'DOC-02',
+ last_verified: '2026-08-11',
+ path_audit: 'reviewed-against-motrix',
+ pair_status: 'paired',
+ progress_completed: 1,
+ progress_schema: 'stable-task-ids-v1',
+ progress_total: 2,
+ verified_head: 'abc123',
+ verified_repository: 'Motrix',
+ bilingual_pair:
+ language === 'en'
+ ? '[[projects/example/30-active-plans/sample.zh-CN]]'
+ : '[[projects/example/30-active-plans/sample]]',
+ ...overrides,
+ },
+ }
+}
+
+function activePlanPair() {
+ const content = '- [x] [DOC-01] First\n- [ ] [DOC-02] Second'
+ const englishPath = 'projects/example/30-active-plans/sample.md'
+ const chinesePath = 'projects/example/30-active-plans/sample.zh-CN.md'
+ const english = planDocument(englishPath, 'en', content)
+ const chinese = planDocument(chinesePath, 'zh-CN', content)
+ return [
+ {
+ ...english,
+ pairPath: chinesePath,
+ relatedPaths: [],
+ },
+ {
+ ...chinese,
+ pairPath: englishPath,
+ relatedPaths: [],
+ },
+ ]
+}
+
+describe('Obsidian docs configuration', () => {
+ it('accepts a generic vault layout', () => {
+ expect(() => validateDocsConfig(config)).not.toThrow()
+ expect(projectPath(config, 'activePlans')).toBe(
+ 'projects/example/30-active-plans'
+ )
+ })
+
+ it('rejects traversal in configured and requested paths', () => {
+ expect(() =>
+ validateDocsConfig({
+ ...config,
+ directories: { ...config.directories, activePlans: '../plans' },
+ })
+ ).toThrow(/safe relative path/)
+ expect(() => assertProjectMarkdownPath(config, '../outside.md')).toThrow(
+ /safe relative path/
+ )
+ expect(() =>
+ assertProjectMarkdownPath(config, 'projects/other/plan.md')
+ ).toThrow(/must stay under/)
+ for (const unsafePath of [
+ '..\\outside.json',
+ 'C:\\outside.json',
+ '\\\\server\\share\\outside.json',
+ ]) {
+ expect(() =>
+ validateDocsConfig({ ...config, contextFile: unsafePath })
+ ).toThrow(/safe relative path/)
+ }
+ expect(() =>
+ validateDocsConfig({ ...config, contextFile: 'package.json' })
+ ).toThrow(/contextFile must be/)
+ })
+
+ it('explains how to create an optional local config', () => {
+ const repoRoot = mkdtempSync(path.join(tmpdir(), 'motrix-docs-'))
+ try {
+ expect(() => loadDocsConfig(repoRoot)).toThrow(
+ /obsidian-docs\.config\.example\.json/
+ )
+ } finally {
+ rmSync(repoRoot, { force: true, recursive: true })
+ }
+ })
+})
+
+describe('stable plan tasks', () => {
+ it('parses stable task IDs and derives progress', () => {
+ const parsed = parseTaskLines(`## Tasks
+
+- [x] [DOC-01] Add the gateway.
+- [ ] [DOC-02] Verify the gateway.
+`)
+ expect(parsed.duplicates).toEqual([])
+ expect(parsed.tasks).toEqual([
+ expect.objectContaining({ id: 'DOC-01', done: true, line: 3 }),
+ expect.objectContaining({ id: 'DOC-02', done: false, line: 4 }),
+ ])
+ expect(deriveProgress(parsed.tasks)).toEqual({
+ completed: 1,
+ currentTask: 'DOC-02',
+ implementationStatus: 'in-progress',
+ total: 2,
+ })
+ })
+
+ it('detects duplicate and bilingual task drift', () => {
+ const english = planDocument(
+ 'projects/example/30-active-plans/sample.md',
+ 'en',
+ '- [x] [DOC-01] First\n- [ ] [DOC-01] Duplicate'
+ )
+ const chinese = planDocument(
+ 'projects/example/30-active-plans/sample.zh-CN.md',
+ 'zh-CN',
+ '- [ ] [DOC-02] 第二项'
+ )
+ expect(validatePlanPair(english, chinese)).toEqual(
+ expect.arrayContaining([
+ expect.stringMatching(/duplicate task IDs DOC-01/),
+ expect.stringMatching(/task ID order differs/),
+ expect.stringMatching(/task completion differs/),
+ ])
+ )
+ })
+
+ it('detects stale frontmatter progress', () => {
+ const content = '- [x] [DOC-01] First\n- [x] [DOC-02] Second'
+ const english = planDocument(
+ 'projects/example/30-active-plans/sample.md',
+ 'en',
+ content
+ )
+ const chinese = planDocument(
+ 'projects/example/30-active-plans/sample.zh-CN.md',
+ 'zh-CN',
+ content
+ )
+ expect(validatePlanPair(english, chinese)).toEqual(
+ expect.arrayContaining([
+ expect.stringMatching(/progress_completed is stale/),
+ expect.stringMatching(/implementation_status is stale/),
+ ])
+ )
+ })
+})
+
+describe('CLI parsing', () => {
+ it('parses positional arguments and named values', () => {
+ expect(
+ parseArguments([
+ 'task',
+ 'done',
+ 'DOC-01',
+ '--commit',
+ 'HEAD',
+ '--format',
+ 'json',
+ ])
+ ).toEqual({
+ positional: ['task', 'done', 'DOC-01'],
+ options: { commit: 'HEAD', format: 'json' },
+ })
+ })
+
+ it('ignores the package-run separator forwarded by pnpm', () => {
+ expect(parseArguments(['status', '--', 'motrix.plan.sample'])).toEqual({
+ positional: ['status', 'motrix.plan.sample'],
+ options: {},
+ })
+ })
+
+ it('parses Obsidian eval output without exposing its prefix', () => {
+ expect(parseEvalJson('=> {"ok":true}\n')).toEqual({ ok: true })
+ expect(parseEvalJson('debug\n=> [1,2,3]\n')).toEqual([1, 2, 3])
+ expect(parseEvalJson('=> {"arrow":"a=>b"}\n')).toEqual({
+ arrow: 'a=>b',
+ })
+ })
+
+ it('stores the selected plan in checkout-local ignored state', () => {
+ const repoRoot = mkdtempSync(path.join(tmpdir(), 'motrix-docs-'))
+ try {
+ const localConfig = { ...config, repoRoot }
+ const written = writeLocalContext(localConfig, {
+ id: 'motrix.plan.sample',
+ path: 'projects/example/30-active-plans/sample.md',
+ })
+ expect(
+ lstatSync(path.join(repoRoot, config.contextFile)).mode & 0o077
+ ).toBe(0)
+ expect(readLocalContext(localConfig)).toEqual(written)
+ expect(clearLocalContext(localConfig)).toBe(true)
+ expect(readLocalContext(localConfig)).toBeUndefined()
+ expect(clearLocalContext(localConfig)).toBe(false)
+ } finally {
+ rmSync(repoRoot, { force: true, recursive: true })
+ }
+ })
+
+ it('refuses a symlinked local context file', () => {
+ const repoRoot = mkdtempSync(path.join(tmpdir(), 'motrix-docs-'))
+ const outside = path.join(repoRoot, 'outside.json')
+ try {
+ writeFileSync(outside, '{"safe":true}\n')
+ symlinkSync(outside, path.join(repoRoot, config.contextFile))
+ const localConfig = { ...config, repoRoot }
+ expect(() =>
+ writeLocalContext(localConfig, {
+ id: 'example.plan.sample',
+ path: 'projects/example/30-active-plans/sample.md',
+ })
+ ).toThrow(/symlink/)
+ expect(() => clearLocalContext(localConfig)).toThrow(/symlink/)
+ } finally {
+ rmSync(repoRoot, { force: true, recursive: true })
+ }
+ })
+})
+
+describe('plan selection security', () => {
+ it('selects one validated bilingual plan pair', () => {
+ const index = activePlanPair()
+ expect(selectPlanDocuments(config, index, 'motrix.plan.sample')).toEqual({
+ pairPath: 'projects/example/30-active-plans/sample.zh-CN.md',
+ paths: [
+ 'projects/example/30-active-plans/sample.md',
+ 'projects/example/30-active-plans/sample.zh-CN.md',
+ ],
+ planPath: 'projects/example/30-active-plans/sample.md',
+ })
+ })
+
+ it('rejects ambiguous IDs and pairs outside the active-plan root', () => {
+ const index = activePlanPair()
+ const duplicate = activePlanPair().map((document) => ({
+ ...document,
+ path: document.path.replace('sample', 'second'),
+ basename: document.basename.replace('sample', 'second'),
+ pairPath: document.pairPath.replace('sample', 'second'),
+ metadata: {
+ ...document.metadata,
+ bilingual_pair: String(document.metadata.bilingual_pair).replace(
+ 'sample',
+ 'second'
+ ),
+ },
+ }))
+ expect(() =>
+ selectPlanDocuments(
+ config,
+ [...index, ...duplicate],
+ 'motrix.plan.sample'
+ )
+ ).toThrow(/Ambiguous/)
+
+ const unsafe = activePlanPair()
+ unsafe[1] = {
+ ...unsafe[1],
+ path: 'projects/example/40-decisions/sample.zh-CN.md',
+ pairPath: unsafe[0].path,
+ }
+ unsafe[0] = { ...unsafe[0], pairPath: unsafe[1].path }
+ expect(() =>
+ selectPlanDocuments(config, unsafe, 'motrix.plan.sample')
+ ).toThrow(/leaves its directory/)
+ })
+
+ it('reports missing metadata, duplicate identities, and invalid pairs', () => {
+ const pair = activePlanPair()
+ const invalid = {
+ ...pair[0],
+ path: 'projects/example/30-active-plans/invalid.md',
+ metadata: {},
+ }
+ const duplicate = {
+ ...pair[0],
+ path: 'projects/example/30-active-plans/duplicate.md',
+ basename: 'duplicate',
+ }
+ const result = validateActivePlanDocuments(config, [
+ ...pair,
+ invalid,
+ duplicate,
+ ])
+ expect(result.errors).toEqual(
+ expect.arrayContaining([
+ expect.stringMatching(/unsupported or missing document_type/),
+ expect.stringMatching(/language must be en or zh-CN/),
+ expect.stringMatching(/missing doc_id/),
+ expect.stringMatching(/duplicate doc_id\/language/),
+ ])
+ )
+ })
+})