@daogee/mdgraph 1.0.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 (106) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/README-ZH.md +66 -4
  3. package/README.md +84 -22
  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 +260 -25
  12. package/dist/config/limits.d.ts +2 -0
  13. package/dist/config/limits.js +3 -1
  14. package/dist/config/load-config.js +8 -2
  15. package/dist/db/connection.js +17 -1
  16. package/dist/db/repositories.d.ts +55 -4
  17. package/dist/db/repositories.js +458 -11
  18. package/dist/db/sqlite-adapter.js +8 -2
  19. package/dist/evaluation/context-packing-evaluation.d.ts +29 -0
  20. package/dist/evaluation/context-packing-evaluation.js +134 -0
  21. package/dist/evaluation/entity-extraction-evaluation.d.ts +38 -0
  22. package/dist/evaluation/entity-extraction-evaluation.js +118 -0
  23. package/dist/evaluation/historical-baseline.d.ts +70 -0
  24. package/dist/evaluation/historical-baseline.js +278 -0
  25. package/dist/evaluation/related-documents-evaluation.d.ts +26 -0
  26. package/dist/evaluation/related-documents-evaluation.js +163 -0
  27. package/dist/evaluation/retrieval-eval.d.ts +25 -5
  28. package/dist/evaluation/retrieval-eval.js +79 -7
  29. package/dist/evaluation/structured-query-evaluation.d.ts +27 -0
  30. package/dist/evaluation/structured-query-evaluation.js +156 -0
  31. package/dist/extraction/entity-extractor.js +42 -22
  32. package/dist/extraction/graph-builder.js +2 -18
  33. package/dist/index.d.ts +24 -4
  34. package/dist/index.js +12 -4
  35. package/dist/indexer.js +80 -4
  36. package/dist/mcp/server.d.ts +4 -0
  37. package/dist/mcp/server.js +21 -11
  38. package/dist/mcp/tools.d.ts +5 -1
  39. package/dist/mcp/tools.js +116 -18
  40. package/dist/parser/markdown-parser.js +2 -0
  41. package/dist/query/context-builder.d.ts +32 -2
  42. package/dist/query/context-builder.js +191 -12
  43. package/dist/query/knowledge-card.d.ts +90 -0
  44. package/dist/query/knowledge-card.js +676 -0
  45. package/dist/query/search.d.ts +5 -1
  46. package/dist/query/search.js +85 -16
  47. package/dist/query/structured-query-executor.d.ts +28 -0
  48. package/dist/query/structured-query-executor.js +138 -0
  49. package/dist/query/structured-query.d.ts +50 -0
  50. package/dist/query/structured-query.js +390 -0
  51. package/dist/relationships/derive-related.d.ts +86 -0
  52. package/dist/relationships/derive-related.js +322 -0
  53. package/dist/reporting/report.js +2 -2
  54. package/dist/semantic/embed-chunks.d.ts +2 -0
  55. package/dist/semantic/embed-chunks.js +31 -0
  56. package/dist/semantic/ollama-provider.d.ts +6 -0
  57. package/dist/semantic/ollama-provider.js +136 -0
  58. package/dist/semantic/provider-registry.d.ts +8 -0
  59. package/dist/semantic/provider-registry.js +66 -0
  60. package/dist/semantic/provider.d.ts +35 -0
  61. package/dist/semantic/provider.js +29 -0
  62. package/dist/semantic/status.d.ts +6 -1
  63. package/dist/semantic/status.js +49 -3
  64. package/dist/types.d.ts +7 -2
  65. package/dist/types.js +2 -1
  66. package/dist/utils/path-safety.d.ts +3 -0
  67. package/dist/utils/path-safety.js +27 -0
  68. package/dist/watcher/file-watcher.d.ts +4 -0
  69. package/dist/watcher/file-watcher.js +151 -17
  70. package/dist/watcher/watch-health.d.ts +34 -0
  71. package/dist/watcher/watch-health.js +75 -0
  72. package/dist/wiki/wiki-dependencies.d.ts +20 -0
  73. package/dist/wiki/wiki-dependencies.js +45 -0
  74. package/dist/wiki/wiki-domains.d.ts +13 -0
  75. package/dist/wiki/wiki-domains.js +55 -0
  76. package/dist/wiki/wiki-evidence.d.ts +27 -0
  77. package/dist/wiki/wiki-evidence.js +112 -0
  78. package/dist/wiki/wiki-plan.d.ts +121 -0
  79. package/dist/wiki/wiki-plan.js +616 -0
  80. package/dist/wiki/wiki-status.d.ts +67 -0
  81. package/dist/wiki/wiki-status.js +451 -0
  82. package/docs/EN/Agent_Integration.md +15 -5
  83. package/docs/EN/Architecture.md +52 -16
  84. package/docs/EN/Evaluation_Questions.md +35 -5
  85. package/docs/EN/Knowledge_Cards_and_Wiki_Workflow.md +97 -0
  86. package/docs/EN/Operations.md +111 -0
  87. package/docs/EN/Output_Contracts.md +83 -10
  88. package/docs/EN/Public_Contracts.md +25 -16
  89. package/docs/EN/Public_Contracts_1.0.md +32 -18
  90. package/docs/EN/README.md +24 -0
  91. package/docs/EN/Release_Checklist.md +27 -13
  92. package/docs/EN/Retrieval_and_Context.md +118 -0
  93. package/docs/EN/Structured_Query_and_Relationships.md +111 -0
  94. package/docs/ZH/Agent_Integration.md +15 -5
  95. package/docs/ZH/Architecture.md +52 -21
  96. package/docs/ZH/Evaluation_Questions.md +36 -6
  97. package/docs/ZH/Knowledge_Cards_and_Wiki_Workflow.md +99 -0
  98. package/docs/ZH/Operations.md +111 -0
  99. package/docs/ZH/Output_Contracts.md +83 -10
  100. package/docs/ZH/Public_Contracts.md +24 -15
  101. package/docs/ZH/Public_Contracts_1.0.md +31 -17
  102. package/docs/ZH/README.md +24 -0
  103. package/docs/ZH/Release_Checklist.md +27 -13
  104. package/docs/ZH/Retrieval_and_Context.md +118 -0
  105. package/docs/ZH/Structured_Query_and_Relationships.md +111 -0
  106. package/package.json +50 -19
@@ -3,9 +3,14 @@ implements:
3
3
  - src/indexer.ts
4
4
  - src/db/repositories.ts
5
5
  - src/query/context-builder.ts
6
+ - src/wiki/wiki-plan.ts
7
+ - src/wiki/wiki-status.ts
6
8
  source_refs:
7
9
  - src/db/schema.sql
8
10
  - src/types.ts
11
+ - src/semantic/provider.ts
12
+ - src/semantic/provider-registry.ts
13
+ - src/semantic/ollama-provider.ts
9
14
  ---
10
15
 
11
16
  # MDGraph Architecture
@@ -23,16 +28,17 @@ MDGraph uses this implemented pipeline: scanner -> parser -> extractor/resolver
23
28
  | Extraction | `src/extraction/*` | Converts parsed documents into graph records and deterministic entity/edge signals. |
24
29
  | Resolution | `src/resolution/link-resolver.ts` | Resolves Markdown and WikiLink targets to indexed documents or sections. |
25
30
  | Storage | `src/db/*` | SQLite connection, schema, record replacement, incremental updates, graph queries, and storage diagnostics. |
26
- | Query | `src/query/*` | Search ranking, context packing, and graph trace. |
31
+ | Query | `src/query/*` | Search ranking, context packing, graph trace, and the experimental structured-query tokenizer/AST/executor. |
32
+ | Wiki | `src/wiki/*` | Experimental deterministic Wiki planning, evidence briefs, impact status, and read-only verification; prose remains host-agent/user maintained. |
27
33
  | Evaluation | `src/evaluation/*` | Retrieval evaluation cases, expected records, and lightweight metrics for search/context/trace quality. |
28
34
  | Benchmark | `src/benchmark/*` | Structured with/without-MDGraph agent run record parsing and paired delta aggregation. |
29
35
  | Bundle | `src/bundle/*` | Private directory graph bundle creation and verification using schema/source/config/document hashes. |
30
36
  | Reporting | `src/reporting/*` | CI-friendly graph workflow reports that aggregate counts, storage, doctor, eval, bundle, diff, and benchmark summaries. |
31
37
  | Diff | `src/diff/*` | Git base-ref documentation graph diff and PR impact summary generation. |
32
38
  | Export/Import | `src/export/*` | Deterministic GraphJSON, Mermaid, Markdown/docs-site, and read-only source bridge adapters. |
33
- | Semantic | `src/semantic/*` | Deterministic local vector generation, Float32 vector codec, provider status, and cosine scoring. |
39
+ | Semantic | `src/semantic/*` | Pluggable embedding providers, the compatibility `local-hash` implementation, opt-in Ollama integration, Float32 vector codec, provider diagnostics, and cosine scoring. |
34
40
  | MCP | `src/mcp/*` | Newline-delimited JSON-RPC MCP server and tool handlers. |
35
- | Watch | `src/watcher/file-watcher.ts` | Debounced incremental reindexing via chokidar. |
41
+ | Watch | `src/watcher/file-watcher.ts`, `src/watcher/watch-health.ts` | Debounced incremental reindexing via chokidar plus persistent in-process health classification. |
36
42
  | Analysis | `src/analysis/doctor.ts` | Documentation health and governance report. |
37
43
 
38
44
  ## Public Contract Boundary
@@ -60,11 +66,26 @@ Primary records:
60
66
 
61
67
  1. `scanMarkdownFiles` selects candidate Markdown files from config.
62
68
  2. `parseMarkdownDocument` reads front matter and Markdown structure.
63
- 3. `buildGraphRecords` creates documents, sections, entities, source refs, chunks, vectors, and edges.
64
- 4. `GraphRepository.replaceAll` writes a full rebuild, or `replaceDocuments` updates changed/deleted documents.
65
- 5. `indexProject` compares stored hashes to parsed hashes and chooses full or incremental mode.
69
+ 3. `buildGraphRecords` synchronously creates deterministic documents, sections, entities, source refs, chunks, and edges.
70
+ 4. When embedding is enabled, `indexProject` resolves an `EmbeddingProvider` and asynchronously embeds all chunks for a new/provider-changed index or only changed chunks for a matching incremental index.
71
+ 5. `GraphRepository.replaceAll` writes a full rebuild, or `replaceDocuments` updates changed/deleted documents and their vectors.
72
+ 6. `indexProject` compares stored hashes and vector profile coverage to choose full or incremental mode.
66
73
 
67
- Incremental mode deletes document-derived records for changed and removed files, removes their FTS terms, reinserts changed records, and prunes unreferenced global entities/source refs after cleanup. Full rebuilds optimize and vacuum the SQLite database so old FTS pages and deleted rows do not keep inflating the on-disk file.
74
+ Embedding completes before either repository write begins. A provider error therefore leaves the prior graph intact instead of committing partial vector coverage. Incremental mode deletes document-derived records for changed and removed files, removes their FTS terms, reinserts changed records, and prunes unreferenced global entities/source refs after cleanup. Full rebuilds optimize and vacuum the SQLite database so old FTS pages and deleted rows do not keep inflating the on-disk file.
75
+
76
+ ## Derived Relationship Flow
77
+
78
+ `relationships derive` is an explicit post-index workflow; it is not part of ordinary indexing or watch mode. It requires a clean doctor content-hash/ID freshness audit with no parse failures, a configured `semantic-model` provider, and complete vector coverage for the current provider/model/dimensions. `local-hash` is rejected. The implementation samples bounded document chunks, uses normalized document centroids for candidate filtering, requires multiple independent high-similarity section pairs, and keeps only reciprocal top-K neighbors.
79
+
80
+ Accepted pairs become two symmetric, low-weight `RELATED_TO` edges with `embedding_similarity` provenance and metadata containing provider/model identity, algorithm and gate versions, thresholds, evidence section IDs, and generation time. Replacement is atomic. Incremental indexing removes derived edges connected to changed or deleted documents, while a full rebuild removes the optional layer entirely. See [Structured Query and Relationships](Structured_Query_and_Relationships.md#derived-related-document-relationships) for the workflow, safety budgets, and lifecycle.
81
+
82
+ Derived edges can contribute to graph retrieval, trace, and structured edge predicates. They are excluded from doctor orphan/weak-link authoritative-link counts so inference cannot conceal missing maintained links.
83
+
84
+ ## Entity Extraction
85
+
86
+ `extractEntities` is deterministic and source-aware. Explicit front matter and `Defines` sections create definitions. Ordinary prose emits only high-structure references such as API routes, error codes, and shaped config keys; broad PascalCase words are not promoted. Standalone inline code may identify a complete Latin or CJK symbol, while fenced code limits bare symbols to declaration and type-reference contexts. Unicode-aware patterns cover CJK API paths, segmented config keys, and function identifiers. Route boundaries prevent a file path from also producing a truncated route.
87
+
88
+ `entities.stopEntities` suppresses inferred references of every entity kind, while author-declared definitions remain authoritative. This layer is an interpretable heuristic, not general-purpose NER or a source-language AST. Its signal policy and limits are documented in [Retrieval and Context](Retrieval_and_Context.md#deterministic-entity-extraction).
68
89
 
69
90
  ## Storage Diagnostics
70
91
 
@@ -102,34 +123,49 @@ The diff report includes Markdown document additions, modifications, deletions,
102
123
 
103
124
  - FTS5 chunk hits, including lightweight CJK n-gram matches for continuous Chinese/Japanese/Korean text.
104
125
  - Exact entity matches.
105
- - Optional local semantic vector matches.
126
+ - Optional embedding vector matches.
106
127
  - Graph neighbors around matching entities.
107
128
 
108
129
  When the same document or section is reached by multiple paths, search applies reciprocal rank fusion (RRF) across definition, FTS, and optional semantic channels, then keeps the highest base score while merging the main reasons and matched entities so provenance is not lost. Each fused result keeps an explainable `RRF fusion (...)` reason.
109
130
 
110
- `buildContext` then starts from ranked search sections, performs bounded graph expansion through non-containment edges, orders candidates to preserve cross-document diversity before repeating sections from one document, packages selected sections under a character budget, and includes reasons such as FTS hit, semantic hit, exact entity match, or the graph edge traversal path.
131
+ The synchronous `searchGraph`, `buildContext`, and `evaluateRetrieval` APIs retain their 1.0 behavior and can execute `local-hash` in process. Their async counterparts resolve external providers such as Ollama and are used by CLI and MCP query paths. Provider unavailability, timeouts, invalid responses, missing models, and missing vector coverage fall back to keyword/entity/graph retrieval with an additive `semanticDiagnostic`; CLI text and non-explain JSON commands also write the diagnostic to stderr.
111
132
 
112
- When requested through `context --debug`, context building also reports seed nodes, visited nodes, expanded edges, skipped expansion reasons, candidate counts, MMR-style document-diverse packing diagnostics, and budget truncation counts. These diagnostics are not graph facts; they exist to explain context packing and evaluate retrieval quality.
133
+ `buildContext` then starts from ranked search sections, performs bounded graph expansion through non-containment edges, packages selected sections under a character budget, and includes reasons such as FTS hit, semantic hit, exact entity match, or the graph edge traversal path. The compatibility default orders candidates by document round-robin. Opt-in `mmr` maximizes query relevance minus redundancy, uses stored configured-provider vectors when both candidates have them, falls back to deterministic Unicode-token Jaccard otherwise, and prunes same-document near duplicates while preserving a first candidate from each document.
134
+
135
+ Every context result includes additive packing metadata. When requested through `context --debug`, context building also reports seed nodes, visited nodes, expanded edges, skipped expansion reasons, candidate counts, strategy/similarity selection, per-item query relevance, redundancy penalty and MMR score, redundancy pruning, and budget truncation counts. These diagnostics are not graph facts; they exist to explain context packing and evaluate retrieval quality.
136
+
137
+ The experimental structured-query path is separate from natural-language search. `structured-query.ts` tokenizes bounded input and validates a typed boolean AST. `GraphRepository` compiles document, tag, date, and outgoing-edge predicates from closed field/operator sets into parameterized SQLite operations. `structured-query-executor.ts` uses that direct SQL path unless the AST contains a doctor-derived health predicate; health queries combine parameterized atomic document-id sets with a fresh doctor report and evaluate the original boolean tree. Source file mtime is captured in the existing `documents.updated_at` column during indexing so date governance queries require no schema migration.
113
138
 
114
139
  `traceNodes` performs bounded graph traversal between resolved nodes and returns each step with edge kind, provenance, and confidence.
115
140
 
116
- `evaluateRetrieval` runs the repository-owned alpha or CJK evaluation cases against an indexed project. It reuses `searchGraph`, `buildContext`, and `traceNodes`, then reports expected-document recall, expected-section recall, context precision, trace success, latency, returned character budget, context diversity, reason coverage, RRF channels, query mode, and optional semantic reranker status. The evaluation output is a measurement aid, not a learned ranking model and not a replacement for focused regression tests.
141
+ `evaluateRetrieval` and `evaluateRetrievalAsync` run the repository-owned alpha or CJK evaluation cases against an indexed project. They reuse the corresponding search/context path plus `traceNodes`, then report expected-document recall, expected-section recall, context precision, trace success, latency, returned character budget, context diversity, reason coverage, RRF channels, query mode, optional semantic reranker status, and async provider diagnostics. The evaluation output is a measurement aid, not a learned ranking model and not a replacement for focused regression tests.
117
142
 
118
143
  `generateBenchmarkReport` consumes structured `AgentRunRecord` JSON only. It pairs one `with_mdgraph` and one `without_mdgraph` record by `questionId`, reports incomplete or duplicate pairs as skipped, and calculates deltas for file reads, searches, tool calls, MDGraph calls, character/token budgets, latency, raw-file fallback, and citation correctness. It does not parse transcripts, invoke models, or host agent runs.
119
144
 
145
+ ## Wiki Workflow
146
+
147
+ The experimental Wiki path is separate from indexing and natural-language query ranking. `buildWikiPlan` classifies only evidence-backed domains from indexed document metadata and explicit graph relationships, records graph/source hashes, and gives every page a dependency-local `evidenceHash` that also fingerprints safe project source refs. `buildWikiPageBrief` reuses context packing, known files, Knowledge Cards, and a shared character budget.
148
+
149
+ `buildWikiStatus` compares user-maintained page front matter with the plan and current dependency evidence, reporting `current`, `needs_update`, `missing`, or `orphaned` without modifying files. `verifyWiki` adds bounded checks for plan shape, indexed source documents, safe existing source refs, evidence freshness, and resolvable relative Markdown links. It does not evaluate prose quality, delete orphaned pages, invoke a model, or add an MCP tool.
150
+
120
151
  ## MCP Boundary
121
152
 
122
- The MCP server intentionally exposes only five tools. Tool output is text-first and JSON-compatible so agents can use it without needing to inspect the SQLite database or read raw files first. The server is project-bound: initialize roots and tool `projectPath` values must stay inside the served root.
153
+ The MCP server intentionally exposes only five tools. Search and context dispatch through the async provider-aware handlers, while node, trace, and status retain their synchronous behavior. Tool output is text-first and JSON-compatible so agents can use it without needing to inspect the SQLite database or read raw files first. A semantic fallback adds a text banner and structured diagnostic without turning a usable lexical/graph result into an MCP error. The server is project-bound: initialize roots and tool `projectPath` values must stay inside the served root.
123
154
 
124
155
  ## Current Tradeoffs
125
156
 
126
- - The semantic provider is deterministic and local, but it is a lightweight hash embedding rather than a high-quality language model embedding. Unsupported configured providers degrade to FTS5 and graph search; `semantic status` reports provider support, vector coverage, storage format, and reindex guidance.
127
- - Watch mode updates SQLite on file changes; long-running MCP freshness is achieved by default through `serve --mcp`, or by a separate `watch` process with `serve --mcp --no-watch`, with tools opening current database state on each call.
157
+ - `local-hash` remains a deterministic lexical feature hash for compatibility, not a language-model embedding. Ollama is the first opt-in `semantic-model` provider and requires a separately running local service/model. Unsupported or unavailable providers degrade to FTS5 and graph search; `semantic status` reports capability, runtime availability, vector coverage, storage format, and reindex guidance.
158
+ - Structured `query` is experimental and covers documented stored fields, tags, outgoing edges, and selected doctor health classes. Arbitrary front-matter keys, incoming-edge predicates, aggregations, joins, and an MCP structured filter remain outside the current implementation.
159
+ - Watch mode updates SQLite on file changes and retains `starting | healthy | degraded | failed` health, the last successful index, the last error, and coverage reliability. Startup registration errors are fatal; indexing errors can recover after a later successful index; runtime resource failures remain degraded until restart. Integrated MCP exposes the snapshot through `mdgraph_status`. Native events remain the default, while `watch --poll` and `serve --mcp --watch-poll` are explicit higher-cost fallbacks.
128
160
  - Doctor checks are rule-based warnings. They first compare current files with indexed document hashes and IDs; stale indexes produce a read-only freshness diagnostic instead of mixed-time health conclusions.
129
161
  - `doctor --changed` and `doctor --since <ref>` are Git-scoped views over the same health model; they report scope metadata, scoped graph issues, directly related one-hop graph documents, deleted-document warnings, and freshness diagnostics.
130
162
  - Storage diagnostics are exposed through `status --storage` and reused by doctor for storage health summaries; they are not graph facts and do not expand the MCP tool surface.
131
163
  - Private bundle artifacts are local workflow artifacts, not public exports. Public-safe sanitization and zip packaging are outside the current implementation.
132
164
  - Benchmark reports are aggregate-only measurements from explicit structured records; full transcripts, hosted analytics, and agent runtime capture stay outside MDGraph.
133
165
  - Interoperability adapters are read-oriented. GraphJSON verify, Mermaid/Markdown/docs-site exports, and source bridge reports do not merge external graphs into the main SQLite index.
134
- - `SAME_AS`, `RELATED_TO`, and `CONTRADICTS` are reserved edge kinds in the public model. The deterministic MVP does not emit them during indexing; contradiction-like signals are currently reported by `doctor` rather than inserted as graph edges.
135
- - The current implementation favors a compact MVP over broad Markdown/MDX dialect support.
166
+ - `RELATED_TO` is an experimental derived edge emitted only by explicit provider-gated execution; it is never emitted by ordinary deterministic indexing. `SAME_AS` and `CONTRADICTS` remain reserved, and contradiction-like signals continue to be reported by `doctor` rather than inserted as graph edges.
167
+ - The current implementation favors a compact, deterministic core over broad Markdown/MDX dialect support.
168
+
169
+ ## Knowledge and Wiki evidence ownership
170
+
171
+ Card assembly distinguishes direct edges, inherited document/section context, and related source evidence. Stable provenance travels with references and bounded next-read entries. Wiki evidence hashing and strict content checks are shared in `src/wiki/wiki-evidence.ts`; dependency assessment in `src/wiki/wiki-dependencies.ts` supplies both brief guidance and page status. Plan v2 preserves authored selections and separates new suggestions. Its document source hash excludes Wiki output and volatile indexing metadata. SQLite schema and retrieval ranking are unchanged.
@@ -1,6 +1,6 @@
1
1
  # MDGraph Evaluation Questions
2
2
 
3
- These questions turn the plan's agent evaluation guidance into a reusable smoke set. Use them against a realistic project documentation corpus after indexing.
3
+ These questions provide a reusable engineering smoke set for a realistic project documentation corpus. They test whether MDGraph returns the right documents, sections, entities, graph evidence, and context rather than treating a single ranking score as sufficient evidence.
4
4
 
5
5
  The built-in CLI entry is:
6
6
 
@@ -11,7 +11,23 @@ mdgraph eval --query-set cjk --path /path/to/project --json
11
11
  mdgraph eval --query-mode semantic --json
12
12
  ```
13
13
 
14
- `mdgraph eval` runs the repository-owned alpha query set by default and reports pass/fail plus lightweight retrieval metrics. It also reports deterministic ranking diagnostics: query mode, RRF search fusion channels, MMR-style document-diverse context packing, and optional semantic reranking status. `--query-set cjk` selects a small Chinese/Japanese retrieval baseline covered by lightweight CJK n-gram preprocessing. It is a deterministic engineering smoke check, not a completed IR benchmark or real agent A/B benchmark.
14
+ `mdgraph eval` runs the repository-owned `alpha` query set by default and reports pass/fail plus lightweight retrieval metrics. It also reports query mode, RRF channels, compatibility context packing, and optional semantic-provider status. `--query-set cjk` selects a small Chinese/Japanese retrieval baseline covered by lightweight CJK n-gram preprocessing. These are deterministic engineering checks, not a completed IR benchmark or real-agent A/B benchmark.
15
+
16
+ ## Repository Regression Suites
17
+
18
+ Maintainers use focused, non-public suites in addition to `mdgraph eval`. Their names describe the capability they protect. None adds a value to the frozen `eval --query-set alpha | cjk` enum or writes the repository's `.mdgraph` index.
19
+
20
+ | Command | Capability protected | Recorded result / gate |
21
+ |---|---|---|
22
+ | `npm run baseline:historical` | Historical lexical-hash, entity, context, and watch-failure comparison snapshot | Keyword synonym Recall@5 `0.0000`; `local-hash` `0.5000`; historical entity precision/recall `0.5000 / 1.0000`; round-robin average pairwise Jaccard `0.3808` with three near-duplicate pairs. These values are intentionally immutable historical evidence. |
23
+ | `npm run baseline:entity-extraction` | Source-aware Latin/CJK entity extraction | Precision `1.0000`, recall `1.0000`, CJK recall `1.0000`, and zero known-noise leakage; gates are `>= 0.90`, `>= 0.80`, `>= 0.80`, and zero. |
24
+ | `npm run baseline:context-packing` | Opt-in true-MMR context packing | Expected-document recall remains `1.0000`; average pairwise Jaccard falls from `0.3808` to `0.1576` and near-duplicate pairs from three to zero, a `58.61%` redundancy reduction. |
25
+ | `npm run baseline:structured-query` | Structured-query correctness and safety | Four of four annotated governance queries correct; parameterized repository predicates and SQL-injection isolation pass. |
26
+ | `npm run baseline:related-documents` | Provider-gated related-document derivation | Precision `1.0000`, recall `1.0000`, complete provenance, and deterministic replacement; gates require precision `>= 0.90`, recall `>= 0.80`, complete provenance, and stable replacement. |
27
+
28
+ The provider integration fixture also maps four no-overlap semantic cases through a deterministic fake Ollama endpoint and reaches Recall@5 `1.0000`. This validates batching, vector persistence, async routing, RRF participation, diagnostics, and provider attribution; it does not predict the quality of an arbitrary live model.
29
+
30
+ Watcher tests cover startup/runtime `ENOSPC`, runtime `EMFILE`, startup `EACCES`, indexing failure, recovery, persistent in-process health, and explicit polling. See [Retrieval and Context](Retrieval_and_Context.md), [Operations](Operations.md), and [Structured Query and Relationships](Structured_Query_and_Relationships.md) for the user-facing behavior behind these suites.
15
31
 
16
32
  1. Why does a specific error code affect a specific user flow?
17
33
  2. Which older decisions does a given design document depend on?
@@ -45,7 +61,7 @@ The machine-readable expected records live in `src/evaluation/retrieval-eval.ts`
45
61
 
46
62
  ## CJK Expected Records
47
63
 
48
- The `cjk` query set is a v0.5 retrieval baseline for Chinese and Japanese Markdown. It uses expected records from the repository test fixture `createCjkFixtureDocs`, including Chinese design/API/runbook/spec documents and a Japanese design document. Its cases cover:
64
+ The `cjk` query set is the built-in retrieval baseline for Chinese and Japanese Markdown. It uses expected records from the repository test fixture `createCjkFixtureDocs`, including Chinese design/API/runbook/spec documents and a Japanese design document. Its cases cover:
49
65
 
50
66
  - Chinese spaced keyword queries such as `登录流程 缓存超时 认证重试`.
51
67
  - Continuous Chinese natural-language phrasing such as `缓存超时影响登录流程的处理`, covered by the lightweight CJK n-gram preprocessing baseline.
@@ -63,6 +79,20 @@ For each question, compare agent behavior with and without MDGraph attached:
63
79
  - Whether the context returned by MDGraph is sufficient without follow-up file inspection.
64
80
  - Time and tool-call count for the full agent run.
65
81
  - `mdgraph eval` metrics: top-K document recall, expected-section recall, context precision, trace success, latency, returned character count, budget fit, fanout, context diversity, reason coverage, and ranking reason coverage.
66
- - `mdgraph eval` ranking report: query mode, RRF search fusion channels, MMR-style context packing strategy, optional reranker status, and semantic-active case count.
82
+ - `mdgraph eval` ranking report: query mode, RRF search fusion channels, compatibility context packing strategy, optional reranker status, and semantic-active case count. Use the focused context regression suite to compare opt-in true MMR against that frozen default.
83
+
84
+ Use `mdgraph report --benchmark benchmark-runs.json --json` for A/B reporting on these questions. It consumes structured run records and reports aggregate deltas; full transcripts should remain outside public docs.
67
85
 
68
- Use `mdgraph report --benchmark benchmark-runs.json --json` for v0.6 A/B reporting on these questions. It consumes structured run records and reports aggregate deltas; full transcripts should remain outside public docs.
86
+ ## Returned evidence and compatibility metrics
87
+
88
+ The legacy `entityRecall`, `sourceRefRecall`, and `edgeKindCoverage` metrics measure existence in the index (and trace for edge kinds). Their meaning and the legacy `passed` result remain unchanged. They do not establish that a query returned the evidence.
89
+
90
+ Use `retrievedEntityRecall`, `retrievedSourceRefRecall`, and `retrievedEdgeKindCoverage` to measure evidence exposed by search, context, and the requested trace. `observed.retrievedEntities`, `retrievedSourceRefs`, and `retrievedEdgeKinds` identify that evidence. `retrievalEvidencePassed` requires both the legacy checks and complete returned-evidence coverage. `contextIrrelevantRatio` measures the fraction of returned context items outside the expected document set; an empty result has ratio zero but cannot establish recall.
91
+
92
+ ## Reproducible performance samples
93
+
94
+ Run `npm run baseline:performance -- 100,500` after installing dependencies. The script creates independent synthetic document corpora, indexes local-hash vectors, modifies one document, and measures full/incremental indexing plus card, context, and semantic-query latency. Query values are medians of five samples following one warmup. Memory values are process heap/RSS after the operations, not peak allocation. The JSON includes runtime, platform, corpus sizes, counts, and retained fixture paths. These measurements are reproducible engineering samples, not real-agent effectiveness or large-production performance claims.
95
+
96
+ ## Knowledge/Wiki output baseline
97
+
98
+ Run `npm run baseline:knowledge-wiki` for a deterministic orchard-project fixture. It reports Card JSON characters, references lacking ownership labels, and the rank of a known file in next-read entries. A null rank means the output has no matching next-read entry; it does not mean search failed. The plan/brief output checks project-neutral planning and evidence routing. This is an output-behavior comparison, not a measured independent-agent completion-time or prose-quality improvement.
@@ -0,0 +1,97 @@
1
+ ---
2
+ status: implemented
3
+ defines:
4
+ - KnowledgeCard
5
+ - WikiPlan
6
+ - WikiPageBrief
7
+ - WikiStatus
8
+ - WikiVerification
9
+ source_refs:
10
+ - src/query/knowledge-card.ts
11
+ - src/query/context-builder.ts
12
+ - src/query/search.ts
13
+ - src/query/trace.ts
14
+ - src/db/repositories.ts
15
+ - src/mcp/tools.ts
16
+ - src/bin/mdgraph.ts
17
+ - src/wiki/wiki-plan.ts
18
+ - src/wiki/wiki-status.ts
19
+ - src/wiki/wiki-evidence.ts
20
+ - src/wiki/wiki-dependencies.ts
21
+ - src/wiki/wiki-domains.ts
22
+ ---
23
+
24
+ # Knowledge Cards and Wiki Workflow
25
+
26
+ Knowledge Cards help locate and interpret graph evidence. Wiki commands prepare and maintain a project manual whose prose is written by the host agent or user. Neither capability requires a model, embeddings, a source-code graph, or another database.
27
+
28
+ ## Knowledge Cards
29
+
30
+ `node` and MCP `mdgraph_node` expose an experimental `card`. `context` adds a complete `cardSummary` only when packed Markdown leaves enough space. Search ranking, trace paths, and the five-tool MCP surface are unchanged.
31
+
32
+ A card retains `nodeId`, `kind`, `label`, `summary`, `definitions`, `sourceRefs`, `relatedDocuments`, `evidence`, and optional `truncated`. Additive `nextReads` entries supply graph-backed paths and reading reasons.
33
+
34
+ References carry `association` (`direct`, `inherited`, or `related`), `originNodeId`, and optional `viaNodeId`. A section's own evidence is direct; document-level declarations are inherited background. A document may aggregate its sections while retaining the originating node. An entity's source files reached through a defining document are related evidence, not a claim that the entity directly implements all of those files.
35
+
36
+ The deterministic summary emphasizes location and useful relationships. Next reads come from existing graph facts. The default complete serialized JSON budget is 4,000 characters, including ownership metadata, next reads, and omission counts. Direct evidence has priority over inherited/related background. Display text can end in an ellipsis; the stable node identity is retained. An impossible budget produces an explicit error. Cards are generated at query time and are not persisted or exposed through a separate command.
37
+
38
+ ## Create a Wiki plan
39
+
40
+ ```bash
41
+ mdgraph wiki plan --wiki-dir wiki --out .mdgraph/wiki-plan.json --path <project>
42
+ mdgraph wiki brief <page-id> --plan .mdgraph/wiki-plan.json --json --path <project>
43
+ ```
44
+
45
+ Plan v2 records the project-relative Wiki output directory and excludes it from source selection. Project-neutral candidate domains cover overview, architecture, usage, development, operations, and reference; indexed document evidence supplies project vocabulary. Sparse documentation produces limited suggestions and explicit gaps rather than invented project behavior.
46
+
47
+ Pages retain stable IDs, output paths, purpose, audience, outline, selected document IDs, selected source paths, evidence queries, and a dependency-local evidence hash. Dependency snapshots let maintenance reports identify changed files. Global graph hashes remain diagnostic data; changes to indexing metadata alone do not imply that every page needs rewriting.
48
+
49
+ ## Update an authored plan
50
+
51
+ ```bash
52
+ mdgraph wiki plan --from .mdgraph/wiki-plan.json --out .mdgraph/wiki-plan.next.json --path <project>
53
+ ```
54
+
55
+ Review the next plan before replacing the previous one. Existing page IDs, paths, hierarchy, titles, purposes, audiences, outlines, selected documents, source refs, and evidence queries are preserved. New pages and sources are suggestions rather than automatic edits. Missing selected dependencies remain visible instead of silently disappearing. Adopt suggestions by editing the selected page fields and refreshing the plan before writing from its brief.
56
+
57
+ Version 1 plans remain readable. When migrating with `--from`, supply `--wiki-dir wiki` explicitly; write the resulting version 2 plan to a new file. Future unknown formats are diagnosed without overwriting the input. Plan, brief, status, and verification never author or overwrite page prose.
58
+
59
+ ## Author one page
60
+
61
+ A brief identifies primary selected documents, supplementary retrieved material, source files to inspect, and unresolved evidence gaps. Knowledge Cards distinguish direct facts from background. The `maxChars`/`usedChars` budget covers packed context text and serialized cards; page instructions and the source manifest are separate recovery information, not a total JSON-size cap.
62
+
63
+ The shared evidence evaluation supplies freshness and recovery information to JSON, text, and writing requirements. A stale or unknown brief remains readable, but it does not instruct the author to finalize an old evidence hash. Refresh sources/index/plan as directed, inspect the cited files, then write or update the page.
64
+
65
+ Maintain these fields:
66
+
67
+ ```yaml
68
+ ---
69
+ wiki_id: architecture
70
+ evidence_hash: "<hash from the current brief>"
71
+ source_docs:
72
+ - docs/architecture.md
73
+ source_refs:
74
+ - src/main.ts
75
+ ---
76
+ ```
77
+
78
+ Both source fields must be arrays of non-empty project-relative paths; use `[]` for an empty list. Additional user-selected sources must be deliberately incorporated into the plan. A mismatch should be resolved by reviewing source selection, not by blindly removing the user's references.
79
+
80
+ Use [the authoring workflow](../../agent-pack/skills/wiki-authoring/SKILL.md) to preserve correct existing prose and update only affected pages.
81
+
82
+ ## Status, verification, and content acceptance
83
+
84
+ ```bash
85
+ mdgraph wiki status wiki --plan .mdgraph/wiki-plan.json --json --path <project>
86
+ mdgraph wiki verify wiki --plan .mdgraph/wiki-plan.json --json --path <project>
87
+ ```
88
+
89
+ `current` means no change was detected in the recorded dependencies and maintenance fields. `needs_update`, `missing`, and `orphaned` identify work to review. Reports include dependency changes and recovery actions. A new unrelated source can require plan review without forcing unrelated pages to be rewritten. Status and verification preserve user content.
90
+
91
+ Verification checks maintenance fields, safe existing sources, relative links, and evidence consistency. `valid: true` is not a judgment of prose accuracy. Content acceptance separately records the task performed, actual commands, observed results, the source revision, and any unverified claims.
92
+
93
+ ## Validation
94
+
95
+ Focused regression tests cover ownership, budgets, stale evidence, preserved author choices, plan compatibility, and the complete update workflow. `npm run baseline:knowledge-wiki` measures output behavior on a small orchard project; it is not an independent-agent A/B trial or evidence of improved prose quality. `npm run baseline:performance` measures synthetic 100/500-document workloads.
96
+
97
+ The maintained project Wiki in `wiki/` and its `wiki/acceptance.md` record document real workflow validation. Their acceptance is separate from unit-test success.
@@ -0,0 +1,111 @@
1
+ ---
2
+ title: Operations
3
+ type: runbook
4
+ status: active
5
+ defines:
6
+ - MDGraphOperations
7
+ source_refs:
8
+ - src/indexer.ts
9
+ - src/watcher/file-watcher.ts
10
+ - src/watcher/watch-health.ts
11
+ - src/semantic/status.ts
12
+ ---
13
+
14
+ # Operations
15
+
16
+ This guide covers index freshness, watch coverage, semantic-provider recovery, and local artifact safety for long-running MDGraph use.
17
+
18
+ ## Index and Freshness Checks
19
+
20
+ Use explicit status checks before relying on an unfamiliar or long-running project index:
21
+
22
+ ```bash
23
+ mdgraph status --freshness --path /path/to/project
24
+ mdgraph status --storage --path /path/to/project
25
+ mdgraph doctor --path /path/to/project
26
+ ```
27
+
28
+ `status --freshness` compares current Markdown files with indexed paths and hashes. A `stale` result means query results may reflect older graph state; run `mdgraph index`. Doctor health predicates and derived-relationship generation require a fresh index and refuse mixed-time conclusions.
29
+
30
+ Incremental indexing updates changed and deleted documents, their FTS records, vectors, and connected derived edges. Use `index --full` when the embedding profile changes, when storage needs rebuild/compaction, or when a clean reconstruction is operationally preferable.
31
+
32
+ ## Watch Modes
33
+
34
+ Standalone watch mode and integrated MCP serving keep the index current:
35
+
36
+ ```bash
37
+ mdgraph watch --path /path/to/project
38
+ mdgraph serve --mcp --path /path/to/project
39
+ ```
40
+
41
+ The watcher exposes an in-process health snapshot through `WatchHandle.getHealth()`. Integrated MCP serving adds it to `mdgraph_status.structuredContent.watchHealth`.
42
+
43
+ | State | Meaning | Operator action |
44
+ |---|---|---|
45
+ | `starting` | Watch registration or initial setup is in progress. | Wait for healthy state or startup failure. |
46
+ | `healthy` | Registration is active and the latest index attempt succeeded. | No action. |
47
+ | `degraded` | Indexing failed, or native watch coverage is no longer reliable. | Inspect the last error; reindex or restart after fixing the cause. |
48
+ | `failed` | Startup could not establish reliable watch coverage. | Fix the reported error before relying on watch mode. |
49
+
50
+ The snapshot includes last successful index time, last error, failure phase and normalized code, consecutive indexing failures, coverage reliability, polling state, and closure state. It lasts for the watcher process; restart creates a new health lifecycle.
51
+
52
+ Startup registration errors are fatal. A later successful index can recover an indexing failure. Runtime watch errors such as `ENOSPC` or `EMFILE` set `coverageReliable: false`; a successful manual or triggered index does not prove missed native events are recovered, so health remains degraded until restart.
53
+
54
+ ## Polling Fallback
55
+
56
+ Native filesystem events are the default. If operating-system watch limits cannot be raised or native events are unreliable, explicitly enable polling:
57
+
58
+ ```bash
59
+ mdgraph watch --poll --path /path/to/project
60
+ mdgraph serve --mcp --watch-poll --path /path/to/project
61
+ ```
62
+
63
+ Polling is never activated automatically because it can increase I/O and CPU use. Prefer fixing the operating-system resource limit for large, long-running repositories when possible; use polling when that is not under your control.
64
+
65
+ ## Semantic Provider Recovery
66
+
67
+ Check provider and vector state with:
68
+
69
+ ```bash
70
+ mdgraph semantic status --path /path/to/project
71
+ ```
72
+
73
+ | Condition | Query behavior | Recovery |
74
+ |---|---|---|
75
+ | Provider unavailable, timeout, or invalid response | Search/context fall back to FTS5/entity/graph and report `semanticDiagnostic`. | Restore the service/model, then retry; the lexical result remains usable. |
76
+ | Provider/model/dimensions changed | Status reports that reindexing is needed. | Run `mdgraph index --full --semantic`. |
77
+ | Semantic indexing fails | The existing graph remains intact because embedding completes before mutation. | Fix the provider and rerun indexing. |
78
+ | Vector coverage is incomplete | Semantic queries degrade; relationship derivation refuses mutation. | Rebuild a complete semantic index. |
79
+
80
+ `local-hash` does not require an external service, but it is only a lexical feature hash. It cannot satisfy semantic-model gates for derived relationships.
81
+
82
+ ## Derived Relationship Refresh
83
+
84
+ Derived `RELATED_TO` edges are disposable, non-authoritative state. Changes to a document remove touching derived edges; a full rebuild removes all of them. After a successful full semantic index, run a dry derivation and then explicitly refresh the layer if desired. See [Structured Query and Relationships](Structured_Query_and_Relationships.md#derived-related-document-relationships).
85
+
86
+ ## Local and Release Artifacts
87
+
88
+ - Keep `.mdgraph/graph.db`, bundles, reports containing local paths, and private evaluation corpora out of source control and release archives.
89
+ - Keep `.mdgraph/config.json` trackable when it contains no credentials; endpoint URLs with embedded credentials are rejected.
90
+ - Use GraphJSON for the documented structural exchange format instead of depending on SQLite internals.
91
+ - Before publishing MDGraph itself, run the [Release Checklist](Release_Checklist.md), inspect `npm pack --dry-run --json`, and verify the packed package rather than assuming repository contents equal npm contents.
92
+
93
+ ## Served roots and embedding deadlines
94
+
95
+ MCP checks the real filesystem targets of project roots, configuration, and SQLite storage. Links within the served root remain usable, including starting the server through a linked root. To access an external project, start a separate server with `--path` pointing to that project. A link inside the served root does not grant access to an external target.
96
+
97
+ `embedding.timeoutMs` covers response headers and the complete response body, including error responses. A timeout degrades search/context to lexical and graph retrieval; an indexing failure preserves the previous graph. Retry after the local service recovers.
98
+
99
+ ## Incremental consistency and watch configuration
100
+
101
+ Indexing records extraction settings and a generation in SQLite metadata. Changes to extraction settings rebuild the affected graph; query-only settings do not. Incremental updates reconcile deterministic relationships against all parsed documents so alias ambiguity changes are reflected even in untouched documents. Unchanged chunk vectors are reused for matching provider/model/dimensions and content. An explicit full rebuild clears derived relationships; automatic extraction rebuilds preserve unaffected derived relationships when their vector profile is unchanged.
102
+
103
+ Concurrent index commits detect a changed generation and rescan once; repeated contention reports an error and can be retried. Parser failures retain the previous document and its graph, report skipped files, and leave incomplete extraction rebuilds pending. Fix the reported Markdown and rerun indexing before relying on that content.
104
+
105
+ Watch reloads configuration and `.gitignore` rules, including the MDX switch. The replacement watcher becomes ready before the old one closes. Invalid configuration retains the old watch and reports degraded health; correcting the configuration triggers recovery.
106
+
107
+ ## Node.js build requirements
108
+
109
+ The runtime must provide `node:sqlite` with FTS5; a version number of 22.5.0 alone is insufficient. Node 22.23.2 and 26.5.0 pass the full local test suite. Tested stock 22.5.0 and 22.13.0 builds lack FTS5; adding the experimental SQLite flag alone does not supply it. MDGraph checks the actual capability before applying its persistent schema and reports `sqlite_fts5_unavailable` with upgrade guidance. A build that supplies FTS5 through an extension remains usable.
110
+
111
+ The early-runtime CI job exercises SQLite compatibility and missing-capability recovery; it is not a full-product support claim for stock Node 22.5.0. Windows validation is covered by CI and must be checked on the corresponding commit before a cross-platform release claim.
@@ -62,17 +62,24 @@ The text form prints the same workflow groups for humans. `usage` does not read
62
62
 
63
63
  - `query`, `limit`, `queryMode`, `entityCandidates`, `ftsQuery`, `semanticEnabled`, and `semanticActive`.
64
64
  - `ranking`: `fusion`, `fusionK`, `channels`, and `optionalReranker`.
65
+ - `semanticDiagnostic`: optional provider fallback details with `code`, `provider`, `message`, and `degraded: true`.
65
66
  - `matchedEntities`: entity names, kinds, and document frequencies used by ranking diagnostics.
66
67
  - `results`: the same search result records returned by `search --json`.
67
68
 
69
+ When semantic retrieval is requested but cannot run, `search` still returns FTS5/entity/graph results. The CLI writes the fallback diagnostic to stderr so the non-explain `search --json` array remains compatible.
70
+
68
71
  ## `context --json`
69
72
 
70
73
  `mdgraph context <query> --json` returns:
71
74
 
72
75
  - `query`: original query text.
73
76
  - `maxChars`: configured context budget.
74
- - `usedChars`: packed character count.
75
- - `items`: context items with `nodeId`, `documentId`, optional `sectionId`, optional `anchor`, `path`, `title`, optional `heading`, optional `lines`, `reason`, `matchedEntities`, optional `edgePath`, optional `sourceRefs`, optional `riskNotes`, and `content`.
77
+ - `usedChars`: packed `content` plus optional `cardSummary` character count.
78
+ - `packing`: additive packing metadata with `strategy`; opt-in MMR also reports `similarity`, `mmrLambda`, and optional `redundancySkippedItems`.
79
+ - `semanticDiagnostic`: optional provider fallback details; absent when semantic retrieval was not requested or completed normally.
80
+ - `items`: context items with `nodeId`, `documentId`, optional `sectionId`, optional `anchor`, `path`, `title`, optional `heading`, optional `lines`, `reason`, `matchedEntities`, optional `edgePath`, optional `sourceRefs`, optional `riskNotes`, optional `cardSummary`, and `content`.
81
+
82
+ `cardSummary` is an experimental deterministic Knowledge Card summary. It is added only to the highest-ranked packed items when the original document content leaves spare budget; it is omitted if the complete summary does not fit, preserving original content and recovery fields.
76
83
 
77
84
  `riskNotes` can include lifecycle/trust cautions and deterministic content-risk notes such as prompt-injection text, active HTML/data URIs, or hidden Unicode format characters.
78
85
 
@@ -83,14 +90,67 @@ The text form prints the same workflow groups for humans. `usage` does not read
83
90
  - `seedNodes`, `visitedNodes`, and `expandedEdges`.
84
91
  - `skippedVisitedNodes`, `skippedByNodeLimit`, and `skippedByDepth`.
85
92
  - `candidateCount`, `directCandidates`, and `expandedCandidates`.
86
- - `packingStrategy`, `packedItems`, `packedUniqueDocuments`, and `packingDiversityRatio`.
87
- - `budgetTruncatedItems` and `budgetSkippedItems`.
93
+ - `packingStrategy`, optional `packingSimilarity`, optional `mmrLambda`, optional per-item `packingSelections`, `packedItems`, `packedUniqueDocuments`, and `packingDiversityRatio`. Each MMR selection reports `nodeId`, `path`, `queryRelevance`, `redundancyPenalty`, `mmrScore`, and `similaritySource`.
94
+ - `budgetTruncatedItems`, `budgetSkippedItems`, and optional `redundancySkippedItems`.
95
+
96
+ The compatibility default is `mmr-style-document-round-robin`. `--packing mmr` is opt-in and may be tuned with `--mmr-lambda <0..1>`; missing stored vectors fall back to deterministic lexical Jaccard similarity.
97
+
98
+ ## `query --json` (experimental)
99
+
100
+ `mdgraph query <expression> --json` returns:
101
+
102
+ - `query`: original structured expression.
103
+ - `ast`: validated expression tree plus `orderBy` and `limit`.
104
+ - `execution`: `strategy` (`parameterized-sql` or `parameterized-hybrid-doctor`), ordered `stages`, `parameterCount`, and `doctorHealthEvaluated`.
105
+ - `total`, `returned`, and `truncated`: match and limit diagnostics.
106
+ - `items`: entries with `document`, `reason`, `predicateFields`, and execution `provenance`.
107
+
108
+ `document` follows `GraphDocument`, including optional `updatedAt`, which is the source Markdown mtime captured during indexing. Health predicates fail when the index is stale. This output is experimental and may evolve without changing the stable `search` contract.
109
+
110
+ ## `relationships derive --json` (experimental)
111
+
112
+ `mdgraph relationships derive --json` returns:
113
+
114
+ - `algorithmVersion`, `generatedAt`, `provider`, `model`, and `dimensions`.
115
+ - `options`: effective `threshold`, `maxNeighbors`, `minEvidence`, and `dryRun`.
116
+ - `qualityGate`: gate ID, `passed`, and named runtime checks.
117
+ - `corpus`: document/chunk/vector coverage, sampling, pair-evaluation, and vector-comparison diagnostics.
118
+ - `relationships`: canonical document pairs with confidence and independent chunk/section evidence.
119
+ - `relationshipPairs` and `directedEdges`.
120
+ - `mutation`: `dryRun`, `removed`, and `inserted` counts.
121
+
122
+ The command fails before mutation for stale indexes, lexical-hash providers, incomplete current-profile vector coverage, unsafe options, or exceeded computation budgets. A successful non-dry run atomically replaces `RELATED_TO/embedding_similarity` edges. This output is experimental and does not change stable index, search, GraphJSON, or MCP contracts.
123
+
124
+ ## Experimental `wiki` workflow
125
+
126
+ `mdgraph wiki plan --out <file> --json` writes a deterministic plan and returns `out` plus `plan`. The plan contains:
127
+
128
+ - `format: "mdgraph-wiki-plan"`, `formatVersion: 1`, `graphHash`, and `sourceHash`.
129
+ - `pages`: stable page records with `id`, `title`, safe Wiki-relative `path`, optional `parentId`, `purpose`, `audience`, `outline`, `documentIds`, project-relative `sourceRefs`, `evidenceQueries`, and page-local `evidenceHash`.
130
+
131
+ `mdgraph wiki brief <page-id> --plan <file> --json` returns:
132
+
133
+ - `format: "mdgraph-wiki-page-brief"`, `formatVersion: 1`, and the selected `page`.
134
+ - `maxChars` and `usedChars`, where the used budget covers `contextItems` content/Card summaries and serialized `knowledgeCards`.
135
+ - `sourceDocuments` with authoritative document IDs, paths, titles, lifecycle/type/trust metadata; plus `contextItems`, `knowledgeCards`, `writingRequirements`, and `suggestedNextQueries`.
136
+
137
+ `mdgraph wiki status <wiki-dir> --plan <file> --json` is read-only and returns:
138
+
139
+ - `format: "mdgraph-wiki-status"`, `formatVersion: 1`, `wikiDir`, and current/stale plan hashes.
140
+ - `pages` with `current | needs_update | missing | orphaned`; every non-current page includes `reason` and an executable or review-oriented `recovery` action.
141
+ - `summary` counts for all four states.
142
+
143
+ `mdgraph wiki verify <wiki-dir> --plan <file> --json` is read-only and returns `format: "mdgraph-wiki-verification"`, `formatVersion: 1`, `valid`, structured `errors`, `warnings`, and the same `status`. Issues include stable `code`, page/path evidence when available, and `recovery`. Invalid verification exits non-zero.
144
+
145
+ Plan and brief output is deterministic for the same graph and source state. Status and verification never overwrite Wiki prose, do not judge prose quality, and do not require embeddings or a generation provider.
88
146
 
89
147
  ## `node --json`
90
148
 
91
149
  `mdgraph node <query> --json` returns the resolved node record when found:
92
150
 
93
- - `id`, `label`, `kind`, `data`.
151
+ - `id`, `label`, `kind`, `data`, and optional experimental `card` for document, section, entity, and source-ref nodes.
152
+
153
+ `card` is a deterministic, non-persisted query projection with `nodeId`, `kind`, `label`, `summary`, `definitions`, `sourceRefs`, `relatedDocuments`, `evidence`, and optional omission counts in `truncated`. Arrays are stably ordered and retain node IDs, paths, edge kinds, provenance, confidence, anchors, or line ranges where applicable. Chunk nodes retain their existing shape without a card.
94
154
 
95
155
  When a section query is ambiguous, it returns:
96
156
 
@@ -113,14 +173,14 @@ When no node is found, it returns:
113
173
 
114
174
  - `querySet`: `alpha` by default or `cjk` when `--query-set cjk` is provided.
115
175
  - `limit`: search result limit used per case.
116
- - `ranking`: query mode, RRF search fusion, context packing strategy, optional reranker status, semantic-active case count, search channels, ranking reason coverage, and average context diversity.
176
+ - `ranking`: query mode, RRF search fusion, context packing strategy, optional reranker status, semantic-active case count, search channels, ranking reason coverage, average context diversity, and optional deduplicated `semanticDiagnostics`.
117
177
  - `generatedAt`: ISO timestamp for the evaluation run.
118
178
  - `summary`: `cases`, `passed`, `failed`, `averageTopKDocumentRecall`, `averageExpectedSectionRecall`, `averageContextPrecision`, `averageContextDiversity`, `averageLatencyMs`, and `averageReturnedChars`.
119
179
  - `cases`: per-case results with `id`, `query`, `passed`, `expected`, `observed`, and `metrics`.
120
180
 
121
- Per-case `expected` includes expected documents, sections, entities, edge kinds, and source refs. Per-case `observed` includes ranked search document paths, context item paths/headings/reasons, matched entities, resolved entities, resolved source refs, observed edge kinds, optional trace results, and ranking diagnostics. Per-case `metrics` includes top-K document recall, expected-section recall, context precision, entity recall, source-ref recall, edge-kind coverage, trace success, latency, returned characters, budget fit, fanout, reason coverage, ranking reason coverage, and context diversity.
181
+ Per-case `expected` includes expected documents, sections, entities, edge kinds, and source refs. Per-case `observed` includes ranked search document paths, context item paths/headings/reasons, matched entities, resolved entities, resolved source refs, observed edge kinds, optional trace results, and ranking diagnostics with an optional `semanticDiagnostic`. Per-case `metrics` includes top-K document recall, expected-section recall, context precision, entity recall, source-ref recall, edge-kind coverage, trace success, latency, returned characters, budget fit, fanout, reason coverage, ranking reason coverage, and context diversity.
122
182
 
123
- `mdgraph eval --path <project> --json` evaluates an explicit local project path. It does not add MCP tools and does not index automatically; run `mdgraph index` first for the target project. `mdgraph eval --query-set cjk --path <project> --json` uses repository-owned Chinese/Japanese expected records to measure CJK retrieval quality with the lightweight CJK n-gram preprocessing baseline. `mdgraph eval --query-mode semantic --json` requests optional semantic search and reports whether the local semantic reranker was active.
183
+ `mdgraph eval --path <project> --json` evaluates an explicit local project path. It does not add MCP tools and does not index automatically; run `mdgraph index` first for the target project. `mdgraph eval --query-set cjk --path <project> --json` uses repository-owned Chinese/Japanese expected records to measure CJK retrieval quality with the lightweight CJK n-gram preprocessing baseline. `mdgraph eval --query-mode semantic --json` requests optional semantic search and reports whether the configured semantic provider was active.
124
184
 
125
185
  ## `export graphjson --json`
126
186
 
@@ -144,7 +204,7 @@ The structural profile excludes chunks, chunk content, section content, vectors,
144
204
  - `warnings`: non-fatal compatibility notes.
145
205
  - `format`, `formatVersion`, `schemaVersion`, `graphHash`, `counts`, and `exportedCounts` when readable.
146
206
 
147
- The command exits non-zero when `valid` is `false`. GraphJSON merge import is not supported in 0.7. Oversized or deeply nested GraphJSON files are rejected before verification.
207
+ The command exits non-zero when `valid` is `false`. GraphJSON merge import is not supported. Oversized or deeply nested GraphJSON files are rejected before verification.
148
208
 
149
209
  ## `export mermaid trace --json`
150
210
 
@@ -188,7 +248,7 @@ The bridge reads only an explicit MDGraph JSON artifact with a `files` array con
188
248
  - `manifestPath`: absolute path to `manifest.json`.
189
249
  - `manifest`: bundle manifest with `format`, `formatVersion`, `schemaVersion`, `mdgraphVersion`, `createdAt`, `visibility`, `sourceHash`, `configHash`, `provenance`, `counts`, `documents`, and optional `reports`.
190
250
 
191
- The private bundle contains `manifest.json`, `graph.db`, `config.json`, and a `reports/status-storage.json` snapshot. `sourceHash` is derived from canonical config plus sorted document path/hash records; it does not include Markdown body content or the absolute project root. Public or sanitized bundle profiles are not supported in 0.6.
251
+ The private bundle contains `manifest.json`, `graph.db`, `config.json`, and a `reports/status-storage.json` snapshot. `sourceHash` is derived from canonical config plus sorted document path/hash records; it does not include Markdown body content or the absolute project root. Public or sanitized bundle profiles are not supported.
192
252
 
193
253
  ## `bundle verify --json`
194
254
 
@@ -254,6 +314,7 @@ Diff only compares Markdown graph records, source refs, and doctor warning codes
254
314
  - `projectRoot`.
255
315
  - `state`: `disabled`, `not_indexed`, `ready`, `unsupported_provider`, or `needs_reindex`.
256
316
  - `enabled`, `provider`, `model`, `dimensions`, and `providerSupported` for the configured embedding provider.
317
+ - `capability`: `lexical-hash`, `semantic-model`, or `unknown`; `runtimeStatus`: `available`, `unavailable`, `model_missing`, `unchecked`, or `disabled`; optional `runtimeReason` when a runtime check fails.
257
318
  - `indexed`, `chunks`, `vectors`, `vectorStorageFormat`, and `indexedProviders`.
258
319
  - `guidance`: actionable next steps such as running `mdgraph index --semantic`, re-embedding after provider changes, or falling back to FTS5 and graph search for unsupported providers.
259
320
 
@@ -272,3 +333,15 @@ Diff only compares Markdown graph records, source refs, and doctor warning codes
272
333
  Initial warning codes cover the existing doctor checks, front matter diagnostics, lifecycle governance, graph health, storage health, parse failures, and conservative convention linting: `index.stale`, `link.dead`, `source_ref.missing`, `definition.missing`, `definition.duplicate`, `content.risk`, `document.orphan`, `document.deleted`, `document.weakly_linked`, `document.deprecated_referenced`, `document.superseded_referenced`, `document.parse_failed`, `graph.missing_decision_link`, `storage.generated_path_indexed`, `storage.database_oversized`, `storage.fts_shadow_large`, `storage.high_degree_node`, `storage.vector_anomaly`, `front_matter.invalid_yaml`, `front_matter.not_mapping`, `front_matter.unclosed`, `front_matter.invalid_field`, `tag.invalid_format`, and `link.non_posix_path`.
273
334
 
274
335
  `mdgraph doctor --strict` keeps the same output shape and exits with a non-zero status when any summary issue count other than `documents` is greater than zero. `mdgraph doctor --fail-on <severity>` adds a typed warning gate without changing `--strict`, and `--changed` / `--since <ref>` return scoped reports with explicit scope metadata. Scoped reports include scoped Markdown paths plus directly related one-hop graph documents; deleted Markdown paths are preserved in scope metadata and reported with `document.deleted` after the index is fresh. Global storage summaries may still be present for observability, but storage warnings are omitted when `globalHealthIncluded` is `false`.
336
+
337
+ ## Evaluation evidence additions
338
+
339
+ Evaluation cases add `retrievalEvidencePassed`; `metrics` add `retrievedEntityRecall`, `retrievedSourceRefRecall`, `retrievedEdgeKindCoverage`, and `contextIrrelevantRatio`. `observed` adds the corresponding returned-entity, returned-source-ref, and returned-edge-kind arrays. These report this query's exposed evidence. Legacy coverage metrics and `passed` retain their existing meaning. See [Evaluation Questions](Evaluation_Questions.md).
340
+
341
+ ## Knowledge Card ownership and Wiki maintenance
342
+
343
+ Card references add optional `association` (`direct | inherited | related`), `originNodeId`, and `viaNodeId`. Optional `nextReads` contains paths, graph identity, reading reasons, and ownership. These fields count toward the full 4,000-character default Card JSON budget.
344
+
345
+ New Wiki plans use formatVersion 2 and record `wikiDir`, dependency snapshots, source/page suggestions, and evidence gaps. Version 1 plans remain readable; upgrading through `wiki plan --from` requires `--wiki-dir` and a separate `--out` file. Page suggestions are complete page records; source suggestions contain `pageId`, `documentIds`, and `sourceRefs`.
346
+
347
+ Brief, status, and verification retain formatVersion 1 with additive fields. Brief adds `supplementaryDocuments`, `sourceInspections`, `evidenceGaps`, and `dependencyEvidence`. Status pages add `changes`, `selectionChanges`, and `evidenceState`. Verify adds `scope: "maintenance-and-evidence"` and `contentReview: "not-evaluated"`; `valid` does not certify prose accuracy.