@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
@@ -0,0 +1,111 @@
1
+ ---
2
+ title: Structured Query and Relationships
3
+ type: guide
4
+ status: active
5
+ source_refs:
6
+ - src/query/structured-query.ts
7
+ - src/query/structured-query-executor.ts
8
+ - src/relationships/derive-related.ts
9
+ - src/db/repositories.ts
10
+ ---
11
+
12
+ # Structured Query and Relationships
13
+
14
+ MDGraph provides two experimental, explicit workflows beyond natural-language retrieval: a bounded structured query language for documentation governance and a provider-gated process for deriving non-authoritative `RELATED_TO` edges. Neither workflow changes stable `search` behavior or adds an MCP tool.
15
+
16
+ ## Structured Query
17
+
18
+ Use `query` when the request is a filter or audit rather than a relevance-ranked search:
19
+
20
+ ```bash
21
+ mdgraph query --path /path/to/project 'type:adr AND status:accepted' --json
22
+ mdgraph query --path /path/to/project 'type:adr AND edge.IMPLEMENTS ~ auth' --json
23
+ mdgraph query --path /path/to/project 'type:runbook AND health:dead_link ORDER BY updated DESC' --json
24
+ mdgraph query --path /path/to/project 'updated >= 2026-06-21 AND NOT status:draft LIMIT 25' --json
25
+ ```
26
+
27
+ `:` is an alias for `=`. Quote values containing spaces. Keywords and field names are case-insensitive.
28
+
29
+ ### Grammar
30
+
31
+ ```text
32
+ query := expression [ORDER BY sort ("," sort)*] [LIMIT integer]
33
+ expression := or-expression
34
+ or := and (OR and)*
35
+ and := unary (AND unary)*
36
+ unary := NOT unary | "(" expression ")" | predicate
37
+ predicate := field operator value
38
+ operator := = | != | ~ | !~ | < | <= | > | >= | :
39
+ sort := sortable-field [ASC | DESC]
40
+ ```
41
+
42
+ `AND` binds more tightly than `OR`. Parentheses make grouping explicit. Input is limited to 10,000 characters, 256 tokens, 64 predicates, 24 nesting levels, three sort fields, and `LIMIT 1..500`.
43
+
44
+ ### Fields
45
+
46
+ | Field | Meaning | Operators |
47
+ |---|---|---|
48
+ | `type` | Document kind | `=`, `!=`, `~`, `!~` |
49
+ | `status` | Lifecycle status | `=`, `!=`, `~`, `!~` |
50
+ | `trust` / `trust_tier` | Trust tier | `=`, `!=`, `~`, `!~` |
51
+ | `path`, `title` | Indexed path or title | `=`, `!=`, `~`, `!~` |
52
+ | `updated` / `updated_at` | Source file mtime captured during indexing | Date comparisons |
53
+ | `indexed` / `indexed_at` | Index timestamp | Date comparisons |
54
+ | `tag` / `tags` | Explicit front-matter tags | `=`, `!=`, `~`, `!~` |
55
+ | `edge` | Presence of an outgoing edge kind | `=`, `!=` |
56
+ | `edge.<KIND>` | Outgoing edge whose target matches an id, path/title, section heading/anchor, entity, or source ref | `=`, `!=`, `~`, `!~` |
57
+ | `health` | Doctor-derived document health | `=`, `!=` |
58
+
59
+ `~` is a case-insensitive substring operation; `%` and `_` are not wildcards. Dates accept `YYYY-MM-DD` or ISO timestamps. Sortable fields are `path`, `title`, `type`, `status`, `trust`, `updated`, and `indexed`.
60
+
61
+ Health values are `dead_link`, `orphan`, `stale_source_ref`, `missing_definition`, `weakly_linked`, `possible_contradiction`, and `content_risk`. Health predicates refuse stale indexes instead of mixing current files with old graph state.
62
+
63
+ ### Execution and Safety
64
+
65
+ The parser accepts only documented fields, operators, document kinds, trust tiers, edge kinds, health values, dates, sort fields, and limits. Non-health expressions compile to whitelisted SQL fragments with bound parameters; user values are never interpolated into SQL. Edge kinds, columns, and sort directions enter SQL only after closed-enum validation.
66
+
67
+ Queries containing health predicates run parameterized atomic document predicates and doctor-derived health sets separately, then evaluate the original boolean AST. This preserves `AND`, `OR`, and `NOT` semantics. Arbitrary front-matter keys, raw SQL, incoming-edge predicates, joins, and aggregations are not supported.
68
+
69
+ The JSON output contains the validated AST, execution strategy and stages, parameter count, total/returned counts, truncation state, matched documents, reasons, predicate fields, and provenance. The full shape is in [Output Contracts](Output_Contracts.md#query---json-experimental).
70
+
71
+ ## Derived Related-Document Relationships
72
+
73
+ `relationships derive` creates an optional semantic relationship layer from an already complete real-model vector index. It never runs during ordinary indexing or watch mode, and it never uses `local-hash`.
74
+
75
+ ```bash
76
+ mdgraph index --semantic --full --path /path/to/project
77
+ mdgraph relationships derive --dry-run --json --path /path/to/project
78
+ mdgraph relationships derive --threshold 0.86 --max-neighbors 3 \
79
+ --min-evidence 2 --json --path /path/to/project
80
+ ```
81
+
82
+ Always inspect a dry run against your corpus before writing edges. A successful non-dry run atomically replaces earlier `RELATED_TO/embedding_similarity` edges, so reruns do not accumulate duplicates.
83
+
84
+ ### Runtime Gates
85
+
86
+ Derivation refuses mutation unless all checks pass:
87
+
88
+ - The doctor content-hash/ID audit reports a fresh index with no Markdown parse failures.
89
+ - Embeddings are enabled and the configured provider declares `semantic-model` capability.
90
+ - Every indexed chunk has a valid vector for the configured provider, model, and dimensions.
91
+ - The threshold is at least `0.75` (default `0.86`).
92
+ - Each relationship has at least two independent chunk/section matches above the threshold; one chunk cannot fill multiple evidence slots.
93
+ - The pair survives reciprocal top-K selection (default three neighbors per document).
94
+
95
+ These are conservative emission gates, not a certification of a model or corpus. Calibrate the threshold on representative project documents.
96
+
97
+ ### Algorithm and Resource Bounds
98
+
99
+ The workflow samples at most 12 evenly distributed chunks per eligible document, averages normalized chunk vectors into a document centroid, filters candidates with a conservative centroid floor, and then checks independent section evidence and reciprocal neighbors.
100
+
101
+ It fails instead of silently truncating when work would exceed 250,000 document pairs, 2,000,000 section-vector comparisons, or 100,000,000 vector-component comparisons. Documents with fewer than `min-evidence` chunks cannot emit a relationship. `max-neighbors` accepts `1..10`; `min-evidence` accepts `2..4`.
102
+
103
+ ### Stored Edge Contract and Lifecycle
104
+
105
+ Each accepted pair is stored as two directed `RELATED_TO` edges so outgoing queries work from either document. Edges have low `weight: 2`, `embedding_similarity` provenance, confidence from the required evidence pairs, stable endpoint/kind/provenance IDs, and metadata describing provider, model, dimensions, algorithm, gate, threshold, reciprocal top-K, evidence, symmetry, and generation time.
106
+
107
+ Derived edges participate in graph retrieval, trace, and structured outgoing-edge queries. Doctor excludes them from authoritative orphan/weak-link counts, so inference cannot hide a missing maintained link. Incremental indexing removes derived edges touching changed or deleted documents; a full rebuild removes the entire derived layer. Run derivation again after semantic reindexing.
108
+
109
+ Structural GraphJSON includes edge kind, confidence, and provenance but omits edge metadata under its existing privacy profile. See [Output Contracts](Output_Contracts.md#relationships-derive---json-experimental) for the derivation report.
110
+
111
+ Embedding similarity is not proof of identity, contradiction, causality, or logical equivalence. `SAME_AS` and `CONTRADICTS` remain reserved; explicit author links remain authoritative.
@@ -1,6 +1,6 @@
1
1
  # MDGraph Agent 集成指南
2
2
 
3
- 本文是 0.3 阶段面向 coding agent 的共享集成契约。不同宿主的适配应保持很薄:启动同一个 MCP server,暴露同一组五个工具,并教 agent 在直接读取 Markdown 文件前先查询 MDGraph。
3
+ 本文是面向 coding agent 的共享集成契约。不同宿主的适配应保持很薄:启动同一个 MCP server,暴露同一组五个工具,并教 agent 在直接读取 Markdown 文件前先查询 MDGraph。
4
4
 
5
5
  ## 核心行为
6
6
 
@@ -13,16 +13,16 @@ MDGraph 采用以下已实现的流水线:扫描器 → 解析器 → 提取/
13
13
  | 提取 | `src/extraction/*` | 将解析后的文档转换为图记录和确定性的实体/边信号。 |
14
14
  | 解析 | `src/resolution/link-resolver.ts` | 将 Markdown 和 WikiLink 目标解析为已索引的文档或章节。 |
15
15
  | 存储 | `src/db/*` | SQLite 连接、模式、记录替换、增量更新、图查询和存储诊断。 |
16
- | 查询 | `src/query/*` | 搜索排序、上下文打包和图追踪。 |
16
+ | 查询 | `src/query/*` | 搜索排序、上下文打包、图追踪,以及实验性结构化查询 tokenizer/AST/executor。 |
17
17
  | 评估 | `src/evaluation/*` | 检索评估 case、期望记录,以及 search/context/trace 质量的轻量指标。 |
18
18
  | Benchmark | `src/benchmark/*` | 结构化 with/without-MDGraph agent run record 解析和 paired delta 聚合。 |
19
19
  | Bundle | `src/bundle/*` | 基于 schema/source/config/document hashes 的私有目录图 bundle 创建和校验。 |
20
20
  | Reporting | `src/reporting/*` | 面向 CI 的图工作流报告,聚合 counts、storage、doctor、eval、bundle、diff 和 benchmark summary。 |
21
21
  | Diff | `src/diff/*` | 基于 Git base ref 的文档图 diff 和 PR impact summary 生成。 |
22
22
  | Export/Import | `src/export/*` | 确定性 GraphJSON、Mermaid、Markdown/docs-site 和只读 source bridge adapter。 |
23
- | 语义 | `src/semantic/*` | 确定性本地向量生成、Float32 向量编解码、provider 状态和余弦评分。 |
23
+ | 语义 | `src/semantic/*` | 可插拔 embedding provider、兼容用 `local-hash`、可选 Ollama 集成、Float32 向量编解码、provider 诊断和余弦评分。 |
24
24
  | MCP | `src/mcp/*` | 基于换行符分隔的 JSON-RPC MCP 服务器和工具处理器。 |
25
- | 监听 | `src/watcher/file-watcher.ts` | 通过 chokidar 实现防抖增量重新索引。 |
25
+ | 监听 | `src/watcher/file-watcher.ts`、`src/watcher/watch-health.ts` | 通过 chokidar 实现防抖增量重新索引,并维护进程内持久健康分类。 |
26
26
  | 分析 | `src/analysis/doctor.ts` | 文档健康和治理报告。 |
27
27
 
28
28
  ## 公开契约边界
@@ -50,13 +50,28 @@ SQLite 数据库存储在 `.mdgraph/graph.db`,由 `src/db/schema.sql` 创建
50
50
 
51
51
  1. `scanMarkdownFiles` 从配置中选择候选 Markdown 文件。
52
52
  2. `parseMarkdownDocument` 读取前置元数据和 Markdown 结构。
53
- 3. `buildGraphRecords` 创建文档、章节、实体、源引用、块、向量和边。
54
- 4. `GraphRepository.replaceAll` 写入完整重建,或 `replaceDocuments` 更新已更改/已删除的文档。
55
- 5. `indexProject` 比较存储的哈希值与解析后的哈希值,选择全量或增量模式。
56
-
57
- 增量模式会删除已更改和已移除文件的文档派生记录,移除对应 FTS 词项,重新插入已更改的记录,并在清理后修剪未引用的全局实体/源引用。完整重建会 optimize 并 vacuum SQLite 数据库,避免旧 FTS 页面和已删除行继续放大磁盘文件。
58
-
59
- ## 存储诊断
53
+ 3. `buildGraphRecords` 同步创建确定性的文档、章节、实体、源引用、块和边。
54
+ 4. embedding 启用时,`indexProject` 解析 `EmbeddingProvider`;新索引或 provider profile 变化时异步嵌入全部 chunks,profile 匹配的增量索引只嵌入 changed chunks。
55
+ 5. `GraphRepository.replaceAll` 写入完整重建,或 `replaceDocuments` 更新已更改/已删除的文档及其 vectors。
56
+ 6. `indexProject` 比较已存储 hash 与 vector profile coverage,选择全量或增量模式。
57
+
58
+ 向量生成会在 repository write 开始前全部完成,因此 provider 失败时旧 graph 保持不变,不会提交部分 vector coverage。增量模式会删除已更改和已移除文件的文档派生记录,移除对应 FTS 词项,重新插入已更改的记录,并在清理后修剪未引用的全局实体/源引用。完整重建会 optimize 并 vacuum SQLite 数据库,避免旧 FTS 页面和已删除行继续放大磁盘文件。
59
+
60
+ ## 派生关系流程
61
+
62
+ `relationships derive` 是显式 post-index workflow,不属于普通 indexing 或 watch mode。它要求 doctor content-hash/ID freshness 审计通过且没有 parse failure、已配置的 `semantic-model` provider,以及当前 provider/model/dimensions 的完整 vector coverage;`local-hash` 会被拒绝。实现会有界采样文档 chunk,使用归一化 document centroid 过滤候选,要求多组独立高相似度 section pair,并只保留 reciprocal top-K neighbor。
63
+
64
+ 通过门禁的文档对会变成两条对称、低权重的 `RELATED_TO` edge,使用 `embedding_similarity` provenance;metadata 包含 provider/model identity、algorithm/gate version、threshold、evidence section ID 和 generation time。替换是原子的。Incremental indexing 会删除连接 changed/deleted document 的派生 edge;full rebuild 会删除整个可选层。工作流、安全预算和生命周期见[结构化查询与派生关系](Structured_Query_and_Relationships.md#派生相关文档关系)。
65
+
66
+ 派生 edge 可以参与 graph retrieval、trace 和 structured edge predicate,但会从 doctor orphan/weak-link 的权威链接计数中排除,避免推断结果掩盖缺失的维护链接。
67
+
68
+ ## 实体抽取
69
+
70
+ `extractEntities` 是确定性、source-aware 的实现。显式 front matter 和 `Defines` 章节创建 definition。普通正文只发射 API route、error code 和形状明确的 config key 等高结构 reference,不会提升宽泛的 PascalCase 单词。独立 inline code 可以识别完整的 Latin/CJK symbol;fenced code 中的裸 symbol 则限制在声明和类型引用上下文。Unicode-aware pattern 覆盖 CJK API path、分段 config key 和 function identifier;route 边界避免从 file path 中截取伪 route。
71
+
72
+ `entities.stopEntities` 会抑制所有 entity kind 的推断 reference,而作者显式声明的 definition 继续保持权威性。这一层是可解释的启发式规则,不是通用 NER 或源码语言 AST。信号策略和边界见[检索与上下文](Retrieval_and_Context.md#确定性实体抽取)。
73
+
74
+ ## 存储诊断
60
75
 
61
76
  `GraphRepository.storageDiagnostics` 支撑 `mdgraph status --storage`。它报告 SQLite 页数、freelist、journal/WAL checkpoint 状态、`dbstat` 可用时的表/索引/FTS shadow 对象大小、按路径分组的内容贡献、边类型分布、高度数节点、向量存储格式和向量 provider 计数。
62
77
 
@@ -92,16 +107,20 @@ Diff report 包含 Markdown 文档新增、修改、删除、Git 识别的 renam
92
107
 
93
108
  - FTS5 块命中,包含连续中文/日文/韩文文本的轻量 CJK n-gram 命中。
94
109
  - 精确实体匹配。
95
- - 可选的本地语义向量匹配。
110
+ - 可选 embedding 向量匹配。
96
111
  - 匹配实体周围的图邻居。
97
112
 
98
113
  当同一文档或章节通过多条路径命中时,搜索会在 definition、FTS 和可选 semantic 通道之间应用 reciprocal rank fusion(RRF),再保留最高基础分,同时合并主要命中原因和匹配实体,避免丢失来源解释。每个融合结果都会保留可解释的 `RRF fusion (...)` reason。
99
114
 
100
- 然后 `buildContext` 从排序后的搜索章节开始,通过非包含边执行有界图扩展,在重复同一文档章节前优先保持跨文档多样性,在字符预算下打包选定的章节,并包含原因,如 FTS 命中、语义命中、精确实体匹配或图边遍历路径。
115
+ 同步 `searchGraph`、`buildContext` 和 `evaluateRetrieval` API 保留 1.0 行为,可在进程内执行 `local-hash`。对应的异步 API 会解析 Ollama 等外部 provider,CLI 与 MCP 查询路径使用异步版本。provider 不可用、超时、响应非法、模型缺失或 vector coverage 不完整时,会降级到 keyword/entity/graph retrieval,并返回 additive `semanticDiagnostic`;CLI 文本和非 explain JSON 命令还会把诊断写到 stderr。
116
+
117
+ 然后 `buildContext` 从排序后的搜索章节开始,通过非包含边执行有界图扩展,在字符预算下打包选定的章节,并包含原因,如 FTS 命中、语义命中、精确实体匹配或图边遍历路径。兼容默认策略按文档轮询排序候选。可选 `mmr` 最大化 query relevance 并惩罚冗余;两个候选都有当前 provider 已存向量时使用向量相似度,否则回退到确定性的 Unicode token Jaccard,并剪除同文档近重复项,同时保留每个文档的首个候选。
118
+
119
+ 每个 context 结果都会包含 additive packing metadata。当请求 `context --debug` 时,上下文构建还会报告 seed nodes、visited nodes、expanded edges、跳过原因、候选数量、策略/相似度选择、逐项 query relevance、redundancy penalty 和 MMR score、冗余剪枝及预算截断计数。这些诊断不是图事实,只用于解释上下文打包和评估检索质量。
101
120
 
102
- 当请求 `context --debug` 时,上下文构建还会报告 seed nodes、visited nodes、expanded edges、跳过原因、候选数量、MMR-style 跨文档打包诊断和预算截断计数。这些诊断不是图事实,只用于解释上下文打包和评估检索质量。
121
+ 实验性结构化查询路径与自然语言 search 分离。`structured-query.ts` 对有界输入进行 tokenize,并校验 typed boolean AST。`GraphRepository` 从 closed field/operator set 把文档、tag、日期和 outgoing-edge predicate 编译为参数化 SQLite operation。除非 AST 包含 doctor 派生 health predicate,否则 `structured-query-executor.ts` 使用直接 SQL 路径;health query 会把参数化原子 document-id set 与 fresh doctor report 合并,再对原始 boolean tree 求值。索引时会把源文件 mtime 写入已有 `documents.updated_at` 列,因此日期治理查询无需 schema migration。
103
122
 
104
- `evaluateRetrieval` 会针对已索引项目运行仓库自有的 alpha 或 CJK evaluation cases。它复用 `searchGraph`、`buildContext` 和 `traceNodes`,并报告预期文档召回、预期章节召回、上下文精度、trace 成功率、延迟、返回字符预算、上下文多样性、reason 覆盖率、RRF 通道、query mode 和可选语义 reranker 状态。evaluation 输出是度量辅助,不是学习式 ranking model,也不能替代聚焦回归测试。
123
+ `evaluateRetrieval` 与 `evaluateRetrievalAsync` 会针对已索引项目运行仓库自有的 alpha 或 CJK evaluation cases。它们复用对应的 search/context 路径和 `traceNodes`,并报告预期文档召回、预期章节召回、上下文精度、trace 成功率、延迟、返回字符预算、上下文多样性、reason 覆盖率、RRF 通道、query mode、可选语义 reranker 状态和异步 provider 诊断。evaluation 输出是度量辅助,不是学习式 ranking model,也不能替代聚焦回归测试。
105
124
 
106
125
  `generateBenchmarkReport` 只消费结构化 `AgentRunRecord` JSON。它按 `questionId` 配对一个 `with_mdgraph` 和一个 `without_mdgraph` record,将不完整或重复 pair 报告为 skipped,并计算 file reads、searches、tool calls、MDGraph calls、字符/token 预算、延迟、raw-file fallback 和引用正确率 delta。它不解析 transcript、不调用模型,也不托管 agent run。
107
126
 
@@ -109,16 +128,17 @@ Diff report 包含 Markdown 文档新增、修改、删除、Git 识别的 renam
109
128
 
110
129
  ## MCP 边界
111
130
 
112
- MCP 服务器有意仅暴露五个工具。工具输出以文本为主且兼容 JSON,以便代理可以直接使用,无需先检查 SQLite 数据库或读取原始文件。服务器会绑定到项目根:initialize root 和工具 `projectPath` 必须位于服务根之内。
131
+ MCP 服务器有意仅暴露五个工具。Search/context 通过 provider-aware 异步 handler 调度,node/trace/status 保留同步行为。工具输出以文本为主且兼容 JSON,以便代理可以直接使用,无需先检查 SQLite 数据库或读取原始文件。semantic 降级会增加文本提示和结构化诊断,但不会把仍然可用的 lexical/graph 结果变成 MCP error。服务器会绑定到项目根:initialize root 和工具 `projectPath` 必须位于服务根之内。
113
132
 
114
133
  ## 当前权衡
115
134
 
116
- - 语义提供者是确定性的和本地的,但它是轻量级的哈希嵌入,而非高质量的语言模型嵌入。配置了不支持的 provider 时会降级到 FTS5 和 graph search;`semantic status` 会报告 provider 支持、向量覆盖率、存储格式和重新索引指引。
117
- - 监听模式在文件更改时更新 SQLite;长时间运行的 MCP 新鲜度通过每次调用时工具打开当前数据库状态来实现。
135
+ - `local-hash` 为兼容保留,仍是确定性的词法 feature hash,并非语言模型 embedding。Ollama 是第一个可选 `semantic-model` provider,需要单独运行本地服务和模型。不支持或不可用的 provider 会降级到 FTS5 和 graph search;`semantic status` 会报告 capability、runtime availability、vector coverage、存储格式和重新索引指引。
136
+ - 结构化 `query` 是 experimental,覆盖已记录的存储字段、tags、outgoing edges 和选定的 doctor health 类型。任意 front matter key、incoming-edge predicate、aggregation、join 和 MCP structured filter 不属于当前实现。
137
+ - 监听模式在文件更改时更新 SQLite,并保留 `starting | healthy | degraded | failed` 健康状态、最近成功索引、最近错误和覆盖可靠性。启动注册错误是 fatal;索引错误可在后续成功索引后恢复;运行期资源失败在重启前保持 degraded。集成 MCP 通过 `mdgraph_status` 暴露快照。原生事件仍是默认值,`watch --poll` 和 `serve --mcp --watch-poll` 是显式的较高成本 fallback。
118
138
  - Doctor 检查是基于规则的警告。它们会先比较当前文件与索引中的文档 hash 和 id;陈旧索引会返回只读的新鲜度诊断,而不是混合时态的健康结论。
119
139
  - 存储诊断通过 `status --storage` 暴露;它们不是图事实,也不会扩展 MCP 工具面。
120
140
  - 私有 bundle artifact 是本地工作流 artifact,不是公开导出。公开安全脱敏和 zip packaging 不属于当前实现。
121
141
  - Benchmark report 只来自显式结构化 records 的聚合度量;完整 transcript、hosted analytics 和 agent runtime capture 不属于 MDGraph。
122
142
  - 互操作 adapter 是只读导向的。GraphJSON verify、Mermaid/Markdown/docs-site export 和 source bridge report 不会把外部 graph 合并进主 SQLite index。
123
- - `SAME_AS`、`RELATED_TO` 和 `CONTRADICTS` 是公共模型中保留的边类型。确定性 MVP 在索引期间不发出这些类型;类似矛盾的信号目前由 `doctor` 报告,而不是作为图边插入。
124
- - 当前实现优先考虑紧凑的 MVP,而非广泛的 Markdown/MDX 方言支持。
143
+ - `RELATED_TO` 是实验性派生 edge,只能由显式、provider-gated 的流程发射,普通确定性 indexing 永远不会发射它。`SAME_AS` 和 `CONTRADICTS` 继续保留;类似矛盾的信号仍由 `doctor` 报告,而不是作为 graph edge 插入。
144
+ - 当前实现优先考虑紧凑、确定性的核心,而非广泛的 Markdown/MDX 方言支持。
@@ -1,6 +1,6 @@
1
1
  # MDGraph 评估
2
2
 
3
- 这些问题将计划中的代理评估指导转化为可复用的冒烟测试集。在索引后,针对真实的项目文档语料库使用它们。
3
+ 这些问题是一组可复用的工程冒烟测试,可在索引后用于真实项目文档语料。它们检查 MDGraph 是否返回正确的文档、章节、实体、图证据和上下文,而不是把单一排序分数当作充分证据。
4
4
 
5
5
  内置 CLI 入口:
6
6
 
@@ -11,8 +11,24 @@ 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` 默认运行仓库自有的 `alpha` query set,并报告 pass/fail 以及轻量检索指标。它还报告确定性的排序诊断:query mode、RRF 搜索融合通道、MMR-style 跨文档上下文打包,以及可选语义 reranking 状态。`--query-set cjk` 面向小型中文/日文检索基线,并由轻量 CJK n-gram 预处理覆盖连续 CJK 查询。它是确定性的工程 smoke 检查,不是完整 IR benchmark 或真实 agent A/B benchmark。
15
-
14
+ `mdgraph eval` 默认运行仓库自有的 `alpha` query set,并报告 pass/fail 与轻量检索指标,同时给出 query mode、RRF channel、兼容上下文打包和可选 semantic-provider 状态。`--query-set cjk` 选择由轻量 CJK n-gram 预处理覆盖的小型中文/日文检索基线。这些是确定性的工程检查,不是完整 IR benchmark 或真实 agent A/B benchmark。
15
+
16
+ ## 仓库回归套件
17
+
18
+ 除 `mdgraph eval` 外,维护者还会运行聚焦的非公开套件。套件名称直接描述其保护的能力。它们不会增加已冻结的 `eval --query-set alpha | cjk` 值,也不会写入仓库的 `.mdgraph` 索引。
19
+
20
+ | 命令 | 保护的能力 | 已记录结果 / 门禁 |
21
+ |---|---|---|
22
+ | `npm run baseline:historical` | 历史 lexical-hash、实体、上下文和 watch failure 对比快照 | Keyword 同义词 Recall@5 `0.0000`,`local-hash` 为 `0.5000`;历史实体 precision/recall 为 `0.5000 / 1.0000`;文档轮询 average pairwise Jaccard 为 `0.3808`,有三组近重复。这些数值是刻意保持不变的历史证据。 |
23
+ | `npm run baseline:entity-extraction` | Source-aware Latin/CJK 实体抽取 | Precision `1.0000`、recall `1.0000`、CJK recall `1.0000`、已知噪声泄漏为零;门禁分别为 `>= 0.90`、`>= 0.80`、`>= 0.80` 和零。 |
24
+ | `npm run baseline:context-packing` | 可选真 MMR 上下文打包 | Expected-document recall 保持 `1.0000`;average pairwise Jaccard 从 `0.3808` 降至 `0.1576`,近重复 pair 从三组降为零,冗余降低 `58.61%`。 |
25
+ | `npm run baseline:structured-query` | 结构化查询正确性与安全 | 四条标注治理 query 全部正确,repository predicate 参数化与 SQL injection 隔离通过。 |
26
+ | `npm run baseline:related-documents` | Provider 门禁相关文档派生 | Precision `1.0000`、recall `1.0000`、provenance 完整且替换结果确定;门禁要求 precision `>= 0.90`、recall `>= 0.80`、完整 provenance 和稳定替换。 |
27
+
28
+ Provider 集成 fixture 还通过确定性的 fake Ollama endpoint 映射四条无词面重叠语义 case,Recall@5 达到 `1.0000`。它验证 batching、vector persistence、async routing、RRF 参与、诊断和 provider attribution,不预测任意真实模型的质量。
29
+
30
+ Watcher tests 覆盖启动/运行期 `ENOSPC`、运行期 `EMFILE`、启动期 `EACCES`、索引失败、恢复、进程内持续 health 和显式 polling。各套件背后的用户行为见[检索与上下文](Retrieval_and_Context.md)、[运行与故障处理](Operations.md)和[结构化查询与派生关系](Structured_Query_and_Relationships.md)。
31
+
16
32
  1. 为什么某个特定的错误码会影响特定的用户流程?
17
33
  2. 给定的设计文档依赖于哪些早期决策?
18
34
  3. 某个特定的 API 路由在哪里定义、又在哪里被引用?
@@ -51,13 +67,13 @@ mdgraph eval --query-mode semantic --json
51
67
  - MDGraph 返回的上下文是否足够,无需进一步检查文件。
52
68
  - 整个代理运行的时间和工具调用次数。
53
69
  - `mdgraph eval` 指标:top-K 文档召回、预期章节召回、上下文精度、trace 成功率、延迟、返回字符数、预算适配、fanout、上下文多样性、reason 覆盖率和 ranking reason 覆盖率。
54
- - `mdgraph eval` 排序报告:query mode、RRF 搜索融合通道、MMR-style 上下文打包策略、可选 reranker 状态和 semantic-active case 数量。
70
+ - `mdgraph eval` 排序报告:query mode、RRF 搜索融合通道、兼容上下文打包策略、可选 reranker 状态和 semantic-active case 数量。使用聚焦 context 回归套件对比可选真 MMR 和冻结默认策略。
55
71
 
56
- v0.6 的 A/B 报告入口是 `mdgraph report --benchmark benchmark-runs.json --json`。它消费结构化 run records 并报告 aggregate deltas;完整 transcript 应保留在公开文档之外。
72
+ A/B 报告入口是 `mdgraph report --benchmark benchmark-runs.json --json`。它消费结构化 run records 并报告 aggregate deltas;完整 transcript 应保留在公开文档之外。
57
73
 
58
74
  ## CJK 期望记录
59
75
 
60
- `cjk` query set 是 v0.5 的中文/日文检索基线。它使用仓库测试 fixture `createCjkFixtureDocs` 中的期望记录,覆盖中文 design/API/runbook/spec 文档和一篇日文 design 文档。case 范围包括:
76
+ `cjk` query set 是内置的中文/日文检索基线。它使用仓库测试 fixture `createCjkFixtureDocs` 中的期望记录,覆盖中文 design/API/runbook/spec 文档和一篇日文 design 文档。case 范围包括:
61
77
 
62
78
  - 空格分隔的中文关键词查询,例如 `登录流程 缓存超时 认证重试`。
63
79
  - 连续中文自然语言查询,例如 `缓存超时影响登录流程的处理`,该 case 由轻量 CJK n-gram 预处理覆盖。
@@ -0,0 +1,91 @@
1
+ ---
2
+ title: 运行与故障处理
3
+ type: runbook
4
+ status: active
5
+ defines:
6
+ - MDGraphOperationsZH
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
+ # 运行与故障处理
15
+
16
+ 本文说明长期运行 MDGraph 时的索引新鲜度、watch coverage、semantic provider 恢复和本地产物安全。
17
+
18
+ ## 索引与新鲜度检查
19
+
20
+ 在依赖陌生项目或长期运行的索引前,先显式检查状态:
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` 会比较当前 Markdown 文件与已索引的 path/hash。`stale` 表示查询结果可能反映旧 graph state,应运行 `mdgraph index`。Doctor health predicate 和派生关系都要求 fresh index,并拒绝混合时间状态的结论。
29
+
30
+ 增量索引会更新 changed/deleted document、对应 FTS record、vector 和相连的派生 edge。Embedding profile 改变、存储需要重建/压缩,或运维上希望做干净重建时,使用 `index --full`。
31
+
32
+ ## Watch 模式
33
+
34
+ 独立 watch mode 和集成 MCP serving 都可以保持索引最新:
35
+
36
+ ```bash
37
+ mdgraph watch --path /path/to/project
38
+ mdgraph serve --mcp --path /path/to/project
39
+ ```
40
+
41
+ Watcher 通过 `WatchHandle.getHealth()` 暴露进程内 health snapshot。集成 MCP serving 会把它加入 `mdgraph_status.structuredContent.watchHealth`。
42
+
43
+ | 状态 | 含义 | 运维动作 |
44
+ |---|---|---|
45
+ | `starting` | 正在注册 watch 或执行初始 setup。 | 等待进入 healthy 或报告启动失败。 |
46
+ | `healthy` | 注册有效,最近一次索引成功。 | 无需动作。 |
47
+ | `degraded` | 索引失败,或原生 watch coverage 已不可靠。 | 检查最近错误;修复原因后重新索引或重启。 |
48
+ | `failed` | 启动阶段无法建立可靠 watch coverage。 | 修复报告的错误后再依赖 watch mode。 |
49
+
50
+ Snapshot 包含最近成功索引时间、最近错误、failure phase 与 normalized code、连续索引失败次数、coverage reliability、polling 和 closed 状态。它只在 watcher 进程内持续;重启会创建新的 health lifecycle。
51
+
52
+ 启动注册错误是 fatal。索引失败可以在后续索引成功后恢复。`ENOSPC`、`EMFILE` 等运行期 watch error 会设置 `coverageReliable: false`;后续手动或触发索引成功并不能证明漏掉的原生事件已恢复,因此在重启前保持 degraded。
53
+
54
+ ## Polling Fallback
55
+
56
+ 默认使用原生文件系统事件。当操作系统 watch limit 无法提高或原生事件不可靠时,可以显式启用 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 可能增加 I/O 与 CPU,因此不会自动开启。大型长期运行仓库应优先修复操作系统资源限制;无法控制环境时再使用 polling。
64
+
65
+ ## Semantic Provider 恢复
66
+
67
+ 使用以下命令检查 provider 和 vector 状态:
68
+
69
+ ```bash
70
+ mdgraph semantic status --path /path/to/project
71
+ ```
72
+
73
+ | 条件 | 查询行为 | 恢复方式 |
74
+ |---|---|---|
75
+ | Provider 不可用、超时或响应非法 | Search/context 降级到 FTS5/entity/graph 并报告 `semanticDiagnostic`。 | 恢复服务/模型后重试;词法结果仍可使用。 |
76
+ | Provider/model/dimensions 改变 | Status 报告需要重新索引。 | 运行 `mdgraph index --full --semantic`。 |
77
+ | 语义索引失败 | Embedding 在 mutation 前完成,因此既有 graph 保持不变。 | 修复 provider 后重新索引。 |
78
+ | Vector coverage 不完整 | 语义查询降级;派生关系拒绝修改。 | 重建完整语义索引。 |
79
+
80
+ `local-hash` 不需要外部服务,但它只是词法 feature hash,不能通过派生关系的 semantic-model 门禁。
81
+
82
+ ## 派生关系刷新
83
+
84
+ 派生 `RELATED_TO` edge 是可丢弃、非权威状态。文档变更会删除接触它的派生 edge,完整重建会删除全部派生关系。成功完成 full semantic index 后,如仍需要该层,应先执行 dry run,再显式刷新。详见[结构化查询与派生关系](Structured_Query_and_Relationships.md#派生相关文档关系)。
85
+
86
+ ## 本地与发布产物
87
+
88
+ - 不要把 `.mdgraph/graph.db`、包含本地路径的 bundle/report 或私有评估语料加入 source control 或 release archive。
89
+ - `.mdgraph/config.json` 不含凭据时可以跟踪;MDGraph 会拒绝 endpoint URL 中嵌入的凭据。
90
+ - 结构化交换应使用已记录的 GraphJSON,不要依赖 SQLite 内部结构。
91
+ - 发布 MDGraph 本身前,运行[发布清单](Release_Checklist.md),检查 `npm pack --dry-run --json`,并实际验证 packed package,不要假设仓库内容等同于 npm 内容。
@@ -62,9 +62,12 @@
62
62
 
63
63
  - `query`、`limit`、`queryMode`、`entityCandidates`、`ftsQuery`、`semanticEnabled` 和 `semanticActive`。
64
64
  - `ranking`:`fusion`、`fusionK`、`channels` 和 `optionalReranker`。
65
+ - `semanticDiagnostic`:可选 provider 降级详情,包含 `code`、`provider`、`message` 和 `degraded: true`。
65
66
  - `matchedEntities`:排序诊断使用的实体名称、类型和文档频次。
66
67
  - `results`:与 `search --json` 相同的搜索结果记录。
67
68
 
69
+ 请求了 semantic retrieval 但无法运行时,`search` 仍返回 FTS5/entity/graph 结果。CLI 会把降级诊断写到 stderr,从而保持非 explain `search --json` 数组兼容。
70
+
68
71
  ## `context --json`
69
72
 
70
73
  `mdgraph context <query> --json` 返回:
@@ -72,6 +75,8 @@
72
75
  - `query`:原始查询文本。
73
76
  - `maxChars`:配置的上下文预算。
74
77
  - `usedChars`:已打包字符数。
78
+ - `packing`:additive 打包 metadata,包含 `strategy`;可选 MMR 还会报告 `similarity`、`mmrLambda` 和可选 `redundancySkippedItems`。
79
+ - `semanticDiagnostic`:可选 provider 降级详情;未请求 semantic retrieval 或正常完成时不出现。
75
80
  - `items`:上下文条目,包含 `nodeId`、`documentId`、可选 `sectionId`、可选 `anchor`、`path`、`title`、可选 `heading`、可选 `lines`、`reason`、`matchedEntities`、可选 `edgePath`、可选 `sourceRefs`、可选 `riskNotes` 和 `content`。
76
81
 
77
82
  `riskNotes` 可包含生命周期/trust 提醒,以及确定性的内容风险提示,例如 prompt-injection 文本、active HTML/data URI 或隐藏 Unicode 格式字符。
@@ -83,8 +88,36 @@
83
88
  - `seedNodes`、`visitedNodes` 和 `expandedEdges`。
84
89
  - `skippedVisitedNodes`、`skippedByNodeLimit` 和 `skippedByDepth`。
85
90
  - `candidateCount`、`directCandidates` 和 `expandedCandidates`。
86
- - `packingStrategy`、`packedItems`、`packedUniqueDocuments` 和 `packingDiversityRatio`。
87
- - `budgetTruncatedItems` 和 `budgetSkippedItems`。
91
+ - `packingStrategy`、可选 `packingSimilarity`、可选 `mmrLambda`、可选逐项 `packingSelections`、`packedItems`、`packedUniqueDocuments` 和 `packingDiversityRatio`。每个 MMR selection 报告 `nodeId`、`path`、`queryRelevance`、`redundancyPenalty`、`mmrScore` 和 `similaritySource`。
92
+ - `budgetTruncatedItems`、`budgetSkippedItems` 和可选 `redundancySkippedItems`。
93
+
94
+ 兼容默认值为 `mmr-style-document-round-robin`。`--packing mmr` 为 opt-in,并可通过 `--mmr-lambda <0..1>` 调整;缺少已存向量时回退到确定性词法 Jaccard 相似度。
95
+
96
+ ## `query --json`(experimental)
97
+
98
+ `mdgraph query <expression> --json` 返回:
99
+
100
+ - `query`:原始结构化表达式。
101
+ - `ast`:已校验的 expression tree,以及 `orderBy` 和 `limit`。
102
+ - `execution`:`strategy`(`parameterized-sql` 或 `parameterized-hybrid-doctor`)、有序 `stages`、`parameterCount` 和 `doctorHealthEvaluated`。
103
+ - `total`、`returned` 和 `truncated`:匹配与 limit 诊断。
104
+ - `items`:包含 `document`、`reason`、`predicateFields` 和执行 `provenance` 的条目。
105
+
106
+ `document` 遵循 `GraphDocument`,包括可选 `updatedAt`,其值为索引时记录的源 Markdown mtime。Health predicate 会在索引陈旧时失败。该输出是 experimental,不改变稳定 `search` 契约。
107
+
108
+ ## `relationships derive --json`(experimental)
109
+
110
+ `mdgraph relationships derive --json` 返回:
111
+
112
+ - `algorithmVersion`、`generatedAt`、`provider`、`model` 和 `dimensions`。
113
+ - `options`:实际使用的 `threshold`、`maxNeighbors`、`minEvidence` 和 `dryRun`。
114
+ - `qualityGate`:gate ID、`passed` 和具名运行时检查。
115
+ - `corpus`:document/chunk/vector coverage、采样、pair evaluation 和 vector comparison 诊断。
116
+ - `relationships`:规范化 document pair,以及 confidence 和独立 chunk/section evidence。
117
+ - `relationshipPairs` 和 `directedEdges`。
118
+ - `mutation`:`dryRun`、`removed` 和 `inserted` 计数。
119
+
120
+ Stale index、lexical-hash provider、当前 profile vector coverage 不完整、不安全 option 或计算预算超限都会在 mutation 前失败。成功的非 dry-run 会原子替换 `RELATED_TO/embedding_similarity` edge。该输出是 experimental,不改变稳定的 index、search、GraphJSON 或 MCP 契约。
88
121
 
89
122
  ## `node --json`
90
123
 
@@ -113,14 +146,14 @@
113
146
 
114
147
  - `querySet`:默认是 `alpha`;传入 `--query-set cjk` 时为 `cjk`。
115
148
  - `limit`:每个 case 使用的搜索结果上限。
116
- - `ranking`:query mode、RRF 搜索融合、上下文打包策略、可选 reranker 状态、semantic-active case 数量、搜索通道、ranking reason 覆盖率和平均上下文多样性。
149
+ - `ranking`:query mode、RRF 搜索融合、上下文打包策略、可选 reranker 状态、semantic-active case 数量、搜索通道、ranking reason 覆盖率、平均上下文多样性,以及可选的去重 `semanticDiagnostics`。
117
150
  - `generatedAt`:评估运行时间。
118
151
  - `summary`:`cases`、`passed`、`failed`、`averageTopKDocumentRecall`、`averageExpectedSectionRecall`、`averageContextPrecision`、`averageContextDiversity`、`averageLatencyMs` 和 `averageReturnedChars`。
119
152
  - `cases`:每个 case 的 `id`、`query`、`passed`、`expected`、`observed` 和 `metrics`。
120
153
 
121
- 每个 case 的 `expected` 包含预期文档、章节、实体、边类型和 source refs。`observed` 包含排序后的搜索文档路径、上下文条目路径/标题/reason、匹配实体、已解析实体、已解析 source refs、观测到的边类型、可选 trace 结果和排序诊断。`metrics` 包含 top-K 文档召回、预期章节召回、上下文精度、实体召回、source-ref 召回、边类型覆盖、trace 成功率、延迟、返回字符数、预算适配、fanout、reason 覆盖率、ranking reason 覆盖率和上下文多样性。
154
+ 每个 case 的 `expected` 包含预期文档、章节、实体、边类型和 source refs。`observed` 包含排序后的搜索文档路径、上下文条目路径/标题/reason、匹配实体、已解析实体、已解析 source refs、观测到的边类型、可选 trace 结果,以及带可选 `semanticDiagnostic` 的排序诊断。`metrics` 包含 top-K 文档召回、预期章节召回、上下文精度、实体召回、source-ref 召回、边类型覆盖、trace 成功率、延迟、返回字符数、预算适配、fanout、reason 覆盖率、ranking reason 覆盖率和上下文多样性。
122
155
 
123
- `--query-set cjk` 使用仓库自有的中文/日文期望记录,用于度量轻量 CJK n-gram 预处理基线下的检索质量。`--query-mode semantic` 请求可选语义搜索,并报告本地语义 reranker 是否实际生效。`mdgraph eval` 不会自动索引目标项目,运行前需先执行 `mdgraph index`。
156
+ `--query-set cjk` 使用仓库自有的中文/日文期望记录,用于度量轻量 CJK n-gram 预处理基线下的检索质量。`--query-mode semantic` 请求可选语义搜索,并报告配置的 semantic provider 是否实际生效。`mdgraph eval` 不会自动索引目标项目,运行前需先执行 `mdgraph index`。
124
157
 
125
158
  ## `export graphjson --json`
126
159
 
@@ -144,7 +177,7 @@ Structural profile 不包含 chunks、chunk content、section content、vectors
144
177
  - `warnings`:非致命兼容性说明。
145
178
  - 可读取时的 `format`、`formatVersion`、`schemaVersion`、`graphHash`、`counts` 和 `exportedCounts`。
146
179
 
147
- 当 `valid` 为 `false` 时命令返回非零退出码。0.7 不支持 GraphJSON merge import。过大或过深嵌套的 GraphJSON 会在校验前被拒绝。
180
+ 当 `valid` 为 `false` 时命令返回非零退出码。不支持 GraphJSON merge import。过大或过深嵌套的 GraphJSON 会在校验前被拒绝。
148
181
 
149
182
  ## `export mermaid trace --json`
150
183
 
@@ -188,7 +221,7 @@ Bridge 只读取显式传入的 MDGraph JSON artifact;该 artifact 使用 `fil
188
221
  - `manifestPath`:`manifest.json` 的绝对路径。
189
222
  - `manifest`:bundle manifest,包含 `format`、`formatVersion`、`schemaVersion`、`mdgraphVersion`、`createdAt`、`visibility`、`sourceHash`、`configHash`、`provenance`、`counts`、`documents` 和可选 `reports`。
190
223
 
191
- 私有 bundle 包含 `manifest.json`、`graph.db`、`config.json` 和 `reports/status-storage.json` 快照。`sourceHash` 来自规范化配置与按路径排序的文档 path/hash 记录;不包含 Markdown 正文或绝对项目根目录。0.6 不支持 public 或脱敏 bundle profile。
224
+ 私有 bundle 包含 `manifest.json`、`graph.db`、`config.json` 和 `reports/status-storage.json` 快照。`sourceHash` 来自规范化配置与按路径排序的文档 path/hash 记录;不包含 Markdown 正文或绝对项目根目录。不支持 public 或脱敏 bundle profile。
192
225
 
193
226
  ## `bundle verify --json`
194
227
 
@@ -254,6 +287,7 @@ Diff 只比较 Markdown 图记录、source refs 和 doctor warning codes。它
254
287
  - `projectRoot`。
255
288
  - `state`:`disabled`、`not_indexed`、`ready`、`unsupported_provider` 或 `needs_reindex`。
256
289
  - `enabled`、`provider`、`model`、`dimensions` 和 `providerSupported`:当前配置的 embedding provider 状态。
290
+ - `capability`:`lexical-hash`、`semantic-model` 或 `unknown`;`runtimeStatus`:`available`、`unavailable`、`model_missing`、`unchecked` 或 `disabled`;runtime check 失败时可带 `runtimeReason`。
257
291
  - `indexed`、`chunks`、`vectors`、`vectorStorageFormat` 和 `indexedProviders`。
258
292
  - `guidance`:可行动的下一步,例如运行 `mdgraph index --semantic`、provider 变化后重新 embedding,或 unsupported provider 降级到 FTS5 和 graph search。
259
293
 
@@ -1,12 +1,12 @@
1
1
  # MDGraph 公开契约
2
2
 
3
- 本文记录当前 `1.0.0` public surface 的公开契约边界。它补充 [Output_Contracts.md](Output_Contracts.md)、[Architecture.md](Architecture.md) 和 [Release_Checklist.md](Release_Checklist.md)。完整的逐命令、逐格式、逐配置、逐 schema 清单见 [1.0 契约冻结附录](Public_Contracts_1.0.md)。
3
+ 本文记录当前发布线的公开契约边界,并以冻结的 `1.0.0` 兼容性基线为基础。它补充 [Output_Contracts.md](Output_Contracts.md)、[Architecture.md](Architecture.md) 和 [Release_Checklist.md](Release_Checklist.md)。完整的逐命令、逐格式、逐配置、逐 schema 清单见 [1.0 契约冻结附录](Public_Contracts_1.0.md)。
4
4
 
5
5
  ## 稳定性标签
6
6
 
7
7
  - `stable`:用户和 agent 可以依赖该形状。允许追加字段;`1.0` 后删除或重命名已记录字段属于破坏性变更。
8
8
  - `stable-additive`:既有字段和语义稳定;只要旧消费者继续有效,该 surface 可以增加 optional 字段或指标。
9
- - `experimental`:`1.0` 前可用,但语义可能随 changelog 和 focused tests 调整。
9
+ - `experimental`:可用但不提供稳定兼容承诺;语义可以随 changelog、必要的 migration guidance 和 focused tests 调整。
10
10
  - `reserved`:为未来用途保留名称;在 emitter 或 workflow 被记录和测试前不代表已启用。
11
11
  - `internal`:实现细节,不提供兼容承诺。
12
12
 
@@ -15,27 +15,34 @@
15
15
  | Surface | 状态 | Owner | 契约 |
16
16
  |---|---|---|---|
17
17
  | Package 根 JavaScript/TypeScript exports | experimental | `src/index.ts`、`package.json` | Package 根提供已记录的 ESM 入口和对应 TypeScript 声明。除非其他条目明确冻结其行为或 record shape,否则各 helper export 仍为 experimental。 |
18
- | CLI command names 和已记录 flags | stable | `src/bin/mdgraph.ts` | `usage`、`init`、`index`、`status`、`search`、`context`、`node`、`trace`、`eval`、`semantic status`、`bundle create/verify`、`export`、`import graphjson --verify`、`diff`、`report`、`serve --mcp`、`watch` 和 `doctor`。项目相关命令在适用处支持 additive `--path <project>`。`serve --mcp` 默认保持 graph fresh,并额外支持 additive optional `--watch`、`--no-watch`、`--semantic` 和 `--debounce <ms>`,用于集成 watch-based freshness。`status --freshness` 增加可选 freshness diagnostics,不改变默认 `status --json` 形状。 |
18
+ | CLI command names 和已记录 flags | stable | `src/bin/mdgraph.ts` | `usage`、`init`、`index`、`status`、`search`、`context`、`node`、`trace`、`eval`、`semantic status`、`bundle create/verify`、`export`、`import graphjson --verify`、`diff`、`report`、`serve --mcp`、`watch` 和 `doctor`。项目相关命令在适用处支持 additive `--path <project>`。`context` 增加可选 `--packing` 和 `--mmr-lambda`;`serve --mcp` 增加显式 `--watch-poll`;`watch` 增加显式 `--poll`。`status --freshness` 继续为 additive,不改变默认 `status --json` 形状。 |
19
19
  | 项目级 `--path` for project-related commands | stable-additive | `src/bin/mdgraph.ts` | 项目相关命令(`init`、`index`、`status`、`search`、`context`、`node`、`trace`、`eval`、`semantic status`、`bundle create/verify`、`export`、`import graphjson --verify`、`diff`、`report`、`serve --mcp`、`watch`、`doctor` 和 `usage`)接受 additive `--path <project>` flag,让 agent 和脚本不必切换 shell cwd 即可定位仓库。 |
20
20
  | `mdgraph usage` 命令 | stable-additive | `src/bin/mdgraph.ts` | `usage` 打印面向 agent 的 workflow guide;`usage --json` 返回同一组 workflows 的机器可读 JSON,且不读写 graph index。 |
21
+ | 实验性结构化 `query` 命令 | experimental | `src/query/structured-query.ts`、`src/query/structured-query-executor.ts`、`src/bin/mdgraph.ts` | `query <expression>` 提供有界 typed DSL,覆盖已记录的文档字段、tag、出边、日期、排序/limit 与 doctor health。它支持 `--json` 和 `--path`;不会改变稳定的 `search` 或五工具 MCP surface。 |
22
+ | 实验性 `relationships derive` 命令 | experimental | `src/relationships/derive-related.ts`、`src/bin/mdgraph.ts` | 在 freshness、capability、coverage、threshold、独立 evidence、reciprocal top-K 和资源预算全部通过后,基于完整 semantic-model vector 显式派生低权重对称 `RELATED_TO` edge。支持 dry-run,且不会在 index/watch 中自动运行。 |
21
23
  | `status --freshness` diagnostics | stable-additive | `src/bin/mdgraph.ts` | `status --freshness` 增加可选 freshness diagnostics(`state`、`recommendation`、`lastIndexedAt`、`checkedAt`、`issues`),不改变默认 `status --json` 形状;`--storage` 与 `--freshness` 可组合。 |
22
- | `serve --mcp` 默认 watch 与 `--no-watch` 退路 | stable-additive | `src/bin/mdgraph.ts` | `serve --mcp` 默认保持 Markdown graph fresh,并暴露 `--no-watch` 作为只读退路;`--watch`、`--semantic` 和 `--debounce <ms>` 仍是集成 watch-based freshness 的 additive flag。 |
23
- | 顶层 CLI JSON output shapes | stable | `docs/ZH/Output_Contracts.md` | Output Contracts 中记录的必需字段稳定;命令内嵌 graph record 遵循 `src/types.ts`,除非另有说明。 |
24
+ | `serve --mcp` 默认 watch 与 `--no-watch` 退路 | stable-additive | `src/bin/mdgraph.ts` | `serve --mcp` 默认保持 Markdown graph fresh,并暴露 `--no-watch` 作为只读退路;`--watch`、`--semantic`、`--debounce <ms>` 和显式 `--watch-poll` 是集成 watch-based freshness 的 additive flag。 |
25
+ | 顶层 CLI JSON output shapes | stable | `docs/ZH/Output_Contracts.md` | Output Contracts 中记录的必需字段稳定;命令内嵌 graph record 遵循 `src/types.ts`,除非某一 section(例如实验性结构化 `query` 或 `relationships derive`)另有明确标记。 |
24
26
  | MCP tool names 和 input schemas | stable | `src/mcp/tools.ts` | 固定五个工具:`mdgraph_search`、`mdgraph_context`、`mdgraph_node`、`mdgraph_trace` 和 `mdgraph_status`;schema 拒绝未声明属性。 |
25
27
  | MCP structured freshness metadata | stable-additive | `src/mcp/tools.ts` | 当已建立索引时,`mdgraph_status` 会在 `structuredContent` 中返回 `freshness` metadata;当索引 `stale` 或 `unknown` 时,`mdgraph_search` / `mdgraph_context` / `mdgraph_node` / `mdgraph_trace` 也可能追加同一 `freshness` object,并在文本结果前加 warning banner。 |
28
+ | MCP semantic fallback diagnostics | stable-additive | `src/mcp/tools.ts` | `mdgraph_search` 和 `mdgraph_context` 使用异步 provider 路径。semantic retrieval 无法运行时继续返回 lexical/graph 结果并在文本前增加 warning。Search 追加 `structuredContent.semanticDiagnostic`;context 追加 `structuredContent.context.semanticDiagnostic`。两者都包含 `code`、`provider`、`message` 和 `degraded: true`。 |
29
+ | Context packing 选择 | stable-additive | `src/query/context-builder.ts`、`src/mcp/tools.ts` | 已有调用继续使用 `mmr-style-document-round-robin`。CLI `--packing mmr`、MCP `mdgraph_context.packingStrategy` 和库 options 可选择真 MMR。Context 输出增加 `packing`;debug 输出增加相似度、lambda、selection score 和冗余跳过诊断。 |
30
+ | Watch health 与 polling | stable-additive | `src/watcher/file-watcher.ts`、`src/watcher/watch-health.ts`、`src/mcp/tools.ts` | `WatchHandle.getHealth()` 暴露进程内状态、时间、最近错误、覆盖可靠性、polling 和关闭状态。集成 MCP status 可增加 `structuredContent.watchHealth`。只有 `watch --poll`、`serve --mcp --watch-poll` 或 `usePolling: true` 才启用 polling。 |
31
+ | Structured query AST 与执行 | experimental | `src/query/structured-query.ts`、`src/query/structured-query-executor.ts`、`src/db/repositories.ts` | 用户值使用 SQL bound parameter。字段、operator、sort 与 edge enum 在白名单 SQL 组装前完成验证。Health predicate 要求 fresh doctor report,并保留原始 boolean AST。不会暴露任意 front matter 或 raw SQL 逃生口。 |
32
+ | 派生关系执行 | experimental | `src/relationships/derive-related.ts`、`src/db/repositories.ts` | `RELATED_TO/embedding_similarity` edge 非权威、低权重且可原子替换,并携带 provider/model/algorithm/threshold/evidence/generation metadata。`local-hash` 无权发射。GraphJSON 保持结构化隐私 profile,因此不导出这些 edge metadata。 |
26
33
  | MCP text output wording | experimental | `src/mcp/tools.ts` | 文本是面向人的提示;机器契约优先使用 `structuredContent`。 |
27
34
  | Context recovery fields | stable-additive | `src/query/context-builder.ts` | Context item 暴露 `nodeId`、`documentId`、可选 `sectionId`、可选 `anchor`、line range、source refs、risk notes 和 graph-expansion `edgePath`,让 agent 无需从 prose 猜测即可恢复节点和 provenance。 |
28
- | `.mdgraph/config.json` fields | stable | `src/config/load-config.ts` | `docs`、`index`、`search`、`entities` 和 `embedding` 默认字段稳定。当前 merge 逻辑会忽略未知字段。 |
35
+ | `.mdgraph/config.json` fields | stable | `src/config/load-config.ts` | `docs`、`index`、`search`、`entities` 和 `embedding` 默认字段稳定。Additive embedding 字段为 `endpoint`、`timeoutMs` 和 `batchSize`,既有配置文件会取得默认值。当前 merge 逻辑会忽略未知字段。 |
29
36
  | `.mdgraph` file governance | stable | `src/config/load-config.ts`、`src/bin/mdgraph.ts` | `mdgraph init` 保持 `.mdgraph/config.json` 可跟踪,在没有等价 ignore 规则时通过根 `.gitignore` 保护本地 `.mdgraph` artifacts,并默认构建初始 graph index。`.mdgraph/graph.db` 和生成的 `.mdgraph` artifacts 属于本地 workflow state,不是 source files。需要只生成配置时使用 `--no-index`。 |
30
37
  | SQLite schema metadata | stable | `src/db/schema.sql`、`src/db/connection.ts` | `schema_metadata.schema_version` 是兼容 gate。未来 schema version 会在应用本地 schema 前失败。 |
31
38
  | SQLite table internals | internal | `src/db/schema.sql` | rowid、FTS shadow table、vector blob 表示细节和 private bundle database 内容不是 public API。 |
32
39
  | Public graph record types | stable | `src/types.ts` | `GraphDocument`、`GraphSection`、`GraphEntity`、`SourceRef`、`GraphEdge`、`GraphChunk`、`ChunkVector`、`SearchResult` 和 `TraceStep`。 |
33
- | Edge kinds | stable/reserved | `src/types.ts` | 已启用 edge kind 稳定。`SAME_AS`、`RELATED_TO` 和 `CONTRADICTS` 是 reserved,直到 emitter 被记录和测试。 |
40
+ | Edge kinds | stable/experimental/reserved | `src/types.ts` | 既有显式 edge kind 保持 stable。`RELATED_TO` 是由 `DERIVED_EDGE_KINDS` 标识的实验性 opt-in 派生 kind;`SAME_AS` 和 `CONTRADICTS` 继续 reserved,直到独立 emitter 被记录和测试。 |
34
41
  | Doctor warning shape | stable | `src/analysis/doctor.ts` | Warning 包含 `code`、`severity`、`message`、`evidence`、`affectedNodes` 和 `remediation`。warning code 通过 changelog 和 tests 管理版本。 |
35
42
  | GraphJSON export 和 verify | stable format v1 | `src/export/graphjson.ts` | `format: "mdgraph-graphjson"`、`formatVersion: 1`、structural profile、确定性排序和 `graphHash` 验证。 |
36
43
  | Bundle manifest | experimental | `src/bundle/bundle.ts` | `formatVersion: 1` private workflow artifact。它不是公开 sanitized exchange format。 |
37
- | Report、diff 和 benchmark JSON | experimental | `src/reporting`、`src/diff`、`src/benchmark` | 面向 CI 的 workflow 输出;必需顶层字段已记录,详细 metrics 在 `1.0` 前仍可能扩展。 |
38
- | Semantic vector provider behavior | experimental | `src/semantic/*` | 可选本地 provider 不可用或不支持时,必须降级到 FTS5/graph search。 |
44
+ | Report、diff 和 benchmark JSON | experimental | `src/reporting`、`src/diff`、`src/benchmark` | 面向 CI 的 workflow 输出;必需顶层字段已记录,但只要 surface 仍为 experimental,详细 metrics 仍可能扩展。 |
45
+ | Semantic vector provider behavior | experimental | `src/semantic/*` | `local-hash` 作为 `lexical-hash` 兼容 provider 保留;Ollama 是第一个可选 `semantic-model` provider。外部 provider 只通过异步 indexing/query API 运行;不可用或不支持时,query 必须带诊断降级到 FTS5/graph search。显式 indexing 失败不得提交部分 graph/vector 更新。 |
39
46
 
40
47
  ## 兼容策略
41
48
 
@@ -59,23 +66,23 @@
59
66
 
60
67
  ## Release Matrix
61
68
 
62
- 以 `1.0.0` 发布基线为准,应继续保留稳定的 1.0 surfaces,并把 0.9 additive surfaces(`usage`、项目级 `--path`、`status --freshness`、MCP freshness metadata、context recovery fields 和默认 fresh MCP serving)与 0.7-0.8 契约一起验证。
69
+ 每次发布都必须保留稳定的 1.0 基线,并验证所有 `stable-additive` surface,包括 `usage`、项目级 `--path`、`status --freshness`、MCP freshness metadata、context recovery fields、可选 context packing、watch health 和默认 fresh MCP serving。实验性的 structured query、semantic-provider 与 derived-relationship 行为必须保持明确标记,并由聚焦测试覆盖。
63
70
 
64
71
  `1.0` candidate release 前:
65
72
 
66
- - 运行 `npm run typecheck`、focused contract tests、`npm test`、`npm run build`、`npm run smoke:cli`、`npm run smoke:eval`、`npm run smoke:pack`、`npm run task:public-check` 和 `git diff --check`。
73
+ - 运行 `npm run docs:check`、`npm run typecheck`、focused contract tests、`npm test`、`npm run build`、`npm run smoke:cli`、`npm run smoke:eval`、`npm run smoke:pack`、`npm run task:public-check` 和 `git diff --check`。
67
74
  - 当 package metadata 或 included public docs 变化时运行 `npm pack --dry-run`。
68
75
  - 验证 Node.js `>=22.5.0`;常规开发基线是当前 Node 22.x。
69
76
  - Linux 和 Windows full CI 是 release gate 基线;`1.0` 前 macOS 由 CI smoke 覆盖 build-output CLI 和 packed-artifact 行为。
70
77
  - 对平台相关的长运行 surface 使用 release maintainer smoke,而不是 CI,例如 `serve --mcp` 和 `watch`。
71
78
  - 外部语料的评估数据应保留在公开仓库之外,除非它拥有独立许可并被明确采纳为公开 fixture。
72
79
 
73
- ## 1.0 Readiness
80
+ ## 发布就绪条件
74
81
 
75
- 只有满足以下条件后,MDGraph 才应从 `0.9` 进入 `1.0`:
82
+ 只有满足以下条件后才可以发布:
76
83
 
77
- - 上述 ledger 覆盖每个 public surface。
84
+ - 上述 ledger 对每个被触及的 public surface 保持最新。
78
85
  - 关键 public shape 已由 focused tests 或 smoke gates 保护。
79
86
  - Experimental 和 internal surface 已在文档中明确标注。
80
- - 已知 output-shape 不一致已经被规范化,或被明确记录为刻意保留。
87
+ - 已知 output-shape 不一致已经被规范化,或在本次发布中被明确记录为刻意保留。
81
88
  - Release checklist 能捕获意外 public contract drift。