@daogee/mdgraph 1.0.0 → 1.1.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 (81) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README-ZH.md +54 -2
  3. package/README.md +73 -21
  4. package/dist/bin/mdgraph.js +136 -19
  5. package/dist/config/limits.d.ts +2 -0
  6. package/dist/config/limits.js +3 -1
  7. package/dist/config/load-config.js +8 -2
  8. package/dist/db/repositories.d.ts +27 -0
  9. package/dist/db/repositories.js +310 -6
  10. package/dist/evaluation/context-packing-evaluation.d.ts +29 -0
  11. package/dist/evaluation/context-packing-evaluation.js +134 -0
  12. package/dist/evaluation/entity-extraction-evaluation.d.ts +38 -0
  13. package/dist/evaluation/entity-extraction-evaluation.js +118 -0
  14. package/dist/evaluation/historical-baseline.d.ts +70 -0
  15. package/dist/evaluation/historical-baseline.js +278 -0
  16. package/dist/evaluation/related-documents-evaluation.d.ts +26 -0
  17. package/dist/evaluation/related-documents-evaluation.js +163 -0
  18. package/dist/evaluation/retrieval-eval.d.ts +14 -5
  19. package/dist/evaluation/retrieval-eval.js +44 -6
  20. package/dist/evaluation/structured-query-evaluation.d.ts +27 -0
  21. package/dist/evaluation/structured-query-evaluation.js +156 -0
  22. package/dist/extraction/entity-extractor.js +42 -22
  23. package/dist/extraction/graph-builder.js +2 -18
  24. package/dist/index.d.ts +17 -4
  25. package/dist/index.js +9 -4
  26. package/dist/indexer.js +20 -2
  27. package/dist/mcp/server.d.ts +4 -0
  28. package/dist/mcp/server.js +16 -7
  29. package/dist/mcp/tools.d.ts +5 -1
  30. package/dist/mcp/tools.js +93 -9
  31. package/dist/parser/markdown-parser.js +2 -0
  32. package/dist/query/context-builder.d.ts +31 -2
  33. package/dist/query/context-builder.js +162 -12
  34. package/dist/query/search.d.ts +5 -1
  35. package/dist/query/search.js +77 -13
  36. package/dist/query/structured-query-executor.d.ts +28 -0
  37. package/dist/query/structured-query-executor.js +138 -0
  38. package/dist/query/structured-query.d.ts +50 -0
  39. package/dist/query/structured-query.js +390 -0
  40. package/dist/relationships/derive-related.d.ts +86 -0
  41. package/dist/relationships/derive-related.js +322 -0
  42. package/dist/reporting/report.js +2 -2
  43. package/dist/semantic/embed-chunks.d.ts +2 -0
  44. package/dist/semantic/embed-chunks.js +31 -0
  45. package/dist/semantic/ollama-provider.d.ts +6 -0
  46. package/dist/semantic/ollama-provider.js +131 -0
  47. package/dist/semantic/provider-registry.d.ts +8 -0
  48. package/dist/semantic/provider-registry.js +66 -0
  49. package/dist/semantic/provider.d.ts +35 -0
  50. package/dist/semantic/provider.js +29 -0
  51. package/dist/semantic/status.d.ts +6 -1
  52. package/dist/semantic/status.js +49 -3
  53. package/dist/types.d.ts +7 -2
  54. package/dist/types.js +2 -1
  55. package/dist/watcher/file-watcher.d.ts +4 -0
  56. package/dist/watcher/file-watcher.js +75 -10
  57. package/dist/watcher/watch-health.d.ts +34 -0
  58. package/dist/watcher/watch-health.js +75 -0
  59. package/docs/EN/Agent_Integration.md +1 -1
  60. package/docs/EN/Architecture.md +39 -16
  61. package/docs/EN/Evaluation_Questions.md +21 -5
  62. package/docs/EN/Operations.md +91 -0
  63. package/docs/EN/Output_Contracts.md +41 -7
  64. package/docs/EN/Public_Contracts.md +23 -16
  65. package/docs/EN/Public_Contracts_1.0.md +28 -18
  66. package/docs/EN/README.md +23 -0
  67. package/docs/EN/Release_Checklist.md +26 -13
  68. package/docs/EN/Retrieval_and_Context.md +112 -0
  69. package/docs/EN/Structured_Query_and_Relationships.md +111 -0
  70. package/docs/ZH/Agent_Integration.md +1 -1
  71. package/docs/ZH/Architecture.md +39 -19
  72. package/docs/ZH/Evaluation_Questions.md +22 -6
  73. package/docs/ZH/Operations.md +91 -0
  74. package/docs/ZH/Output_Contracts.md +41 -7
  75. package/docs/ZH/Public_Contracts.md +22 -15
  76. package/docs/ZH/Public_Contracts_1.0.md +27 -17
  77. package/docs/ZH/README.md +23 -0
  78. package/docs/ZH/Release_Checklist.md +26 -13
  79. package/docs/ZH/Retrieval_and_Context.md +112 -0
  80. package/docs/ZH/Structured_Query_and_Relationships.md +111 -0
  81. package/package.json +44 -18
package/CHANGELOG.md CHANGED
@@ -2,6 +2,28 @@
2
2
 
3
3
  All notable changes to MDGraph are documented here. MDGraph follows semantic versioning for its public releases.
4
4
 
5
+ ## Unreleased
6
+
7
+ ## 1.1.0 - 2026-08-03
8
+
9
+ ### Added
10
+
11
+ - Opt-in Ollama embeddings through a provider interface, with batched asynchronous indexing, provider-aware query paths, runtime diagnostics, and atomic failure behavior.
12
+ - Source-aware entity extraction for higher-precision technical symbols plus Unicode-aware CJK API routes, configuration keys, and function identifiers.
13
+ - Opt-in true MMR context packing, persistent watcher health, and explicit polling fallbacks for environments where native file watching is unreliable.
14
+ - An experimental, parameterized `query` DSL for document metadata, tags, outgoing edges, dates, sorting, limits, and selected documentation-health predicates.
15
+ - An experimental `relationships derive` workflow for conservative, provider-gated `RELATED_TO` edges with independent evidence, reciprocal-neighbor checks, provenance, and atomic replacement.
16
+
17
+ ### Changed
18
+
19
+ - `local-hash` is documented and reported as a deterministic lexical feature hash rather than a language-model embedding.
20
+ - Public documentation is organized by user task instead of implementation-stage pages, and the npm package uses an explicit documentation allowlist.
21
+ - Internal regression suites, evaluation APIs, and release commands use capability names instead of implementation milestone labels.
22
+
23
+ ### Compatibility
24
+
25
+ - 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.
26
+
5
27
  ## 1.0.0 - 2026-07-12
6
28
 
7
29
  ### Added
package/README-ZH.md CHANGED
@@ -11,7 +11,7 @@
11
11
  [![Node](https://img.shields.io/badge/Node-%3E%3D22.5.0-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
- <a href="./README.md">English</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> · <a href="./docs/ZH/Output_Contracts.md">输出契约</a>
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>
15
15
 
16
16
  </div>
17
17
 
@@ -26,7 +26,7 @@
26
26
  ```text
27
27
  $ mdgraph context "Markdown 文件如何经过索引流程变成代理上下文?"
28
28
 
29
- docs/EN/Architecture.md:49 · Indexing Flow
29
+ docs/EN/Architecture.md:59 · Indexing Flow
30
30
  Reason: FTS5 content match; RRF fusion
31
31
 
32
32
  1. scanMarkdownFiles 选择候选 Markdown 文件。
@@ -119,6 +119,7 @@ mdgraph status --freshness --path /your/project
119
119
  # CLI 搜索和上下文打包
120
120
  mdgraph search --path /your/project "authentication timeout"
121
121
  mdgraph context --path /your/project "why does RedisTimeoutError affect login"
122
+ mdgraph context --packing mmr --debug --path /your/project "why does RedisTimeoutError affect login"
122
123
 
123
124
  # 解析单个节点或追溯图谱路径
124
125
  mdgraph node --path /your/project "AuthService"
@@ -128,12 +129,59 @@ mdgraph trace --path /your/project "AuthService" "RedisTimeoutError"
128
129
  mdgraph doctor --path /your/project
129
130
  mdgraph doctor --since origin/main --fail-on warn --json --path /your/project
130
131
 
132
+ # 实验性结构化治理查询
133
+ mdgraph query --path /your/project 'type:adr AND status:accepted ORDER BY updated DESC'
134
+
135
+ # 实验性的 provider 门禁相关文档层
136
+ mdgraph relationships derive --dry-run --json --path /your/project
137
+ mdgraph relationships derive --threshold 0.86 --json --path /your/project
138
+
131
139
  # Agent 友好的使用指引
132
140
  mdgraph usage --path /your/project
133
141
  ```
134
142
 
135
143
  完整 CLI 参考请使用 `mdgraph help` 或 `mdgraph help <command>`。
136
144
 
145
+ 真 MMR 打包为 opt-in,文档轮询继续作为兼容默认值,详见[检索与上下文](./docs/ZH/Retrieval_and_Context.md)。Watcher polling 也必须显式启用(`watch --poll` 或 `serve --mcp --watch-poll`),因为它可能增加 I/O 和 CPU;详见[运行与故障处理](./docs/ZH/Operations.md)。
146
+
147
+ 实验性的 `query` 命令提供有界、参数化的文档治理 DSL,不改变 `search` 或五工具 MCP surface。
148
+
149
+ 实验性的 `relationships derive` 只会基于 fresh、完整的 semantic-model index,在独立 evidence 与 reciprocal-neighbor 门禁通过后创建低权重 `RELATED_TO` edge;它不会在 indexing 或 watch mode 中自动运行。两个实验性工作流均记录在[结构化查询与派生关系](./docs/ZH/Structured_Query_and_Relationships.md)。
150
+
151
+ ---
152
+
153
+ ## 可选 Ollama Embedding
154
+
155
+ 真实语义检索需要显式启用;确定性的 FTS5/entity/graph 流水线仍是默认行为。先在本机启动 Ollama 并安装 embedding 模型:
156
+
157
+ ```bash
158
+ ollama pull nomic-embed-text
159
+ ```
160
+
161
+ 配置 `.mdgraph/config.json`(其他配置 section 可保持不变):
162
+
163
+ ```json
164
+ {
165
+ "embedding": {
166
+ "enabled": true,
167
+ "provider": "ollama",
168
+ "model": "nomic-embed-text",
169
+ "dimensions": 768,
170
+ "endpoint": "http://127.0.0.1:11434",
171
+ "timeoutMs": 30000,
172
+ "batchSize": 16
173
+ }
174
+ }
175
+ ```
176
+
177
+ ```bash
178
+ mdgraph index --full --semantic --path /your/project
179
+ mdgraph semantic status --path /your/project
180
+ mdgraph search --semantic --path /your/project "authentication login"
181
+ ```
182
+
183
+ 查询时 provider 失败会降级到 FTS5/entity/graph 结果并输出诊断。显式 semantic indexing 会在替换现有 graph 前失败,因此不会提交部分 vector coverage。`local-hash` 为兼容继续可用,但它是词法 feature hash,不是语言模型 embedding。
184
+
137
185
  ---
138
186
 
139
187
  ## 为什么团队可以信任它
@@ -148,8 +196,12 @@ mdgraph usage --path /your/project
148
196
 
149
197
  ## 文档导航
150
198
 
199
+ - `docs/ZH/README.md` — 按任务组织的文档入口。
151
200
  - `docs/ZH/Architecture.md` — 流水线、模块边界、数据流和取舍。
152
201
  - `docs/ZH/Agent_Integration.md` — MCP 配置、共享 agent 指令和宿主说明。
202
+ - `docs/ZH/Retrieval_and_Context.md` — 搜索通道、embedding provider、实体抽取、CJK 行为和上下文打包。
203
+ - `docs/ZH/Structured_Query_and_Relationships.md` — 结构化治理 DSL 和显式派生关系。
204
+ - `docs/ZH/Operations.md` — 索引新鲜度、watcher health、polling 和 provider 恢复。
153
205
  - `docs/ZH/Public_Contracts.md` — 稳定公开表面、兼容策略和发布门禁。
154
206
  - `docs/ZH/Public_Contracts_1.0.md` — 1.0 契约冻结附录,列出当前 `1.0.0` 基线下冻结的 CLI、配置、MCP、JSON 与 schema 清单。
155
207
  - `docs/ZH/Output_Contracts.md` — CLI 和 MCP 消费者使用的 JSON 输出形状。
package/README.md CHANGED
@@ -11,7 +11,7 @@
11
11
  [![Node](https://img.shields.io/badge/Node-%3E%3D22.5.0-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
- <a href="./README-ZH.md">简体中文</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> · <a href="./docs/EN/Output_Contracts.md">Output Contracts</a>
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>
15
15
 
16
16
  </div>
17
17
 
@@ -26,7 +26,7 @@ Text search finds matching words. MDGraph finds the surrounding decision, the co
26
26
  ```text
27
27
  $ mdgraph context "How does indexing flow from Markdown files to agent context?"
28
28
 
29
- docs/EN/Architecture.md:49 · Indexing Flow
29
+ docs/EN/Architecture.md:59 · Indexing Flow
30
30
  Reason: FTS5 content match; RRF fusion
31
31
 
32
32
  1. scanMarkdownFiles selects candidate Markdown files.
@@ -117,26 +117,74 @@ mdgraph index --path /your/project
117
117
  mdgraph status --freshness --path /your/project
118
118
 
119
119
  # Search and context-pack from the CLI
120
- mdgraph search --path /your/project "authentication timeout"
121
- mdgraph context --path /your/project "why does RedisTimeoutError affect login"
120
+ mdgraph search --path /your/project "authentication timeout"
121
+ mdgraph context --path /your/project "why does RedisTimeoutError affect login"
122
+ mdgraph context --packing mmr --debug --path /your/project "why does RedisTimeoutError affect login"
122
123
 
123
124
  # Resolve one node or trace a graph path
124
125
  mdgraph node --path /your/project "AuthService"
125
126
  mdgraph trace --path /your/project "AuthService" "RedisTimeoutError"
126
127
 
127
- # Documentation health checks
128
- mdgraph doctor --path /your/project
129
- mdgraph doctor --since origin/main --fail-on warn --json --path /your/project
130
-
131
- # Agent-friendly workflow guide
132
- mdgraph usage --path /your/project
128
+ # Documentation health checks
129
+ mdgraph doctor --path /your/project
130
+ mdgraph doctor --since origin/main --fail-on warn --json --path /your/project
131
+
132
+ # Experimental structured governance query
133
+ mdgraph query --path /your/project 'type:adr AND status:accepted ORDER BY updated DESC'
134
+
135
+ # Experimental provider-gated related-document layer
136
+ mdgraph relationships derive --dry-run --json --path /your/project
137
+ mdgraph relationships derive --threshold 0.86 --json --path /your/project
138
+
139
+ # Agent-friendly workflow guide
140
+ mdgraph usage --path /your/project
133
141
  ```
134
142
 
135
- Use `mdgraph help` or `mdgraph help <command>` for the full CLI reference.
136
-
137
- ---
138
-
139
- ## Why Teams Can Trust It
143
+ Use `mdgraph help` or `mdgraph help <command>` for the full CLI reference.
144
+
145
+ True MMR packing is opt-in; document round-robin remains the compatibility default. See [Retrieval and Context](./docs/EN/Retrieval_and_Context.md). Watcher polling is also explicit (`watch --poll` or `serve --mcp --watch-poll`) because it can increase I/O and CPU use; see [Operations](./docs/EN/Operations.md).
146
+
147
+ The experimental `query` command provides a bounded, parameterized DSL for document governance without changing `search` or the five-tool MCP surface.
148
+
149
+ 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).
150
+
151
+ ---
152
+
153
+ ## Optional Ollama Embeddings
154
+
155
+ Real semantic retrieval is opt-in; the deterministic FTS5/entity/graph pipeline remains the default. Start Ollama locally and install an embedding model:
156
+
157
+ ```bash
158
+ ollama pull nomic-embed-text
159
+ ```
160
+
161
+ Configure `.mdgraph/config.json` (the other config sections may remain unchanged):
162
+
163
+ ```json
164
+ {
165
+ "embedding": {
166
+ "enabled": true,
167
+ "provider": "ollama",
168
+ "model": "nomic-embed-text",
169
+ "dimensions": 768,
170
+ "endpoint": "http://127.0.0.1:11434",
171
+ "timeoutMs": 30000,
172
+ "batchSize": 16
173
+ }
174
+ }
175
+ ```
176
+
177
+ ```bash
178
+ mdgraph index --full --semantic --path /your/project
179
+ mdgraph semantic status --path /your/project
180
+ mdgraph search --semantic --path /your/project "authentication login"
181
+ ```
182
+
183
+ Query-time provider failures fall back to FTS5/entity/graph results and emit a diagnostic. Explicit semantic indexing fails before replacing the existing graph, so it cannot commit partial vector coverage. `local-hash` remains available for compatibility but is a lexical feature hash, not a language-model embedding.
184
+
185
+ ---
186
+
187
+ ## Why Teams Can Trust It
140
188
 
141
189
  - **Local by default.** Markdown, chunks, vectors, and SQLite artifacts stay in the project environment.
142
190
  - **Explainable by design.** Results retain matching reasons, entities, edge provenance, confidence, paths, and budget information where relevant.
@@ -146,15 +194,19 @@ Use `mdgraph help` or `mdgraph help <command>` for the full CLI reference.
146
194
 
147
195
  ---
148
196
 
149
- ## Documentation Map
150
-
151
- - `docs/EN/Architecture.md` — pipeline, module boundaries, data flow, tradeoffs.
152
- - `docs/EN/Agent_Integration.md` — MCP setup, shared agent instructions, host notes.
153
- - `docs/EN/Public_Contracts.md` — stable public surfaces, compatibility policy, release gates.
197
+ ## Documentation Map
198
+
199
+ - `docs/EN/README.md` — task-oriented documentation index.
200
+ - `docs/EN/Architecture.md` — pipeline, module boundaries, data flow, tradeoffs.
201
+ - `docs/EN/Agent_Integration.md` — MCP setup, shared agent instructions, host notes.
202
+ - `docs/EN/Retrieval_and_Context.md` — search channels, embedding providers, entity extraction, CJK behavior, and context packing.
203
+ - `docs/EN/Structured_Query_and_Relationships.md` — structured governance DSL and explicit derived relationships.
204
+ - `docs/EN/Operations.md` — index freshness, watcher health, polling, and provider recovery.
205
+ - `docs/EN/Public_Contracts.md` — stable public surfaces, compatibility policy, release gates.
154
206
  - `docs/EN/Public_Contracts_1.0.md` — 1.0 contract-freeze appendix with the frozen CLI, config, MCP, JSON, and schema inventory for the current `1.0.0` baseline.
155
207
  - `docs/EN/Output_Contracts.md` — JSON output shapes for CLI and MCP consumers.
156
208
  - `docs/EN/Evaluation_Questions.md` — retrieval/evaluation prompts.
157
- - `docs/EN/Release_Checklist.md` — release validation checklist.
209
+ - `docs/EN/Release_Checklist.md` — release validation checklist.
158
210
  - `agent-pack/` — reusable MCP config, instructions, and prompt templates.
159
211
 
160
212
  ---
@@ -10,18 +10,20 @@ import { databasePath, initProjectConfig, loadConfig } from "../config/load-conf
10
10
  import { openExistingDatabase } from "../db/connection.js";
11
11
  import { GraphRepository } from "../db/repositories.js";
12
12
  import { formatGraphDiff, generateGraphDiff } from "../diff/graph-diff.js";
13
- import { EVALUATION_QUERY_SET_NAMES, evaluateRetrieval } from "../evaluation/retrieval-eval.js";
13
+ import { EVALUATION_QUERY_SET_NAMES, evaluateRetrievalAsync } from "../evaluation/retrieval-eval.js";
14
14
  import { buildMermaidTraceExport } from "../export/diagram.js";
15
15
  import { buildGraphJsonExport, formatGraphJsonVerification, readGraphJsonFile, stableGraphJson, verifyGraphJsonExport } from "../export/graphjson.js";
16
16
  import { buildDocsSiteIndex, formatWikiLinkMarkdownIndex } from "../export/markdown-index.js";
17
17
  import { buildSourceBridgeReport } from "../export/source-bridge.js";
18
18
  import { indexProject } from "../indexer.js";
19
19
  import { startStdioMcpServer } from "../mcp/server.js";
20
- import { buildContext } from "../query/context-builder.js";
21
- import { explainSearchGraph, searchGraph } from "../query/search.js";
20
+ import { CONTEXT_PACKING_STRATEGIES, buildContextAsync } from "../query/context-builder.js";
21
+ import { explainSearchGraphAsync } from "../query/search.js";
22
22
  import { traceNodes } from "../query/trace.js";
23
+ import { executeStructuredQuery } from "../query/structured-query-executor.js";
24
+ import { deriveRelatedRelationships } from "../relationships/derive-related.js";
23
25
  import { formatReport, generateReport } from "../reporting/report.js";
24
- import { semanticStatusReport } from "../semantic/status.js";
26
+ import { semanticStatusReportAsync } from "../semantic/status.js";
25
27
  import { packageVersion } from "../version.js";
26
28
  import { watchProject } from "../watcher/file-watcher.js";
27
29
  const program = new Command();
@@ -111,18 +113,18 @@ program
111
113
  .option("--semantic", "Include local semantic vector matches when vectors are indexed")
112
114
  .option("--explain", "Include query parsing and ranking explanation details")
113
115
  .option("--path <path>", "Project root. Defaults to the current working directory")
114
- .action((query, options) => {
116
+ .action(async (query, options) => {
115
117
  const projectRoot = projectRootFromOption(options.path);
116
118
  const config = loadConfig(projectRoot);
117
119
  const repository = openRepository(projectRoot);
118
120
  try {
121
+ const explanation = await explainSearchGraphAsync(repository, config, query, options.limit ?? config.search.defaultLimit, { semantic: options.semantic });
122
+ printSemanticDiagnostic(explanation.semanticDiagnostic);
119
123
  if (options.explain) {
120
- const explanation = explainSearchGraph(repository, config, query, options.limit ?? config.search.defaultLimit, { semantic: options.semantic });
121
124
  printResult(options.json, explanation, formatSearchExplanation(explanation));
122
125
  return;
123
126
  }
124
- const results = searchGraph(repository, config, query, options.limit ?? config.search.defaultLimit, { semantic: options.semantic });
125
- printResult(options.json, results, formatSearchResults(results));
127
+ printResult(options.json, explanation.results, formatSearchResults(explanation.results));
126
128
  }
127
129
  finally {
128
130
  closeRepository(repository);
@@ -134,19 +136,43 @@ program
134
136
  .argument("<query>")
135
137
  .option("--json", "Print JSON output")
136
138
  .option("--debug", "Include context packing and graph expansion debug details")
139
+ .option("--packing <strategy>", `Context packing strategy: ${CONTEXT_PACKING_STRATEGIES.join(" | ")}`, parseContextPackingStrategy)
140
+ .option("--mmr-lambda <number>", "MMR query-relevance weight from 0 to 1", parseUnitInterval)
137
141
  .option("--path <path>", "Project root. Defaults to the current working directory")
138
- .action((query, options) => {
142
+ .action(async (query, options) => {
139
143
  const projectRoot = projectRootFromOption(options.path);
140
144
  const config = loadConfig(projectRoot);
141
145
  const repository = openRepository(projectRoot);
142
146
  try {
143
- const context = buildContext(repository, config, query, { debug: options.debug });
147
+ const context = await buildContextAsync(repository, config, query, {
148
+ debug: options.debug,
149
+ packingStrategy: options.packing,
150
+ mmrLambda: options.mmrLambda
151
+ });
152
+ printSemanticDiagnostic(context.semanticDiagnostic);
144
153
  printResult(options.json, context, formatContext(context));
145
154
  }
146
155
  finally {
147
156
  closeRepository(repository);
148
157
  }
149
158
  });
159
+ program
160
+ .command("query")
161
+ .description("Run an experimental deterministic structured document query")
162
+ .argument("<expression>", "Structured expression, for example: type:adr AND status:accepted")
163
+ .option("--json", "Print JSON output")
164
+ .option("--path <path>", "Project root. Defaults to the current working directory")
165
+ .action(async (expression, options) => {
166
+ const projectRoot = projectRootFromOption(options.path);
167
+ const repository = openRepository(projectRoot);
168
+ try {
169
+ const result = await executeStructuredQuery(repository, projectRoot, expression);
170
+ printResult(options.json, result, formatStructuredQueryResult(result));
171
+ }
172
+ finally {
173
+ closeRepository(repository);
174
+ }
175
+ });
150
176
  program
151
177
  .command("node")
152
178
  .description("Show a document, entity, source ref, section, or chunk")
@@ -189,12 +215,15 @@ program
189
215
  .option("--limit <number>", "Search results per evaluation case", parseInteger)
190
216
  .option("--query-set <name>", `Evaluation query set (${EVALUATION_QUERY_SET_NAMES.join(", ")})`, "alpha")
191
217
  .option("--query-mode <mode>", "Search query mode for evaluation (auto, keyword, semantic)", parseSearchQueryMode, "auto")
192
- .action((options) => {
218
+ .action(async (options) => {
193
219
  const projectRoot = validateProjectRoot(options.path);
194
220
  const config = loadConfig(projectRoot);
195
221
  const repository = openRepository(projectRoot);
196
222
  try {
197
- const report = evaluateRetrieval(repository, config, { limit: options.limit, querySet: options.querySet, queryMode: options.queryMode });
223
+ const report = await evaluateRetrievalAsync(repository, config, { limit: options.limit, querySet: options.querySet, queryMode: options.queryMode });
224
+ for (const diagnostic of report.ranking.semanticDiagnostics ?? []) {
225
+ printSemanticDiagnostic(diagnostic);
226
+ }
198
227
  printResult(options.json, report, formatEvaluationReport(report));
199
228
  }
200
229
  finally {
@@ -209,23 +238,52 @@ semanticCommand
209
238
  .description("Show semantic provider, vector coverage, and reindex guidance")
210
239
  .option("--json", "Print JSON output")
211
240
  .option("--path <path>", "Project root to inspect", process.cwd())
212
- .action((options) => {
241
+ .action(async (options) => {
213
242
  const projectRoot = validateProjectRoot(options.path);
214
243
  const config = loadConfig(projectRoot);
215
244
  if (!fs.existsSync(databasePath(projectRoot))) {
216
- const report = semanticStatusReport(config, undefined, undefined);
245
+ const report = await semanticStatusReportAsync(config, undefined, undefined);
217
246
  printResult(options.json, { projectRoot, ...report }, formatSemanticStatus(projectRoot, report));
218
247
  return;
219
248
  }
220
249
  const repository = openRepository(projectRoot);
221
250
  try {
222
- const report = semanticStatusReport(config, repository.counts(), repository.storageDiagnostics());
251
+ const report = await semanticStatusReportAsync(config, repository.counts(), repository.storageDiagnostics());
223
252
  printResult(options.json, { projectRoot, ...report }, formatSemanticStatus(projectRoot, report));
224
253
  }
225
254
  finally {
226
255
  closeRepository(repository);
227
256
  }
228
257
  });
258
+ const relationshipsCommand = program
259
+ .command("relationships")
260
+ .description("Manage opt-in derived graph relationships");
261
+ relationshipsCommand
262
+ .command("derive")
263
+ .description("Derive provider-gated RELATED_TO edges from indexed semantic vectors")
264
+ .option("--json", "Print JSON output")
265
+ .option("--threshold <number>", "Minimum independent chunk similarity from 0.75 to 1", parseUnitInterval)
266
+ .option("--max-neighbors <number>", "Maximum reciprocal neighbors per document from 1 to 10", parseInteger)
267
+ .option("--min-evidence <number>", "Independent section-pair evidence required from 2 to 4", parseInteger)
268
+ .option("--dry-run", "Evaluate relationships without replacing stored derived edges")
269
+ .option("--path <path>", "Project root. Defaults to the current working directory")
270
+ .action(async (options) => {
271
+ const projectRoot = projectRootFromOption(options.path);
272
+ const config = loadConfig(projectRoot);
273
+ const repository = openRepository(projectRoot);
274
+ try {
275
+ const report = await deriveRelatedRelationships(repository, projectRoot, config, {
276
+ threshold: options.threshold,
277
+ maxNeighbors: options.maxNeighbors,
278
+ minEvidence: options.minEvidence,
279
+ dryRun: options.dryRun
280
+ });
281
+ printResult(options.json, report, formatDerivedRelationships(report));
282
+ }
283
+ finally {
284
+ closeRepository(repository);
285
+ }
286
+ });
229
287
  const bundleCommand = program
230
288
  .command("bundle")
231
289
  .description("Create and verify reusable local graph bundle artifacts");
@@ -424,6 +482,7 @@ program
424
482
  .option("--no-watch", "Disable automatic index updates while serving MCP requests")
425
483
  .option("--semantic", "Build local semantic vectors during watch indexing")
426
484
  .option("--debounce <ms>", "Debounce delay in milliseconds for serve watch mode", parseInteger)
485
+ .option("--watch-poll", "Use explicit polling instead of native file-system events")
427
486
  .option("--path <path>", "Project root to serve", process.cwd())
428
487
  .action((options) => {
429
488
  if (!options.mcp) {
@@ -434,7 +493,8 @@ program
434
493
  projectRoot: validateProjectRoot(options.path),
435
494
  watch,
436
495
  semantic: watch ? options.semantic : undefined,
437
- debounceMs: watch ? options.debounce : undefined
496
+ debounceMs: watch ? options.debounce : undefined,
497
+ usePolling: watch ? options.watchPoll : undefined
438
498
  });
439
499
  });
440
500
  program
@@ -442,18 +502,29 @@ program
442
502
  .description("Watch Markdown files and incrementally update the graph index")
443
503
  .option("--semantic", "Build local semantic vectors during watch indexing")
444
504
  .option("--debounce <ms>", "Debounce delay in milliseconds", parseInteger)
505
+ .option("--poll", "Use explicit polling instead of native file-system events")
445
506
  .option("--path <path>", "Project root. Defaults to the current working directory")
446
507
  .action(async (options) => {
447
508
  const projectRoot = projectRootFromOption(options.path);
448
509
  console.error("MDGraph watch started. Press Ctrl+C to stop.");
510
+ let lastHealthState;
449
511
  const handle = await watchProject(projectRoot, {
450
512
  semantic: options.semantic,
451
513
  debounceMs: options.debounce,
514
+ usePolling: options.poll,
452
515
  onIndexed: (result) => {
453
516
  console.error(`Indexed ${result.changed} changed, ${result.deleted} deleted, ${result.unchanged} unchanged, ${result.skipped} skipped document(s).`);
454
517
  },
455
518
  onError: (error) => {
456
- console.error(`Watch indexing failed: ${error.message}`);
519
+ console.error(`Watch error: ${error.message}`);
520
+ },
521
+ onHealthChanged: (health) => {
522
+ if (health.state === lastHealthState) {
523
+ return;
524
+ }
525
+ lastHealthState = health.state;
526
+ const error = health.lastError ? ` (${health.lastError.code}/${health.lastError.phase}: ${health.lastError.message})` : "";
527
+ console.error(`Watch health: ${health.state}${health.polling ? " [polling]" : ""}${error}`);
457
528
  }
458
529
  });
459
530
  await new Promise((resolve) => {
@@ -571,7 +642,7 @@ function buildUsageGuide(projectRoot) {
571
642
  {
572
643
  name: "Help",
573
644
  purpose: "Inspect syntax for all commands or a specific command.",
574
- commands: ["mdgraph help", "mdgraph help search", "mdgraph usage --json"]
645
+ commands: ["mdgraph help", "mdgraph help search", "mdgraph help query", "mdgraph usage --json"]
575
646
  },
576
647
  {
577
648
  name: "Agent MCP",
@@ -710,9 +781,35 @@ function formatContext(context) {
710
781
  `Expanded edges: ${context.debug.expandedEdges}`,
711
782
  `Candidates: ${context.debug.candidateCount} (${context.debug.directCandidates} direct, ${context.debug.expandedCandidates} expanded)`,
712
783
  `Packing: ${context.debug.packingStrategy}, items: ${context.debug.packedItems}, unique documents: ${context.debug.packedUniqueDocuments}, diversity: ${context.debug.packingDiversityRatio.toFixed(2)}`,
784
+ context.debug.mmrLambda !== undefined
785
+ ? `MMR: lambda ${context.debug.mmrLambda.toFixed(2)}, similarity: ${context.debug.packingSimilarity}, redundancy skipped: ${context.debug.redundancySkippedItems ?? 0}`
786
+ : "",
713
787
  `Skipped visited: ${context.debug.skippedVisitedNodes}, node-limit: ${context.debug.skippedByNodeLimit}, depth: ${context.debug.skippedByDepth}`,
714
788
  `Budget truncated items: ${context.debug.budgetTruncatedItems}, skipped items: ${context.debug.budgetSkippedItems}`
715
- ].join("\n");
789
+ ].filter(Boolean).join("\n");
790
+ }
791
+ function formatStructuredQueryResult(result) {
792
+ const header = [
793
+ "MDGraph structured query",
794
+ `Query: ${result.query}`,
795
+ `Execution: ${result.execution.strategy} (${result.execution.stages.join(", ")}; ${result.execution.parameterCount} SQL parameter(s))`,
796
+ `Matches: ${result.total}; returned: ${result.returned}${result.truncated ? " (truncated)" : ""}`
797
+ ];
798
+ const items = result.items.map((item) => (`- ${item.document.path} [${item.document.type}/${item.document.status}; ${item.document.trustTier}]`));
799
+ return [...header, ...(items.length ? ["Results:", ...items] : ["No documents matched."])].join("\n");
800
+ }
801
+ function formatDerivedRelationships(report) {
802
+ const lines = [
803
+ "MDGraph derived relationships",
804
+ `Provider: ${report.provider}/${report.model} (${report.dimensions} dimensions)`,
805
+ `Gate: ${report.qualityGate.id} passed`,
806
+ `Corpus: ${report.corpus.eligibleDocuments}/${report.corpus.documents} eligible documents, ${report.corpus.vectors}/${report.corpus.chunks} vectors`,
807
+ `Relationships: ${report.relationshipPairs} pair(s), ${report.directedEdges} directed edge(s)${report.options.dryRun ? " [dry run]" : ""}`
808
+ ];
809
+ if (report.relationships.length) {
810
+ lines.push("Matches:", ...report.relationships.map((relationship) => (`- ${relationship.fromPath} <-> ${relationship.toPath} (${relationship.confidence.toFixed(4)}, ${relationship.evidenceSections.length} evidence section pair(s))`)));
811
+ }
812
+ return lines.join("\n");
716
813
  }
717
814
  function formatTrace(trace) {
718
815
  if (!trace.found) {
@@ -752,6 +849,8 @@ function formatSemanticStatus(projectRoot, report) {
752
849
  `State: ${report.state}`,
753
850
  `Configured provider: ${report.provider}/${report.model} (${report.dimensions} dimensions, enabled: ${report.enabled})`,
754
851
  `Provider supported: ${report.providerSupported}`,
852
+ `Provider capability: ${report.capability}`,
853
+ `Provider runtime: ${report.runtimeStatus}${report.runtimeReason ? ` - ${report.runtimeReason}` : ""}`,
755
854
  `Indexed: ${report.indexed}`,
756
855
  `Vectors: ${report.vectors}/${report.chunks} chunks`,
757
856
  `Vector storage: ${report.vectorStorageFormat}`,
@@ -759,6 +858,11 @@ function formatSemanticStatus(projectRoot, report) {
759
858
  `Guidance: ${report.guidance.join(" ") || "none"}`
760
859
  ].join("\n");
761
860
  }
861
+ function printSemanticDiagnostic(diagnostic) {
862
+ if (diagnostic) {
863
+ console.error(`MDGraph semantic fallback [${diagnostic.provider}/${diagnostic.code}]: ${diagnostic.message}`);
864
+ }
865
+ }
762
866
  function formatBundleCreate(result) {
763
867
  return [
764
868
  "Created MDGraph bundle",
@@ -844,6 +948,19 @@ function parseSearchQueryMode(value) {
844
948
  }
845
949
  throw new Error(`Expected query mode to be one of auto, keyword, or semantic; got ${value}`);
846
950
  }
951
+ function parseContextPackingStrategy(value) {
952
+ if (CONTEXT_PACKING_STRATEGIES.includes(value)) {
953
+ return value;
954
+ }
955
+ throw new Error(`Expected one of ${CONTEXT_PACKING_STRATEGIES.join(", ")}, got ${value}`);
956
+ }
957
+ function parseUnitInterval(value) {
958
+ const parsed = Number(value);
959
+ if (!Number.isFinite(parsed) || parsed < 0 || parsed > 1 || value.trim() === "") {
960
+ throw new Error(`Expected a number from 0 to 1, got ${value}`);
961
+ }
962
+ return parsed;
963
+ }
847
964
  function doctorIssueCount(summary) {
848
965
  return Object.entries(summary)
849
966
  .filter(([key]) => key !== "documents")
@@ -5,6 +5,8 @@ export declare const CONFIG_LIMITS: {
5
5
  readonly searchMaxContextChars: 200000;
6
6
  readonly searchHighFrequencyEntityThreshold: 100000;
7
7
  readonly embeddingDimensions: 4096;
8
+ readonly embeddingTimeoutMs: 120000;
9
+ readonly embeddingBatchSize: 256;
8
10
  };
9
11
  export declare const MCP_LIMITS: {
10
12
  readonly searchLimit: 100;
@@ -4,7 +4,9 @@ export const CONFIG_LIMITS = {
4
4
  searchMaxDepth: 12,
5
5
  searchMaxContextChars: 200_000,
6
6
  searchHighFrequencyEntityThreshold: 100_000,
7
- embeddingDimensions: 4096
7
+ embeddingDimensions: 4096,
8
+ embeddingTimeoutMs: 120_000,
9
+ embeddingBatchSize: 256
8
10
  };
9
11
  export const MCP_LIMITS = {
10
12
  searchLimit: CONFIG_LIMITS.searchDefaultLimit,
@@ -57,7 +57,10 @@ export const DEFAULT_CONFIG = {
57
57
  enabled: false,
58
58
  provider: "local-hash",
59
59
  model: "mdgraph-local-hash-v1",
60
- dimensions: 128
60
+ dimensions: 128,
61
+ endpoint: "http://127.0.0.1:11434",
62
+ timeoutMs: 30_000,
63
+ batchSize: 16
61
64
  }
62
65
  };
63
66
  export function configPath(projectRoot) {
@@ -143,7 +146,10 @@ function mergeConfig(base, override) {
143
146
  enabled: boolOr(override.embedding?.enabled, base.embedding.enabled),
144
147
  provider: stringOr(override.embedding?.provider, base.embedding.provider),
145
148
  model: stringOr(override.embedding?.model, base.embedding.model),
146
- dimensions: boundedPositiveInteger(override.embedding?.dimensions, base.embedding.dimensions, "embedding.dimensions", CONFIG_LIMITS.embeddingDimensions)
149
+ dimensions: boundedPositiveInteger(override.embedding?.dimensions, base.embedding.dimensions, "embedding.dimensions", CONFIG_LIMITS.embeddingDimensions),
150
+ endpoint: stringOr(override.embedding?.endpoint, base.embedding.endpoint ?? "http://127.0.0.1:11434"),
151
+ timeoutMs: boundedPositiveInteger(override.embedding?.timeoutMs, base.embedding.timeoutMs ?? 30_000, "embedding.timeoutMs", CONFIG_LIMITS.embeddingTimeoutMs),
152
+ batchSize: boundedPositiveInteger(override.embedding?.batchSize, base.embedding.batchSize ?? 16, "embedding.batchSize", CONFIG_LIMITS.embeddingBatchSize)
147
153
  }
148
154
  };
149
155
  }