@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.
- package/CHANGELOG.md +51 -0
- package/README-ZH.md +66 -4
- package/README.md +84 -22
- package/agent-pack/README.md +2 -0
- package/agent-pack/mdgraph-agent-instructions.md +3 -1
- package/agent-pack/prompts/wiki-authoring.md +12 -0
- package/agent-pack/skills/wiki-authoring/SKILL.md +38 -0
- package/agent-pack/skills/wiki-authoring/agents/openai.yaml +4 -0
- package/dist/analysis/status-freshness.d.ts +8 -1
- package/dist/analysis/status-freshness.js +19 -6
- package/dist/bin/mdgraph.js +260 -25
- package/dist/config/limits.d.ts +2 -0
- package/dist/config/limits.js +3 -1
- package/dist/config/load-config.js +8 -2
- package/dist/db/connection.js +17 -1
- package/dist/db/repositories.d.ts +55 -4
- package/dist/db/repositories.js +458 -11
- package/dist/db/sqlite-adapter.js +8 -2
- package/dist/evaluation/context-packing-evaluation.d.ts +29 -0
- package/dist/evaluation/context-packing-evaluation.js +134 -0
- package/dist/evaluation/entity-extraction-evaluation.d.ts +38 -0
- package/dist/evaluation/entity-extraction-evaluation.js +118 -0
- package/dist/evaluation/historical-baseline.d.ts +70 -0
- package/dist/evaluation/historical-baseline.js +278 -0
- package/dist/evaluation/related-documents-evaluation.d.ts +26 -0
- package/dist/evaluation/related-documents-evaluation.js +163 -0
- package/dist/evaluation/retrieval-eval.d.ts +25 -5
- package/dist/evaluation/retrieval-eval.js +79 -7
- package/dist/evaluation/structured-query-evaluation.d.ts +27 -0
- package/dist/evaluation/structured-query-evaluation.js +156 -0
- package/dist/extraction/entity-extractor.js +42 -22
- package/dist/extraction/graph-builder.js +2 -18
- package/dist/index.d.ts +24 -4
- package/dist/index.js +12 -4
- package/dist/indexer.js +80 -4
- package/dist/mcp/server.d.ts +4 -0
- package/dist/mcp/server.js +21 -11
- package/dist/mcp/tools.d.ts +5 -1
- package/dist/mcp/tools.js +116 -18
- package/dist/parser/markdown-parser.js +2 -0
- package/dist/query/context-builder.d.ts +32 -2
- package/dist/query/context-builder.js +191 -12
- package/dist/query/knowledge-card.d.ts +90 -0
- package/dist/query/knowledge-card.js +676 -0
- package/dist/query/search.d.ts +5 -1
- package/dist/query/search.js +85 -16
- package/dist/query/structured-query-executor.d.ts +28 -0
- package/dist/query/structured-query-executor.js +138 -0
- package/dist/query/structured-query.d.ts +50 -0
- package/dist/query/structured-query.js +390 -0
- package/dist/relationships/derive-related.d.ts +86 -0
- package/dist/relationships/derive-related.js +322 -0
- package/dist/reporting/report.js +2 -2
- package/dist/semantic/embed-chunks.d.ts +2 -0
- package/dist/semantic/embed-chunks.js +31 -0
- package/dist/semantic/ollama-provider.d.ts +6 -0
- package/dist/semantic/ollama-provider.js +136 -0
- package/dist/semantic/provider-registry.d.ts +8 -0
- package/dist/semantic/provider-registry.js +66 -0
- package/dist/semantic/provider.d.ts +35 -0
- package/dist/semantic/provider.js +29 -0
- package/dist/semantic/status.d.ts +6 -1
- package/dist/semantic/status.js +49 -3
- package/dist/types.d.ts +7 -2
- package/dist/types.js +2 -1
- package/dist/utils/path-safety.d.ts +3 -0
- package/dist/utils/path-safety.js +27 -0
- package/dist/watcher/file-watcher.d.ts +4 -0
- package/dist/watcher/file-watcher.js +151 -17
- package/dist/watcher/watch-health.d.ts +34 -0
- package/dist/watcher/watch-health.js +75 -0
- package/dist/wiki/wiki-dependencies.d.ts +20 -0
- package/dist/wiki/wiki-dependencies.js +45 -0
- package/dist/wiki/wiki-domains.d.ts +13 -0
- package/dist/wiki/wiki-domains.js +55 -0
- package/dist/wiki/wiki-evidence.d.ts +27 -0
- package/dist/wiki/wiki-evidence.js +112 -0
- package/dist/wiki/wiki-plan.d.ts +121 -0
- package/dist/wiki/wiki-plan.js +616 -0
- package/dist/wiki/wiki-status.d.ts +67 -0
- package/dist/wiki/wiki-status.js +451 -0
- package/docs/EN/Agent_Integration.md +15 -5
- package/docs/EN/Architecture.md +52 -16
- package/docs/EN/Evaluation_Questions.md +35 -5
- package/docs/EN/Knowledge_Cards_and_Wiki_Workflow.md +97 -0
- package/docs/EN/Operations.md +111 -0
- package/docs/EN/Output_Contracts.md +83 -10
- package/docs/EN/Public_Contracts.md +25 -16
- package/docs/EN/Public_Contracts_1.0.md +32 -18
- package/docs/EN/README.md +24 -0
- package/docs/EN/Release_Checklist.md +27 -13
- package/docs/EN/Retrieval_and_Context.md +118 -0
- package/docs/EN/Structured_Query_and_Relationships.md +111 -0
- package/docs/ZH/Agent_Integration.md +15 -5
- package/docs/ZH/Architecture.md +52 -21
- package/docs/ZH/Evaluation_Questions.md +36 -6
- package/docs/ZH/Knowledge_Cards_and_Wiki_Workflow.md +99 -0
- package/docs/ZH/Operations.md +111 -0
- package/docs/ZH/Output_Contracts.md +83 -10
- package/docs/ZH/Public_Contracts.md +24 -15
- package/docs/ZH/Public_Contracts_1.0.md +31 -17
- package/docs/ZH/README.md +24 -0
- package/docs/ZH/Release_Checklist.md +27 -13
- package/docs/ZH/Retrieval_and_Context.md +118 -0
- package/docs/ZH/Structured_Query_and_Relationships.md +111 -0
- package/package.json +50 -19
|
@@ -7,13 +7,13 @@ source_refs:
|
|
|
7
7
|
|
|
8
8
|
# MDGraph Public Contracts
|
|
9
9
|
|
|
10
|
-
This document records the public contract boundary for the current `1.0.0`
|
|
10
|
+
This document records the public contract boundary for the current release line, anchored to the frozen `1.0.0` compatibility baseline. It complements [Output_Contracts.md](Output_Contracts.md), [Architecture.md](Architecture.md), and [Release_Checklist.md](Release_Checklist.md). The full per-command, per-format, per-config, and per-schema inventory lives in the [1.0 Contract Freeze Appendix](Public_Contracts_1.0.md).
|
|
11
11
|
|
|
12
12
|
## Stability Labels
|
|
13
13
|
|
|
14
14
|
- `stable`: users and agents may rely on this shape. Additive fields are allowed; removing or renaming documented fields is a breaking change after 1.0.
|
|
15
15
|
- `stable-additive`: existing fields and semantics are stable, and the surface may gain optional fields or metrics when old consumers remain valid.
|
|
16
|
-
- `experimental`: available
|
|
16
|
+
- `experimental`: available without a stable compatibility promise; semantics may be adjusted with changelog notes, migration guidance where needed, and focused tests.
|
|
17
17
|
- `reserved`: named for future use, but not active until an emitter or workflow is documented and tested.
|
|
18
18
|
- `internal`: implementation detail. It may change without compatibility guarantees.
|
|
19
19
|
|
|
@@ -22,27 +22,36 @@ This document records the public contract boundary for the current `1.0.0` publi
|
|
|
22
22
|
| Surface | Status | Owner | Contract |
|
|
23
23
|
|---|---|---|---|
|
|
24
24
|
| Package root JavaScript/TypeScript exports | experimental | `src/index.ts`, `package.json` | The package root exposes the documented ESM entry point and matching TypeScript declarations. Individual helper exports remain experimental unless another row explicitly freezes their behavior or record shape. |
|
|
25
|
-
| CLI command names and documented 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`, and `doctor`. Project-related commands support additive `--path <project>` where applicable. `
|
|
25
|
+
| CLI command names and documented 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`, and `doctor`. Project-related commands support additive `--path <project>` where applicable. `context` adds optional `--packing` and `--mmr-lambda`; `serve --mcp` adds explicit `--watch-poll`; `watch` adds explicit `--poll`. `status --freshness` remains additive without changing the default `status --json` shape. |
|
|
26
26
|
| Project-wide `--path` for project-related commands | stable-additive | `src/bin/mdgraph.ts` | Project-related commands (`init`, `index`, `status`, `search`, `context`, `node`, `trace`, `eval`, `semantic status`, `bundle create/verify`, `export`, `import graphjson --verify`, `diff`, `report`, `serve --mcp`, `watch`, `doctor`, and `usage`) accept an additive `--path <project>` flag so agents and scripts can target a repository without changing the shell cwd. |
|
|
27
27
|
| `mdgraph usage` command | stable-additive | `src/bin/mdgraph.ts` | `usage` prints an agent-friendly workflow guide and `usage --json` returns the same workflows as machine-readable JSON without reading or writing the graph index. |
|
|
28
|
+
| Experimental structured `query` command | experimental | `src/query/structured-query.ts`, `src/query/structured-query-executor.ts`, `src/bin/mdgraph.ts` | `query <expression>` provides a bounded typed DSL over documented document fields, tags, outgoing edges, dates, sorting/limits, and doctor health. It supports `--json` and `--path`; it does not change stable `search` or the five-tool MCP surface. |
|
|
29
|
+
| Experimental `relationships derive` command | experimental | `src/relationships/derive-related.ts`, `src/bin/mdgraph.ts` | Explicitly derives low-weight symmetric `RELATED_TO` edges from complete semantic-model vectors after freshness, capability, coverage, threshold, independent-evidence, reciprocal-top-K, and resource-budget checks. It supports dry-run and never runs automatically during index/watch. |
|
|
30
|
+
| Experimental Wiki workflow | experimental | `src/wiki/wiki-plan.ts`, `src/wiki/wiki-status.ts`, `src/bin/mdgraph.ts` | `wiki plan/brief/status/verify` adds deterministic planning, bounded evidence briefs, impact status, and read-only verification without adding MCP tools or generating/overwriting prose. WikiPlan and WikiPageBrief formatVersion 1, page-state names, structured verification issue fields, and non-zero invalid verification are experimental. |
|
|
28
31
|
| `status --freshness` diagnostics | stable-additive | `src/bin/mdgraph.ts` | `status --freshness` adds optional freshness diagnostics (`state`, `recommendation`, `lastIndexedAt`, `checkedAt`, `issues`) without changing the default `status --json` shape; `--storage` and `--freshness` may be combined. |
|
|
29
|
-
| `serve --mcp` default watch and `--no-watch` escape hatch | stable-additive | `src/bin/mdgraph.ts` | `serve --mcp` keeps the Markdown graph fresh by default and exposes `--no-watch` as the read-only escape hatch; `--watch`, `--semantic`,
|
|
30
|
-
| Top-level CLI JSON output shapes | stable | `docs/EN/Output_Contracts.md` | Required fields documented in Output Contracts are stable; command-specific nested graph records follow `src/types.ts` unless marked otherwise. |
|
|
32
|
+
| `serve --mcp` default watch and `--no-watch` escape hatch | stable-additive | `src/bin/mdgraph.ts` | `serve --mcp` keeps the Markdown graph fresh by default and exposes `--no-watch` as the read-only escape hatch; `--watch`, `--semantic`, `--debounce <ms>`, and explicit `--watch-poll` are additive flags for integrated watch-based freshness. |
|
|
33
|
+
| Top-level CLI JSON output shapes | stable | `docs/EN/Output_Contracts.md` | Required fields documented in Output Contracts are stable; command-specific nested graph records follow `src/types.ts` unless a section, such as experimental structured `query`, `relationships derive`, or `wiki`, is explicitly marked otherwise. |
|
|
31
34
|
| MCP tool names and input schemas | stable | `src/mcp/tools.ts` | Exactly five tools: `mdgraph_search`, `mdgraph_context`, `mdgraph_node`, `mdgraph_trace`, and `mdgraph_status`; schemas reject undeclared properties. |
|
|
32
35
|
| MCP structured freshness metadata | stable-additive | `src/mcp/tools.ts` | `mdgraph_status` always returns `freshness` metadata in `structuredContent` when indexed, and `mdgraph_search`/`mdgraph_context`/`mdgraph_node`/`mdgraph_trace` may add the same `freshness` object plus a text warning banner when the index is `stale` or `unknown`. |
|
|
36
|
+
| MCP semantic fallback diagnostics | stable-additive | `src/mcp/tools.ts` | `mdgraph_search` and `mdgraph_context` use the async provider path. When semantic retrieval cannot run, they keep lexical/graph results and prepend a text warning. Search adds `structuredContent.semanticDiagnostic`; context adds `structuredContent.context.semanticDiagnostic`. Both contain `code`, `provider`, `message`, and `degraded: true`. |
|
|
37
|
+
| Context packing selection | stable-additive | `src/query/context-builder.ts`, `src/mcp/tools.ts` | Existing callers retain `mmr-style-document-round-robin`. CLI `--packing mmr`, MCP `mdgraph_context.packingStrategy`, and library options select true MMR. Context output adds `packing`; debug output adds similarity, lambda, selection scores, and redundancy skip diagnostics. |
|
|
38
|
+
| Watch health and polling | stable-additive | `src/watcher/file-watcher.ts`, `src/watcher/watch-health.ts`, `src/mcp/tools.ts` | `WatchHandle.getHealth()` exposes in-process state, timestamps, last error, coverage reliability, polling, and closure. Integrated MCP status may add `structuredContent.watchHealth`. Polling is enabled only by `watch --poll`, `serve --mcp --watch-poll`, or `usePolling: true`. |
|
|
39
|
+
| Structured query AST and execution | experimental | `src/query/structured-query.ts`, `src/query/structured-query-executor.ts`, `src/db/repositories.ts` | User values use bound SQL parameters. Field/operator/sort/edge enums are validated before whitelisted SQL assembly. Health predicates require a fresh doctor report and preserve the original boolean AST. No arbitrary front-matter or raw SQL escape is exposed. |
|
|
40
|
+
| Derived relationship execution | experimental | `src/relationships/derive-related.ts`, `src/db/repositories.ts` | `RELATED_TO/embedding_similarity` edges are non-authoritative, low weight, atomically replaceable, and carry provider/model/algorithm/threshold/evidence/generation metadata. `local-hash` cannot emit them. GraphJSON retains its structural privacy profile and therefore omits this edge metadata. |
|
|
33
41
|
| MCP text output wording | experimental | `src/mcp/tools.ts` | Text is human-facing guidance; `structuredContent` is the preferred machine contract. |
|
|
42
|
+
| Dynamic Knowledge Card projection | experimental / stable-additive | `src/query/knowledge-card.ts`, `src/query/context-builder.ts`, `src/bin/mdgraph.ts`, `src/mcp/tools.ts` | Found document, section, entity, and source-ref `node` results may add a deterministic non-persisted `card`; selected context items may add `cardSummary`, counted in `usedChars`, only from budget left after original content. Existing node fields, ranking, trace paths, SQLite counts, and the five-tool MCP surface remain unchanged. |
|
|
34
43
|
| Context recovery fields | stable-additive | `src/query/context-builder.ts` | Context items expose `nodeId`, `documentId`, optional `sectionId`, optional `anchor`, line ranges, source refs, risk notes, and graph-expansion `edgePath` so agents can recover nodes and provenance without guessing from prose. |
|
|
35
|
-
| `.mdgraph/config.json` fields | stable | `src/config/load-config.ts` | `docs`, `index`, `search`, `entities`, and `embedding` default fields are stable. Unknown fields are currently ignored by merge logic. |
|
|
44
|
+
| `.mdgraph/config.json` fields | stable | `src/config/load-config.ts` | `docs`, `index`, `search`, `entities`, and `embedding` default fields are stable. The additive embedding fields are `endpoint`, `timeoutMs`, and `batchSize`; existing config files receive defaults. Unknown fields are currently ignored by merge logic. |
|
|
36
45
|
| `.mdgraph` file governance | stable | `src/config/load-config.ts`, `src/bin/mdgraph.ts` | `mdgraph init` keeps `.mdgraph/config.json` trackable, protects local `.mdgraph` artifacts through the root `.gitignore` when no equivalent ignore rule exists, and builds the initial graph index by default. `.mdgraph/graph.db` and generated `.mdgraph` artifacts are local workflow state, not source files. Use `--no-index` for config-only initialization. |
|
|
37
46
|
| SQLite schema metadata | stable | `src/db/schema.sql`, `src/db/connection.ts` | `schema_metadata.schema_version` gates compatibility. Future schema versions fail before local schema is applied. |
|
|
38
47
|
| SQLite table internals | internal | `src/db/schema.sql` | Rowids, FTS shadow tables, vector blob representation internals, and private bundle database contents are not public API. |
|
|
39
48
|
| Public graph record types | stable | `src/types.ts` | `GraphDocument`, `GraphSection`, `GraphEntity`, `SourceRef`, `GraphEdge`, `GraphChunk`, `ChunkVector`, `SearchResult`, and `TraceStep`. |
|
|
40
|
-
| Edge kinds | stable/reserved | `src/types.ts` |
|
|
49
|
+
| Edge kinds | stable/experimental/reserved | `src/types.ts` | Existing explicit edge kinds are stable. `RELATED_TO` is an experimental opt-in derived kind identified by `DERIVED_EDGE_KINDS`; `SAME_AS` and `CONTRADICTS` remain reserved until separate emitters are documented and tested. |
|
|
41
50
|
| Doctor warning shape | stable | `src/analysis/doctor.ts` | Warnings include `code`, `severity`, `message`, `evidence`, `affectedNodes`, and `remediation`. Warning codes are versioned by changelog and tests. |
|
|
42
51
|
| GraphJSON export and verify | stable format v1 | `src/export/graphjson.ts` | `format: "mdgraph-graphjson"`, `formatVersion: 1`, structural profile, deterministic ordering, and `graphHash` verification. |
|
|
43
52
|
| Bundle manifest | experimental | `src/bundle/bundle.ts` | `formatVersion: 1` private workflow artifact. It is not a public sanitized exchange format. |
|
|
44
|
-
| Report, diff, and benchmark JSON | experimental | `src/reporting`, `src/diff`, `src/benchmark` | CI-facing workflow outputs; required top-level fields are documented, but detailed metrics may expand
|
|
45
|
-
| Semantic vector provider behavior | experimental | `src/semantic/*` |
|
|
53
|
+
| Report, diff, and benchmark JSON | experimental | `src/reporting`, `src/diff`, `src/benchmark` | CI-facing workflow outputs; required top-level fields are documented, but detailed metrics may expand while the surface remains experimental. |
|
|
54
|
+
| Semantic vector provider behavior | experimental | `src/semantic/*` | `local-hash` remains a `lexical-hash` compatibility provider; Ollama is the first opt-in `semantic-model` provider. External providers run only through async indexing/query APIs and must degrade queries to FTS5/graph search with diagnostics when unavailable or unsupported. Explicit indexing failures must not commit partial graph/vector updates. |
|
|
46
55
|
|
|
47
56
|
## Compatibility Policy
|
|
48
57
|
|
|
@@ -66,23 +75,23 @@ This document records the public contract boundary for the current `1.0.0` publi
|
|
|
66
75
|
|
|
67
76
|
## Release Matrix
|
|
68
77
|
|
|
69
|
-
|
|
78
|
+
Every release must preserve the stable 1.0 baseline and validate all `stable-additive` surfaces, including `usage`, project-wide `--path`, `status --freshness`, MCP freshness metadata, context recovery fields, optional context packing, watch health, and default fresh MCP serving. Experimental structured query, semantic-provider, and derived-relationship behavior must remain explicitly labeled and covered by focused tests.
|
|
70
79
|
|
|
71
80
|
Before a release that changes public surfaces:
|
|
72
81
|
|
|
73
|
-
- Run `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`, and `git diff --check`.
|
|
82
|
+
- Run `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`, and `git diff --check`.
|
|
74
83
|
- Run `npm pack --dry-run` when package metadata or included public docs change.
|
|
75
84
|
- Validate on Node.js `>=22.5.0`; the regular development baseline is the current Node 22.x line.
|
|
76
|
-
- Treat Linux and Windows full CI as the release-gate baseline, and keep macOS covered by CI smoke for build-output CLI and packed-artifact behavior
|
|
85
|
+
- Treat Linux and Windows full CI as the release-gate baseline, and keep macOS covered by CI smoke for build-output CLI and packed-artifact behavior.
|
|
77
86
|
- Use release maintainer smoke, not CI, for platform-specific long-running surfaces such as `serve --mcp` and `watch`.
|
|
78
87
|
- Keep any external-corpus evaluation data outside the public repository unless it is independently licensed and intentionally adopted as a public fixture.
|
|
79
88
|
|
|
80
|
-
##
|
|
89
|
+
## Release Readiness
|
|
81
90
|
|
|
82
|
-
|
|
91
|
+
A release is ready only after:
|
|
83
92
|
|
|
84
|
-
- The ledger above is
|
|
93
|
+
- The ledger above is current for every touched public surface.
|
|
85
94
|
- Critical public shapes are protected by focused tests or smoke gates.
|
|
86
95
|
- Experimental and internal surfaces are explicitly labeled in docs.
|
|
87
|
-
- Known output-shape inconsistencies are either normalized or intentionally documented.
|
|
96
|
+
- Known output-shape inconsistencies are either normalized or intentionally documented in the release.
|
|
88
97
|
- The release checklist can catch accidental public contract drift.
|
|
@@ -2,19 +2,14 @@
|
|
|
2
2
|
|
|
3
3
|
Status: active
|
|
4
4
|
Created: 2026-07-09
|
|
5
|
-
Companion to: [Public_Contracts.md](Public_Contracts.md) and [Output_Contracts.md](Output_Contracts.md)
|
|
6
|
-
Task: 2026-06-27-roadmap-1-0-contract-freeze
|
|
5
|
+
Companion to: [Public_Contracts.md](Public_Contracts.md) and [Output_Contracts.md](Output_Contracts.md)
|
|
7
6
|
|
|
8
7
|
This appendix is the authoritative inventory of the MDGraph public surface
|
|
9
8
|
frozen for the `1.0.0` release. It supplements the [Public Contracts](Public_Contracts.md)
|
|
10
9
|
ledger with the full per-command, per-format, per-config, per-schema
|
|
11
10
|
details that the ledger summarizes.
|
|
12
11
|
|
|
13
|
-
|
|
14
|
-
`docs/tasks/2026-06-27-roadmap-1-0-contract-freeze/`, which stays ignored
|
|
15
|
-
and is not a GitHub deliverable.
|
|
16
|
-
|
|
17
|
-
## Freeze Baseline
|
|
12
|
+
## Freeze Baseline
|
|
18
13
|
|
|
19
14
|
- Package version: `1.0.0`
|
|
20
15
|
- SQLite `schemaVersion`: `1`
|
|
@@ -50,7 +45,7 @@ semantics are stricter.
|
|
|
50
45
|
| `index` | none | `index --json` returns `files`, `changed`, `deleted`, `unchanged`, `skipped`, `skippedFiles`, `mode`, `counts` | progress summary | `--semantic` and `--full` are `stable-additive` |
|
|
51
46
|
| `status` | none | `status --json` returns graph counts; `--storage` adds `storage`; `--freshness` adds `freshness` | counts summary | `--freshness` is `stable-additive` |
|
|
52
47
|
| `search` | `<query>` | `search --json` returns `document`, optional `section`, `score`, `reason`, `content`, `matchedEntities`, optional `semantic`; `--explain` adds `query`, `limit`, `queryMode`, `entityCandidates`, `ftsQuery`, `semanticEnabled`, `semanticActive`, `ranking`, `matchedEntities`, `results` | text list | `--explain`, `--semantic`, `--limit` are `stable-additive` |
|
|
53
|
-
| `context` | `<query>` | `context --json` returns `query`, `maxChars`, `usedChars`, `items`; each item carries `nodeId`, `documentId`, optional `sectionId`, optional `anchor`, `path`, `title`, optional `heading`, optional `lines`, `reason`, `matchedEntities`, optional `edgePath` (with `fromId`, `fromLabel`, `edgeFromId`, `edgeToId`, `edgeKind`, `toId`, `toLabel`, `traversalDirection`, `confidence`, `provenance`), optional `sourceRefs`, optional `riskNotes`, and `content`; `--debug` adds `debug` | text context summary | recovery fields are `stable-additive` |
|
|
48
|
+
| `context` | `<query>` | `context --json` returns `query`, `maxChars`, `usedChars`, additive `packing`, and `items`; each item carries `nodeId`, `documentId`, optional `sectionId`, optional `anchor`, `path`, `title`, optional `heading`, optional `lines`, `reason`, `matchedEntities`, optional `edgePath` (with `fromId`, `fromLabel`, `edgeFromId`, `edgeToId`, `edgeKind`, `toId`, `toLabel`, `traversalDirection`, `confidence`, `provenance`), optional `sourceRefs`, optional `riskNotes`, and `content`; `--debug` adds `debug` | text context summary | recovery and packing fields are `stable-additive`; `--packing mmr` and `--mmr-lambda` are opt-in |
|
|
54
49
|
| `node` | `<query>` | `node --json` returns `id`, `label`, `kind`, `data`; `error: "ambiguous_section"` or `error: "not_found"` when unresolved | text node summary | section lookup with anchor is `stable-additive` |
|
|
55
50
|
| `trace` | `<from>`, `<to>` | `trace --json` returns `from`, `to`, `found`, `steps` | text trace summary | `--depth` is `stable-additive` |
|
|
56
51
|
| `eval` | none | `eval --json` returns `querySet`, `limit`, `ranking`, `generatedAt`, `summary`, `cases` | summary | `--path`, `--query-set`, `--query-mode`, `--limit` are `stable-additive`; `--query-set` accepts the closed enum `alpha | cjk`; `--limit` accepts a positive integer |
|
|
@@ -65,12 +60,28 @@ semantics are stricter.
|
|
|
65
60
|
| `import graphjson` | `<file>` | `import graphjson <file> --verify --json` returns `valid`, `errors`, `warnings`, plus readable `format`, `formatVersion`, `schemaVersion`, `graphHash`, `counts`, `exportedCounts` | summary | `--verify` is required; exit non-zero on `valid: false`; project root is implicit from the file argument |
|
|
66
61
|
| `diff` | none | `diff --base <ref> --json` returns `mode`, `base`, `head`, `summary`, `documents`, `impact` | summary | base index is created in a temp directory |
|
|
67
62
|
| `report` | none | `report --json` returns `projectRoot`, `generatedAt`, `mdgraphVersion`, `indexed`, `schema`, `counts`, `storage`, `source`, `doctor`, `eval`, `bundle`, `diff`, `benchmark`, `trend` | summary | optional flags are `experimental` |
|
|
68
|
-
| `serve --mcp` | none | not applicable; emits MCP JSON-RPC over stdio | stdio JSON-RPC; stderr logs when watch or MCP debug is enabled | default watch is `stable-additive`; `--no-watch` is the read-only escape hatch |
|
|
69
|
-
| `watch` | none | none | progress log | `--semantic
|
|
70
|
-
| `doctor` | none | `doctor --json` returns `staleIndex`, `summary` (with `documents`, `orphanDocs`, `deadLinks`, `staleSourceRefs`, `missingDefinitions`, `weaklyLinkedDocs`, `possibleContradictions`, `contentRisks`, `staleIndex`), `issues`, optional `scope` (with `mode`, `baseRef`, `changedPaths`, `deletedPaths`, `renamedPaths`, `untrackedPaths`, `globalHealthIncluded`), optional `health` (with `graph`, `storage`), optional `frontmatterDiagnostics` | summary | `--changed` and `--since <ref>` are `stable-additive`; `--fail-on <severity>` (closed enum `error | warn | info`) exits non-zero at or above severity; `--strict` is the legacy strict mode |
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
63
|
+
| `serve --mcp` | none | not applicable; emits MCP JSON-RPC over stdio | stdio JSON-RPC; stderr logs when watch or MCP debug is enabled | default watch is `stable-additive`; `--no-watch` is the read-only escape hatch; `--watch-poll` is an explicit `stable-additive` fallback |
|
|
64
|
+
| `watch` | none | none | progress and health log | `--semantic`, `--debounce <ms>`, and explicit `--poll` are `stable-additive` |
|
|
65
|
+
| `doctor` | none | `doctor --json` returns `staleIndex`, `summary` (with `documents`, `orphanDocs`, `deadLinks`, `staleSourceRefs`, `missingDefinitions`, `weaklyLinkedDocs`, `possibleContradictions`, `contentRisks`, `staleIndex`), `issues`, optional `scope` (with `mode`, `baseRef`, `changedPaths`, `deletedPaths`, `renamedPaths`, `untrackedPaths`, `globalHealthIncluded`), optional `health` (with `graph`, `storage`), optional `frontmatterDiagnostics` | summary | `--changed` and `--since <ref>` are `stable-additive`; `--fail-on <severity>` (closed enum `error | warn | info`) exits non-zero at or above severity; `--strict` is the legacy strict mode |
|
|
66
|
+
|
|
67
|
+
### Post-freeze Experimental Addition
|
|
68
|
+
|
|
69
|
+
`query <expression>` is an experimental post-freeze command and is not part of
|
|
70
|
+
the frozen 1.0 CLI inventory above. Its bounded DSL and JSON output are documented in
|
|
71
|
+
[Structured Query and Relationships](Structured_Query_and_Relationships.md#structured-query) and
|
|
72
|
+
[Output Contracts](Output_Contracts.md).
|
|
73
|
+
|
|
74
|
+
`relationships derive` is experimental and is also outside the
|
|
75
|
+
frozen inventory. Its provider/evidence gates and JSON output are documented in
|
|
76
|
+
[Structured Query and Relationships](Structured_Query_and_Relationships.md#derived-related-document-relationships) and Output Contracts.
|
|
77
|
+
|
|
78
|
+
`wiki plan/brief/status/verify` is an experimental post-freeze CLI group. It adds no
|
|
79
|
+
MCP tools, does not generate prose, and is documented in
|
|
80
|
+
[Knowledge Cards and Wiki Workflow](Knowledge_Cards_and_Wiki_Workflow.md) and Output Contracts.
|
|
81
|
+
The stable `search` command and five-tool MCP surface are unchanged.
|
|
82
|
+
|
|
83
|
+
Project-related commands accept an additive `--path <project>` flag so
|
|
84
|
+
agents and scripts can target a repository without changing the shell cwd.
|
|
74
85
|
|
|
75
86
|
## Config Defaults
|
|
76
87
|
|
|
@@ -87,10 +98,13 @@ agents and scripts can target a repository without changing the shell cwd.
|
|
|
87
98
|
| `search.highFrequencyEntityThreshold` | `50` | upper bound `100000` |
|
|
88
99
|
| `entities.enabledKinds` | `["symbol", "api_route", "error_code", "config_key", "file_path", "command", "package", "concept"]` | |
|
|
89
100
|
| `entities.stopEntities` | `["Config", "Error", "Service", "API", "User", "Data"]` | noise-suppression list |
|
|
90
|
-
| `embedding.enabled` | `false` | optional local semantic vectors |
|
|
91
|
-
| `embedding.provider` | `"local-hash"` | `
|
|
92
|
-
| `embedding.model` | `"mdgraph-local-hash-v1"` | |
|
|
93
|
-
| `embedding.dimensions` | `128` | upper bound `4096` |
|
|
101
|
+
| `embedding.enabled` | `false` | optional local semantic vectors |
|
|
102
|
+
| `embedding.provider` | `"local-hash"` | compatibility `lexical-hash`; `ollama` is supported as an opt-in async provider |
|
|
103
|
+
| `embedding.model` | `"mdgraph-local-hash-v1"` | |
|
|
104
|
+
| `embedding.dimensions` | `128` | upper bound `4096` |
|
|
105
|
+
| `embedding.endpoint` | `"http://127.0.0.1:11434"` | additive Ollama endpoint; credentials in the URL are rejected |
|
|
106
|
+
| `embedding.timeoutMs` | `30000` | upper bound `120000` |
|
|
107
|
+
| `embedding.batchSize` | `16` | upper bound `256` |
|
|
94
108
|
|
|
95
109
|
Unknown keys are currently ignored by the merge logic. Rejecting unknown
|
|
96
110
|
keys is intentionally not a 1.0 breaking change; the conservative default
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# MDGraph Documentation
|
|
2
|
+
|
|
3
|
+
[简体中文](../ZH/README.md)
|
|
4
|
+
|
|
5
|
+
MDGraph documentation is organized by user task. Start with the repository [README](https://github.com/daoGEE/mdgraph#readme) for installation and a first query, then use the guide that matches what you are trying to do.
|
|
6
|
+
|
|
7
|
+
## Use MDGraph
|
|
8
|
+
|
|
9
|
+
- [Agent Integration](Agent_Integration.md) — connect MDGraph to an MCP host and give coding agents a reliable documentation workflow.
|
|
10
|
+
- [Retrieval and Context](Retrieval_and_Context.md) — understand search channels, optional semantic providers, entity extraction, CJK handling, and context packing.
|
|
11
|
+
- [Structured Query and Relationships](Structured_Query_and_Relationships.md) — run governance queries and explicitly derive non-authoritative related-document edges.
|
|
12
|
+
- [Operations](Operations.md) — keep indexes fresh, interpret watcher health, use polling safely, and recover from provider or file-watcher failures.
|
|
13
|
+
- [Knowledge Cards and Wiki Workflow](Knowledge_Cards_and_Wiki_Workflow.md) — plan and maintain an evidence-backed user Wiki without in-process prose generation.
|
|
14
|
+
|
|
15
|
+
## Integrate and Maintain MDGraph
|
|
16
|
+
|
|
17
|
+
- [Architecture](Architecture.md) — implemented pipeline, module boundaries, data model, and tradeoffs.
|
|
18
|
+
- [Output Contracts](Output_Contracts.md) — machine-readable CLI and MCP result shapes.
|
|
19
|
+
- [Public Contracts](Public_Contracts.md) — compatibility labels and the current public boundary.
|
|
20
|
+
- [1.0 Contract Freeze](Public_Contracts_1.0.md) — versioned inventory of the stable 1.0 baseline.
|
|
21
|
+
- [Evaluation](Evaluation_Questions.md) — public evaluation commands, reference questions, and repository regression suites.
|
|
22
|
+
- [Release Checklist](Release_Checklist.md) — maintainer checks for GitHub and npm releases.
|
|
23
|
+
|
|
24
|
+
Experimental commands are labeled in their guides and output contracts. Their presence does not change the deterministic default indexing pipeline, the stable `search` command, or the five-tool MCP surface.
|
|
@@ -5,30 +5,35 @@ Use this checklist before publishing an MDGraph release or asking a maintainer t
|
|
|
5
5
|
## Public checks
|
|
6
6
|
|
|
7
7
|
- Confirm the public package is `@daogee/mdgraph`, the installed binary remains `mdgraph`, and `package.json` / CLI versions match the release tag.
|
|
8
|
-
-
|
|
8
|
+
- Promote the relevant [CHANGELOG.md](../../CHANGELOG.md) `Unreleased` entries into a dated version whose number matches `package.json` before tagging.
|
|
9
9
|
- Review README quick start, requirements, MCP setup, output contracts, public contract labels, and known tradeoffs when public CLI/MCP behavior changed.
|
|
10
|
+
- Confirm the GitHub repository still exposes `README.md`, `LICENSE`, `CONTRIBUTING.md`, `SECURITY.md`, issue templates, and the pull-request template; review the GitHub community profile before a public launch.
|
|
10
11
|
|
|
11
|
-
##
|
|
12
|
+
## Contract gate
|
|
12
13
|
|
|
13
14
|
- Confirm [Public_Contracts.md](Public_Contracts.md) labels every touched public surface as `stable`, `stable-additive`, `experimental`, `reserved`, or `internal`.
|
|
14
15
|
- Confirm focused contract tests cover MCP tool definitions, representative JSON fields, edge kinds, doctor warning shape, config defaults, and schema compatibility guidance.
|
|
15
16
|
- Confirm structured error outputs include a stable `code` and remediation where the command already returns structured errors.
|
|
17
|
+
- Confirm experimental commands remain explicitly labeled in the guides, public ledger, output contracts, and release notes.
|
|
18
|
+
- Confirm `wiki status` and `wiki verify` remain read-only, every non-current page/issue has recovery guidance, and the five-tool MCP surface is unchanged.
|
|
16
19
|
|
|
17
|
-
##
|
|
20
|
+
## Evidence gate
|
|
18
21
|
|
|
19
22
|
- Confirm [Public_Contracts.md](Public_Contracts.md) labels context recovery fields as `stable-additive`.
|
|
20
23
|
- Confirm context, MCP, and contract tests cover `nodeId`, `documentId`, optional `sectionId`, optional `anchor`, and graph-expansion `edgePath`.
|
|
21
24
|
- Confirm `smoke:cli` exercises a multi-question structured benchmark using repository-owned fixtures.
|
|
22
25
|
- Confirm optional semantic behavior remains experimental unless a separate release explicitly freezes it.
|
|
26
|
+
- Run the focused lexical-history, entity, context, structured-query, and derived-relationship regression suites. Treat recorded historical values as immutable comparison evidence, not current product targets.
|
|
23
27
|
|
|
24
|
-
##
|
|
28
|
+
## Compatibility gate
|
|
25
29
|
|
|
26
30
|
- Confirm known output-shape inconsistencies are either normalized or intentionally documented.
|
|
27
31
|
- Confirm `context --json` and MCP `mdgraph_context.structuredContent` expose recovery fields (`nodeId`, `documentId`, optional `sectionId`, optional `anchor`, and graph-expansion `edgePath`) for agent handoff to `node`, `trace`, and raw Markdown.
|
|
28
32
|
- Confirm Node.js `>=22.5.0` remains the supported floor and the active release was tested on the current Node 22.x line.
|
|
29
|
-
- Confirm Linux and Windows full CI rows pass. Confirm the macOS CI smoke row passes build-output CLI and packed-artifact smoke
|
|
33
|
+
- Confirm Linux and Windows full CI rows pass. Confirm the macOS CI smoke row passes build-output CLI and packed-artifact smoke.
|
|
30
34
|
- Run maintainer smoke for platform-specific long-running surfaces that CI intentionally does not automate: `serve --mcp` and `watch` on each target OS where those paths matter.
|
|
31
|
-
- Confirm
|
|
35
|
+
- Confirm release notes call out compatibility promises separately from feature additions.
|
|
36
|
+
- Confirm new behavior does not silently change the frozen 1.0 defaults, five-tool MCP surface, schema version, or `alpha | cjk` evaluation enum.
|
|
32
37
|
|
|
33
38
|
## Command gate
|
|
34
39
|
|
|
@@ -36,8 +41,14 @@ Run from the repository root after dependencies are installed:
|
|
|
36
41
|
|
|
37
42
|
```bash
|
|
38
43
|
npm run typecheck
|
|
44
|
+
npm run docs:check
|
|
39
45
|
npm run build
|
|
40
46
|
npm run test:run
|
|
47
|
+
npm run baseline:historical
|
|
48
|
+
npm run baseline:entity-extraction
|
|
49
|
+
npm run baseline:context-packing
|
|
50
|
+
npm run baseline:structured-query
|
|
51
|
+
npm run baseline:related-documents
|
|
41
52
|
npm run smoke:cli
|
|
42
53
|
npm run smoke:eval
|
|
43
54
|
npm run smoke:pack
|
|
@@ -57,7 +68,7 @@ git diff --check
|
|
|
57
68
|
|
|
58
69
|
Expected results:
|
|
59
70
|
|
|
60
|
-
-
|
|
71
|
+
- Documentation links, typecheck, tests, build, focused regression suites, CLI smoke, and pack smoke exit 0.
|
|
61
72
|
- `doctor --strict --json` reports `staleIndex: 0` and no issue counts for the MDGraph repository.
|
|
62
73
|
- `status --storage --json` returns `{ counts, storage }` with database, object, path group, edge kind, high-degree node, and vector sections.
|
|
63
74
|
- `bundle create`, `bundle verify`, and `report --json --eval --bundle` return valid private workflow artifacts for the current repository index.
|
|
@@ -68,12 +79,15 @@ Expected results:
|
|
|
68
79
|
- Keep private or third-party evaluation corpora outside release artifacts and public fixtures.
|
|
69
80
|
- The macOS CI row is smoke-only. It does not replace the full command gate or maintainer checks for MCP server, watcher, and external-corpus behavior.
|
|
70
81
|
|
|
71
|
-
## Package gate
|
|
72
|
-
|
|
73
|
-
- Inspect the tarball contents
|
|
74
|
-
- Confirm
|
|
75
|
-
-
|
|
76
|
-
- Confirm
|
|
82
|
+
## Package gate
|
|
83
|
+
|
|
84
|
+
- Inspect the machine-readable tarball contents whenever package metadata or public docs change: `npm pack --dry-run --json`.
|
|
85
|
+
- Confirm npm Trusted Publishing is bound to `daoGEE/mdgraph` and the exact workflow filename `publish.yml`, with the `npm publish` action allowed.
|
|
86
|
+
- Publish by pushing a `v*` tag whose version matches `package.json`; `.github/workflows/publish.yml` uses GitHub Actions OIDC and does not require a long-lived npm token.
|
|
87
|
+
- Confirm the package includes `dist`, the agent pack, both README files, `CHANGELOG.md`, `LICENSE`, and the explicitly allowlisted English/Chinese guides.
|
|
88
|
+
- Confirm the package does not contain numbered implementation-stage docs, internal implementation ADRs, `docs/tasks/`, `.mdgraph/`, local databases, `.DS_Store`, temporary output, or external workspace content.
|
|
89
|
+
- Install the packed tarball globally under a clean temporary prefix and verify `mdgraph --version`, `init`, and one representative query before publishing.
|
|
90
|
+
- Run `npm run smoke:pack`; it verifies runtime/type consumption and rejects implementation-stage documentation in the tarball.
|
|
77
91
|
|
|
78
92
|
## Note text
|
|
79
93
|
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Retrieval and Context
|
|
3
|
+
type: guide
|
|
4
|
+
status: active
|
|
5
|
+
source_refs:
|
|
6
|
+
- src/query/search.ts
|
|
7
|
+
- src/query/context-builder.ts
|
|
8
|
+
- src/extraction/entity-extractor.ts
|
|
9
|
+
- src/semantic/provider.ts
|
|
10
|
+
- src/semantic/ollama-provider.ts
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
# Retrieval and Context
|
|
14
|
+
|
|
15
|
+
MDGraph combines deterministic full-text, entity, and graph retrieval by default. A real embedding provider and true Maximal Marginal Relevance (MMR) context packing are available as explicit options; neither is required to index or query a project.
|
|
16
|
+
|
|
17
|
+
## Search Channels
|
|
18
|
+
|
|
19
|
+
`search` combines and deduplicates four explainable channels:
|
|
20
|
+
|
|
21
|
+
- FTS5 chunk matches, with lightweight CJK n-gram augmentation for continuous Chinese, Japanese, and Korean text.
|
|
22
|
+
- Exact technical-entity matches.
|
|
23
|
+
- Graph neighbors around matching entities and documents.
|
|
24
|
+
- Optional embedding-vector matches when a supported provider is enabled, indexed, and requested.
|
|
25
|
+
|
|
26
|
+
Reciprocal rank fusion (RRF) combines the active channels. Results retain reasons, matched entities, edge provenance, and optional semantic provider/model metadata. Semantic results are an additional signal; they do not replace the deterministic channels.
|
|
27
|
+
|
|
28
|
+
## Semantic Providers
|
|
29
|
+
|
|
30
|
+
Embedding support is provider-based. The default configuration keeps embeddings disabled.
|
|
31
|
+
|
|
32
|
+
| Provider | Capability | Intended use |
|
|
33
|
+
|---|---|---|
|
|
34
|
+
| `local-hash` | `lexical-hash` | Compatibility and deterministic lexical projection. It is not a language-model embedding and should not be treated as synonym understanding. |
|
|
35
|
+
| `ollama` | `semantic-model` | Opt-in local semantic retrieval through a separately running Ollama service and embedding model. |
|
|
36
|
+
|
|
37
|
+
Example Ollama configuration:
|
|
38
|
+
|
|
39
|
+
```json
|
|
40
|
+
{
|
|
41
|
+
"embedding": {
|
|
42
|
+
"enabled": true,
|
|
43
|
+
"provider": "ollama",
|
|
44
|
+
"model": "nomic-embed-text",
|
|
45
|
+
"dimensions": 768,
|
|
46
|
+
"endpoint": "http://127.0.0.1:11434",
|
|
47
|
+
"timeoutMs": 30000,
|
|
48
|
+
"batchSize": 16
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Build a complete provider-backed index before semantic queries:
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
mdgraph index --full --semantic --path /path/to/project
|
|
57
|
+
mdgraph semantic status --path /path/to/project
|
|
58
|
+
mdgraph search --semantic --path /path/to/project "authentication login"
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Provider identity, model, dimensions, and vector coverage are stored with the index. Changing that profile requires a full semantic reindex. Embedding finishes before a repository write begins, so provider failure cannot commit partial graph or vector coverage.
|
|
62
|
+
|
|
63
|
+
At query time, an unavailable provider, timeout, invalid response, missing model, or incomplete vector profile falls back to FTS5/entity/graph retrieval. CLI and MCP outputs include an additive `semanticDiagnostic`; a usable lexical result is not converted into an error.
|
|
64
|
+
|
|
65
|
+
## Deterministic Entity Extraction
|
|
66
|
+
|
|
67
|
+
Entity extraction is source-aware and favors precision. It is an interpretable heuristic, not general-purpose named-entity recognition and not a programming-language AST.
|
|
68
|
+
|
|
69
|
+
| Source | Inferred technical signals |
|
|
70
|
+
|---|---|
|
|
71
|
+
| Front matter and `Defines` / `定义` sections | Explicit definitions, including names otherwise suppressed by the stop list. |
|
|
72
|
+
| Technical headings | API routes, Latin symbols, shaped configuration keys, and empty-call function forms. |
|
|
73
|
+
| Ordinary prose | API routes, error codes, shaped uppercase or dotted configuration keys, and segmented CJK configuration keys. |
|
|
74
|
+
| Standalone inline code | Structured signals plus a complete Latin or CJK symbol value. |
|
|
75
|
+
| Fenced code | Structured signals, empty-call functions, declaration names, and bounded type-reference contexts. |
|
|
76
|
+
| Markdown and WikiLinks | Structured link signals; WikiLink labels must look like a complete entity. |
|
|
77
|
+
|
|
78
|
+
Broad PascalCase scanning is intentionally absent from prose and code blocks. This avoids promoting words such as “The”, “When”, and “Note” to graph nodes. `entities.stopEntities` suppresses every inferred reference kind; author-declared definitions remain authoritative.
|
|
79
|
+
|
|
80
|
+
Unicode-aware rules recognize CJK API paths such as `POST /接口/登录`, segmented keys such as `登录.认证.重试`, and empty-call identifiers such as `验证登录()` or `認証を確認()`. Route boundaries prevent a file path such as `src/auth/session.ts` from also emitting the truncated route `/auth/session.ts`. Bare CJK prose is not inferred as an entity without explicit structural evidence.
|
|
81
|
+
|
|
82
|
+
## Context Packing
|
|
83
|
+
|
|
84
|
+
`context` starts from ranked search sections, performs bounded graph expansion through non-containment edges, and packs selected sections under a character budget.
|
|
85
|
+
|
|
86
|
+
The compatibility default, `mmr-style-document-round-robin`, introduces documents in round-robin order. It is deterministic and preserves existing behavior, but it does not calculate pairwise relevance and redundancy.
|
|
87
|
+
|
|
88
|
+
True MMR is opt-in:
|
|
89
|
+
|
|
90
|
+
```bash
|
|
91
|
+
mdgraph context --packing mmr --mmr-lambda 0.65 --debug --json \
|
|
92
|
+
--path /path/to/project "session recovery"
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
MCP callers select the same behavior with `packingStrategy: "mmr"` and may provide `mmrLambda`. At each selection step, MMR maximizes:
|
|
96
|
+
|
|
97
|
+
```text
|
|
98
|
+
lambda * queryRelevance - (1 - lambda) * maximumSimilarityToSelected
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Candidate similarity uses stored vectors for the configured provider/model when both chunks have them. Otherwise it uses deterministic Unicode-token Jaccard similarity. Same-document candidates at least `0.8` similar to an already selected section are pruned, while the first candidate from another document is preserved as cross-document evidence.
|
|
102
|
+
|
|
103
|
+
Every result includes `packing` metadata. `--debug` additionally reports candidate and graph-expansion counts, similarity source, lambda, per-item relevance and redundancy scores, pruned duplicates, and budget truncation.
|
|
104
|
+
|
|
105
|
+
## Limits and Evaluation
|
|
106
|
+
|
|
107
|
+
- CJK n-grams improve lexical matching but do not provide morphology, word segmentation, translation, or synonym understanding.
|
|
108
|
+
- Entity rules recognize bounded technical shapes; projects should use explicit front matter for authoritative domain entities.
|
|
109
|
+
- Embedding quality depends on the chosen model and target corpus. Repository fixtures verify integration behavior, not universal model quality.
|
|
110
|
+
- MMR reduces measured redundancy on the repository fixture, but its best lambda and similarity threshold remain corpus-dependent.
|
|
111
|
+
|
|
112
|
+
See [Evaluation](Evaluation_Questions.md) for public `eval` commands, regression suites, and the limits of the recorded evidence. See [Operations](Operations.md) for index freshness and provider failure recovery.
|
|
113
|
+
|
|
114
|
+
## Exact entity queries and Knowledge Cards
|
|
115
|
+
|
|
116
|
+
Search first checks the normalized complete query against indexed entities, including Chinese names and lowercase configuration keys. Definitions declared only in front matter still return their matched entity even when the section text does not repeat it.
|
|
117
|
+
|
|
118
|
+
`node` responses include a deterministic Knowledge Card with stable node identity, definitions, source references, relationships, and evidence. The card's `maxChars` budget measures serialized JSON characters (default 4,000). Optional lists and display text are shortened with omission counts or `…`; node identity is preserved. A budget too small for the required structure and truncation diagnostics produces an explicit error. Context adds complete card summaries only when its remaining text budget can accommodate them; Markdown content already packed is preserved.
|
|
@@ -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
|
-
|
|
3
|
+
本文是面向 coding agent 的共享集成契约。不同宿主的适配应保持很薄:启动同一个 MCP server,暴露同一组五个工具,并教 agent 在直接读取 Markdown 文件前先查询 MDGraph。
|
|
4
4
|
|
|
5
5
|
## 核心行为
|
|
6
6
|
|
|
@@ -90,13 +90,23 @@ Task-start documentation brief:
|
|
|
90
90
|
2. 对解析出的节点调用 `mdgraph_trace`
|
|
91
91
|
3. 如果 trace 路径还需要上下文,再调用 `mdgraph_context`
|
|
92
92
|
|
|
93
|
-
文档健康检查:
|
|
93
|
+
文档健康检查:
|
|
94
94
|
|
|
95
95
|
1. `mdgraph_status`
|
|
96
96
|
2. 当用户要求 docs health 或 CI gate 时,使用 CLI `mdgraph doctor --json`
|
|
97
|
-
3. 只有在 doctor 输出点名 affected documents 后才编辑原文件
|
|
98
|
-
|
|
99
|
-
|
|
97
|
+
3. 只有在 doctor 输出点名 affected documents 后才编辑原文件
|
|
98
|
+
|
|
99
|
+
项目 Wiki authoring:
|
|
100
|
+
|
|
101
|
+
1. 针对当前图运行一次 CLI `mdgraph wiki plan --out <plan-file>`。
|
|
102
|
+
2. 运行 `mdgraph wiki status <wiki-dir> --plan <plan-file> --json`,只选择 missing 或 needs-update 页面。
|
|
103
|
+
3. 每次获取一个 `mdgraph wiki brief <page-id> --plan <plan-file> --json`,阅读其 document/source-ref evidence 后再编写。
|
|
104
|
+
4. 保留用户正文与维护 front matter,然后运行 `mdgraph wiki verify`。
|
|
105
|
+
5. 人工评审 orphaned 页面;工作流永不自动删除它们。
|
|
106
|
+
|
|
107
|
+
支持 reusable skill 的宿主可使用 [`agent-pack/skills/wiki-authoring`](../../agent-pack/skills/wiki-authoring/SKILL.md),其他宿主可使用对应 prompt template。
|
|
108
|
+
|
|
109
|
+
## 当前限制
|
|
100
110
|
|
|
101
111
|
- MDGraph 索引 Markdown 文档,不索引源码 AST 或任意文件。
|
|
102
112
|
- MCP surface 故意保持五个工具:search、context、node、trace、status。
|