@daogee/mdgraph 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +30 -1
  2. package/README-ZH.md +12 -2
  3. package/README.md +12 -2
  4. package/agent-pack/README.md +2 -0
  5. package/agent-pack/mdgraph-agent-instructions.md +3 -1
  6. package/agent-pack/prompts/wiki-authoring.md +12 -0
  7. package/agent-pack/skills/wiki-authoring/SKILL.md +38 -0
  8. package/agent-pack/skills/wiki-authoring/agents/openai.yaml +4 -0
  9. package/dist/analysis/status-freshness.d.ts +8 -1
  10. package/dist/analysis/status-freshness.js +19 -6
  11. package/dist/bin/mdgraph.js +124 -6
  12. package/dist/db/connection.js +17 -1
  13. package/dist/db/repositories.d.ts +28 -4
  14. package/dist/db/repositories.js +148 -5
  15. package/dist/db/sqlite-adapter.js +8 -2
  16. package/dist/evaluation/retrieval-eval.d.ts +11 -0
  17. package/dist/evaluation/retrieval-eval.js +35 -1
  18. package/dist/index.d.ts +7 -0
  19. package/dist/index.js +3 -0
  20. package/dist/indexer.js +64 -6
  21. package/dist/mcp/server.js +5 -4
  22. package/dist/mcp/tools.js +23 -9
  23. package/dist/query/context-builder.d.ts +1 -0
  24. package/dist/query/context-builder.js +30 -1
  25. package/dist/query/knowledge-card.d.ts +90 -0
  26. package/dist/query/knowledge-card.js +676 -0
  27. package/dist/query/search.js +8 -3
  28. package/dist/semantic/ollama-provider.js +6 -1
  29. package/dist/utils/path-safety.d.ts +3 -0
  30. package/dist/utils/path-safety.js +27 -0
  31. package/dist/watcher/file-watcher.js +85 -16
  32. package/dist/wiki/wiki-dependencies.d.ts +20 -0
  33. package/dist/wiki/wiki-dependencies.js +45 -0
  34. package/dist/wiki/wiki-domains.d.ts +13 -0
  35. package/dist/wiki/wiki-domains.js +55 -0
  36. package/dist/wiki/wiki-evidence.d.ts +27 -0
  37. package/dist/wiki/wiki-evidence.js +112 -0
  38. package/dist/wiki/wiki-plan.d.ts +121 -0
  39. package/dist/wiki/wiki-plan.js +616 -0
  40. package/dist/wiki/wiki-status.d.ts +67 -0
  41. package/dist/wiki/wiki-status.js +451 -0
  42. package/docs/EN/Agent_Integration.md +14 -4
  43. package/docs/EN/Architecture.md +13 -0
  44. package/docs/EN/Evaluation_Questions.md +14 -0
  45. package/docs/EN/Knowledge_Cards_and_Wiki_Workflow.md +97 -0
  46. package/docs/EN/Operations.md +20 -0
  47. package/docs/EN/Output_Contracts.md +42 -3
  48. package/docs/EN/Public_Contracts.md +3 -1
  49. package/docs/EN/Public_Contracts_1.0.md +4 -0
  50. package/docs/EN/README.md +1 -0
  51. package/docs/EN/Release_Checklist.md +1 -0
  52. package/docs/EN/Retrieval_and_Context.md +6 -0
  53. package/docs/ZH/Agent_Integration.md +14 -4
  54. package/docs/ZH/Architecture.md +13 -2
  55. package/docs/ZH/Evaluation_Questions.md +14 -0
  56. package/docs/ZH/Knowledge_Cards_and_Wiki_Workflow.md +99 -0
  57. package/docs/ZH/Operations.md +20 -0
  58. package/docs/ZH/Output_Contracts.md +42 -3
  59. package/docs/ZH/Public_Contracts.md +3 -1
  60. package/docs/ZH/Public_Contracts_1.0.md +4 -0
  61. package/docs/ZH/README.md +1 -0
  62. package/docs/ZH/Release_Checklist.md +1 -0
  63. package/docs/ZH/Retrieval_and_Context.md +6 -0
  64. package/package.json +7 -2
package/CHANGELOG.md CHANGED
@@ -2,7 +2,36 @@
2
2
 
3
3
  All notable changes to MDGraph are documented here. MDGraph follows semantic versioning for its public releases.
4
4
 
5
- ## Unreleased
5
+ ## 1.2.0 - 2026-09-12
6
+
7
+ ### Added
8
+
9
+ - Experimental deterministic Knowledge Cards on `node` plus spare-budget Card summaries in `context`.
10
+ - Experimental `wiki plan/brief/status/verify` commands for evidence-backed user-maintained Wiki planning, impact status, and read-only verification.
11
+ - A reusable Wiki authoring prompt/skill without changing the five-tool MCP surface or adding a generation provider.
12
+ - Returned-evidence retrieval metrics alongside unchanged legacy index-coverage metrics, plus a reproducible performance sampling script.
13
+ - CI coverage for Node 22 and 26 and early SQLite compatibility; packaged CLI checks for cards and Wiki briefs.
14
+
15
+ ### Changed
16
+
17
+ - Knowledge Cards distinguish direct, inherited, and related evidence, preserve source ownership, and provide bounded next-read paths.
18
+ - WikiPlan v2 preserves authored page selections during updates, records the output directory and dependency snapshots, and separates suggested pages/sources from selected evidence. Version 1 plans remain readable.
19
+ - Wiki briefs and status share dependency assessment, explain unavailable or changed sources, and preserve user-selected references during review. Verification explicitly reports that prose correctness is not evaluated.
20
+
21
+ ### Fixed
22
+
23
+ - Enforce real served-project boundaries for MCP roots and SQLite/configuration paths, including symbolic links.
24
+ - Apply embedding deadlines through complete response bodies and retain lexical fallback and existing indexes on failure.
25
+ - Reconcile incremental graph relationships and extraction settings, reuse matching vectors, detect concurrent index commits, and reload watcher configuration without dropping the previous watch.
26
+ - Match complete Chinese/entity/configuration-key queries and retain definition evidence; enforce serialized Knowledge Card budgets.
27
+ - Verify Wiki evidence against current Markdown hashes and validate maintenance field types.
28
+ - Normalize early node:sqlite empty-row behavior and provide actionable recovery when FTS5 is unavailable.
29
+ - Update test dependencies to audited Vitest and nanoid versions so the release workflow reports no known vulnerabilities.
30
+
31
+ ### Compatibility
32
+
33
+ - Deterministic indexing, the default context-packing strategy, stable `search`, the five-tool MCP surface, schema version 1, and the public `alpha | cjk` evaluation query-set enum remain unchanged.
34
+ - Supported Node.js builds must provide FTS5 through `node:sqlite`; Node 22.23.2 and 26.5.0 are verified.
6
35
 
7
36
  ## 1.1.0 - 2026-08-03
8
37
 
package/README-ZH.md CHANGED
@@ -8,7 +8,7 @@
8
8
 
9
9
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
10
10
  [![CI](https://github.com/daoGEE/mdgraph/actions/workflows/ci.yml/badge.svg)](https://github.com/daoGEE/mdgraph/actions/workflows/ci.yml)
11
- [![Node](https://img.shields.io/badge/Node-%3E%3D22.5.0-brightgreen.svg)](https://nodejs.org/)
11
+ [![Node](https://img.shields.io/badge/Node-22%2B%20with%20FTS5-brightgreen.svg)](https://nodejs.org/)
12
12
  [![Release](https://img.shields.io/github/v/release/daoGEE/mdgraph?include_prereleases&label=release)](https://github.com/daoGEE/mdgraph/releases)
13
13
 
14
14
  <a href="./README.md">English</a> · <a href="./docs/ZH/README.md">文档</a> · <a href="./docs/ZH/Architecture.md">架构说明</a> · <a href="./docs/ZH/Agent_Integration.md">Agent 集成</a> · <a href="./docs/ZH/Public_Contracts.md">公开契约</a>
@@ -136,6 +136,12 @@ mdgraph query --path /your/project 'type:adr AND status:accepted ORDER BY update
136
136
  mdgraph relationships derive --dry-run --json --path /your/project
137
137
  mdgraph relationships derive --threshold 0.86 --json --path /your/project
138
138
 
139
+ # 实验性的用户维护 Wiki 工作流
140
+ mdgraph wiki plan --out .mdgraph/wiki-plan.json --path /your/project
141
+ mdgraph wiki brief architecture --plan .mdgraph/wiki-plan.json --json --path /your/project
142
+ mdgraph wiki status wiki --plan .mdgraph/wiki-plan.json --json --path /your/project
143
+ mdgraph wiki verify wiki --plan .mdgraph/wiki-plan.json --json --path /your/project
144
+
139
145
  # Agent 友好的使用指引
140
146
  mdgraph usage --path /your/project
141
147
  ```
@@ -148,6 +154,10 @@ mdgraph usage --path /your/project
148
154
 
149
155
  实验性的 `relationships derive` 只会基于 fresh、完整的 semantic-model index,在独立 evidence 与 reciprocal-neighbor 门禁通过后创建低权重 `RELATED_TO` edge;它不会在 indexing 或 watch mode 中自动运行。两个实验性工作流均记录在[结构化查询与派生关系](./docs/ZH/Structured_Query_and_Relationships.md)。
150
156
 
157
+ 实验性的 `wiki` group 会确定性规划页面、准备有界证据 brief、报告更新影响,并验证维护字段、source 和相对链接。MDGraph 不生成或覆盖 Wiki 正文;宿主 Agent 工作流见 [Knowledge Card 与 Wiki 工作流](./docs/ZH/Knowledge_Cards_and_Wiki_Workflow.md)。
158
+
159
+ 更新已有 Wiki 计划时,使用 `mdgraph wiki plan --from <plan> --out <next-plan> --path <project>` 保留人工调整的页面。迁移 v1 计划时增加 `--wiki-dir wiki`。新计划使用 v2,新增页面和来源需审视后采纳。`current` 表示依赖一致,`wiki verify` 不判断正文是否正确。
160
+
151
161
  ---
152
162
 
153
163
  ## 可选 Ollama Embedding
@@ -222,7 +232,7 @@ mdgraph search --semantic --path /your/project "authentication login"
222
232
 
223
233
  ## 环境要求
224
234
 
225
- - Node.js `>=22.5.0`
235
+ - Node.js `>=22.5.0`,且内置 `node:sqlite` 启用了 FTS5。已验证 22.23.2 和 26.5.0;仅满足版本号不保证具备 FTS5,请使用当前 Node 22 或更新发行版。
226
236
  - Node 内置 `node:sqlite` 支持
227
237
  - 本地项目目录中的 Markdown 文件
228
238
 
package/README.md CHANGED
@@ -8,7 +8,7 @@
8
8
 
9
9
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
10
10
  [![CI](https://github.com/daoGEE/mdgraph/actions/workflows/ci.yml/badge.svg)](https://github.com/daoGEE/mdgraph/actions/workflows/ci.yml)
11
- [![Node](https://img.shields.io/badge/Node-%3E%3D22.5.0-brightgreen.svg)](https://nodejs.org/)
11
+ [![Node](https://img.shields.io/badge/Node-22%2B%20with%20FTS5-brightgreen.svg)](https://nodejs.org/)
12
12
  [![Release](https://img.shields.io/github/v/release/daoGEE/mdgraph?include_prereleases&label=release)](https://github.com/daoGEE/mdgraph/releases)
13
13
 
14
14
  <a href="./README-ZH.md">简体中文</a> · <a href="./docs/EN/README.md">Documentation</a> · <a href="./docs/EN/Architecture.md">Architecture</a> · <a href="./docs/EN/Agent_Integration.md">Agent Integration</a> · <a href="./docs/EN/Public_Contracts.md">Public Contracts</a>
@@ -136,6 +136,12 @@ mdgraph query --path /your/project 'type:adr AND status:accepted ORDER BY update
136
136
  mdgraph relationships derive --dry-run --json --path /your/project
137
137
  mdgraph relationships derive --threshold 0.86 --json --path /your/project
138
138
 
139
+ # Experimental user-maintained Wiki workflow
140
+ mdgraph wiki plan --out .mdgraph/wiki-plan.json --path /your/project
141
+ mdgraph wiki brief architecture --plan .mdgraph/wiki-plan.json --json --path /your/project
142
+ mdgraph wiki status wiki --plan .mdgraph/wiki-plan.json --json --path /your/project
143
+ mdgraph wiki verify wiki --plan .mdgraph/wiki-plan.json --json --path /your/project
144
+
139
145
  # Agent-friendly workflow guide
140
146
  mdgraph usage --path /your/project
141
147
  ```
@@ -147,6 +153,10 @@ True MMR packing is opt-in; document round-robin remains the compatibility defau
147
153
  The experimental `query` command provides a bounded, parameterized DSL for document governance without changing `search` or the five-tool MCP surface.
148
154
 
149
155
  The experimental `relationships derive` command creates low-weight `RELATED_TO` edges only from a fresh, complete semantic-model index after independent-evidence and reciprocal-neighbor gates pass. It never runs automatically during indexing or watch mode. Both experimental workflows are documented in [Structured Query and Relationships](./docs/EN/Structured_Query_and_Relationships.md).
156
+
157
+ The experimental `wiki` group deterministically plans pages, prepares bounded evidence briefs, reports update impact, and verifies maintenance fields, sources, and relative links. MDGraph does not generate or overwrite Wiki prose; use the host-agent workflow in [Knowledge Cards and Wiki Workflow](./docs/EN/Knowledge_Cards_and_Wiki_Workflow.md).
158
+
159
+ To preserve a Wiki plan's authored pages while refreshing its evidence, use `mdgraph wiki plan --from <plan> --out <next-plan> --path <project>`. Add `--wiki-dir wiki` when migrating a v1 plan. New plans use v2; review suggestions before adopting them. `current` describes dependency consistency, and `wiki verify` does not evaluate prose correctness.
150
160
 
151
161
  ---
152
162
 
@@ -222,7 +232,7 @@ Query-time provider failures fall back to FTS5/entity/graph results and emit a d
222
232
 
223
233
  ## Requirements
224
234
 
225
- - Node.js `>=22.5.0`
235
+ - Node.js `>=22.5.0` with an FTS5-enabled `node:sqlite` build. Node 22.23.2 and 26.5.0 are verified; the version number alone does not guarantee FTS5. Use a current Node 22 or newer release.
226
236
  - SQLite support from Node's built-in `node:sqlite`
227
237
  - Markdown files in a local project directory
228
238
 
@@ -10,6 +10,8 @@ This pack contains reusable guidance for MCP-capable coding agents. It keeps hos
10
10
  - [`prompts/task-start-context.md`](prompts/task-start-context.md): prompt template for task-start documentation briefs.
11
11
  - [`prompts/relationship-trace.md`](prompts/relationship-trace.md): prompt template for relationship and dependency questions.
12
12
  - [`prompts/status-doctor.md`](prompts/status-doctor.md): prompt template for readiness, stale-index, and documentation health checks.
13
+ - [`prompts/wiki-authoring.md`](prompts/wiki-authoring.md): prompt template for evidence-backed Wiki page creation and maintenance.
14
+ - [`skills/wiki-authoring/SKILL.md`](skills/wiki-authoring/SKILL.md): reusable skill for WikiPlan, per-page brief, status, and verification workflows.
13
15
 
14
16
  ## Host Placement
15
17
 
@@ -18,4 +18,6 @@ Default order for Markdown/documentation questions:
18
18
  - Prefer returned context when it includes enough content, reasons, provenance, source refs, and risk notes.
19
19
  - Fall back to normal file reads when MDGraph is inactive, stale for the task, too sparse, or when exact source text is required.
20
20
 
21
- Do not treat MDGraph as hidden memory, a source AST index, or an authority beyond the indexed Markdown corpus. Do not create or update an index unless the user asks for it.
21
+ Do not treat MDGraph as hidden memory, a source AST index, or an authority beyond the indexed Markdown corpus. Do not create or update an index unless the user asks for it.
22
+
23
+ See the [Agent Integration guide](../docs/EN/Agent_Integration.md) for the shared setup and host-specific placement notes.
@@ -0,0 +1,12 @@
1
+ # Create or update a project Wiki
2
+
3
+ Use MDGraph to prepare evidence, then author the Markdown after reading the sources.
4
+
5
+ 1. Check the index and existing Wiki status. Refresh stale evidence within the requested maintenance scope.
6
+ 2. Create a plan or preserve an existing one with `wiki plan --from <plan> --out <next-plan>`. Specify `--wiki-dir` for v1 migration. Review suggested pages, sources, and gaps before adopting changes.
7
+ 3. For each affected page, obtain `wiki brief`. Use the primary documents, supplementary material, source inspection paths, and Card ownership labels. Resolve stale or unknown evidence before accepting its hash.
8
+ 4. Preserve correct prose and selected sources. Update `wiki_id`, `evidence_hash`, `source_docs`, and `source_refs` from the reviewed plan. Both source fields are arrays; additional author-selected sources should be added to the plan instead of silently removed.
9
+ 5. Run `wiki verify`; fix the affected page's maintenance, link, and evidence issues. Do not delete orphaned pages automatically.
10
+ 6. Execute the key documented user steps and record the revision, commands, results, and limitations separately. Verification does not evaluate prose correctness.
11
+
12
+ See the [Knowledge Cards and Wiki Workflow](../../docs/EN/Knowledge_Cards_and_Wiki_Workflow.md) guide and the [reusable Wiki authoring skill](../skills/wiki-authoring/SKILL.md) for the full maintenance contract.
@@ -0,0 +1,38 @@
1
+ ---
2
+ name: wiki-authoring
3
+ description: Author or update a user-maintained project Wiki from MDGraph plans and page evidence. Use for project handbook creation and maintenance.
4
+ ---
5
+
6
+ # Wiki Authoring
7
+
8
+ MDGraph locates evidence and reports dependency changes. The host agent reads source material and writes the prose.
9
+
10
+ ## Workflow
11
+
12
+ 1. Check index availability and refresh stale Markdown evidence within the user's requested maintenance scope.
13
+ 2. For a new Wiki, run `mdgraph wiki plan --wiki-dir <wiki-dir> --out <plan-file> --path <project>`. For an existing Wiki, first run `wiki status <wiki-dir> --plan <plan-file> --json --path <project>`.
14
+ 3. Update an existing plan with `wiki plan --from <plan-file> --out <next-plan> --path <project>`. Add `--wiki-dir <wiki-dir>` when migrating a v1 plan. Review suggestions and gaps. Keep stable page IDs, user-authored goals, outlines, and source selections. Explicitly adopt useful suggested pages/sources before refreshing the plan. Preserve the previous file for recovery.
15
+ 4. Run `wiki brief <page-id> --plan <reviewed-plan> --json --path <project>` for each affected page. Inspect `strictFreshness`, `dependencyEvidence`, and `evidenceGaps`. A stale or unknown brief can be read, but its evidence hash must not be treated as current.
16
+ 5. Read `sourceDocuments` as the selected primary material. Use `supplementaryDocuments` for additional context and perform the listed `sourceInspections` before making implementation claims. Card association distinguishes direct evidence, inherited context, and related background.
17
+ 6. Preserve correct existing prose. Update only affected pages unless the user asks for a broader rewrite. Maintain:
18
+
19
+ ```yaml
20
+ ---
21
+ wiki_id: <page-id>
22
+ evidence_hash: <hash from the current reviewed brief>
23
+ source_docs:
24
+ - <project-relative-markdown-path>
25
+ source_refs:
26
+ - <project-relative-source-path>
27
+ ---
28
+ ```
29
+
30
+ Both source fields are arrays; use `[]` when empty. If the author needs additional sources, add them to the plan's selected dependencies and refresh its evidence before synchronizing the page. Do not discard user-selected references merely to make verification pass.
31
+ 7. Run `wiki verify <wiki-dir> --plan <reviewed-plan> --json --path <project>`. Repair issues attributable to the current page and preserve unrelated pages. Review orphaned pages without automatically deleting them.
32
+ 8. Separately check prose correctness: execute the key documented workflow, inspect supporting source, and record commands, outcomes, the code revision, and unverified claims. `current` and `valid: true` describe dependency/maintenance consistency; they do not prove prose accuracy.
33
+
34
+ ## Recovery
35
+
36
+ Restore the previous plan or page copy if an update is unsuitable. For changed dependencies, refresh the index and plan, then obtain a new brief. For unavailable paths, inspect the reported source and restore it or explicitly revise the selection. Keep Wiki output outside its own source evidence.
37
+
38
+ The workflow remains usable without embeddings, a Source Bridge, or a generation provider. MDGraph commands never generate or overwrite Wiki prose.
@@ -0,0 +1,4 @@
1
+ interface:
2
+ display_name: "Wiki Authoring"
3
+ short_description: "Author evidence-backed MDGraph Wiki pages"
4
+ default_prompt: "Use $wiki-authoring to create or update the planned project Wiki pages from current evidence."
@@ -10,4 +10,11 @@ export interface StatusFreshness {
10
10
  reason: "added" | "deleted" | "modified";
11
11
  }>;
12
12
  }
13
- export declare function computeStatusFreshness(projectRoot: string, config: MDGraphConfig, repository: GraphRepository): StatusFreshness;
13
+ export interface StatusFreshnessOptions {
14
+ /** Compare Markdown bytes with the indexed document hashes. This detects edits
15
+ * whose mtime was intentionally preserved; the default remains the cheap mtime check. */
16
+ strictContentHash?: boolean;
17
+ /** Project-relative Markdown paths outside the source snapshot being evaluated. */
18
+ ignorePaths?: string[];
19
+ }
20
+ export declare function computeStatusFreshness(projectRoot: string, config: MDGraphConfig, repository: GraphRepository, options?: StatusFreshnessOptions): StatusFreshness;
@@ -1,8 +1,9 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { scanMarkdownFilesSync } from "../scanner/file-scanner.js";
4
+ import { contentHash } from "../utils/id.js";
4
5
  import { normalizePath } from "../utils/text.js";
5
- export function computeStatusFreshness(projectRoot, config, repository) {
6
+ export function computeStatusFreshness(projectRoot, config, repository, options = {}) {
6
7
  const lastIndexedAt = repository.latestIndexedAt();
7
8
  const checkedAt = new Date().toISOString();
8
9
  if (!lastIndexedAt) {
@@ -16,19 +17,26 @@ export function computeStatusFreshness(projectRoot, config, repository) {
16
17
  const indexedAtMs = Date.parse(lastIndexedAt);
17
18
  const scanned = scanMarkdownFilesSync(projectRoot, config);
18
19
  const indexed = repository.documentHashes();
19
- const scannedByPath = new Map(scanned.map((filePath) => [normalizePath(path.relative(projectRoot, filePath)), filePath]));
20
+ const ignored = new Set((options.ignorePaths ?? []).map(normalizePath));
21
+ const isIgnored = (relativePath) => [...ignored].some((ignoredPath) => relativePath === ignoredPath || relativePath.startsWith(`${ignoredPath}/`));
22
+ const scannedByPath = new Map(scanned
23
+ .map((filePath) => [normalizePath(path.relative(projectRoot, filePath)), filePath])
24
+ .filter(([relativePath]) => !isIgnored(relativePath)));
20
25
  const issues = [];
21
26
  for (const [relativePath, absolutePath] of scannedByPath) {
22
27
  if (!indexed.has(relativePath)) {
23
28
  issues.push({ path: relativePath, reason: "added" });
24
29
  continue;
25
30
  }
26
- if (Number.isFinite(indexedAtMs) && fs.statSync(absolutePath).mtimeMs > indexedAtMs + 1) {
31
+ const changed = options.strictContentHash
32
+ ? contentHash(fs.readFileSync(absolutePath, "utf8")) !== indexed.get(relativePath).hash
33
+ : Number.isFinite(indexedAtMs) && fs.statSync(absolutePath).mtimeMs > indexedAtMs + 1;
34
+ if (changed) {
27
35
  issues.push({ path: relativePath, reason: "modified" });
28
36
  }
29
37
  }
30
38
  for (const documentPath of indexed.keys()) {
31
- if (!scannedByPath.has(documentPath)) {
39
+ if (!isIgnored(documentPath) && !scannedByPath.has(documentPath)) {
32
40
  issues.push({ path: documentPath, reason: "deleted" });
33
41
  }
34
42
  }
@@ -39,8 +47,13 @@ export function computeStatusFreshness(projectRoot, config, repository) {
39
47
  checkedAt,
40
48
  recommendation: sortedIssues.length
41
49
  ? "Markdown files changed since indexing; run `mdgraph index` before relying on results"
42
- : "indexed Markdown files match the lightweight status freshness check",
43
- issues: sortedIssues.length ? sortedIssues.slice(0, 20) : undefined
50
+ : options.strictContentHash
51
+ ? "indexed Markdown files match the strict content-hash freshness check"
52
+ : "indexed Markdown files match the lightweight status freshness check",
53
+ // Strict callers make policy decisions from this list (for example, which
54
+ // Wiki pages depend on a changed document), so never truncate their evidence.
55
+ // Existing lightweight status callers retain the bounded public payload.
56
+ issues: sortedIssues.length ? (options.strictContentHash ? sortedIssues : sortedIssues.slice(0, 20)) : undefined
44
57
  };
45
58
  }
46
59
  catch (error) {
@@ -19,6 +19,7 @@ import { indexProject } from "../indexer.js";
19
19
  import { startStdioMcpServer } from "../mcp/server.js";
20
20
  import { CONTEXT_PACKING_STRATEGIES, buildContextAsync } from "../query/context-builder.js";
21
21
  import { explainSearchGraphAsync } from "../query/search.js";
22
+ import { buildKnowledgeCard, formatKnowledgeCard } from "../query/knowledge-card.js";
22
23
  import { traceNodes } from "../query/trace.js";
23
24
  import { executeStructuredQuery } from "../query/structured-query-executor.js";
24
25
  import { deriveRelatedRelationships } from "../relationships/derive-related.js";
@@ -26,6 +27,8 @@ import { formatReport, generateReport } from "../reporting/report.js";
26
27
  import { semanticStatusReportAsync } from "../semantic/status.js";
27
28
  import { packageVersion } from "../version.js";
28
29
  import { watchProject } from "../watcher/file-watcher.js";
30
+ import { buildWikiPageBrief, buildWikiPlan, formatWikiPageBrief, formatWikiPlan, readWikiPlan, writeWikiPlan } from "../wiki/wiki-plan.js";
31
+ import { buildWikiStatus, formatWikiStatus, formatWikiVerification, verifyWiki } from "../wiki/wiki-status.js";
29
32
  const program = new Command();
30
33
  program
31
34
  .name("mdgraph")
@@ -183,7 +186,8 @@ program
183
186
  const repository = openRepository(projectRootFromOption(options.path));
184
187
  try {
185
188
  const resolution = repository.resolveNodeDetailed(query);
186
- printResult(options.json, nodeResolutionJson(resolution), formatNodeResolution(resolution));
189
+ const card = resolution.status === "found" ? buildKnowledgeCard(repository, resolution.node) : undefined;
190
+ printResult(options.json, nodeResolutionJson(resolution, card), formatNodeResolution(resolution, card));
187
191
  }
188
192
  finally {
189
193
  closeRepository(repository);
@@ -284,6 +288,100 @@ relationshipsCommand
284
288
  closeRepository(repository);
285
289
  }
286
290
  });
291
+ const wikiCommand = program
292
+ .command("wiki")
293
+ .description("Plan, brief, inspect, and verify a user-maintained project Wiki");
294
+ wikiCommand
295
+ .command("plan")
296
+ .description("Create a deterministic WikiPlan without generating page prose")
297
+ .requiredOption("--out <file>", "WikiPlan JSON output path")
298
+ .option("--from <file>", "Preserve authored pages from an existing plan and suggest new evidence")
299
+ .option("--wiki-dir <dir>", "Project-relative Wiki output directory (required when migrating a v1 plan)")
300
+ .option("--json", "Print JSON output")
301
+ .option("--path <path>", "Project root. Defaults to the current working directory")
302
+ .action((options) => {
303
+ const projectRoot = projectRootFromOption(options.path);
304
+ const out = resolveProjectArtifactPath(projectRoot, options.out);
305
+ const fromPath = options.from ? resolveProjectArtifactPath(projectRoot, options.from) : undefined;
306
+ if (fromPath && out === fromPath) {
307
+ throw new Error("Choose a different --out path when updating a plan with --from; review the new plan before replacing the original.");
308
+ }
309
+ const from = fromPath ? readWikiPlan(fromPath) : undefined;
310
+ const repository = openRepository(projectRoot);
311
+ try {
312
+ const plan = buildWikiPlan(projectRoot, repository, { from, wikiDir: options.wikiDir });
313
+ writeWikiPlan(out, plan);
314
+ printResult(options.json, { out, plan }, [`Wrote Wiki plan: ${out}`, formatWikiPlan(plan)].join("\n"));
315
+ }
316
+ finally {
317
+ closeRepository(repository);
318
+ }
319
+ });
320
+ wikiCommand
321
+ .command("brief")
322
+ .description("Build an evidence-bounded brief for one planned Wiki page")
323
+ .argument("<page-id>")
324
+ .requiredOption("--plan <file>", "WikiPlan JSON path")
325
+ .option("--json", "Print JSON output")
326
+ .option("--max-chars <number>", "Maximum context and Knowledge Card characters", parseInteger)
327
+ .option("--path <path>", "Project root. Defaults to the current working directory")
328
+ .action((pageId, options) => {
329
+ const projectRoot = projectRootFromOption(options.path);
330
+ const planPath = resolveProjectArtifactPath(projectRoot, options.plan);
331
+ const plan = readWikiPlan(planPath);
332
+ const config = loadConfig(projectRoot);
333
+ const repository = openRepository(projectRoot);
334
+ try {
335
+ const brief = buildWikiPageBrief(projectRoot, repository, config, plan, pageId, { maxChars: options.maxChars });
336
+ printResult(options.json, brief, formatWikiPageBrief(brief));
337
+ }
338
+ finally {
339
+ closeRepository(repository);
340
+ }
341
+ });
342
+ wikiCommand
343
+ .command("status")
344
+ .description("Report current, needs-update, missing, and orphaned Wiki pages without modifying them")
345
+ .argument("<wiki-dir>")
346
+ .requiredOption("--plan <file>", "WikiPlan JSON path")
347
+ .option("--json", "Print JSON output")
348
+ .option("--path <path>", "Project root. Defaults to the current working directory")
349
+ .action((wikiDir, options) => {
350
+ const projectRoot = projectRootFromOption(options.path);
351
+ const planPath = resolveProjectArtifactPath(projectRoot, options.plan);
352
+ const plan = readWikiPlan(planPath);
353
+ const repository = openRepository(projectRoot);
354
+ try {
355
+ const status = buildWikiStatus(projectRoot, repository, resolveProjectArtifactPath(projectRoot, wikiDir), plan, { planPath });
356
+ printResult(options.json, status, formatWikiStatus(status));
357
+ }
358
+ finally {
359
+ closeRepository(repository);
360
+ }
361
+ });
362
+ wikiCommand
363
+ .command("verify")
364
+ .description("Verify Wiki plan, maintenance fields, source paths, evidence freshness, and relative links")
365
+ .argument("<wiki-dir>")
366
+ .requiredOption("--plan <file>", "WikiPlan JSON path")
367
+ .option("--json", "Print JSON output")
368
+ .option("--path <path>", "Project root. Defaults to the current working directory")
369
+ .action((wikiDir, options) => {
370
+ const projectRoot = projectRootFromOption(options.path);
371
+ const planPath = resolveProjectArtifactPath(projectRoot, options.plan);
372
+ const plan = readWikiPlan(planPath);
373
+ const repository = openRepository(projectRoot);
374
+ try {
375
+ const verification = verifyWiki(projectRoot, repository, resolveProjectArtifactPath(projectRoot, wikiDir), plan, { planPath });
376
+ printResult(options.json, verification, formatWikiVerification(verification));
377
+ if (!verification.valid) {
378
+ process.exitCode = 1;
379
+ }
380
+ }
381
+ finally {
382
+ closeRepository(repository);
383
+ }
384
+ });
287
385
  const bundleCommand = program
288
386
  .command("bundle")
289
387
  .description("Create and verify reusable local graph bundle artifacts");
@@ -629,6 +727,17 @@ function buildUsageGuide(projectRoot) {
629
727
  `mdgraph trace "Architecture.md" "src/indexer.ts" --path ${project}`
630
728
  ]
631
729
  },
730
+ {
731
+ name: "Wiki Maintenance",
732
+ purpose: "Plan and maintain a user-authored project Wiki from deterministic evidence without generating prose inside MDGraph.",
733
+ commands: [
734
+ `mdgraph wiki plan --out .mdgraph/wiki-plan.json --path ${project}`,
735
+ `mdgraph wiki brief architecture --plan .mdgraph/wiki-plan.json --json --path ${project}`,
736
+ `mdgraph wiki status wiki --plan .mdgraph/wiki-plan.json --json --path ${project}`,
737
+ `mdgraph wiki verify wiki --plan .mdgraph/wiki-plan.json --json --path ${project}`
738
+ ],
739
+ notes: ["Status and verify are read-only; the host agent writes pages and preserves user-authored prose."]
740
+ },
632
741
  {
633
742
  name: "CI And Artifacts",
634
743
  purpose: "Produce reproducible graph reports and interoperability artifacts.",
@@ -683,6 +792,9 @@ function shellPath(value) {
683
792
  function projectRootFromOption(projectRoot) {
684
793
  return validateProjectRoot(projectRoot ?? process.cwd());
685
794
  }
795
+ function resolveProjectArtifactPath(projectRoot, artifactPath) {
796
+ return path.isAbsolute(artifactPath) ? path.resolve(artifactPath) : path.resolve(projectRoot, artifactPath);
797
+ }
686
798
  function formatIndexResult(result) {
687
799
  return `Indexed ${result.files} file(s) in ${result.mode} mode. Changed: ${result.changed}, deleted: ${result.deleted}, unchanged: ${result.unchanged}, skipped: ${result.skipped}. Documents: ${result.counts.documents}, entities: ${result.counts.entities}, edges: ${result.counts.edges}.`;
688
800
  }
@@ -766,7 +878,8 @@ function formatContext(context) {
766
878
  .map((item, index) => {
767
879
  const heading = item.heading ? `# ${item.heading}` : item.title;
768
880
  const lines = item.lines ? `:${item.lines.start}` : "";
769
- return `## ${index + 1}. ${item.path}${lines}\nReason: ${item.reason}\n${heading}\n${item.content}`;
881
+ const cardSummary = item.cardSummary ? `\nKnowledge Card: ${item.cardSummary}` : "";
882
+ return `## ${index + 1}. ${item.path}${lines}\nReason: ${item.reason}${cardSummary}\n${heading}\n${item.content}`;
770
883
  })
771
884
  .join("\n\n");
772
885
  if (!context.debug) {
@@ -836,6 +949,8 @@ function formatEvaluationReport(report) {
836
949
  `${result.id}: ${status}`,
837
950
  ` query: ${result.query}`,
838
951
  ` topKDocumentRecall=${formatMetric(result.metrics.topKDocumentRecall)}, expectedSectionRecall=${formatMetric(result.metrics.expectedSectionRecall)}, contextPrecision=${formatMetric(result.metrics.contextPrecision)}, contextDiversity=${formatMetric(result.metrics.contextDiversity)}`,
952
+ ` retrievedEntityRecall=${formatMetric(result.metrics.retrievedEntityRecall)}, retrievedSourceRefRecall=${formatMetric(result.metrics.retrievedSourceRefRecall)}, retrievedEdgeKindCoverage=${formatMetric(result.metrics.retrievedEdgeKindCoverage)}, evidencePassed=${result.retrievalEvidencePassed}`,
953
+ ` contextIrrelevantRatio=${formatMetric(result.metrics.contextIrrelevantRatio)}`,
839
954
  ` traceSuccess=${result.metrics.traceSuccess ?? "n/a"}, returnedChars=${result.metrics.returnedChars}, budgetFit=${result.metrics.budgetFit}`
840
955
  ].join("\n");
841
956
  })
@@ -908,18 +1023,21 @@ function formatSourceBridgeReport(report) {
908
1023
  function formatMetric(value) {
909
1024
  return value.toFixed(2);
910
1025
  }
911
- function nodeResolutionJson(resolution) {
1026
+ function nodeResolutionJson(resolution, card) {
912
1027
  if (resolution.status === "found") {
913
- return resolution.node;
1028
+ return card ? { ...resolution.node, card } : resolution.node;
914
1029
  }
915
1030
  if (resolution.status === "ambiguous") {
916
1031
  return { error: resolution.error, query: resolution.query, candidates: resolution.candidates };
917
1032
  }
918
1033
  return { error: resolution.error, query: resolution.query };
919
1034
  }
920
- function formatNodeResolution(resolution) {
1035
+ function formatNodeResolution(resolution, card) {
921
1036
  if (resolution.status === "found") {
922
- return `${resolution.node.kind}: ${resolution.node.label}`;
1037
+ return [
1038
+ `${resolution.node.kind}: ${resolution.node.label}`,
1039
+ card ? formatKnowledgeCard(card) : ""
1040
+ ].filter(Boolean).join("\n\n");
923
1041
  }
924
1042
  if (resolution.status === "ambiguous") {
925
1043
  const candidates = resolution.candidates
@@ -23,13 +23,14 @@ export function openDatabase(projectRoot, options = {}) {
23
23
  }
24
24
  catch (error) {
25
25
  const message = error instanceof Error ? error.message : String(error);
26
- throw new Error(`Failed to open MDGraph database at ${target}: ${message}. Confirm Node.js >=22.5.0 has node:sqlite support, the directory is writable, and run \`mdgraph index\` to rebuild the local index if the database is corrupt.`);
26
+ throw new Error(`Failed to open MDGraph database at ${target}: ${message}. Use a Node.js build with node:sqlite and FTS5 (Node 22.23.2 or newer is verified), confirm the directory is writable, and run \`mdgraph index\` to rebuild the local index if the database is corrupt.`);
27
27
  }
28
28
  db.pragma("foreign_keys = ON");
29
29
  db.pragma("busy_timeout = 5000");
30
30
  if (applySchema) {
31
31
  try {
32
32
  assertCompatibleExistingSchema(db, target);
33
+ ensureFts5Available(db);
33
34
  const hadMetadata = hasSchemaMetadata(db);
34
35
  const schemaSql = readSchemaSql();
35
36
  db.exec(schemaSql);
@@ -44,6 +45,21 @@ export function openDatabase(projectRoot, options = {}) {
44
45
  }
45
46
  return db;
46
47
  }
48
+ function ensureFts5Available(db) {
49
+ const capability = db.prepare("SELECT sqlite_compileoption_used('ENABLE_FTS5') AS enabled").get();
50
+ if (capability.enabled)
51
+ return;
52
+ try {
53
+ // A runtime can load FTS5 as an extension without the compile-time option.
54
+ // Confirm actual availability before declaring the capability absent.
55
+ db.exec("CREATE VIRTUAL TABLE temp.mdgraph_fts5_probe USING fts5(content); DROP TABLE temp.mdgraph_fts5_probe;");
56
+ }
57
+ catch (error) {
58
+ if (!(error instanceof Error) || !error.message.includes("no such module: fts5"))
59
+ throw error;
60
+ throw Object.assign(new Error("SQLite FTS5 is unavailable in this Node.js build. Upgrade to a Node.js build with FTS5, such as the verified Node 22.23.2 runtime, then run `mdgraph index` again.", { cause: error }), { code: "sqlite_fts5_unavailable" });
61
+ }
62
+ }
47
63
  export function openExistingDatabase(projectRoot) {
48
64
  return openDatabase(projectRoot, { createIfMissing: false, applySchema: true });
49
65
  }
@@ -1,6 +1,6 @@
1
1
  import type { SqliteDatabase } from "./sqlite-adapter.js";
2
2
  import { type SchemaMetadata } from "./connection.js";
3
- import type { EdgeKind, GraphChunk, GraphDocument, GraphEdge, GraphEntity, GraphRecordSet, GraphSection, SourceRef } from "../types.js";
3
+ import type { ChunkVector, EdgeKind, GraphChunk, GraphDocument, GraphEdge, GraphEntity, GraphRecordSet, GraphSection, SourceRef } from "../types.js";
4
4
  import type { StructuredQueryAST, StructuredQueryPredicate } from "../query/structured-query.js";
5
5
  export interface StatusCounts {
6
6
  documents: number;
@@ -11,6 +11,13 @@ export interface StatusCounts {
11
11
  chunks: number;
12
12
  vectors: number;
13
13
  }
14
+ export interface IndexWriteState {
15
+ expectedGeneration?: number;
16
+ extractionFingerprint?: string;
17
+ }
18
+ export declare class IndexGenerationConflict extends Error {
19
+ constructor();
20
+ }
14
21
  export interface StorageObjectStat {
15
22
  name: string;
16
23
  type: string;
@@ -78,6 +85,9 @@ export interface ChunkSearchRow {
78
85
  chunk: GraphChunk;
79
86
  rank: number;
80
87
  }
88
+ export interface EntityDefinitionSearchRow extends ChunkSearchRow {
89
+ entityId: string;
90
+ }
81
91
  export interface NodeRecord {
82
92
  id: string;
83
93
  label: string;
@@ -138,8 +148,12 @@ export declare class GraphRepository {
138
148
  private readonly db;
139
149
  constructor(db: SqliteDatabase);
140
150
  close(): void;
141
- replaceAll(records: GraphRecordSet): void;
142
- replaceDocuments(records: GraphRecordSet, changedDocumentIds: string[], deletedDocumentIds: string[]): void;
151
+ indexWriteState(): {
152
+ extractionFingerprint?: string;
153
+ generation: number;
154
+ };
155
+ replaceAll(records: GraphRecordSet, state?: IndexWriteState): void;
156
+ replaceDocuments(records: GraphRecordSet, changedDocumentIds: string[], deletedDocumentIds: string[], canonical?: GraphRecordSet, state?: IndexWriteState): void;
143
157
  counts(): StatusCounts;
144
158
  latestIndexedAt(): string | undefined;
145
159
  schemaMetadata(): SchemaMetadata;
@@ -149,10 +163,16 @@ export declare class GraphRepository {
149
163
  id: string;
150
164
  hash: string;
151
165
  }>;
166
+ reusableVectors(chunks: GraphChunk[], profile: {
167
+ provider: string;
168
+ model: string;
169
+ dimensions: number;
170
+ }): ChunkVector[];
171
+ preservedDerivedEdges(records: GraphRecordSet): GraphEdge[];
152
172
  searchChunks(ftsQuery: string, limit: number): ChunkSearchRow[];
153
173
  findEntitiesByNormalizedNames(names: string[]): GraphEntity[];
154
174
  entityDocumentFrequencies(entityIds: string[]): Map<string, number>;
155
- findEntityDefinitions(entityIds: string[]): ChunkSearchRow[];
175
+ findEntityDefinitions(entityIds: string[]): EntityDefinitionSearchRow[];
156
176
  searchSemanticChunks(queryVector: number[], provider: string, model: string, limit: number): SemanticSearchRow[];
157
177
  semanticVectorCount(provider: string, model: string, dimensions: number): number;
158
178
  chunkVectors(chunkIds: string[], provider: string, model: string, dimensions: number): Map<string, number[]>;
@@ -179,6 +199,10 @@ export declare class GraphRepository {
179
199
  documentLinkStats(): DocumentLinkStats[];
180
200
  definitionCollisions(): DefinitionCollision[];
181
201
  private insertRecords;
202
+ private reconcileSharedGraphRecords;
203
+ private assertExpectedGeneration;
204
+ private writeIndexState;
205
+ private documentHash;
182
206
  private prepareInsertVector;
183
207
  private deleteDocumentDerivedRecords;
184
208
  private pruneUnreferencedEntitiesAndSources;